App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-25] [$250] Issue with adding contact method in offline mode

Open IuliiaHerets opened this issue 1 month ago • 89 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: 9.5.14-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://test-management.browserstack.com/projects/2219752/test-plans/203241/linked-test-cases/79083052/41236653/1869288445?p=1&q=TC-3301

Action Performed:

  1. Navigate to account settings > Profile
  2. Click on "Contact Method"
  3. Verify the main contact method is the user email
  4. Click on "New Contact method"
  5. Verify the user is requested to add the magic code sent to the main account
  6. Navigate to the email inbox
  7. Verify the email you receive reads ".....trying to: • Add a new contact method to your account"
  8. Verify no sign-in button is rendered
  9. Enter the magic code sent to the main account and Click "Verify"
  10. Add a email you have access to
  11. Verify you're now requested to enter the magic code sent to the secondary contact
  12. Do not validate the secondary login yet - Click on back arrow to navigate back to profile page
  13. Verify the email is added as contact method with GBR
  14. Click on the contact method push row
  15. Verify enter the magic code page displayed
  16. Copy the Magic Code included in the validation email
  17. Verify the email you receive has the subject "Verify secondary email for Expensify" and looks different from all the other magic code emails
  18. Disable the internet connection
  19. Verify the "Verify" button is disabled
  20. Paste the magic code found in the email inbox in the field
  21. Verify the user is not redirected back to the contact methods list
  22. Enable the internet connection in the device

Expected Result:

User should be navigated back to the contact methods list

Actual Result:

User is getting navigated to the contact method details screen

Workaround:

Can the user still use Expensify without this being fixed? Have you informed them of the workaround?

Platforms:

Select the officially supported platforms where the issue was reproduced:

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

Screenshots/Videos

https://github.com/user-attachments/assets/30803b83-a4b9-43d8-bda5-90bca3949d0a

View all open jobs on GitHub

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

IuliiaHerets avatar Oct 20 '26 10:10 IuliiaHerets

⚠️ Preliminary analysis (low confidence) — treat as a starting point, not a conclusion.

I think the "go back to the list" call is skipped, or does nothing, when validation finishes after reconnecting on Android. The page then stays open and switches to the validated details view, which matches the actual result.

The only trigger for going back is a one-time effect in DynamicContactMethodDetailsPage.tsx:133-161. It fires once, when validatedDate goes from empty to set, and calls Navigation.goBack(listPath). I see two weak points:

  • The target is computed from global state. listPath comes from useDynamicBackPath.ts:24-44. That hook reads whichever route is focused in the whole navigation tree, not this screen's route. After a reconnect, validatedDate lands in the same batch as the ReconnectApp data. If the focused path is different at that moment, goBack goes to the wrong route or does nothing. 83362 migrate settings profile part 2 v2 replaced the old static route with this hook.
  • Nothing retries. If goBack bails out, it only logs Log.hmmm and the effect never fires again.

While offline, the code is never sent. ValidateCodeInput.tsx:237-253 blocks submit and submits automatically on reconnect. So this flow differs from the online flow only in timing: validation completes right after the reconnect.

Related: [Due for payment 2026-03-17] Contact method - After going online, user not redirected to contact method list on verifying secondary login (closed) had the same symptom. fix: prevent navigation logic when screen isn't focused fixed it for the case where the troubleshoot modal had focus. This report is an Android variant that fix doesn't cover.

Possible fix: Go back whenever the page saw the login unvalidated and it is now validated and the screen is focused. Re-check when focus changes. Build the list path from this screen's own route, not from global navigation state.

I couldn't verify this. The bug is Android-only, and reproducing it needs the magic code sent to the secondary email. To confirm it, reproduce on Android and check for two things:

  1. Client logs around the ValidateSecondaryLogin response contain [Navigation] Unable to go up.
  2. What listPath is when the effect fires.

Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis.


view run

MelvinBot avatar Oct 20 '26 11:10 MelvinBot

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

melvin-bot[bot] avatar Oct 20 '26 11:10 melvin-bot[bot]

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

melvin-bot[bot] avatar Oct 20 '26 11:10 melvin-bot[bot]

Proposal

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

When adding a secondary contact method while offline and submitting the magic code, once the device reconnects to the internet and validation succeeds, the user is not navigated back to the contact methods list and remains on the contact method details screen (which transitions into its validated state).

What is the root cause of that problem?

In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:133-161:

  1. The screen relies on an effect watching validatedDate to trigger navigation back to the list:
    const prevValidatedDate = usePrevious(loginData?.validatedDate);
    const isFocused = useIsFocused();
    const [shouldNavigateOnFocus, setShouldNavigateOnFocus] = useState(false);
    
    useEffect(() => {
        if (prevValidatedDate || !loginData?.validatedDate) {
            return;
        }
    
        if (isFocused) {
            Navigation.goBack(listPath);
        } else {
            setShouldNavigateOnFocus(true);
        }
    }, [prevValidatedDate, loginData?.validatedDate, isDefaultContactMethod, listPath]);
    
  2. When submitting while offline, validateSecondaryLogin places the network request in Onyx's sequential queue.
  3. Upon reconnecting to the internet, ReconnectApp and the queued ValidateSecondaryLogin API response execute simultaneously, firing a flurry of batch state updates (reconnecting network state, root navigation state re-evaluations, and Onyx logins updates).
  4. During this batch update on Android, useDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path) momentarily resolves against a transitional root state or fails inside Navigation.goBack(listPath) (logging [Navigation] Unable to go up).
  5. Because loginData?.validatedDate is now populated, on the immediate subsequent render prevValidatedDate is no longer falsy. Consequently, the condition if (prevValidatedDate || !loginData?.validatedDate) evaluates to true and permanently exits the effect without ever attempting navigation again.
  6. The screen therefore stays mounted and renders the validated contact method details view (getMenuItems()).

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

  1. In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:
    • Track validation transition using a dedicated ref (hasHandledValidationNavigation = useRef(false)) initialized to !!loginData?.validatedDate on mount.
    • When the screen mounts on an unvalidated contact method and later receives validatedDate, compute the explicit fallback route rather than relying solely on global focused navigation state.
    • Ensure that if Navigation.goBack(listPath) fails or if the screen transitions to validated state while mounted from the verification form, we fallback to navigating explicitly to ROUTES.SETTINGS_CONTACT_METHODS.route or invoke Navigation.goBack().
    const hasHandledValidationNavigation = useRef(!!loginData?.validatedDate);
    
    useEffect(() => {
        if (hasHandledValidationNavigation.current || !loginData?.validatedDate) {
            return;
        }
    
        hasHandledValidationNavigation.current = true;
        if (isFocused) {
            Navigation.goBack(listPath || ROUTES.SETTINGS_CONTACT_METHODS.route);
        } else {
            setShouldNavigateOnFocus(true);
        }
    }, [loginData?.validatedDate, isFocused, listPath]);
    
  2. In the focus restoration effect:
    useEffect(() => {
        if (!isFocused || !shouldNavigateOnFocus) {
            return;
        }
        setShouldNavigateOnFocus(false);
        Navigation.goBack(listPath || ROUTES.SETTINGS_CONTACT_METHODS.route);
    }, [isFocused, shouldNavigateOnFocus, listPath]);
    

What alternative solutions did you explore? (Optional)

Using a timeout or polling. Rejected because cleanly tracking the initial mount validation state via ref and providing a reliable fallback to ROUTES.SETTINGS_CONTACT_METHODS.route directly resolves the root cause deterministically without arbitrary delays.

Automated Tests

In tests/unit/DynamicContactMethodDetailsPageTest.tsx:

  • Render DynamicContactMethodDetailsPage with an unvalidated contact method (validatedDate: undefined).
  • Simulate network reconnection by updating Onyx ONYXKEYS.LOGINS with a populated validatedDate.
  • Assert that Navigation.goBack is called with the contact methods list path.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0170d6b02e9440e604

camesenin avatar Oct 20 '26 11:10 camesenin

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 20 '26 11:10 melvin-bot[bot]

Proposal

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

When a secondary contact method is added while offline, the user enters the magic code, reconnects, and the validation succeeds - but the user is left on the contact method details screen (which flips to its validated view) instead of being navigated back to the contact methods list.

What is the root cause of that problem?

The only navigation trigger is the one-shot effect in DynamicContactMethodDetailsPage.tsx:137-151, which fires when validatedDate transitions from empty to set (guarded by usePrevious):

if (prevValidatedDate || !loginData?.validatedDate) {
    return;
}
if (isFocused) {
    Navigation.goBack(listPath);
} else {
    setShouldNavigateOnFocus(true);
}

Two problems make this fail permanently in the offline flow:

  1. The destination is computed from global navigation state at the worst moment. listPath comes from useDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path), which serializes the whole root navigation tree at the currently focused route (useRootNavigationState) and derives the back path from whichever route happens to be focused. In the offline flow, the queued ValidateSecondaryLogin response lands in the same batch as the ReconnectApp reconnect data, so on Android the root navigation state is mid-transition when the effect fires. goBack(listPath) then silently no-ops (logging [Navigation] Unable to go up) or targets the wrong route.

  2. A failed attempt is never retried. On the next render prevValidatedDate is already truthy, so the guard if (prevValidatedDate || !loginData?.validatedDate) exits the effect forever. The existing shouldNavigateOnFocus fallback only covers the case where the screen was not focused when the effect fired - it does not cover a focused-screen goBack that silently failed.

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

  1. In DynamicContactMethodDetailsPage.tsx, navigate to backTo (already computed at line 85: getPathWithoutDynamicSuffix(listPath, DYNAMIC_ROUTES.CONTACT_METHODS.path) || ROUTES.SETTINGS_PROFILE.route) instead of the raw listPath. backTo derives the contact-methods list destination from this screen's own route, so it is stable even when the global focused route is transitional during the reconnect batch.
  2. Replace the usePrevious one-shot guard with a ref latch (hasNavigatedOnValidation) that flips only after the goBack call is actually issued. In the existing focus-restoration effect, retry the navigation if loginData.validatedDate is set, the latch is not set, and the screen is focused - so a no-op during the reconnect batch is retried once navigation settles. Keep the existing unfocused-case fallback (shouldNavigateOnFocus) as-is.

What alternative solutions did you explore? (Optional)

Delaying the navigation with a timeout until the reconnect batch settles. Rejected: arbitrary delays are flaky on slow devices, and the deterministic route plus retry latch fixes the root cause without timing hacks.

Automated Tests

In tests/unit/DynamicContactMethodDetailsPageTest.tsx:

  • Render DynamicContactMethodDetailsPage with an unvalidated contact method (validatedDate undefined).
  • Simulate the reconnect batch by updating Onyx ONYXKEYS.LOGINS with a populated validatedDate while the root navigation state is transitional.
  • Assert Navigation.goBack is called with the contact methods list path (not the raw global listPath).
  • Simulate a failed first attempt (goBack no-op) followed by a refocus, and assert the navigation is retried.

khizzcr7 avatar Oct 20 '26 12:10 khizzcr7

Contributor details Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~011091133bbb09cd1c

Proposal

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

When adding a secondary contact method offline and entering the magic code, once the device reconnects to the internet and validation succeeds, the user is not navigated back to the contact methods list and is left stranded on the contact method details menu view.

What is the root cause of that problem?

In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:

  1. One-shot guard via usePrevious: The validation navigation effect (lines 137–151) is guarded by if (prevValidatedDate || !loginData?.validatedDate). usePrevious updates its internal ref during an effect; once validatedDate populates, prevValidatedDate becomes truthy on the immediate next render. If the navigation call is delayed or dropped during network reconnection, or if shouldNavigateOnFocus is set, the guard exits permanently on all subsequent renders and navigation is never re-attempted.
  2. Omitted dependency in focus effect: In the focus restoration effect (lines 154–161), shouldNavigateOnFocus is omitted from the dependency array ([isFocused]). If shouldNavigateOnFocus is set to true while isFocused remains true (e.g., toggling Wi-Fi via Android quick settings / status bar without an actual route transition), the effect never fires.
  3. Reactive listPath instability during reconnection: listPath is derived from useDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path). During the reconnection batch update (ReconnectApp + ValidateSecondaryLogin), root navigation state can be transitional, causing useDynamicBackPath to fall back to ROUTES.HOME or no-op on distanceToPop <= 0.
  4. Premature view flip: isValidateCodeFormVisible is updated purely on !loginData?.validatedDate (lines 163–165). As soon as validatedDate arrives, it flips to render getMenuItems() before the screen is popped, leaving the details options visible to the user.

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

  1. In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:
    • Compute the canonical contact methods list route using createDynamicRoute:
      const contactMethodsListRoute = useMemo(
          () => createDynamicRoute(DYNAMIC_ROUTES.CONTACT_METHODS.path, backTo),
          [backTo],
      );
      
      This matches the pattern established in SetDefaultContactMethodConfirmValidateCodePage.tsx:47 and guarantees the destination is always deterministic regardless of transient root navigation state.
    • Replace usePrevious with a ref tracking validation navigation state (hasNavigatedAfterValidation = useRef(!!loginData?.validatedDate)), matching the pattern established in VerifyAccountPageBase.tsx:76.
    • Update the validation navigation effect to navigate to contactMethodsListRoute when isFocused is true, or set shouldNavigateOnFocus(true) if not focused:
      useEffect(() => {
          if (!loginData?.validatedDate || hasNavigatedAfterValidation.current) {
              return;
          }
      
          if (isFocused) {
              hasNavigatedAfterValidation.current = true;
              Navigation.goBack(contactMethodsListRoute);
          } else {
              setShouldNavigateOnFocus(true);
          }
      }, [loginData?.validatedDate, isFocused, contactMethodsListRoute]);
      
    • In the focus restoration effect, include shouldNavigateOnFocus in the dependencies and invoke Navigation.goBack(contactMethodsListRoute) when focus is active and validation is complete:
      useEffect(() => {
          if (!isFocused || !shouldNavigateOnFocus || hasNavigatedAfterValidation.current) {
              return;
          }
          hasNavigatedAfterValidation.current = true;
          setShouldNavigateOnFocus(false);
          Navigation.goBack(contactMethodsListRoute);
      }, [isFocused, shouldNavigateOnFocus, contactMethodsListRoute]);
      
    • Only render getMenuItems() if the screen was already mounted with a validated contact method, avoiding the visual flash when popping upon newly completed validation.

What alternative solutions did you explore? (Optional)

  • Navigating directly to backTo: Rejected because backTo is the profile root (settings/profile), which skips the contact methods list and pops two screens instead of one.
  • Using a timeout or delay: Rejected because timing-based solutions are non-deterministic across devices; using a ref latch with deterministic route construction directly eliminates the race condition.

Automated Tests

In tests/unit/DynamicContactMethodDetailsPageTest.tsx:

  • Render DynamicContactMethodDetailsPage with an unvalidated contact method.
  • Update Onyx ONYXKEYS.LOGINS with a populated validatedDate while isFocused = false.
  • Assert Navigation.goBack is not called yet.
  • Switch isFocused = true and assert Navigation.goBack is called with the contact methods list route.

sijo0218 avatar Oct 20 '26 14:10 sijo0218

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0163955a2ba221e513

Proposal

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

When adding a secondary contact method while offline and submitting the magic code, once the device reconnects to the internet and validation succeeds, the user is not navigated back to the contact methods list and remains on the contact method details screen (which transitions into its validated state).

What is the root cause of that problem?

In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:133-161:

  1. Unstable target route during reconnect batching: The validation success navigation effect calls Navigation.goBack(listPath) where listPath is derived from useDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path). useDynamicBackPath computes the path by serializing the global root navigation tree via useRootNavigationState. When the app reconnects to the network, ReconnectApp and queued API responses execute in the same tick. The router state is temporarily transitional, causing Navigation.goBack(listPath) to silently fail with [Navigation] Unable to go up or evaluate to an invalid dynamic path. Conversely, line 85 already defines backTo = getPathWithoutDynamicSuffix(listPath, DYNAMIC_ROUTES.CONTACT_METHODS.path) || ROUTES.SETTINGS_PROFILE.route, which provides a clean static fallback target.
  2. One-shot guard with usePrevious prevents retry on drop: The effect is guarded by:
    if (prevValidatedDate || !loginData?.validatedDate) {
        return;
    }
    
    usePrevious updates its internal ref on each render cycle. Once validatedDate arrives in Onyx, prevValidatedDate becomes truthy on the immediate next render. If the goBack call fails or is dropped during the reconnect transition, the effect never re-runs, stranding the user on the contact method details view.

What alternative solutions did you explore? (Optional)

None, ensuring route target stability via backTo and using an explicit navigation latch ref is the robust pattern.

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

In src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx:

  1. Use a ref latch (hasNavigatedOnValidation) instead of relying solely on usePrevious.
  2. Target backTo (or listPath with backTo fallback) rather than bare listPath:
--- a/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx
+++ b/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx
@@ -134,18 +134,22 @@ function DynamicContactMethodDetailsPage({route}: DynamicContactMethodDetailsPage
     const isFocused = useIsFocused();
     const [shouldNavigateOnFocus, setShouldNavigateOnFocus] = useState(false);
+    const hasNavigatedOnValidation = useRef(false);
 
     useEffect(() => {
-        if (prevValidatedDate || !loginData?.validatedDate) {
+        if (hasNavigatedOnValidation.current || !loginData?.validatedDate) {
             return;
         }
 
         if (isFocused) {
+            hasNavigatedOnValidation.current = true;
             // Navigate to methods page on successful validateCode verification.
             // The validatedDate property indicates successful validateCode verification.
-            Navigation.goBack(listPath);
+            Navigation.goBack(backTo);
         } else {
             // Set flag to navigate when screen regains focus
             setShouldNavigateOnFocus(true);
         }
-    }, [prevValidatedDate, loginData?.validatedDate, isDefaultContactMethod, listPath]);
+    }, [loginData?.validatedDate, isFocused, backTo]);
 
     // Handle navigation when screen regains focus and flag is set
     useEffect(() => {
@@ -155,7 +159,8 @@ function DynamicContactMethodDetailsPage({route}: DynamicContactMethodDetailsPage
         }
         setShouldNavigateOnFocus(false);
-        Navigation.goBack(listPath);
+        hasNavigatedOnValidation.current = true;
+        Navigation.goBack(backTo);
     }, [isFocused, shouldNavigateOnFocus, backTo]);

What automated tests can you add to prevent this from re-occurring?

Add a unit test in tests/unit/pages/DynamicContactMethodDetailsPageTest.tsx simulating:

  1. Entering magic code offline (login marked pending).
  2. Simulating reconnect batch updating loginData.validatedDate while DynamicContactMethodDetailsPage is mounted.
  3. Asserting that Navigation.goBack(backTo) is called, returning the user to the contact methods list.

jloa-dev avatar Oct 21 '26 01:10 jloa-dev

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 21 '26 01:10 melvin-bot[bot]

@getusha Whoops! This issue is 2 days overdue. Let's get this updated quick!

melvin-bot[bot] avatar Oct 23 '26 21:10 melvin-bot[bot]

:sos: C+ Help Wanted

getusha avatar Oct 26 '26 09:10 getusha

🚨 Edited by proposal-police: This proposal was edited at 2026-10-26 10:35:25 UTC.

Proposal

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

After validating a new secondary contact method that was entered while offline, going back online from the Test Preferences modal leaves the user on the (now validated) contact method details page instead of taking them back to the contact methods list.

What is the root cause of that problem?

Going frame by frame through the attached video (around 2:36 to 2:41) shows what actually happens:

  1. "Force offline" is switched off inside the Test Preferences modal, the queued code is sent and the page behind the modal flips to the validated view ("Set as default").
  2. The tester taps outside, the modal closes and the details page shows for a single frame.
  3. Right away the Test Preferences modal opens again, and this time the Profile page is behind it, the details page is gone.
  4. The tester taps outside again and lands on a freshly mounted details page that is already validated, so nothing navigates anymore. Back from there goes to Profile, the list is gone (2:52).

So goBack isn't silently failing or being dropped. It runs, but with the wrong target.

The code is only sent on reconnect, which here happens while the modal is open: https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/components/ValidateCodeInput.tsx#L237-L253

While the modal is open the details page is not focused, so the validation effect only sets shouldNavigateOnFocus and the navigation is deferred to the focus effect: https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L133-L161

Both effects navigate to listPath, which isn't derived from this screen. It's the path of whatever route is focused in the whole root state, with our suffix stripped only if it happens to be at the end: https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L80-L81 https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/hooks/useDynamicBackPath.ts#L23-L37

While the modal is on top, the focused path is test-tools?backTo=settings/profile/contact-methods/<email>/details (the modal is opened with the current route as backTo). It doesn't end with :contactMethod/details, so the strip does nothing and listPath becomes the test tools URL.

When the modal closes, isFocused and listPath don't update in the same render:

  • useIsFocused is a useSyncExternalStore over the navigator's focus/blur events (useIsFocused.tsx#L44). The navigator emits focus from its own effect and the store update re-renders synchronously.
  • listPath is plain useState set from the container's state listener (useRootNavigationState.ts#L34-L43), and the container emits state from its own useEffect (BaseNavigationContainer.tsx#L418). The container is the parent, so that runs after the navigator's effects, and it lands one render later.

The focus effect only depends on isFocused, so it runs exactly once, in the render where focus has already flipped but listPath is still the modal URL, and calls Navigation.goBack('test-tools?backTo=...details'). The test tools navigator was just popped, so goUp can't find it in the root state and replaces instead: https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/libs/Navigation/Navigation.ts#L612-L618

That replaces the whole RHP (list + details) with a new Test Preferences modal, which is why the modal "reopens" over Profile. Closing it calls goBack(backTo) with the details URL it was originally opened from: https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/libs/actions/TestTool.ts#L27-L33

That URL isn't in the stack anymore either, so a new details page is pushed. It mounts with validatedDate already set, so prevValidatedDate is set on the first render and the validation effect never navigates. The user is stuck on the details page, which matches "User is getting navigated to the contact method details screen".

This started when #97526 replaced the static ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo), which #81673 used for this same focus fallback (twin issue #81043), with the root-state-derived listPath. The static route couldn't change while the screen was covered, the new one does.

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

Resolve the list path at the moment we navigate, not from the render that happened to flip isFocused. When the focus effect runs, the root state is already committed with this screen focused (getRootState() reads the live navigator state). Only the state event that refreshes listPath is late.

useDynamicBackPath is just getPathFromState(rootState) + stripDynamicRouteSuffixFromPath, and both already exist as plain functions (Navigation.getActiveRoute() is exactly getPathFromState(navigationRef.getRootState())): https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/libs/Navigation/helpers/getActiveRoute.ts#L8-L25

So in DynamicContactMethodDetailsPage add a small helper and use it for the two validation navigations (the isFocused branch of the validation effect and the shouldNavigateOnFocus effect):

// Read the path when navigating, the rendered listPath can still be the route of a screen just closed over this one
const goBackToContactMethods = () => {
    Navigation.goBack(stripDynamicRouteSuffixFromPath(Navigation.getActiveRoute(), DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path));
};

That's the whole fix. It doesn't depend on which of isFocused / listPath re-renders first, so it doesn't rely on React's render ordering at all. The header back button and the other goBack(listPath) calls are user taps on a focused page where listPath is already current, so they stay as they are, and useDynamicBackPath (used in 240+ files) isn't touched.

I have the fix with tests here, the new test fails on main and passes with the change: Compare branch: https://github.com/Expensify/App/compare/main...David-2002065:App:fix/104461-contact-method-stale-list-path

What alternative solutions did you explore? (Optional)

  1. Bind the list path to this screen instead of the focused root route, the same way useScreenBoundDynamicRoute does "so a link built during render survives another screen being stacked over it": https://github.com/Expensify/App/blob/237cf70dbf866bd9d0e9a1628becf6302b30ebf8/src/hooks/useScreenBoundDynamicRoute.ts#L16-L45 That means syncing the path only while this route is focused and stripping our suffix from it. It covers every listPath use on the page, but it's more code than this bug needs. Doing the same inside useDynamicBackPath itself (remembering the last matched value) fixes the whole class, but it changes what a shared hook returns for every screen that's covered by something, which is a much bigger blast radius for a one-screen report.

  2. Keep listPath, but make the focus effect also depend on listPath and wait for it to catch up before navigating. This works today, but it's correct only because the container's state effect happens to land after the navigator's focus event. If those ever arrive in the other order (or in the same render), the effect has to be written carefully to not miss the navigation, while reading the live state at call time doesn't care.

A ref latch, a retry, or a fallback like listPath || ROUTES.SETTINGS_CONTACT_METHODS.route doesn't help here: goBack doesn't fail or bail out, it succeeds with the test tools URL (which isn't empty), and the remounted page has already lost its shouldNavigateOnFocus state anyway.

Automated Tests

In tests/unit/DynamicContactMethodDetailsPageTest.tsx (already in the branch):

  1. Render with an unvalidated login while another screen covers the page (isFocused = false, useDynamicBackPath returning test-tools?backTo=...details). Merge validatedDate and check Navigation.goBack isn't called yet.
  2. Flip isFocused to true while the hook still returns the stale modal path but the live route is the details page (the render where focus flips first). Check goBack is called once with settings/profile/contact-methods and not the test tools URL. This fails on main.
  3. The existing focused case (validated while the page is focused) still calls goBack.
  4. Opening an already validated contact method doesn't call goBack.
Test run
npx jest tests/unit/DynamicContactMethodDetailsPageTest.tsx

main:
  ✕ goes back to the contact methods list when the screen is refocused after being validated under another screen
    Expected: "settings/profile/contact-methods"
    Received: "test-tools?backTo=settings/profile/contact-methods/fake%40gmail.com/details"
  Tests: 1 failed, 4 passed, 5 total

branch:
  Tests: 5 passed, 5 total

David-2002065 avatar Oct 26 '26 09:10 David-2002065

Proposal

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

After pasting the magic code while offline and going back online, the contact method is validated but the user is not taken back to the contact methods list. They stay on the details screen, now in its validated state.

What is the root cause of that problem?

The deferred "go back on focus" navigation runs one render too early, with a back path that still points at the Test tools modal, so goBack replaces the settings RHP with that modal instead of popping to the list.

  1. Offline, the code is not submitted: ValidateCodeInput returns early on isOffline and re-submits in onReconnect (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/components/ValidateCodeInput.tsx#L237-L262). So the request goes out the moment "Force offline" is switched off, while the Test tools modal is still open above the page.
  2. ValidateSecondaryLogin succeeds and sets validatedDate. The page's effect sees the transition, but the screen is not focused (the modal is a root-stack route above the RHP), so it only sets shouldNavigateOnFocus (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L137-L151). The page flips to its validated view behind the modal at 2:37.8 in the video.
  3. When the modal is dismissed, the second effect fires on isFocused and calls Navigation.goBack(listPath) (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L153-L161). listPath comes from useDynamicBackPath, which is derived from whichever route is focused in the whole tree and returns the path unchanged when the :contactMethod/details suffix does not match (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/hooks/useDynamicBackPath.ts#L24-L44). While the modal was focused that value was test-tools?backTo=settings/profile/contact-methods/.../details.
  4. The effect's two inputs update in different renders. useIsFocused is a useSyncExternalStore over the live navigation state, so it re-renders synchronously as soon as the modal is popped. listPath is plain useState fed by the container's state event, which the container emits from its own effect, one render later (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/hooks/useRootNavigationState.ts#L20-L45). Keyed on isFocused alone, the effect runs while listPath is still the modal path.
  5. goBack('test-tools?...') targets a route that is no longer in the root state, so goUp dispatches REPLACE at the root (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/libs/Navigation/Navigation.ts#L604-L609), replacing the RHP (list + details) with the Test tools modal. The video shows this: the modal closes at 2:39.3 and re-opens one frame later over Profile, because the RHP is gone.
  6. Dismissing the modal again runs Navigation.goBack(backTo) with the details path stored in the modal's params (https://github.com/Expensify/App/blob/b0238c54ff2b733782ae5c35d3618708924be195/src/libs/actions/TestTool.ts#L27-L31). That route is gone too, so it is pushed fresh: the user lands on the details screen with no list beneath it, and back goes to Profile (2:52 in the video).

This is a regression from PR #97526 (b980c643331). The fix for the twin issue #81043 (PR #81673) built the target from route.params.backTo, which could not change while the screen was covered. #97526 swapped it for useDynamicBackPath, which follows global focus and lags it by one render.

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

Key the deferred navigation on the back path catching up with the focus change, not on the focus change itself. In DynamicContactMethodDetailsPage.tsx change the second effect's dependency list from [isFocused] to [listPath, shouldNavigateOnFocus]:

useEffect(() => {
    if (!isFocused || !shouldNavigateOnFocus) {
        return;
    }
    setShouldNavigateOnFocus(false);
    Navigation.goBack(listPath);
    // listPath lags isFocused by a render (state event vs. sync focus read), so wait for it
}, [listPath, shouldNavigateOnFocus]);

Why this is enough: the flag is only set while the screen is covered, so listPath at that time is the covering route's path. When the cover is removed the focused path becomes this screen's own path, so listPath always changes, and only after isFocused is already true (the container emits state after every navigator's focus effects). The effect runs once with isFocused === true and the correct list path. If both update in the same render it still works, since listPath is a dep. The online path is untouched: the first effect still navigates immediately while focused, and every other goBack(listPath) in the page is user-initiated while focused, where listPath is current.

Why the obvious alternatives fail: adding isFocused to the deps, or useFocusEffect, fires in the same early render (focus events come from navigator effects, which run before the container's state effect) and goes back to the same stale path. A fallback like listPath || ROUTES.SETTINGS_CONTACT_METHODS.route never triggers, because listPath is not empty, it is the modal path.

What alternative solutions did you explore? (Optional)

  • Track "did this page submit a code" with a ref and navigate on validatedDate. The video shows the navigation already fires; its target is wrong, so this changes nothing on the repro.
  • Read the path live inside the effect (Navigation.getActiveRoute() plus the suffix strip from useDynamicBackPath). Correct, but duplicates the hook's logic in the page for one call site.
  • Make useDynamicBackPath keep its last matching value when the focused route is not the caller's. Fixes the class for all consumers, but changes a shared hook for a one-screen report.

ahmdshrif avatar Oct 26 '26 09:10 ahmdshrif

Proposal

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

On the contact method details page, you open an unvalidated secondary contact method, go offline, and paste the magic code. While offline the verification can't be sent, so nothing happens (expected). When you re-enable the internet, the verification is submitted and the contact method gets validated — but instead of being taken back to the contact methods list, you are left on the contact method details screen (now showing the validated "Set as default / Remove" view).

What is the root cause of that problem?

1. While offline, the magic code is not submitted — the submission is deferred until the device reconnects.

ValidateCodeInput refuses to auto-submit while offline (|| isOffline in the validateAndSubmit guard), and instead registers the same validateAndSubmit as the onReconnect callback of useNetwork. So when the user pastes the code offline, nothing is sent; the actual validateSecondaryLogin call only fires once the network comes back.

https://github.com/Expensify/App/blob/fa269bae19c71e05e78fd54dc85d8a3acb90c88e/src/components/ValidateCodeInput.tsx#L237-L253

2. The contact method is marked validated only in the success response, which arrives after reconnect.

validateSecondaryLogin sets validatedDate in successData (not in optimisticData). Because the submission itself is deferred to reconnect, loginData.validatedDate flips from empty to set during the reconnect cycle, not while the user is actively interacting with the form.

https://github.com/Expensify/App/blob/fa269bae19c71e05e78fd54dc85d8a3acb90c88e/src/libs/actions/User.ts#L647-L661

3. The "go back to the list" navigation is driven by watching that validatedDate flip, and its fallback for the "not focused at the moment of validation" case is broken.

In DynamicContactMethodDetailsPage, the first effect navigates back to the list the moment validatedDate becomes set — but only if isFocused is true at that render. If the screen is not focused at that render (which is exactly what happens when validation resolves during the reconnect cycle rather than during a live user interaction), it instead takes the else branch and sets a shouldNavigateOnFocus flag, expecting a second effect to complete the navigation later.

The second effect is meant to perform that deferred navigation, but its dependency array is [isFocused] only. It therefore runs only when isFocused changes value — never when shouldNavigateOnFocus flips from false to true. So in the reconnect path, the flag is set but the fallback effect never fires, the goBack is silently dropped, and the user is stranded on the details page (which has meanwhile switched to its validated view via the setIsValidateCodeFormVisible(!loginData?.validatedDate) effect).

https://github.com/Expensify/App/blob/fa269bae19c71e05e78fd54dc85d8a3acb90c88e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L137-L161

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

Fix the fallback effect so it actually fires when the deferred-navigation flag is set, not only on focus transitions. Add shouldNavigateOnFocus (and listPath, which the effect uses) to its dependency array. With the flag now in the deps, the effect runs as soon as the first effect sets it, and — because the screen is already focused on reconnect — immediately navigates back to the contact methods list. The existing setShouldNavigateOnFocus(false) + the prevValidatedDate guard already prevent any double navigation when listPath recomputes after goBack.

https://github.com/Expensify/App/blob/fa269bae19c71e05e78fd54dc85d8a3acb90c88e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L154-L161

    }, [isFocused, shouldNavigateOnFocus, listPath]);

The react-hooks/exhaustive-deps disable comment above the array can be removed, since all referenced values (isFocused, shouldNavigateOnFocus, listPath) are now listed (setShouldNavigateOnFocus and Navigation are stable).

abbasifaizan70 avatar Oct 26 '26 09:10 abbasifaizan70

🚨 Edited by proposal-police: This proposal was edited at 2026-10-26 10:01:25 UTC.

Proposal

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

An unvalidated contact method opens on the magic-code screen (the contact method details page). The user goes offline, pastes the magic code, then restores the internet connection. Once the queued validation completes, the user should be navigated back to the contact methods list, but on Android they end up on the contact method details screen instead.

What is the root cause of that problem?

Two pieces combine.

First, pasting a complete code submits the form even while offline. The code input's fulfill handler calls the submit callback directly, bypassing the offline-disabled Verify button, so validateSecondaryLogin is queued by the offline request queue:

https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/components/ValidateCodeActionModal/ValidateCodeForm/BaseValidateCodeForm.tsx#L329-L339

Because of that, the success data that stamps validatedDate on the login only arrives after connectivity returns — and at that moment the details screen is no longer the focused route. In the issue's video the connection is restored through the test-tools modal, which is a route stacked on top of the root navigator; any screen stacked over the details page when the queued request completes triggers the same failure.

Second, the back target used by the navigate-on-success logic is wrong whenever the details screen is covered. The page computes its back path with useDynamicBackPath:

https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L80-L85

That hook derives the back path from the path of the currently focused route in the root navigation state. When another screen sits on top, the focused path no longer ends with the :contactMethod/details suffix, the suffix match fails, and the hook falls through to returning the covering route's own path unchanged:

https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/hooks/useDynamicBackPath.ts#L25-L43

So when validatedDate lands while the screen is covered, the navigate-on-success effects consume a listPath that points at the covering screen rather than the contact methods list:

https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L133-L161

Calling Navigation.goBack with that path resolves to the route that is already focused, so the navigation silently does nothing — and because the effect is guarded by prevValidatedDate, it is a one-shot that never retries. The user is never returned to the contact methods list; when the covering screen closes they land back on the contact method details screen, which now shows the validated state ("Set as default" / "Remove"). That is exactly the reported actual result.

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

Make useDynamicBackPath screen-bound, in the same spirit as useScreenBoundDynamicRoute for forward routes: remember the last back path computed while the expected dynamic suffix actually matched the focused path (i.e. while the owning screen was the focused route), and when the suffix no longer matches — because another screen is stacked on top — keep returning that remembered value instead of falling back to the covering route's path. Only if the suffix has never matched does the hook keep today's fallback of returning the path as-is. The forward-route hook already documents this exact trap — a route built during render but followed later must not resolve against whatever happens to be focused at that time:

https://github.com/Expensify/App/blob/9d14b70be07d516add0a1fe43c06aef15bec321e/src/hooks/useScreenBoundDynamicRoute.ts#L22-L47

With the retained value, the existing focused/unfocused handling in the details page works as designed on every platform: if validation succeeds while the screen is focused, it goes back to the list immediately; if it succeeds while the screen is covered, the shouldNavigateOnFocus flag fires on refocus with the correct list path and the user is returned to the contact methods list.

I also added a unit test to the existing useDynamicBackPath tests covering a route that gets covered by another screen and later refocused.

Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/104461-dynamic-back-path-covered-screen?expand=1

What alternative solutions did you explore? (Optional)

A scoped fix inside DynamicContactMethodDetailsPage only: snapshot listPath into a ref while the screen is focused (when the suffix match is valid) and have both navigate-on-success effects use that snapshot. This avoids touching the shared hook, but it leaves every other useDynamicBackPath consumer exposed to the same covered-screen staleness, so fixing the hook is preferable.

wildan-m avatar Oct 26 '26 09:10 wildan-m

🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.

github-actions[bot] avatar Oct 26 '26 09:10 github-actions[bot]

Proposal updated — added compare branch with implementation.

wildan-m avatar Oct 26 '26 10:10 wildan-m

🚨 Edited by proposal-police: This proposal was edited at 2026-10-26 17:21:13 UTC.

Proposal

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

After adding a secondary contact method, the user goes offline and pastes the magic code, then goes back online by switching off "Force offline" in the Test Tools modal (Cmd+D on Android). The user is expected to land on the contact methods list. Instead, the new email's details page ("Set as default" / "Remove") opens, and Back from it goes to Profile.

What is the root cause of that problem?

The root cause is useDynamicBackPath. It is meant to return the back path of the screen that calls it, but it builds that path from the focused route of the whole app. So whenever another screen is stacked on top of the caller, it returns a path that is not the caller's.

  1. The details page builds its back path from the hook: const listPath = useDynamicBackPath(DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path); https://github.com/Expensify/App/blob/main/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx

  2. The hook reads the focused route of the whole app, and removes :contactMethod/details from the end of it. If the end does not match, it returns the path unchanged: https://github.com/Expensify/App/blob/main/src/hooks/useDynamicBackPath.ts https://github.com/Expensify/App/blob/main/src/libs/Navigation/helpers/dynamicRoutesUtils/stripDynamicRouteSuffixFromPath.ts

  3. Test Tools opens on top with the current page in backTo: https://github.com/Expensify/App/blob/main/src/libs/actions/TestTool.ts

    So while it is open, the focused path is test-tools?backTo=.../details. It does not end with /details, so listPath becomes the Test Tools route. This is what the logs show:

    listPath settings/profile/contact-methods                        isFocused true    (details page open)
    listPath settings/profile/contact-methods                        isFocused false   (Test Tools opening)
    listPath test-tools?backTo=%2Fsettings%2Fprofile%2Fcontact-methods%2F<email>%2Fdetails   isFocused false
    listPath test-tools?backTo=...                                   isFocused true    (Test Tools closing)
    
  4. With "Force offline" switched off inside Test Tools, the queued ValidateSecondaryLogin finishes. validatedDate is set while the page is covered (isFocused is false). The page can't go back yet, so it only stores a flag:

    if (isFocused) { Navigation.goBack(listPath); } else { setShouldNavigateOnFocus(true); }
    
  5. When Test Tools closes, the focus effect runs Navigation.goBack(listPath). But listPath is the Test Tools route, and it was just closed:

    if (!isFocused || !shouldNavigateOnFocus) return;
    Navigation.goBack(listPath);   // listPath = 'test-tools?backTo=...'
    
  6. goUp cannot find that route in the navigation state, so it does a REPLACE instead of a pop: https://github.com/Expensify/App/blob/main/src/libs/Navigation/Navigation.ts (canPopToRoute, then REPLACE)

    That replaces the whole right-hand panel (the contact methods list and the details page) with Test Tools.

  7. Closing Test Tools follows its backTo, which is the details URL. That opens a new details page directly on top of Profile. validatedDate is already set, so we see "Set as default / Remove", and the list is gone from the stack.

It is not related to whether the account was validated first. It happens every time the connection is restored through Test Tools.

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

Make useDynamicBackPath read the path of its own screen instead of the focused route of the app. The hook already runs inside the screen, so it knows its own route key (React Navigation's NavigationRouteContext). Nothing has to be remembered or guessed:

  1. Read the route key of the calling screen.
  2. Take the navigation state and drop every screen stacked above that route (Test Tools is one of them). This gives the state as it was before the modal opened.
  3. Build the path from that state and remove the suffix, as today.

With this, listPath is settings/profile/contact-methods the whole time, whether Test Tools is open or not. When Test Tools closes, Navigation.goBack(listPath) pops to the contact methods list.

Why this is the more direct fix: the root cause is "the hook looks at the wrong screen". This makes it look at the right one, so the path is always derived from the current state. There is no extra state to keep in sync, and it cannot go stale. It also fixes every other screen that calls the hook (more than 200), not only the details page.

New helper .../helpers/getStateFocusedOnRoute.ts:

function getStateFocusedOnRoute(state: State, routeKey: string): State | undefined {
    for (const [index, route] of (state.routes ?? []).entries()) {
        if (route.key === routeKey) {
            // Found it: drop the routes above it and make it the focused one
            return {...state, routes: state.routes.slice(0, index + 1), index};
        }

        // Look inside nested navigators, and do the same on the way back up
        const nestedState = route.state ? getStateFocusedOnRoute(route.state, routeKey) : undefined;
        if (nestedState) {
            const routes = state.routes.slice(0, index + 1);
            routes[index] = {...route, state: nestedState};
            return {...state, routes, index};
        }
    }

    return undefined;
}

Change in src/hooks/useDynamicBackPath.ts:

// `useRoute` throws outside a screen, so read the route from the context directly
const routeKey = useContext(NavigationRouteContext)?.key;

const path = useRootNavigationState((state) => {
    if (!isEnabled || !state) {
        return undefined;
    }

    // Build the path as if our screen were the focused one. Fall back to the real focused route
    // if we are not in a screen, or not in the state yet.
    const ownState = routeKey ? getStateFocusedOnRoute(state, routeKey) : undefined;
    return getPathFromState(ownState ?? state);
});
// ...the rest of the hook is unchanged: HOME when there is no path, then strip the suffix

Edge cases

Case Result
Covered by a modal (Test Tools) The covering screen is dropped, so the back path is the contact methods list (the bug fix)
Covered by several screens, or by another screen in the same stack Same result, every screen above ours is dropped
Hook used outside a screen (no route in context) Old behavior: uses the focused route
Screen not in the navigation state yet (still mounting) Old behavior: uses the focused route, no crash
Navigation not ready (empty state) The helper returns undefined, no crash
Hook disabled (isEnabled = false) Reads nothing, returns HOME
Screen remounted Nothing is stored in the hook, so there is nothing to lose
Screen is not covered Same path as before the change, because our screen is already the focused one

The navigation state is never changed. The helper returns a copy that is only used to build the path.

I checked it with the getStateFromPath and getPathFromState and the route names, with Test Tools stacked on top of the contact method details. Without the fix the hook returns exactly the value from the logs (test-tools?backTo=%2Fsettings%2Fprofile%2Fcontact-methods%2F...%2Fdetails). With the fix it returns the same path as when nothing is stacked on top.

What alternative solutions did you explore? (Optional)

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

Result

https://github.com/user-attachments/assets/06008494-9c54-4652-8e98-1bea26128d78

samranahm avatar Oct 26 '26 10:10 samranahm

🚨 Edited by proposal-police: This proposal was edited at 2026-10-26 11:05:04 UTC.

Proposal

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

After a secondary contact method’s security code is submitted by turning off Force offline inside the Test tools modal, closing the modal leaves the user on a newly opened contact method details page. The contact methods list has been removed from the stack, so Back goes to Profile.

What is the root cause of that problem?

The code is held until reconnect, and that reconnect happens while Test tools is the focused route. ValidateCodeInput returns early while offline and submits from onReconnect: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/components/ValidateCodeInput.tsx#L237-L253

validatedDate is set on success. The details page is covered, so the validation effect only raises shouldNavigateOnFocus. The effect that runs when focus returns calls Navigation.goBack(listPath): https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L133-L161

listPath is the focused route in the whole tree, with this screen’s suffix removed only when that suffix is the tail: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L80-L81 and https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/hooks/useDynamicBackPath.ts#L23-L37

An unmatched suffix is returned unchanged: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/libs/Navigation/helpers/dynamicRoutesUtils/stripDynamicRouteSuffixFromPath.ts#L18-L25

Test tools is opened with the current route as backTo, so the focused path is test-tools?backTo=settings/profile/contact-methods/<email>/details. That path does not end in :contactMethod/details, and listPath becomes the Test tools URL: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/libs/actions/TestTool.ts#L26-L44

useIsFocused updates in the render that pops the modal. listPath updates a render later, because useRootNavigationState only copies the path inside the state listener: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/hooks/useRootNavigationState.ts#L35-L42

The focus effect therefore calls Navigation.goBack('test-tools?backTo=…details') after that route has already been popped. canPopToRoute is false when the route is absent, and goUp replaces the current route: https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/libs/Navigation/Navigation.ts#L444-L448 and https://github.com/Expensify/App/blob/c08c85f3c5d20214e219dd1a1286936a513527cc/src/libs/Navigation/Navigation.ts#L614-L617

That replace removes the right-hand panel, which held both the list and the details page, and puts Test tools back. Closing it follows the modal’s backTo, the details URL, and mounts a new details page. usePrevious is initialized to the current validatedDate, so the one-shot effect does not navigate. The user is on the details screen, and Back goes to Profile.

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

In DynamicContactMethodDetailsPage.tsx, build the list URL from the live route when navigating. Navigation.getActiveRoute() reads navigationRef.getRootState(), which is already the details page when the focus effect runs. The rendered listPath is the value that is one render behind.

+import stripDynamicRouteSuffixFromPath from '@libs/Navigation/helpers/dynamicRoutesUtils/stripDynamicRouteSuffixFromPath';

+const goBackToContactMethodsList = () => {
+    Navigation.goBack(stripDynamicRouteSuffixFromPath(Navigation.getActiveRoute(), DYNAMIC_ROUTES.CONTACT_METHOD_DETAILS.path));
+};

-            Navigation.goBack(listPath);
+            goBackToContactMethodsList();

-        Navigation.goBack(listPath);
+        goBackToContactMethodsList();

Use the helper in both validation effects. The focused branch needs it too, so a validation update that lands in the same render as the focus change cannot still close over the Test tools URL.

Header back and the other goBack(listPath) calls stay on listPath. They run from a tap while this page is focused, after the state listener has caught up. useDynamicBackPath is left alone.

Online verification is unchanged: the screen is focused, the live route ends in :contactMethod/details, and the strip result is the contact methods list. The case where a modal covers the page is unchanged in timing: navigation still waits for focus, then pops to the list instead of replacing the panel.

What alternative solutions did you explore? (Optional)

  • Remembering the last matched back path inside useDynamicBackPath for every caller. That also keeps this page’s listPath stable while Test tools is open, and it changes the hook’s contract (“unmatched suffix returns the path as-is”) for every screen that uses it.
  • Re-running the focus effect when listPath changes, so it waits for the late state event. That works with today’s effect order and misses navigation if focus returns without another listPath change.
  • Delaying goBack(listPath) until the next microtask. The call already runs. Its argument is the wrong route, so delaying it still replaces the panel.
  • Restoring ROUTES.SETTINGS_CONTACT_METHODS.getRoute(backTo). backTo is derived from the same listPath, so while the modal is open it falls through to Profile and drops other entry points the dynamic route was added to support.

What specific scenarios should we cover in automated tests?

  • With the page unfocused and useDynamicBackPath returning test-tools?backTo=settings/profile/contact-methods/<email>/details, setting validatedDate does not call Navigation.goBack.
  • Flipping focus to true while that hook value is still the Test tools URL, and Navigation.getActiveRoute() is settings/profile/contact-methods/<email>/details, calls Navigation.goBack once with settings/profile/contact-methods.
  • A focused page whose live route is the details URL still calls Navigation.goBack with the contact methods list when validatedDate transitions from empty to set.
  • Opening an already validated contact method does not call Navigation.goBack.

neerajbachani avatar Oct 26 '26 10:10 neerajbachani

Proposal

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

A secondary contact method is validated while offline. Once connectivity returns, the screen stays on the contact method details view (now showing Set as default / Remove) rather than popping back to the contact methods list.

What is the root cause of that problem?

validatedDate is only written in successData, so the whole sequence necessarily runs on reconnect — and in the OP's video the reconnect is done from inside the Test Tools modal ("Force offline"), which is the focused route at that moment. Stepping the video frame by frame: at ~2:38 the details page flips to Set as default / Remove behind the still-open modal, so the page has already observed validation and has taken the deferred branch added for #81043, storing a flag to go back once focus returns:

https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/pages/settings/Profile/Contacts/DynamicContactMethodDetailsPage.tsx#L137-L161

The destination it will pass is listPath = useDynamicBackPath(...), and the hook's contract is the crux here: it matches registered dynamic suffixes against the tail of the globally focused route's path, and when no suffix matches it returns that active path verbatim:

https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/hooks/useDynamicBackPath.ts#L33-L44

The Test Tools modal is opened with the active route embedded as backTo:

https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/libs/actions/TestTool.ts#L41-L45

so while it is on top, the focused path is test-tools?backTo=settings/profile/contact-methods/<email>/details. :contactMethod/details is not the tail of that path, nothing matches, and the verbatim fallback hands back the modal's own route — listPath is now test-tools?backTo=….

Tapping outside closes the modal, the details screen refocuses, and the deferred effect dispatches Navigation.goBack('test-tools?backTo=…'). goUp can no longer find that route in the root state — it was just popped — so it takes the replace branch:

https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/libs/Navigation/Navigation.ts#L603-L610

REPLACE on the root stack swaps the focused root route, and that route is RIGHT_MODAL_NAVIGATOR — which holds both the contact methods list and the details page — for TestToolsModalNavigator. The frames match that precisely: at ~2:39.4 the modal is fading out over the details page, and at ~2:39.5 it is fully back with Profile behind it, i.e. the Account tab's focused screen, all that is left once the entire RHP route is replaced. Closing the modal again runs Navigation.goBack(backTo) with backTo = the details path, which is why the user ends on the details page — and why Back from there goes to Profile later in the video: the list screen was destroyed along with the RHP stack, so there is nothing to pop to.

The forward direction of this same hazard is already handled in the codebase, bound to the screen "so a link built during render survives another screen being stacked over it":

https://github.com/Expensify/App/blob/840dc3d45fcacc98b7205d06afd0fd55cc5cab0e/src/hooks/useScreenBoundDynamicRoute.ts#L16-L26

useDynamicBackPath has no such binding, so the path it returns is only trustworthy while its own screen is the focused one. Online this never surfaces: the screen stays focused, listPath resolves normally and goBack pops to the list.

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

Bind useDynamicBackPath to its own screen the same way: keep the last back path resolved from a path that actually carried the caller's suffix, and return that while another screen covers us. The current path stays the fallback for a screen that never matched, so a screen reached by a non-dynamic URL keeps today's value.

const pathWithoutLeadingSlash = (path ?? '').replaceAll(/^\/+/g, '');
const match = findAllMatchingDynamicSuffixes(pathWithoutLeadingSlash).find((m) => m.pattern === dynamicRouteSuffix);
const matchedBackPath = match ? getPathWithoutDynamicSuffix(match.pathUsedForMatching, match.actualSuffix, match.pattern) : undefined;

// The active path stops carrying our suffix as soon as another screen is stacked over this one, and
// callers that navigate after that (deferred/on-focus) must not be handed the covering screen's route.
const lastMatchedBackPath = useRef<Route | undefined>(undefined);
useEffect(() => {
    if (!matchedBackPath) {
        return;
    }
    lastMatchedBackPath.current = matchedBackPath;
}, [matchedBackPath]);

if (!path) {
    return ROUTES.HOME;
}
return matchedBackPath ?? lastMatchedBackPath.current ?? (pathWithoutLeadingSlash as Route);

Storing from an effect rather than during render keeps this correct whichever order useIsFocused and useRootNavigationState settle in on the refocus render — a covering screen's path can never be stored. listPath then stays settings/profile/contact-methods, and the deferred goBack pops to the list, for every caller of the hook rather than this page alone.

Add a case to tests/navigation/useDynamicBackPathTests.ts asserting that after a state whose path carries the suffix, a later state whose path does not carry it still returns the matched back path instead of the new path.

What alternative solutions did you explore? (Optional)

Caching the resolved path inside DynamicContactMethodDetailsPage only. Rejected: every deferred or after-blur navigation built on useDynamicBackPath has the same hole, and a page-local copy has to guess which values are "ours", while the hook knows it from the suffix match.

Test branch: https://github.com/Expensify/App/compare/main...trasnake87:App:fix/104461

Regression test

tests/navigation/useDynamicBackPathTests.ts, run with npx jest tests/navigation/useDynamicBackPathTests.ts:

  • without the change: Tests: 1 failed, 22 passed, 23 total
  • with the change: Tests: 23 passed, 23 total

trasnake87 avatar Oct 26 '26 10:10 trasnake87