Skip to content

[Due for payment 2026-09-09] Email - User is logged in and not redirected to User created room as the new user #99156

Closed

Description

@jponikarchuk

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


Version Number: 9.4.58-0
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/folder/54013438/test-cases/41237090
Email or phone of affected tester (no customers): N/A
Issue reported by: Applause Internal Team
Bug source: Regression TC Execution
Device used: Samsung Galaxy S23 Plus - Android 16
App Component: Other

Action Performed:

**** Setup - Can be executed in a Secondary device or browser

  1. Go to staging.new.expensify.com
  2. Register as a new user to the app
  3. Select “Manage my team’s expenses” and click Continue
  4. Add a name for your business
  5. Fill out a first & last name
  6. Create a #room in the workspace
  7. Click on the header of the room and navigate to Members
  8. Click on the Invite button at the top
  9. Invite an email address that does not have an expensify account (Should be a real account with an inbox that can receive the invite)

*****Steps - Main testing device (android)

  1. Go to Mailbox >> Click the link in “Reply to this message or respond at new.expensify.com”

Expected Result:

User should be logged in and redirected to to the User Created Room as the new user

Actual Result:

User is directed to app without logged in

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

Bug7238899_1787284088186.Screen_Recording_20260821_103647_Gmail.mp4
Issue OwnerCurrent Issue Owner: @mallenexpensify

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Aug 21, 2026
  2. MelvinBot commented on Aug 21, 2026

    @MelvinBot
    Contributor

    Issue Analysis

    ⚠️ Medium confidence — the App-side behavior is confirmed in code, but the reason authentication fails almost certainly lives in a backend repo I can't access, and I couldn't reproduce the email-click flow (it needs a real inbox + the actual invite link). Treat the root cause as needing internal confirmation.

    Symptom: A brand-new (unregistered) user invited to a #room taps the "respond at new.expensify.com" link on the Android app → the app opens but they are not logged in and are not taken to the room.

    Root cause (needs internal confirmation): The invite email's magic sign-in link is failing to authenticate the brand-new/shell account. Whether the link auto-logs the user in is decided server-side (the sign-in command that the link triggers, and/or how the email link is generated for a never-registered recipient). That logic lives outside the Expensify/App repo, so this needs a separate internal investigation — the actual fix is likely backend, not App.

    Confirmed App-side gap (in scope for App): Regardless of why auth fails, the Android app handles the failure silently. On native, when the validate-login sign-in comes back FAILED, ValidateLoginPage just calls Navigation.goBack() with no error UI — which is exactly "dropped into the app, not logged in, no message." The web version instead renders an ExpiredValidateCodeModal on the same failure, so web surfaces an error where native shows nothing. Surfacing that failure on native would at least turn a silent dead-end into an actionable "your link expired / try again" state.

    Investigation details & evidence

    Two link shapes are possible; both dead-end for a brand-new user, and both point backend:

    1. Magic/validate link (/v/<accountID>/<validateCode>, likely with exitTo=/r/<roomID>): handled by ValidateLoginPage → signInWithValidateCodeAndNavigate → the sign-in network command in Session/index.ts. Success/failure is entirely determined server-side. On failure, session.autoAuthState → FAILED, and on native the page silently goBack()s (lines 42–50 above). Room navigation is gated behind handleExitToNavigation → waitForUserSignIn, which never resolves without an auth token — so the user is neither logged in nor routed to the room.

    2. Plain report deeplink (/r/<reportID> with no auth payload): handled as an unauthenticated deeplink in Link.ts, which only yields a usable (anonymous) session for public rooms. A private #room invite gets no session and falls through to the sign-in page.

    The expected behavior in the report ("user should be logged in and redirected to the room") implies the email link is meant to be an authenticating magic link — so shape (1) is the more likely path, with the backend sign-in rejecting the code for the never-registered account.

    What would confirm it (backend logs): for the invited accountID from the repro, query the sign-in-with-link command response (staging + prod, v9.4.58-0) for the jsonCode/error explaining why the code is rejected for a brand-new account (expired / already-consumed / account-not-yet-validated / accountID↔validateCode mismatch), and confirm the exact URL the invite email embeds for an unregistered recipient.

    Alternatives considered: a stale non-anonymous auth token on the device would make line 27 skip sign-in entirely — possible on HybridApp but doesn't fit a brand-new user with no prior account. This doesn't change the conclusion that the authenticating step is backend-owned.

    Possibly related: #94549 (closed) — "Web - Email - Member redirects to Home page instead of Workspace chat" and #54174 (closed) — "blank white screen when a new user clicks a workspace invite email link" cover the same email-invite → auth/redirect area and may be worth cross-referencing.


    Next Steps for Contributor+ team:

    • Root cause: escalate to an internal engineer to confirm why the invite magic-link sign-in fails for a brand-new account (backend — outside Expensify/App).
    • App-side follow-up: consider surfacing the FAILED sign-in on native ValidateLoginPage (parity with web's ExpiredValidateCodeModal) so this stops being a silent dead-end.
    • To refine: @MelvinBot <your feedback>

    view run

  3. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Aug 21, 2026
  4. melvin-bot commented on Aug 21, 2026

    @melvin-bot

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

  5. melvin-bot commented on Aug 21, 2026

    @melvin-bot

    Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.

  6. Usama123talib commented on Aug 21, 2026

    @Usama123talib

    Proposal

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

    When a brand-new (unregistered) user receives an invitation email to a user-created workspace #room and taps the link ("Reply to this message or respond at new.expensify.com"), the native app opens but fails to log the user in and silently drops them onto the unauthenticated sign-in screen without navigating to the room and without displaying any error message.


    What is the root cause of that problem?

    There are two contributing factors to this behavior:

    1. Authentication Failure on Validate Link (SignInUserWithLink):
      The invitation email link embeds a magic validate link (/v/:accountID/:validateCode?exitTo=%2Fr%2F<reportID>). When opened, ValidateLoginPage dispatches signInWithValidateCodeAndNavigate(), which calls SignInUserWithLink via Session.ts:1019. When the validate code is rejected or fails to authenticate the shell account, the backend returns a failure response which sets session.autoAuthState to FAILED via failureData.

    2. Native Client-Side Silent Failure Gap:
      In ValidateLoginPage/index.tsx:42-50 (native Android/iOS), when session.autoAuthState === CONST.AUTO_AUTH_STATE.FAILED, a useEffect silently executes Navigation.goBack():

      useEffect(() => {
          if (session?.autoAuthState !== CONST.AUTO_AUTH_STATE.FAILED) {
              return;
          }
          // Go back to initial route if validation fails
          Navigation.isNavigationReady().then(() => {
              Navigation.goBack();
          });
      }, [session?.autoAuthState]);

      Furthermore, native ValidateLoginPage only returns <FullScreenLoadingIndicator />. Unlike the web implementation (ValidateLoginPage/index.web.tsx:168), which renders <ExpiredValidateCodeModal /> on FAILED, native displays no error UI and immediately pops back to the public SignInPage.

      Because authToken is never obtained, handleExitToNavigation never resolves waitForUserSignIn(), leaving the user unauthenticated with no explanation.


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

    1. Client-Side (App Repository):
      • Update src/pages/ValidateLoginPage/index.tsx to bring parity with index.web.tsx:
        • Remove the silent Navigation.goBack() trigger on session.autoAuthState === CONST.AUTO_AUTH_STATE.FAILED.
        • Render <ExpiredValidateCodeModal /> when session?.autoAuthState === CONST.AUTO_AUTH_STATE.FAILED so the user is given clear, actionable feedback ("This link has expired / Request a new link") with an option to start sign-in rather than a silent dead-end.
    2. Internal/Backend Investigation:
      • Escalate to internal engineers to verify backend logs for SignInUserWithLink on why magic sign-in links generated for brand-new/unregistered accounts invited to workspace #rooms are failing to authenticate.

    What alternative solutions did you explore? (Optional)

    Leaving native to silently call Navigation.goBack() and relying solely on backend fixes was considered, but having native match Web's behavior by rendering ExpiredValidateCodeModal provides a robust, fail-safe user experience whenever a link is expired, invalid, or rejected.


    Contributor Details

    cc: @mkhutornyi

  7. mkhutornyi commented on Aug 22, 2026

    @mkhutornyi
    Contributor

    🆘 C+ Help Wanted

  8. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on Aug 22, 2026
  9. oqildev commented on Aug 22, 2026

    @oqildev
    Contributor

    Proposal

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

    The title reads "User is logged in and not redirected," but the Actual Result and the video say the opposite, so let me settle the direction first: a brand-new (never-registered) person is invited to a user-created #room, taps the "respond at new.expensify.com" link in the invite email on the Android app, and the app opens unauthenticated — no room, and no error telling them what happened. Expected is that they end up signed in and land in the room.

    What is the root cause of that problem?

    There are two layers stacked here, and it's worth keeping them apart because only one is fixable in this repo.

    Layer 1 — the sign-in itself fails, and that's backend. The invite link is a security link (/v/<accountID>/<validateCode>?exitTo=/r/<roomID>). Native ValidateLoginPage dispatches signInWithValidateCodeAndNavigate, which calls SIGN_IN_USER_WITH_LINK. For a never-registered/shell account that command comes back failed, so failureData sets session.autoAuthState = FAILED. Whether that code is accepted for a brand-new account is decided server-side — no App change makes a rejected code succeed, so "logged in" needs an internal/backend investigation.

    Layer 2 — the App turns that failure into a silent dead-end, and this part is ours (and native-only). The native page is a stale fork that never got the exitTo/security-link hardening web received for the sibling issue #94549 (commit 3614e46a586, applied to index.web.tsx only). Two consequences:

    So the pixels the reporter sees — spinner, then dropped back into an unauthenticated app with no room and no message — are rendered by native src/pages/ValidateLoginPage/index.tsx. The Android-only report is consistent with this being the native file (web has the guards; iOS simply wasn't in the tester's matrix).

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

    Fix layer: the native page's render + mount effect, plus a small change in the exitTo action, and an escalation for the backend acceptance.

    1. Bring native index.tsx to functional parity with web for the FAILED/exitTo cases:

      • Stop the silent goBack() on FAILED. Render a recoverable failure state instead of an endless spinner.
      • Keep the loader while SIGNING_IN, and keep the exitTo destination registered so that if/when auth is possible the invitee actually lands in the room.
      // native ValidateLoginPage, sketch
      const autoAuthState = session?.autoAuthState ?? CONST.AUTO_AUTH_STATE.NOT_STARTED;
      // remove the useEffect that does goBack() on FAILED
      return autoAuthState === CONST.AUTO_AUTH_STATE.FAILED
          ? <ExpiredValidateCodeModal />
          : <FullScreenLoadingIndicator />;
    2. Abandon the pending exitTo handoff on FAILED. handleExitToNavigation parks a single authPromiseResolver slot; leaving it armed after a failure means a later, unrelated successful sign-in would fire a stale navigate(exitTo) to this room. Clearing it on FAILED makes the not-signed-in state representable rather than an indefinitely-pending promise — the failure is deterministic, not a "hope auth lands first" race.

    3. Escalate the actual code rejection for never-registered invitees to an internal engineer — that's the piece that decides "logged in," and it lives outside this repo.

    This is race-free by construction: the failure renders from autoAuthState in the render path, no timer re-seeds a flag, and there's no ordering under which the user is left staring at a spinner or silently popped back.

    Verification: I authored a native test (importing index.tsx, which today nothing does) asserting that on autoAuthState === FAILED the page renders the recovery UI and does not call Navigation.goBack() — it fails on main (main renders only the loader and calls goBack) and passes with the patch. I could not execute Jest in my working copy (this checkout has no node_modules), so I'm not going to quote a pass count I didn't produce; the command to run in a provisioned checkout is npx jest tests/ui/ValidateLoginPageTest.tsx. Worth flagging: the 12 existing tests in that file all import index.web, which is exactly why this native regression slipped through.

    What alternative solutions did you explore? (Optional)

    Simply rendering the web expired-code modal on native surfaces a message but still dead-ends an email invitee, because that modal's only recovery action is gated on a cached credentials.login the invitee never had (ExpiredValidateCodeModal.tsx:42-58) — which is why I pair the surfaced state with preserving exitTo through a real sign-in.

    A structurally different alternative I rejected: fixing this in the deferred deep-link path in Link.ts. That path only governs navigation after waitForUserSignIn() resolves, so it can't help a case whose whole symptom is that sign-in failed and the token never arrives — it would never run.

    Deferred / out of scope: the backend acceptance of a shell/never-validated account's security code. That's the true "logged in" fix and needs backend logs (the jsonCode returned by SIGN_IN_USER_WITH_LINK for the invited accountID on 9.4.58-0), not an App change.

  10. David-2002065 commented on Aug 22, 2026

    @David-2002065
    Contributor

    Proposal

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

    A brand-new (never-registered) user is invited to a workspace #room and taps the sign-in link in the invite email on the Android app. The app opens but the user is not logged in and is not taken to the room, with no message explaining why. Expected: the link signs them in and redirects them to the room.

    What is the root cause of that problem?

    There are two layers here, and it's worth separating them because only one is fixable in this repo.

    1. Why the user isn't logged in (server-side). The invite email link is a magic/validate link (/v/<accountID>/<validateCode>?exitTo=/r/<roomID>). ValidateLoginPage calls signInWithValidateCodeAndNavigate, which fires the SIGN_IN_USER_WITH_LINK command:

    signInWithValidateCodeAndNavigate(Number(accountID), validateCode, preferredLocale, exitTo);

    function signInWithValidateCode(accountID: number, code: string, preferredLocale: Locale | undefined, twoFactorAuthCode = '', storedValidateCode?: string) {
    // If this is called from the 2fa step, use the validateCode stored in Onyx (passed in as `storedValidateCode`)
    // instead of the one passed from the component state because the state is changing when this method is called.
    const validateCode = twoFactorAuthCode ? storedValidateCode : code;
    const onyxOperationToCleanUpAnonymousUser = buildOnyxDataToCleanUpAnonymousUser();
    const optimisticData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT | typeof ONYXKEYS.SESSION>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    ...CONST.DEFAULT_ACCOUNT_DATA,
    isLoading: true,
    loadingForm: twoFactorAuthCode ? CONST.FORMS.VALIDATE_TFA_CODE_FORM : CONST.FORMS.VALIDATE_CODE_FORM,
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.SESSION,
    value: {autoAuthState: CONST.AUTO_AUTH_STATE.SIGNING_IN},
    },
    ];
    const successData: Array<OnyxUpdate<typeof ONYXKEYS.PERSONAL_DETAILS_LIST | typeof ONYXKEYS.ACCOUNT | typeof ONYXKEYS.CREDENTIALS | typeof ONYXKEYS.SESSION>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    isLoading: false,
    loadingForm: null,
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.CREDENTIALS,
    value: {
    accountID,
    validateCode,
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.SESSION,
    value: {autoAuthState: CONST.AUTO_AUTH_STATE.JUST_SIGNED_IN},
    },
    onyxOperationToCleanUpAnonymousUser,
    ];
    const failureData: Array<OnyxUpdate<typeof ONYXKEYS.ACCOUNT | typeof ONYXKEYS.SESSION>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.ACCOUNT,
    value: {
    isLoading: false,
    loadingForm: null,
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: ONYXKEYS.SESSION,
    value: {autoAuthState: CONST.AUTO_AUTH_STATE.FAILED},
    },
    ];
    Device.getDeviceInfoWithID().then((deviceInfo) => {
    const params: SignInUserWithLinkParams = {
    accountID,
    validateCode,
    twoFactorAuthCode,
    preferredLocale: preferredLocale ?? null,
    deviceInfo,
    };
    API.write(WRITE_COMMANDS.SIGN_IN_USER_WITH_LINK, params, {optimisticData, successData, failureData});
    });
    }

    Whether that command authenticates a never-registered/shell account is decided entirely server-side. When it comes back with a failure, session.autoAuthState becomes FAILED and no authToken is issued — so the user has no session. Confirming why the sign-in is rejected for a brand-new invited account needs backend logs and is outside Expensify/App.

    2. Why it's a silent dead-end on Android specifically (App-side, and the part we can fix). On the failure above, the native ValidateLoginPage handles autoAuthState === FAILED by just calling Navigation.goBack() with no UI at all:

    useEffect(() => {
    if (session?.autoAuthState !== CONST.AUTO_AUTH_STATE.FAILED) {
    return;
    }
    // Go back to initial route if validation fails
    Navigation.isNavigationReady().then(() => {
    Navigation.goBack();
    });
    }, [session?.autoAuthState]);

    The web version renders an ExpiredValidateCodeModal on the exact same FAILED state, so web surfaces an actionable error while native shows nothing:

    {autoAuthStateWithDefault === CONST.AUTO_AUTH_STATE.FAILED && !is2FARequired && <ExpiredValidateCodeModal />}

    That gap is exactly the reported behavior on Android: dropped into the app, no session, no message.

    Note: I checked the theory that native drops the ?exitTo= query param (which would explain a missing redirect). It does not — running the app's React Navigation getStateFromPath (v7.16.1) on v/123/abc?exitTo=/r/456 returns exitTo: "/r/456" as a route param, so exitTo is preserved on native. The missing redirect is a consequence of the failed sign-in (no authToken → handleExitToNavigation's waitForUserSignIn() never resolves), not of param parsing.

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

    The App-side fix is to bring native to parity with web: instead of silently goBack()-ing on FAILED, render the failure state so the user gets feedback rather than a dead-end.

    In src/pages/ValidateLoginPage/index.tsx, drop the silent goBack() effect on FAILED and render ExpiredValidateCodeModal for that state (the loader otherwise):

    import ExpiredValidateCodeModal from '@components/ValidateCode/ExpiredValidateCodeModal';
    
    // ...remove the useEffect that goBack()s on autoAuthState === FAILED
    
    return session?.autoAuthState === CONST.AUTO_AUTH_STATE.FAILED ? <ExpiredValidateCodeModal /> : <FullScreenLoadingIndicator />;

    ExpiredValidateCodeModal is built from cross-platform primitives (View/Text/Icon/TextLink), so it renders on native as-is. For a brand-new invited user there's no cached credentials.login, so it shows the plain "your magic code has expired" copy (no "request one here" link), which is the correct message for an expired/invalid link.

    This turns the Android silent dead-end into the same actionable error web already shows. The underlying "the link should have logged me in" behavior still needs the server-side investigation in root-cause layer 1 above, which should be escalated to an internal engineer in parallel.

    What alternative solutions did you explore? (Optional)

    • Only escalate to backend and change nothing in App. The core auth failure is indeed backend-owned, but leaving native as a silent goBack() keeps a real App-side UX bug (no feedback on a failed link) that is worth fixing regardless of the backend outcome, and gives affected users a next step.
    • Factor the native/web failure rendering into shared logic. The two ValidateLoginPage files have diverged significantly (web carries 2FA / direct-sign-in handling native doesn't). A minimal, native-only render change is lower-risk than a shared refactor; the refactor can be a separate cleanup.
  11. abbasifaizan70 commented on Aug 22, 2026

    @abbasifaizan70
    Contributor

    Proposal

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

    A brand-new external user is invited by email to a room they have no Expensify account for. They open the "Reply to this message or respond at new.expensify.com" magic link from their email inbox on Android. Instead of being automatically signed in and dropped into the room they were invited to, the app opens in a signed-out state — the magic sign-in never happens and the invite destination is lost.

    What is the root cause of that problem?

    The magic link is a ROUTES.VALIDATE_LOGIN URL (/v/:accountID/:validateCode?exitTo=...). That route is registered as a "public screen" route:

    App/src/ROUTES.ts

    Lines 56 to 65 in 650d353

    const PUBLIC_SCREENS_ROUTES = {
    // If the user opens this route, we'll redirect them to the path saved in the last visited path or to the home page if the last visited path is empty.
    ROOT: '',
    TRANSITION_BETWEEN_APPS: 'transition',
    CONNECTION_COMPLETE: 'connection-complete',
    BANK_CONNECTION_COMPLETE: 'bank-connection-complete',
    VALIDATE_LOGIN: 'v/:accountID/:validateCode',
    UNLINK_LOGIN: 'u/:accountID/:validateCode',
    SAML_SIGN_IN: 'sign-in-with-saml',
    } as const;

    isPublicScreenRoute() matches any of those patterns against the parsed route:
    https://github.com/Expensify/App/blob/650d35388a55fce99038f1fa8c89493252d64370/src/libs/isPublicScreenRoute.ts

    The only code that can actually make ValidateLoginPage mount (and run the effect that calls signInWithValidateCodeAndNavigate) is React Navigation's own cold-start deep-link resolution, because openReportFromDeepLink() explicitly refuses to navigate to public-screen routes itself when the user isn't authenticated yet — it assumes React Navigation's linking layer already showed that screen:

    // If we are not authenticated and are navigating to a public screen, we don't want to navigate again to the screen after sign-in/sign-up
    if (!isAuthenticated && isPublicScreenRoute(route)) {
    return;
    }

    ValidateLoginPage only runs its sign-in effect once it is actually mounted with accountID/validateCode/exitTo route params:

    function ValidateLoginPage({
    route: {
    params: {accountID, validateCode, exitTo},
    },
    }: ValidateLoginPageProps) {
    const [session] = useOnyx(ONYXKEYS.SESSION);
    const [preferredLocale] = useOnyx(ONYXKEYS.NVP_PREFERRED_LOCALE);
    useEffect(() => {
    // Wait till navigation becomes available
    Navigation.isNavigationReady().then(() => {
    if (session?.authToken && session?.authTokenType !== CONST.AUTH_TOKEN_TYPES.ANONYMOUS) {
    // If already signed in, do not show the validate code if not on web,
    // because we don't want to block the user with the interstitial page.
    if (exitTo) {
    handleExitToNavigation(exitTo);
    return;
    }
    Navigation.goBack();
    } else {
    signInWithValidateCodeAndNavigate(Number(accountID), validateCode, preferredLocale, exitTo);
    }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    For React Navigation to mount that screen on a cold start, it has to resolve the initial deep-link URL itself. But the app's linkingConfig never supplies a getInitialURL, so React Navigation falls back to its own internal (unguarded, no generous timeout) call to Linking.getInitialURL():

    const linkingConfig: LinkingOptions<RootNavigatorParamList> = {
    getStateFromPath: getAdaptedStateFromPath,
    getPathFromState,
    prefixes,
    config,
    subscribe,
    };

    Meanwhile, the app already has one reliable path to that same URL: DeepLinkHandler races Linking.getInitialURL() against a generous, purpose-built 10s timeout and carefully guards against re-entrancy/stale closures before consuming the result:

    useEffect(() => {
    if (isLoadingOnyxValue(allReportsMetadata, sessionMetadata, conciergeReportIDMetadata, introSelectedMetadata, guidedSetupAndTourStatusMetadata, betasMetadata)) {
    return;
    }
    // Guard against stale closures: when deps change and the effect re-runs, the previous
    // getInitialURL() promise may still be in-flight. Without this guard, its .then() would
    // fire with stale conciergeReportID/introSelected values, causing a duplicate
    // openReportFromDeepLink() call.
    let cancelled = false;
    let timeoutId: ReturnType<typeof setTimeout>;
    // If the app is opened from a deep link, get the reportID (if exists) from the deep link and navigate to the chat report.
    // We race against a timeout to prevent permanently blocking NavigationRoot if getInitialURL() never resolves
    // (e.g. in HybridApp when OldDot fails to send the URL via native bridge).
    Promise.race([
    Linking.getInitialURL(),
    new Promise<null>((resolve) => {
    timeoutId = setTimeout(() => resolve(null), CONST.TIMING.GET_INITIAL_URL_TIMEOUT);
    }),
    ])
    .then((url) => {
    if (cancelled) {
    return;
    }
    // Use hasAuthToken() for the latest auth state at call time, since the isAuthenticated
    // closure value may be stale on cold start (useOnyx reports 'loaded' before storage completes).
    const isCurrentlyAuthenticated = hasAuthToken();
    // Skip post-sign-out re-runs. On web, react-native-web caches Linking.getInitialURL()
    // at JS bundle load, so after sign-out the cached URL still points at the previous
    // session's path. Letting openReportFromDeepLink() see that stale URL would queue a
    // waitForUserSignIn() callback that fires on the next sign-in and navigates the new
    // account to a route it lacks access to.
    if (!isCurrentlyAuthenticated && initialUrlProcessed.current) {
    return;
    }
    initialUrlProcessed.current = true;
    onInitialUrl(url as Route);

    GET_INITIAL_URL_TIMEOUT: 10000,

    For a /v/... link, getReportIDFromLink() returns falsy (it only matches /r/:reportID), so openReportFromDeepLink() immediately calls doneCheckingPublicRoom() and, per the early return above, does nothing further with the URL — it never hands the already-resolved value to React Navigation:

    } else {
    // If we're not opening a public room (no reportID) or the user is authenticated, we unblock the UI (hide splash screen)
    doneCheckingPublicRoom();
    }
    let route = getRouteFromLink(url);
    // Bing search results still link to /signin when searching for “Expensify”, but the /signin route no longer exists in our repo, so we redirect it to the home page to avoid showing a Not Found page.
    if (normalizePath(route) === CONST.SIGNIN_ROUTE) {
    route = '';
    }
    // React Navigation generates /Home (capitalized) for the root URL because PublicScreens uses SCREENS.HOME ('Home')
    // at the root level without a path mapping. Treat it as empty route to avoid showing a “not found” page after sign-in.
    if (normalizePath(route) === `/${SCREENS.HOME}`) {
    route = '';
    }
    // If we are not authenticated and are navigating to a public screen, we don't want to navigate again to the screen after sign-in/sign-up
    if (!isAuthenticated && isPublicScreenRoute(route)) {
    return;
    }

    So the same native "initial URL" is queried twice, independently: once (reliably) by DeepLinkHandler, and once (again, separately) inside React Navigation's own linking machinery — with no sharing of the value that was already fetched. On Android, this second query goes through the app's own Linking.getInitialURL() override, which on the native "App" build (HybridApp) is backed by the OldDot bridge that the codebase itself documents as unreliable:

    if (CONFIG.IS_HYBRID_APP) {
    // On HybridApp we need to shadow official implementation of Linking.getInitialURL on NewDot side with our custom implementation.
    // Main benefit from this approach is that our deeplink-related code can be implemented the same way for both standalone NewDot and HybridApp.
    // It's not possible to use the official implementation from the Linking module because the way OldDot handles deeplinks is significantly different from a standard React Native app.
    Linking.getInitialURL = () => HybridAppModule.getInitialURL();

    App/src/Expensify.tsx

    Lines 304 to 307 in 650d353

    {/* Wait for the initial URL to resolve before mounting NavigationRoot, because its initialState
    is computed once on mount. In HybridApp, getInitialURL() may never resolve (OldDot native
    bridge), so we skip this guard to avoid blocking the app. */}
    {hasAttemptedToOpenPublicRoom && (CONFIG.IS_HYBRID_APP || initialUrl !== undefined) && (

    That comment ("In HybridApp, getInitialURL() may never resolve (OldDot native bridge)") is exactly why the app built its own patient, guarded acquisition path in DeepLinkHandler. But that protection only benefits report links handled inside openReportFromDeepLink; for public-screen routes like the magic sign-in link, React Navigation's unrelated, unprotected second query is the only thing deciding whether ValidateLoginPage ever mounts. When that second query is slow or comes back empty, the magic link is silently dropped and the app boots to its default signed-out screen — matching "user is directed to app without logged in," and losing the exitTo destination (the invited room) entirely.

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

    Instead of letting React Navigation re-query the native bridge a second time for the same value, feed it the URL that DeepLinkHandler already resolved reliably. NavigationRoot already receives that value as its initialUrl prop:

    function NavigationRoot({authenticated, lastVisitedPath, initialUrl, onReady}: NavigationRootProps) {
    useStartSpansOnRender([
    {
    spanId: CONST.TELEMETRY.SPAN_NAVIGATION_ROOT_READY,
    options: {
    name: CONST.TELEMETRY.SPAN_NAVIGATION_ROOT_READY,
    op: CONST.TELEMETRY.SPAN_NAVIGATION_ROOT_READY,
    parentSpan: getSpan(CONST.TELEMETRY.SPAN_BOOTSPLASH.ROOT),
    },
    },
    ]);
    const firstRenderRef = useRef(true);
    const themePreference = useThemePreference();
    const theme = useTheme();
    const {cleanStaleScrollOffsets} = useContext(ScrollOffsetContext);
    const {updateCurrentReportID} = useCurrentReportIDActions();
    const {shouldUseNarrowLayout} = useResponsiveLayout();
    const [account] = useOnyx(ONYXKEYS.ACCOUNT);
    const [isOnboardingCompleted = true] = useOnyx(ONYXKEYS.NVP_ONBOARDING, {
    selector: hasCompletedGuidedSetupFlowSelector,
    });
    const previousAuthenticated = usePrevious(authenticated);
    const initialState = useMemo(() => {

    and currently passes the static linkingConfig straight through to NavigationContainer:

    return (
    <NavigationContainer
    initialState={initialState}
    onStateChange={handleStateChange}
    onReady={onReadyWithSentry}
    theme={navigationTheme}
    ref={navigationRef}
    linking={linkingConfig}

    Override getInitialURL on the linking object passed to NavigationContainer so it resolves to the already-known initialUrl instead of triggering React Navigation's own independent native call:

    const linking = useMemo(() => ({...linkingConfig, getInitialURL: () => Promise.resolve(initialUrl ?? undefined)}), [initialUrl]);

    and pass linking={linking} instead of linking={linkingConfig} on NavigationContainer (line 318).

    This is minimal and reuses what already exists: linkingConfig's prefixes/getStateFromPath/config/subscribe are untouched, and no new deep-link-fetching code is introduced — we simply stop asking the (documented-as-unreliable-on-HybridApp) native bridge a second time for information the app already has.

    Edge cases:

    • No deep link (normal cold start): initialUrl is null, so getInitialURL resolves to undefined/null, which is exactly what React Navigation's own default would produce for "no deep link" — no behavior change.
    • Report links (/r/...): unaffected. openReportFromDeepLink() still owns navigation for these via waitForUserSignIn()/Navigation.navigate(), and this change only makes React Navigation's own initial-state resolution consistent with the URL that was already fetched, rather than introducing a second, divergent read.
    • Web / mWeb: CONFIG.IS_HYBRID_APP is false there, so Linking.getInitialURL() is the fast, standard implementation and already resolves before DeepLinkHandler finishes; reusing that resolved value removes a redundant call with no functional change.
    • Offline / slow network: unaffected — this only changes how the already-captured URL string is delivered to React Navigation, not how or when it's fetched.
    • RTL and other platforms: unaffected — this is a navigation/linking wiring change with no UI impact.
    • Existing callers of linkingConfig: it remains untouched at its export; the override is applied only at the single call site in NavigationRoot.tsx, so no other consumer is affected.
  12. melvin-bot commented on Aug 22, 2026

    @melvin-bot

    Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.

  13. ahmdshrif commented on Aug 22, 2026

    @ahmdshrif
    Contributor

    Proposal

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

    A brand-new user invited to a workspace #room taps the magic link in the invite email on Android and is dropped into the app signed out on the sign-in page, instead of being signed in and taken to the room.

    What is the root cause of that problem?

    The invite link is a validate-login deep link (/v/<accountID>/<validateCode>?exitTo=r/<reportID>), which Android routes to the public ValidateLoginPage. Native and web have separate implementations, and the native one is missing the autoAuthState initialization web does:

    useEffect(() => {
    // Wait till navigation becomes available
    Navigation.isNavigationReady().then(() => {
    if (session?.authToken && session?.authTokenType !== CONST.AUTH_TOKEN_TYPES.ANONYMOUS) {
    // If already signed in, do not show the validate code if not on web,
    // because we don't want to block the user with the interstitial page.
    if (exitTo) {
    handleExitToNavigation(exitTo);
    return;
    }
    Navigation.goBack();
    } else {
    signInWithValidateCodeAndNavigate(Number(accountID), validateCode, preferredLocale, exitTo);
    }
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    useEffect(() => {
    if (session?.autoAuthState !== CONST.AUTO_AUTH_STATE.FAILED) {
    return;
    }
    // Go back to initial route if validation fails
    Navigation.isNavigationReady().then(() => {
    Navigation.goBack();
    });
    }, [session?.autoAuthState]);

    On mount it starts signInWithValidateCodeAndNavigate(), and a second effect — which also runs on that same first render — calls Navigation.goBack() the moment it sees session.autoAuthState === FAILED. autoAuthState is persisted in the SESSION Onyx key, so a FAILED left over from an earlier link attempt is still present at mount: the guard fires against the stale value before the freshly-issued SignInUserWithLink has returned. The page unmounts, goBack() lands on the sign-in screen, and the pending exitTo navigation registered by handleExitToNavigation() is discarded — the observed symptom. Web avoids this by explicitly neutralising the persisted value and ignoring it on the first render, for exactly this reason:

    // When not signed in, ignore stored autoAuthState on the first render to prevent stale values
    // (e.g. FAILED from a previous security link attempt) from briefly rendering incorrect UI.
    // Once initAutoAuthState() runs in the useEffect, the state is set to true and real values are used.
    const [hasInitialized, setHasInitialized] = useState(isSignedIn);
    const [autoAuthState] = useOnyx(ONYXKEYS.SESSION, {selector: autoAuthStateSelector});
    const effectiveAutoAuthState = hasInitialized ? autoAuthState : undefined;

    I can point at the stale-FAILED read in code; I have not confirmed from the video whether the backend call also failed. Either way the native page can't distinguish "this link failed" from "a previous link failed", and surfaces no error in either case.

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

    In src/pages/ValidateLoginPage/index.tsx, mirror web: call initAutoAuthState() on mount so the persisted value is reset before sign-in starts, and only honour FAILED once this mount has initialized it.

    const [hasInitialized, setHasInitialized] = useState(false);
    // mount effect, before signing in:
    initAutoAuthState(session?.autoAuthState ?? CONST.AUTO_AUTH_STATE.NOT_STARTED);
    setHasInitialized(true);
    // failure effect:
    if (!hasInitialized || session?.autoAuthState !== CONST.AUTO_AUTH_STATE.FAILED) { return; }

    Regression risk stays inside the native validate-login path: a genuinely expired link still resolves to FAILED after the API responds and still falls back to goBack() — the only change is that an earlier attempt's result can no longer abort the current one.

  14. 35 remaining items

  15. mallenexpensify commented on Sep 10, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor: @samarroy84 paid $250 via Upwork
    Contributor+: @mkhutornyi due $250 via NewDot

  16. melvin-bot commented on Sep 18, 2026

    @melvin-bot

    @mallenexpensify Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

  17. mallenexpensify commented on Sep 19, 2026

    @mallenexpensify
    Contributor

    @samarroy84 can you please accept the job below? Please reply here and tag me once you have.
    https://www.upwork.com/jobs/~022101102785517701418

    The job that I previously linked above is 👻

  18. samarroy84 commented on Sep 19, 2026

    @samarroy84
    Contributor

    @mallenexpensify I already accepted offer. Can you please check again?

    Offer id: 112502607

    Image
  19. mallenexpensify commented on Sep 21, 2026

    @mallenexpensify
    Contributor

    Found it and paid @samarroy84 , closing other. Sorry for hassle

  20. trjExpensify commented on Oct 1, 2026

    @trjExpensify
    Contributor

    approved $250 for @mkhutornyi

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

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions