App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Navigating via link causes app to freeze

Open m-natarajan opened this issue 3 weeks ago • 58 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.32-2 Reproducible in staging?: Y Reproducible in production?: If this was caught during regression testing, add the test name, ID and link from BrowserStack: TC-3391 Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: Applause Internal team Slack conversation (hyperlinked to channel name): N/A

Action Performed:

  1. Navigate to Workspace > Workflows > Payments
  2. Begin the process of adding a bank account (via Login method)
  3. Exit in the middle of it via pasting the https://staging.new.expensify.com/workspaces/ link and navigating to it

Expected Result:

Navigation happens successfully

Actual Result:

Page gets stuck on loading

Workaround:

Unknown

Platforms:

Select the officially supported platforms where the issue was reproduced:

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

Screenshots/Videos

https://github.com/user-attachments/assets/cdd03a7b-3a88-4d55-9ee4-e976bc76cf8b

https://github.com/user-attachments/assets/dbc1ad4e-9d53-4e83-9cf9-90b0c331a1db

View all open jobs on GitHub

Upwork Automation - Do Not Edit

m-natarajan avatar Nov 05 '26 14:11 m-natarajan

🤖 Web test steps verification results: ⚠️ partial

Verified on dev NewDot web: Payments was accessible, but selecting the bank Login method required an emailed security code. Stopped at this blocker; indefinite loading was not reproduced.

Blocking state where testing stopped
Step Status
Navigate Workspace > Workflows > PaymentsSnapshot showed Payments and Add bank account.
Workspace Workflows Payments
✅
Begin adding a bank account via LoginSelected Add bank account, then Log into your bank. A Validate your account dialog required an emailed six-digit code. No bank credentials entered.
Security-code blocker after selecting bank Login
✅
Navigate via browser URL to /workspaces/ mid-flowNot executed: security-code verification blocked further progress. Browser address-bar navigation was also unavailable through the tester's permitted commands. This is an unexecuted check, not confirmation of the reported freeze.
Blocking state where testing stopped
❌

view run

MelvinBot avatar Nov 05 '26 14:11 MelvinBot

Issue Analysis

⚠️ Preliminary analysis (low confidence) — the root cause is not yet confirmed.

Reported behavior: On staging v9.5.32-2, starting workspace bank setup through Login and then entering /workspaces/ in the address bar leaves the app loading instead of displaying the workspace list.

Working hypothesis: Leaving bank setup may interrupt a request and strand loading state. However, the inspected code does not establish that Plaid loading causes the workspace-list spinner, so a Plaid-state reset is not yet a justified fix.

Code evidence and alternative explanation

These references are from the available checkout, not the affected v9.5.32-2 release; affected-release source could not be inspected in this run.

Verification limits: Web testing reached Payments and selected Login, but an emailed security-code prompt blocked bank setup. The address-bar navigation check was not executed, so the freeze was neither reproduced nor disproved. No production/staging log confirmation was obtained; the report lacks a reproduction timestamp and identifiers for a targeted trace.

Recommended next step: Reproduce on the affected release with an account already past security verification. Capture the exact time, browser console/network activity, active route, and loading state before and after navigating to /workspaces/. Determine which spinner remains mounted and whether OpenPlaidBankLogin, OpenApp, or ReconnectApp completes. Then fix the owning loading lifecycle and add a regression test for full-document navigation mid-bank-login; avoid blanket resets of bank drafts or OAuth continuation state.


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


view run · view recording

MelvinBot avatar Nov 05 '26 14:11 MelvinBot

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

melvin-bot[bot] avatar Nov 05 '26 14:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 05 '26 14:11 melvin-bot[bot]

Proposal

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

Al interrumpir la vinculación bancaria mediante Login y navegar a /workspaces/, se reporta una carga indefinida. Dictamen: evidencia insuficiente para aprobar una causa raíz o un parche.

What is the root cause of that problem?

No determinada. No se aportaron código, commit, stack trace ni trazas del bloqueo. No pude consultar el issue ni el compare; las consultas API también fallaron por conectividad. Esto no demuestra que la rama no exista.

Un indicador de carga persistente no acredita un bloqueo del hilo principal. Atribuirlo a navegación, estado persistido o cancelación bancaria sería especulación. Dar ahora una función y línea exactas sería inventarlas.

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

No aprobar un diff todavía. Primero reproducir en un commit identificado y registrar consola, solicitudes pendientes, estado de carga y destino de navegación. Precisar si pegar la URL provoca una recarga completa o navegación interna: cambia la investigación causal.

Compare branch: https://github.com/Expensify/App/compare/main...camesenin:App:fix-issue-106106?expand=1

Enlace solicitado; contenido no verificado. Exigir entre 3 y 10 líneas antes de localizar la causa incentiva un parche sin fundamento.

What alternative solutions did you explore? (Optional)

No hay propuesta de MelvinBot que refutar. Reiniciar estados globales, forzar recargas o esconder el loader carece de justificación sin demostrar qué condición impide terminar la carga. Duplicidad no evaluada. No existe evidencia aportada de exfiltración ni base para asignar CVSS.

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

Tras identificar la causa, añadir una regresión que falle antes del parche y pase después, verificando que /workspaces/ termine de cargar al interrumpir Login. No se identificó ni ejecutó un test existente; la navegación por barra requiere además reproducción en navegador.

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

camesenin avatar Nov 05 '26 15:11 camesenin

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

melvin-bot[bot] avatar Nov 05 '26 15:11 melvin-bot[bot]

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

Proposal

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

When a user navigates to Workspace > Workflows > Payments, starts adding a bank account via the Login method, and then exits mid-flow by entering/pasting the https://staging.new.expensify.com/workspaces/ URL in the browser address bar, the app gets stuck on an indefinite loading screen instead of rendering the Workspaces list page.

What is the root cause of that problem?

There are two interrelated architectural root causes that create this stranded loading state:

  1. Stale Sub-Page State Rehydration in WorkspaceRouter.ts: In Step 1, when the user visits Workspace > Workflows > Payments, NavigationRoot.tsx (lines 116–118) executes:
if (activeTabName === NAVIGATORS.WORKSPACE_NAVIGATOR) {
    saveWorkspacesTabPathToSessionStorage(currentPath);
}

This stores workspaces/:policyID/workflows/payments in sessionStorage under CONST.SESSION_STORAGE_KEYS.LAST_VISITED_PATH.WORKSPACES_TAB.

In Step 3, when the user inputs https://staging.new.expensify.com/workspaces/ (targeting SCREENS.WORKSPACES_LIST), WorkspaceRouter.ts (lines 40–54) runs getInitialState() during navigator initialization:

getInitialState(configOptions: RouterConfigOptions) {
    const preservedState = getPreservedNavigatorState(options.parentRoute.key);
    if (preservedState) {
        return preservedState;
    }
    const sessionState = buildWorkspaceInitialStateFromSessionStorage();
    if (sessionState) {
        return stackRouter.getRehydratedState(sessionState, configOptions);
    }
    return stackRouter.getInitialState(configOptions);
}

Because sessionStorage still holds the stale path from Step 1, buildWorkspaceInitialStateFromSessionStorage() parses this saved path and constructs a navigation state with WORKSPACE_SPLIT_NAVIGATOR at index: routes.length - 1. Consequently, WorkspaceRouter overrides the user's explicit navigation to the workspaces list and forces rehydration of the workspace sub-page. Inside withPolicyAndFullscreenLoading.tsx (lines 42–46):

if ((isLoadingPolicy || isLoadingReportData) && isEmpty(policy) && isEmpty(policyDraft)) {
    return <FullscreenLoadingIndicator shouldUseGoBackButton={shouldUseNarrowLayout} />;
}

Because the active browser URL (/workspaces/) carries no :policyID, policy and policyDraft are empty objects, and because isLoadingReportData defaults to true on cold start / reconnect, withPolicyAndFullscreenLoading permanently displays <FullscreenLoadingIndicator />.

  1. Stranded Optimistic Loading in Plaid.ts / AddPlaidBankAccount.tsx: In Step 2, selecting the bank Login method calls openPlaidBankLogin() in src/libs/actions/Plaid.ts (lines 29–40), which optimistically writes:
{
    onyxMethod: Onyx.METHOD.SET,
    key: ONYXKEYS.PLAID_DATA,
    value: {...CONST.PLAID.DEFAULT_DATA, isLoading: true},
}

When the user exits the flow prematurely via browser address-bar navigation without completing or cleanly dismissing Plaid Link, ONYXKEYS.PLAID_DATA is left persisted in storage with isLoading: true. In src/components/AddPlaidBankAccount.tsx (lines 236–240):

if (plaidData?.isLoading) {
    return (
        <View style={[styles.flex1, styles.alignItemsCenter, styles.justifyContentCenter]}>
            <ActivityIndicator size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE} />
        </View>
    );
}

There is no unmount cleanup hook in AddPlaidBankAccount.tsx to reset plaidData.isLoading, causing any subsequent render or background tab to trap the view in an unresolved spinner.

  1. Trailing Slash Path Normalization Gap in normalizePath.ts: In src/libs/Navigation/helpers/normalizePath.ts, repeated slashes are collapsed and a leading slash is enforced, but trailing slashes are not normalized (e.g. normalizePath('/workspaces/') returns '/workspaces/'). This causes deep-link matching in getMatchingNewRoute.ts and findAllMatchingDynamicSuffixes.ts to diverge from exact screen route paths registered without a trailing slash (ROUTES.WORKSPACES_LIST.route is 'workspaces').

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

  1. In src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts: When sessionState is evaluated, ensure buildWorkspaceInitialStateFromSessionStorage() does not override an explicit navigation to the root workspaces list or when the current route target is SCREENS.WORKSPACES_LIST:
--- a/src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts
+++ b/src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts
@@ -43,6 +43,10 @@ function WorkspaceRouter(options: WorkspaceNavigatorRouterOptions) {
             if (preservedState) {
                 return preservedState;
             }
+            // If explicitly navigating to the Workspaces list, do not rehydrate stale sub-page from session storage
+            if (options.parentRoute?.name === SCREENS.WORKSPACES_LIST) {
+                return stackRouter.getInitialState(configOptions);
+            }
             const sessionState = buildWorkspaceInitialStateFromSessionStorage();
             if (sessionState) {
                 return stackRouter.getRehydratedState(sessionState, configOptions);
  1. In src/components/AddPlaidBankAccount.tsx: Add a cleanup handler on component unmount so that exiting mid-flow resets the optimistic plaidData.isLoading state:
--- a/src/components/AddPlaidBankAccount.tsx
+++ b/src/components/AddPlaidBankAccount.tsx
@@ -141,7 +141,12 @@ function AddPlaidBankAccount({
         openPlaidBankLogin(allowDebit, bankAccountID);
-        return unsubscribeToNavigationShortcuts;
+        return () => {
+            unsubscribeToNavigationShortcuts();
+            if (plaidData?.isLoading) {
+                Onyx.merge(ONYXKEYS.PLAID_DATA, {isLoading: false});
+            }
+        };
 
         // disabling this rule, as we want this to run only on the first render
         // eslint-disable-next-line react-hooks/exhaustive-deps
     }, []);
  1. In src/libs/Navigation/helpers/normalizePath.ts: Normalize trailing slashes for non-root paths so that URL-pasted paths like /workspaces/ resolve cleanly to /workspaces:
--- a/src/libs/Navigation/helpers/normalizePath.ts
+++ b/src/libs/Navigation/helpers/normalizePath.ts
@@ -19,10 +19,12 @@ function normalizePath(path: string) {
     const collapsedPath = collapseRepeatedSlashes(pathOnly);
+    const withLeading = collapsedPath.startsWith('/') ? collapsedPath : `/${collapsedPath}`;
+    const strippedTrailing = withLeading.length > 1 && withLeading.endsWith('/') ? withLeading.slice(0, -1) : withLeading;
 
     if (pathOnly.includes('//')) {
         // The collapsed path is logged, not the raw one: repeated slashes break the `/v/:accountID/:validateCode`
         // pattern `sanitizeUrlForLogging` matches on, so redaction only works once they're gone.
         Log.alert('[Navigation] normalizePath received a malformed path', {path: sanitizeUrlForLogging(collapsedPath)});
     }
 
-    return `${collapsedPath.startsWith('/') ? collapsedPath : `/${collapsedPath}`}${suffix}`;
+    return `${strippedTrailing}${suffix}`;
 }

What alternative solutions did you explore? (Optional)

  • Completely wiping sessionStorage on every browser navigation: Rejected because preserving the last visited sub-page when switching between main tabs is intentional UX behaviour. Restricting the reset to explicit root-list navigation preserves tab memory while preventing stranded state hijacking.
  • Resetting ONYXKEYS.PLAID_DATA inside WorkspacesListPage.tsx: Rejected because WorkspacesListPage should not have domain knowledge of bank login internals. The cleanup belongs in AddPlaidBankAccount's lifecycle unmount hook.

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

  1. In tests/navigation/normalizePathTests.ts: Add unit tests verifying trailing slash normalization across static and query-bearing URLs:
it('strips trailing slashes from path while preserving leading slash', () => {
    expect(normalizePath('/workspaces/')).toBe('/workspaces');
    expect(normalizePath('workspaces/')).toBe('/workspaces');
    expect(normalizePath('/workspaces/?q=test')).toBe('/workspaces?q=test');
    expect(normalizePath('/')).toBe('/');
});
  1. In tests/unit/WorkspaceRouterTest.ts: Add a unit test verifying that WorkspaceRouter.getInitialState returns the initial stack state without rehydrating sessionStorage when the target is SCREENS.WORKSPACES_LIST:
it('does not rehydrate stale workspace sub-page from session storage when navigating to WORKSPACES_LIST', () => {
    sessionStorage.setItem(CONST.SESSION_STORAGE_KEYS.LAST_VISITED_PATH.WORKSPACES_TAB, 'workspaces/123/workflows');
    const router = WorkspaceRouter({parentRoute: {name: SCREENS.WORKSPACES_LIST, key: 'test'}});
    const state = router.getInitialState({routeNames: [SCREENS.WORKSPACES_LIST]});
    expect(state.routes.at(-1)?.name).toBe(SCREENS.WORKSPACES_LIST);
});
  1. In tests/ui/AddPlaidBankAccountTest.tsx: Add a test verifying that plaidData.isLoading is cleanly cleared to false when AddPlaidBankAccount unmounts before Plaid Link initialization completes:
it('clears plaidData.isLoading when unmounted mid-flow', () => {
    Onyx.set(ONYXKEYS.PLAID_DATA, {isLoading: true});
    const {unmount} = render(<AddPlaidBankAccount plaidData={{isLoading: true}} />);
    unmount();
    expect(Onyx.get(ONYXKEYS.PLAID_DATA)?.isLoading).toBe(false);
});

andregrunert-ctrl avatar Nov 05 '26 15:11 andregrunert-ctrl

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

melvin-bot[bot] avatar Nov 05 '26 15:11 melvin-bot[bot]

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

On staging v9.5.32-2, a user navigates to Workspace → Workflows → Payments and begins adding a bank account via the Login method. Mid-flow they paste https://staging.new.expensify.com/workspaces/ into the browser address bar and navigate to it. Instead of rendering the Workspaces list, the app gets stuck on an indefinite loading screen.

What is the root cause of that problem?

The freeze is a stranded loading state produced by the workspace navigator rehydrating a stale sub-page from sessionStorage and then gating on a loading flag that can never resolve for that route. Two code locations combine to cause it.

Primary cause — stale sessionStorage rehydration overrides the explicit list navigation (WorkspaceRouter.ts).

While the user is on Workspace → Workflows → Payments, NavigationRoot saves that deep path to sessionStorage:

  • src/libs/Navigation/NavigationRoot.tsx:116-117 — when the active tab is WORKSPACE_NAVIGATOR, saveWorkspacesTabPathToSessionStorage(currentPath) stores workspaces/:policyID/workflows/payments under CONST.SESSION_STORAGE_KEYS.LAST_VISITED_PATH.WORKSPACES_TAB.

When the user then pastes /workspaces/ in the address bar, the app does a cold full-page reload to that URL (not an in-app linkTo() dispatch). During that reload the WORKSPACE_NAVIGATOR mounts and its router initialises:

  • src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts:41-49 — getInitialState first checks getPreservedNavigatorState, then calls buildWorkspaceInitialStateFromSessionStorage().
  • buildWorkspaceInitialStateFromSessionStorage (WorkspaceRouter.ts:21-34) parses the saved workspaces/:policyID/workflows/payments path and returns a navigation state whose last (focused) route is WORKSPACES_SPLIT_NAVIGATOR / the payments sub-page, not WORKSPACES_LIST. getRehydratedState then installs that deep route as the navigator's initial state — silently overriding the user's explicit /workspaces/ target.

Because the focused route now points at a workspace sub-page that needs a :policyID, but the address-bar URL carries none, the screen renders through withPolicyAndFullscreenLoading:

  • src/pages/workspace/withPolicyAndFullscreenLoading.tsx:42 — const [isLoadingReportData = true] = useOnyx(ONYXKEYS.IS_LOADING_REPORT_DATA); (the = true default makes the flag true until OpenReport/OpenApp resolves it).
  • src/pages/workspace/withPolicyAndFullscreenLoading.tsx:46 — if ((isLoadingPolicy || isLoadingReportData) && isEmpty(policy) && isEmpty(policyDraft)) { return <FullscreenLoadingIndicator … />; }

With no :policyID, policy and policyDraft are empty, so the guard is true as long as isLoadingReportData/isLoadingPolicy is true. After a mid-flow reload the deferred Onyx updates for the deep page never land for a :policyID that isn't being requested, so isLoadingReportData never flips to false and the FullscreenLoadingIndicator is shown permanently. That is the "freeze."

Secondary contributor — stranded optimistic Plaid loading (Plaid.ts / AddPlaidBankAccount.tsx).

Selecting the Login bank method optimistically sets plaidData.isLoading = true:

  • src/libs/actions/Plaid.ts:29-34 — openPlaidBankLogin writes {key: ONYXKEYS.PLAID_DATA, value: {...CONST.PLAID.DEFAULT_DATA, isLoading: true}}. Its only reset is the failureData at Plaid.ts:55-63, which fires only if the API call fails.
  • src/components/AddPlaidBankAccount.tsx:236-242 — if (plaidData?.isLoading) { return <ActivityIndicator … />; }. There is no unmount cleanup that clears plaidData.isLoading (the useEffect at AddPlaidBankAccount.tsx:133-145 only unsubscribes keyboard shortcuts, return unsubscribeToNavigationShortcuts), so an abandoned mid-flow leaves ONYXKEYS.PLAID_DATA.isLoading persisted as true.

This is a contributor rather than the primary cause: if the navigator landed on WORKSPACES_LIST as intended, the bare list page (WorkspacesListPage.tsx:59-60, shouldShowLoadingIndicator = isAppLoadPending && !isOffline) gates on useIsAppLoadPending, which resolves with OpenApp and would not hang. But the stranded Plaid spinner would still show on a later return to the bank-login screen, so it should be cleaned up for correctness.

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

  1. Stop the stale sub-page from hijacking a bare /workspaces cold load. The rehydration in WorkspaceRouter.getInitialState should not restore a deep workspace sub-page when the app is actually booting to the list root. Since buildWorkspaceInitialStateFromSessionStorage is web-only (it already depends on sessionStorage, which is only present on web), it is safe and accurate to compare the saved path against the current document path:
// WorkspaceRouter.ts — inside buildWorkspaceInitialStateFromSessionStorage,
// after parsing sessionState, before returning it:
const currentPath = typeof window !== 'undefined' ? window.location.pathname.replace(/\/+$/, '') : '';
const isBootingToListRoot = currentPath === '/workspaces' || currentPath === '';
// If the app is cold-loading the bare workspaces list, don't let the saved
// sub-page rehydrate and strand us on a policy-gated loading screen.
if (isBootingToListRoot) {
   return undefined;
}

This preserves the existing tab-memory UX (switching tabs restores the last sub-page) while fixing the address-bar case that strands loading. It is the minimal, targeted change; the preservedState branch above it is unaffected.

  1. Clear stranded plaidData.isLoading when AddPlaidBankAccount unmounts mid-flow, so an abandoned bank login can't leave a persistent spinner. In AddPlaidBankAccount.tsx, extend the existing first-render useEffect cleanup (AddPlaidBankAccount.tsx:133-145) to reset the optimistic flag:
useEffect(() => {
    subscribeToNavigationShortcuts();
    if (isAuthenticated) {
        return () => {
            unsubscribeToNavigationShortcuts();
            if (plaidData?.isLoading) {
                Onyx.merge(ONYXKEYS.PLAID_DATA, {isLoading: false});
            }
        };
    }
    openPlaidBankLogin(allowDebit, bankAccountID);
    return () => {
        unsubscribeToNavigationShortcuts();
        if (plaidData?.isLoading) {
            Onyx.merge(ONYXKEYS.PLAID_DATA, {isLoading: false});
        }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

(Reading plaidData in the cleanup is intentional — it's the value captured at mount per the existing [] deps; for a more current read a plaidDataRef could mirror commentRef's pattern, but the captured value is what openPlaidBankLogin set.)

These two are independent: fix #1 removes the freeze itself; fix #2 removes the stranded-spinner leftover.

What specific scenarios should be covered by automated tests?

  1. Visit workspaces/:policyID/workflows/payments, then paste https://…/workspaces/ in the address bar → the Workspaces list renders (regression test; must fail before the fix).
  2. Visit a workspace sub-page, switch to Inbox, then switch back to the Workspaces tab → the last sub-page is restored (tab-memory UX unchanged).
  3. Begin bank Login, navigate away via address bar mid-flow, return to the bank-login screen later → no indefinite ActivityIndicator; plaidData.isLoading is false.
  4. Begin bank Login, the API call fails → plaidData.isLoading flips to false via failureData (existing behaviour, must not regress).
  5. Cold-load https://…/workspaces/ with nothing in sessionStorage → list renders (unchanged).
  6. Cold-load a deep workspace URL directly → sub-page renders correctly (rehydration still works when the boot path is deep).

What alternative solutions did you explore?

  • Normalise trailing slashes in normalizePath.ts. Investigated and rejected as the primary fix: normalizePath (src/libs/Navigation/helpers/normalizePath.ts:15-29) collapses repeated slashes but does not strip the single trailing slash, so /workspaces/ stays /workspaces/. However React Navigation's own getStateFromPath matches the WORKSPACES_LIST screen against the workspaces config (config.ts:2484-2487, ROUTES.WORKSPACES_LIST.route === 'workspaces'), and a trailing slash doesn't prevent that match — the focused route for /workspaces/ resolves to WORKSPACES_LIST correctly. The freeze happens after that, because WorkspaceRouter.getInitialState overwrites the correctly-resolved list route with the sessionStorage sub-page. Adding trailing-slash normalisation would be cosmetic and wouldn't fix the rehydration override.
  • Gate withPolicyAndFullscreenLoading on a timeout/redirect. Rejected: it treats the symptom (infinite spinner) and could mask real policy loads; the navigator landing on the right route makes the guard resolve naturally.
  • Reset plaidData from WorkspacesListPage. Rejected: WorkspacesListPage shouldn't own Plaid internals; the cleanup belongs in AddPlaidBankAccount's lifecycle.

PR

PR will be linked here once created.

vanshshah11 avatar Nov 07 '26 00:11 vanshshah11

Proposal

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

On Web, when the user is inside the Add Bank Account (Plaid) flow under Workspaces > [Workspace] > Workflows > Connect bank account while the Plaid loading spinner is displayed, and then navigates via the browser address bar to https://staging.new.expensify.com/workspaces/ (with a trailing slash), the app gets stuck on an infinite loading spinner instead of rendering the Workspaces list page.

What is the root cause of that problem?

There are two interacting causes:

  1. Unconditional sessionStorage deep-route restoration in WorkspaceRouter: In src/libs/Navigation/NavigationRoot.tsx:117-118, saveLastWorkspacePath saves the last visited WORKSPACES_CENTRAL_PANE route (e.g. workspaces/:policyID/workflows) and policyID into sessionStorage. When the user navigates via the address bar to /workspaces/, src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts:21-51 invokes buildWorkspaceInitialStateFromSessionStorage(). Whenever state.routes starts with only Workspaces_List (hasWorkspaceScreens === false), buildWorkspaceInitialStateFromSessionStorage() unconditionally injects the saved Workspace_Initial + Workspaces_Central_Pane routes from sessionStorage on top of Workspaces_List (lines 82-119), ignoring the fact that the browser URL was explicitly navigated to /workspaces / /workspaces/.
  2. Stale plaidData.isLoading state when unmounting AddPlaidBankAccount mid-load: In src/components/AddPlaidBankAccount.tsx:86-152, while openPlaidBankAccountSelector is in-flight (plaidData?.isLoading === true), navigating away unmounts the modal without resetting plaidData.isLoading, leaving the workspace workflows/bank account view in a loading state when rehydrated.

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

  1. Respect explicit /workspaces (and /workspaces/) URL navigation in src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts: In getRehydratedState / buildWorkspaceInitialStateFromSessionStorage, check if the current browser pathname is explicitly the root workspaces list (/workspaces or /workspaces/). When the user explicitly navigates to /workspaces(/)+ via link or address bar, do not push the cached sub-workspace route from sessionStorage on top of SCREENS.WORKSPACES_LIST (and clear the saved workspace path from sessionStorage so WorkspacesListPage renders cleanly).
  2. Normalize trailing slashes before matching in src/libs/Navigation/NavigationRoot.tsx / getStateFromPath: Ensure trailing slashes on /workspaces/ are normalized so React Navigation resolves SCREENS.WORKSPACES_LIST consistently without triggering fallback rehydration.

What alternative solutions did you explore? (Optional)

We also considered clearing LAST_WORKSPACE_PATH in sessionStorage inside NavigationRoot.tsx whenever window.location.pathname.replace(/\/+$/, '') === /${ROUTES.WORKSPACES_LIST.route}`` before calling getStateFromPath, which achieves the same result and guarantees buildWorkspaceInitialStateFromSessionStorage() returns undefined.

zaidrain06 avatar Nov 07 '26 01:11 zaidrain06

Proposal

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

After navigating to Workspaces > Workspace > Workflows > Payments > Connect bank account (which opens the bank account login flow) and then navigating via the browser URL bar to /workspaces/, the app freezes on an empty or unresponsive state instead of rendering the Workspaces list page.

What is the root cause of that problem?

When the user visits Workspace > Workflows > Payments, src/libs/Navigation/NavigationRoot.tsx (lines 116–118) saves the full sub-page path (workspaces/:policyID/workflows/payments) into sessionStorage under LAST_VISITED_PATH.WORKSPACES_TAB. When the user starts connecting a bank account and then navigates via the browser URL bar to /workspaces/ (SCREENS.WORKSPACES_LIST), WorkspaceRouter.getInitialState in src/libs/Navigation/AppNavigator/routers/WorkspaceRouter.ts (lines 40–54) inspects the incoming state and, whenever it sees only the single root WORKSPACES_LIST route (state.routes.length === 1 && state.routes.at(0)?.name === SCREENS.WORKSPACES_LIST), unconditionally rehydrates the last visited workspace sub-page from sessionStorage (getLastVisitedWorkspaceTabScreen()). This forces the router back into the WorkspaceWorkflows state while the URL and active modal/reimbursement state are out of sync, stranding the app in a frozen state.

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

  1. In src/libs/Navigation/AppNavigator/routers/WorkspaceRouter.ts inside getInitialState (around lines 40–54), check whether the current browser URL path (window.location.pathname on web or options.routeNames / explicit deep link path) explicitly matches the root /workspaces or /workspaces/ path without a :policyID segment, or when the navigation originates from an explicit URL bar navigation to ROUTES.WORKSPACES_LIST.route.
  2. When the current URL explicitly targets /workspaces (/workspaces/), skip restoring savedScreen from getLastVisitedWorkspaceTabScreen() and clear the stale LAST_VISITED_PATH.WORKSPACES_TAB entry so SCREENS.WORKSPACES_LIST renders cleanly.
  3. Add a unit test in tests/unit/NavigationTest.ts verifying that navigating directly to /workspaces/ via URL does not get hijacked by a stale LAST_VISITED_PATH.WORKSPACES_TAB sub-route.

What alternative solutions did you explore? (Optional)

We considered never saving WORKSPACES_TAB paths in sessionStorage when opening RHP flows, but the issue reproduces whenever a sub-route is saved in sessionStorage and the user explicitly navigates to /workspaces/ via the address bar, so checking the explicit URL path in WorkspaceRouter.getInitialState fixes all cases.

jeffrey-graham avatar Nov 07 '26 04:11 jeffrey-graham

📣 @jeffrey-graham! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 04:11 melvin-bot[bot]

Proposal

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

While the Plaid bank account connection step is loading in the Add Bank Account RHP modal, pasting the workspace list URL (/workspaces) into the browser address bar and navigating causes the app to get stuck on an infinite loading spinner and become unresponsive to clicks.

What is the root cause of that problem?

There are two interacting bugs when navigating via URL while AddPlaidBankAccount is loading:

  1. WorkspaceRouter.ts unconditionally re-injects stale workspace screens from sessionStorage over /workspaces: In src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts (lines 21–53):

    function buildWorkspaceInitialStateFromSessionStorage(state: StackNavigationState<WorkspaceNavigatorParamList>, options: RouterConfigOptions) {
        if (state.routes.at(-1)?.name !== SCREENS.WORKSPACES_LIST) {
            return state;
        }
        ...
        const lastMatchingWorkspaceRoute = getLastMatchingWorkspaceRoute(options);
        ...
    

    When the user navigates to /workspaces from a deep link or address-bar URL change while a workspace RHP modal (like Bank Account setup) was open, getStateFromPath produces a state ending in SCREENS.WORKSPACES_LIST. However, buildWorkspaceInitialStateFromSessionStorage checks only state.routes.at(-1)?.name === SCREENS.WORKSPACES_LIST and reads SESSION_STORAGE_KEYS.LAST_WORKSPACE_ID / cached navigation state, splicing the previous workspace sub-route back on top of WORKSPACES_LIST even when the navigation came from an explicit URL change to /workspaces. This leaves the navigation state and modal overlay out of sync.

  2. AddPlaidBankAccount.tsx leaves plaidData.isLoading stuck and full-screen blocker active on unmount: In src/components/AddPlaidBankAccount.tsx (lines 133–145 & 236–242): When openPlaidBankAccountSelector / openPlaidCompanyCardLogin sets ONYXKEYS.PLAID_DATA with isLoading: true, unmounting AddPlaidBankAccount via direct URL navigation cancels the in-flight Plaid widget lifecycle without clearing plaidData.isLoading or closing any active modal overlay.

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

  1. In src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts (lines 21–53): Only restore the cached workspace sub-route in buildWorkspaceInitialStateFromSessionStorage during initial narrow/wide layout hydration (when the current URL path actually targets a workspace sub-route or layout switches from narrow to wide), not when the browser URL itself is explicitly /${ROUTES.WORKSPACES_LIST.route} (/workspaces). Specifically, check getCurrentUrl() / options.path and return state unchanged if the path explicitly resolves to ROUTES.WORKSPACES_LIST.route.
  2. In src/components/AddPlaidBankAccount.tsx (lines 133–145): Add a cleanup effect on unmount that resets isLoading: false on ONYXKEYS.PLAID_DATA if it was left loading when the component unmounts, ensuring no stale loading spinner persists if the user navigates away mid-load.

What alternative solutions did you explore? (Optional)

Blocking URL navigation while Plaid is loading is not possible when the user edits the browser address bar directly, so ensuring WorkspaceRouter respects explicit /workspaces URLs and AddPlaidBankAccount cleans up its loading state on unmount handles both in-app link navigation and address-bar URL changes cleanly.

tungnguyen84 avatar Nov 07 '26 06:11 tungnguyen84

Proposal

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

Navigating to /workspaces via the browser URL bar or link while the Plaid bank account setup modal is loading causes the app to freeze with an infinite spinner.

What is the root cause of that problem?

  1. In WorkspaceRouter.ts, buildWorkspaceInitialStateFromSessionStorage checks if the target route is SCREENS.WORKSPACES_LIST and unconditionally injects cached workspace route history from sessionStorage (LAST_WORKSPACE_ID).
  2. When navigating while an asynchronous modal (like Plaid / Bank Account setup) is in-flight, the navigator enters a conflicting navigation state transition where the old modal stack is still mounting while the root navigator attempts to restore the cached workspace sub-route, resulting in a locked router state and unresponsive UI.

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

  1. In WorkspaceRouter.ts:
    • Do not re-inject stale workspace sub-screens from sessionStorage if the navigation action was explicitly triggered by a top-level deep link or address bar change to /workspaces.
  2. In AddPlaidBankAccount.tsx / BankConnection:
    • Ensure proper cleanup and unmounting of Plaid event handlers and Onyx connection listeners on component unmount to prevent lingering state transitions.
  3. In NavigationRoot:
    • Clear any pending intermediate modal loading locks when an explicit top-level route replacement occurs.

What alternative solutions did you explore? (Optional)

Using a timeout fallback to force reset navigation state, but addressing the conflicting router state restoration in WorkspaceRouter.ts resolves the root cause cleanly.

TassioSales avatar Nov 08 '26 00:11 TassioSales

Not able to reproduce

dmkt9 avatar Nov 10 '26 08:11 dmkt9

@dmkt9 Note that reproduction requires two specific conditions on Web Desktop:

  1. Direct address bar navigation / URL paste: Navigating by entering https://staging.new.expensify.com/workspaces/ (with trailing slash) into the browser URL bar so that the browser triggers a top-level page load and re-initializes WorkspaceRouter.getInitialState() (in-app clicks or internal transitions bypass this).
  2. Session storage state from Step 1: sessionStorage must retain the previous workspace subpage (CONST.SESSION_STORAGE_KEYS.LAST_VISITED_PATH.WORKSPACES_TAB set to workspaces/:policyID/workflows/payments from Step 1). When re-entering /workspaces/, WorkspaceRouter attempts to rehydrate that sub-page without a :policyID, causing withPolicyAndFullscreenLoading to strand the app in an infinite <FullscreenLoadingIndicator />.

andregrunert-ctrl avatar Nov 10 '26 08:11 andregrunert-ctrl

Not able to reproduce

@dmkt9 I was able to reproduce this. The app stays on the loading splash after navigating to /workspaces/. Could you add the Help Wanted label? I have an RCA and a fix ready to propose once the issue is open for proposals and also with reliable repro steps as well.

https://github.com/user-attachments/assets/3649d8ff-15e2-42b8-8ed6-1e59fca86d82

neerajbachani avatar Nov 10 '26 14:11 neerajbachani

@andregrunert-ctrl @neerajbachani Thanks! Can you reproduce this issue consistently? Are there any specific steps you follow to reproduce it?

dmkt9 avatar Nov 11 '26 04:11 dmkt9

@dmkt9 Yes, it can be reproduced 100% consistently on Web Desktop (Chrome/Safari) with the following exact steps:

Preconditions:

Logged in to staging.new.expensify.com on a desktop browser.

Steps to Reproduce (100% Consistent):

  1. Open any existing workspace and navigate into a settings subpage (e.g. Workspaces -> Select any Workspace -> Workflows -> Payments or click Add bank account). (This populates sessionStorage with LAST_VISITED_PATH.WORKSPACES_TAB pointing to that workspace sub-page).
  2. In the same browser tab, click the browser address bar, type/paste: https://staging.new.expensify.com/workspaces/ (with trailing slash) and press Enter (to trigger a document-level browser navigation).

Expected Result:

The browser loads the Workspaces list page (/workspaces/).

Actual Result:

The app freezes permanently on the splash/loading screen (<FullscreenLoadingIndicator />).


Why this happens (Root Cause):

  1. The Trailing Slash & Full Page Load: Directly entering https://staging.new.expensify.com/workspaces/ into the browser URL bar triggers a document-level page reload and re-initializes WorkspaceRouter.getInitialState().
  2. SessionStorage Override in WorkspaceRouter.ts: In src/libs/Navigation/AppNavigator/createWorkspaceNavigator/WorkspaceRouter.ts:
    function WorkspaceRouter(options: WorkspaceNavigatorRouterOptions) {
        ...
        getInitialState(configOptions: RouterConfigOptions) {
            ...
            const sessionState = buildWorkspaceInitialStateFromSessionStorage();
            if (sessionState) {
                return stackRouter.getRehydratedState(sessionState, configOptions);
            }
            return stackRouter.getInitialState(configOptions);
        }
    }
    
    buildWorkspaceInitialStateFromSessionStorage() unconditionally rehydrates the stale workspace sub-page from sessionStorage (from Step 1) into the navigator state, completely overriding the top-level URL route (/workspaces/).
  3. Because the URL path was /workspaces/ (no :policyID), this state mismatch causes withPolicyAndFullscreenLoading to wait indefinitely for a non-existent policy, stranding the app in an infinite spinner.

(Note: If tested in an incognito window without first visiting a workspace sub-page in Step 1, sessionStorage is empty, which is why it might not reproduce in a clean session).

andregrunert-ctrl avatar Nov 11 '26 05:11 andregrunert-ctrl

This does not work for me

dmkt9 avatar Nov 11 '26 05:11 dmkt9