Skip to content

[$250] Navigating via link causes app to freeze #106106

Open

Description

@m-natarajan

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
  • Windows: Chrome
  • MacOS: Chrome / Safari

Screenshots/Videos

Recording.3788.mp4
695906972-e16bb237-de02-433b-8f73-a57ce9563bb7.mov

View all open jobs on GitHub

Upwork Automation - Do Not Edit

Activity

  1. added
    Daily
    Bug
    on Nov 5, 2026
  2. MelvinBot commented on Nov 5, 2026

    @MelvinBot
    Contributor

    🤖 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

  3. MelvinBot commented on Nov 5, 2026

    @MelvinBot
    Contributor

    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

  4. added
    External
    on Nov 5, 2026
  5. melvin-bot commented on Nov 5, 2026

    @melvin-bot

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

  6. changed the title [-]Navigating via link causes app to freeze[/-] [+][$175] Navigating via link causes app to freeze[/+] on Nov 5, 2026
  7. melvin-bot commented on Nov 5, 2026

    @melvin-bot
  8. camesenin commented on Nov 5, 2026

    @camesenin
  9. melvin-bot commented on Nov 5, 2026

    @melvin-bot

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

  10. andregrunert-ctrl commented on Nov 5, 2026

    @andregrunert-ctrl

    Contributor details
    Your Expensify account email: andregrunert@gmail.com
    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);
    });
  11. melvin-bot commented on Nov 5, 2026

    @melvin-bot

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

  12. vanshshah11 commented on Nov 7, 2026

    @vanshshah11

    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.

  13. 52 remaining items

  14. dmkt9 commented on Nov 26, 2026

    @dmkt9
    Contributor

    It looks like this issue may have already been fixed in PR #106881.

    @m-natarajan Could you please re-test this issue? I think it's currently no longer reproducible

  15. tonightsthenight commented on Nov 26, 2026

    @tonightsthenight

    @dmkt9 A short update on my proposal above. After posting it, I re-checked current main: the ActiveClientManager rejection handling has been rewritten since the snapshot my proposal was written against (commits da6ee9e and 42f3a76, now on main). The current handler clears isStealingLeaderLock on rejection and retries immediately only after a held lock is lost with an AbortError; other rejections back off on a timer or wait for foreground initialization. That covers both changes my proposal made, so the diff no longer applies, and I don't want to leave a proposal standing for work that has already landed.

    For the record, my root-cause analysis was verified against the pre-rewrite code (the Nov 20 main snapshot), and I believe it still describes that version accurately. If the freeze still reproduces on the current staging build, I'm glad to dig into whatever path remains — otherwise, please treat my proposal as withdrawn in favor of the landed fix. Thank you for reviewing.

  16. mvtglobally commented on Nov 28, 2026

    @mvtglobally

    Issue not reproducible during KI retests. (First week)

  17. gesh1518 commented on Nov 28, 2026

    @gesh1518

    Proposal

    What is the root cause of that problem?

    When a browser document leaves the app, its tab may still be involved in Web Lock leader election. In the code present when this issue was reported, a rejected lock request immediately started another request, regardless of why it failed. If the browser repeatedly rejects requests from an inactive document, that creates an unbounded chain of promise callbacks and can prevent the new page from rendering. The original request and retry behavior came from [#104990](#104990).

    Verified: The historical code has that immediate retry. [#106881](#106881) has since added backoff for ordinary failures, and the latest issue retest could not reproduce the freeze. Current code still holds an acquired lock until the browser releases or another document steals it; it does not explicitly release it when pagehide fires.

    Inference: A document entering the back/forward cache while holding the lock is a plausible path through the reported navigation failure. I do not have a trace from the original affected session that proves this was its exact sequence.

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

    Handle the web document’s lifetime in ActiveClientManager. On pagehide, release any held leader lock, abort a waiting request, cancel scheduled retries, and invalidate callbacks from older requests. While the page is suspended, it must not request leadership again. On a visible back/forward-cache restore, use the manager’s existing pageshow initialization path to request the lock again. Schedule a retry after a stolen lock as a browser task so repeated rejections cannot run continuously in promise callbacks. Keep the shared write queue gated on actual lock ownership.

    This follows three relevant patterns already in the app:

    The change is limited to the web manager and its focused tests. The native manager has no Web Lock behavior. Changing the bank-account flow or navigation would leave the lock lifecycle unchanged.

    Verification: With the local implementation, all 30 ActiveClientManager unit tests passed, including new cases for releasing a held lock, handing it to a waiting request, ignoring a stale grant, cancelling a suspended retry, and restoring a hidden page. lint-changed, typecheck, spell-changed, and git diff --check passed using the repository’s Node 26 version. A signed-out local browser navigation and Back/Forward smoke check rendered successfully. I could not run the authenticated bank-account flow against the local offline backend, so this does not establish that the currently reported issue still reproduces or that the change fixes that exact flow.

  18. melvin-bot commented on Nov 28, 2026

    @melvin-bot

    📣 @gesh1518! 📣
    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>
    
  19. dostonbunyodov0006 commented on Nov 28, 2026

    @dostonbunyodov0006
    Contributor

    Proposal

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

    On web, leaving the bank account flow by pasting a /workspaces/ URL into the address bar reloads the page, and the new page stays on the loading screen.

    What is the root cause of that problem?

    A full page load starts the network queue only after ActiveClientManager is ready:

    function startMainQueue() {
    // Start after client initialization. SequentialQueue checks leadership before sending persisted requests.
    ActiveClientManager.isReady().then(() => {
    flushSequentialQueue();
    // A tab that becomes the leader later must send what was queued while another tab led
    ActiveClientManager.onBecomeLeader(() => flushSequentialQueue());
    // Start main queue and process once every n ms delay
    processQueueInterval = setInterval(processMainQueue, CONST.NETWORK.PROCESS_REQUEST_DELAY_MS);
    });
    }

    isReady() is a promise that is resolved only from inside the Web Lock callbacks, when the leader lock is granted or the request rejects:

    /**
    * Waits for client initialization, including a refused first lock request. The main queue can run without
    * leadership; the shared write queue checks the lock separately before sending persisted requests.
    */
    const isReady: IsReady = () => savedSelfPromise;

    navigator.locks
    .request(LEADER_LOCK_NAME, options, () => {
    if (requestID !== leaderLockRequestID) {
    return;
    }
    isHoldingLeaderLock = true;
    isStealingLeaderLock = false;
    leaderLockRetryDelay = INITIAL_LEADER_LOCK_RETRY_DELAY_MS;
    resolveSavedSelfPromise();
    // Saving our ID last tells older build tabs that we lead, and re-renders the UI that depends on the leader in every tab (see SignInPage)
    setActiveClients([clientID]);
    notifyIfBecameLeader();
    // Hold the lock until this tab goes away or another tab steals it
    return new Promise<void>(() => {});
    })
    .catch((error: unknown) => {
    if (requestID !== leaderLockRequestID) {
    return;
    }
    const wasHoldingLeaderLock = isHoldingLeaderLock;
    isHoldingLeaderLock = false;
    isStealingLeaderLock = false;
    notifyIfBecameLeader();
    // A refused first request must not prevent startMainQueue from registering its leadership listener
    // and starting ordinary API requests. This does not grant permission to send the shared write queue.
    resolveSavedSelfPromise();

    So until the browser answers the lock request, processMainQueue never starts and no request, OpenApp included, is sent. The page keeps the loading indicator. On the build this was reported on, a rejected request retried right away with no yield, so the page never got past this point. PR #106881 (merged 2026-11-23) added the backoff and resolves isReady() on rejection, and KI can't reproduce it anymore, so I agree the reported loop is gone. I'm not claiming a different cause for the original report.

    What is left is the same single point of failure: app startup still waits on a browser lock answer with no upper bound. The comment on isReady already says the main queue can run without leadership, and the shared write queue checks the lock on its own. So the wait is not needed for correctness, it only decides when the first requests go out. If a browser holds the request (a document switching during a same tab navigation, a lock manager that is slow to answer), we get this issue again in a new shape.

    The other proposals here change the bank flow, navigation, or release the lock on pagehide. This is about the startup gate itself.

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

    Resolve isReady() after a short timeout if the browser hasn't answered the lock request yet. Leadership still comes only from the lock, so the write queue behaviour does not change.

     const LEADER_LOCK_NAME = 'activeClientLeader';
     const INITIAL_LEADER_LOCK_RETRY_DELAY_MS = 1000;
     const MAX_LEADER_LOCK_RETRY_DELAY_MS = 30 * 1000;
    +// Startup must not depend on the browser answering the lock request. The main queue can run without leadership.
    +const READY_WITHOUT_LEADER_LOCK_TIMEOUT_MS = 3000;
    @@
     const init: Init = () => {
         if (canUseWebLocks()) {
    +        // resolveSavedSelfPromise is a no-op once the promise is settled, so a later grant or rejection is harmless
    +        setTimeout(resolveSavedSelfPromise, READY_WITHOUT_LEADER_LOCK_TIMEOUT_MS);
             if (isHoldingLeaderLock) {

    That's the whole change. When the lock is granted later, requestLeaderLock still sets isHoldingLeaderLock, calls notifyIfBecameLeader(), and the onBecomeLeader listener that startMainQueue registered flushes the persisted queue, which is already the path for a tab that becomes leader later.

    Other callers and why they are not broken:

    • Network.startMainQueue is the only caller of isReady(). With a normal browser the lock answers in milliseconds, so the timeout never matters and the order is the same as today.
    • SequentialQueue, PersistedRequests, OnyxUpdateManager, RequestsQueuesState, Report actions and the Search hooks use isClientTheLeader(), which still reads isHoldingLeaderLock. Before the lock is granted it returns false, exactly as it does today after a rejection (which already resolves isReady()), so persisted writes are not sent from a non-leader tab.
    • AuthScreensInitHandler calls init() again on transitions. Every call schedules one more timer that only resolves an already settled promise, so nothing repeats.
    • The native ActiveClientManager has no Web Locks and is not touched. Browsers without navigator.locks use the ACTIVE_CLIENTS branch, which resolves from setActiveClients as before and is not touched.

    Tests, in the existing tests/unit/ActiveClientManagerTest.ts (it already mocks navigator.locks):

    • a navigator.locks.request mock that never settles: isReady() resolves after READY_WITHOUT_LEADER_LOCK_TIMEOUT_MS with fake timers, and isClientTheLeader() is false (fails on main, where it never resolves)
    • the same mock granting the lock after the timeout: isClientTheLeader() turns true and the onBecomeLeader callback runs once
    • a lock granted right away: isReady() resolves before the timeout, same as now
    • the existing rejection, backoff and pageshow cases stay as they are

    In tests/unit/NetworkTest.tsx: with the never-settling lock, processMainQueue starts after the timeout and a queued read request is sent, while a persisted write stays queued until leadership.

    I haven't run this on a device yet, and I have not reproduced the freeze on the current staging. This is hardening on top of #106881 so the same symptom can't come back from this gate.

    What alternative solutions did you explore? (Optional)

    • Not waiting for isReady() at all in startMainQueue. Simpler, but the first flush would run before the tab knows if it leads, and the existing comment shows the wait was added on purpose for the normal case.
    • Releasing the lock on pagehide. Already proposed in this thread, and it fixes the old document, not the new one that waits.
    • Clearing Plaid state or the saved workspaces path. MelvinBot already showed neither is on the startup path.
  20. dmkt9 commented on Dec 1, 2026

    @dmkt9
    Contributor

    QA can no longer reproduce this issue: #106106 (comment)

  21. melvin-bot commented on Dec 2, 2026

    @melvin-bot

    📣 It's been a week! Do we have any satisfactory proposals yet? Do we need to adjust the bounty for this issue? 💸

  22. ngocsontran208-cyber commented on Dec 3, 2026

    @ngocsontran208-cyber

    Proposal

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

    On desktop web (Chrome and Safari), starting the workspace bank account login flow under Workspace > Workflows > Payments and navigating mid-flow to /workspaces/ via the browser address bar leaves the app stuck on a loading screen instead of rendering the Workspaces list.

    What is the root cause of that problem?

    Pasting /workspaces/ into the address bar triggers a full-document navigation in the same tab. When #106106 was reported on v9.5.32-2, the departing document entered the back/forward cache (bfcache) while still holding the activeClientLeader Web Lock, and stealing that lock from the incoming document triggered an unbounded microtask retry loop in ActiveClientManager that starved migrateOnyx() (src/Expensify.tsx#L220-L243).

    While PR #106881 stopped synchronous microtask retries after non-AbortError rejections, two cross-document Web Lock lifecycle gaps still remain on main in src/libs/ActiveClientManager/index.ts:

    1. Departing documents keep holding activeClientLeader across pagehide and still retry during suspension:
      The lock callback holds leadership via an unresolved new Promise<void>(() => {}) (src/libs/ActiveClientManager/index.ts#L156-L157), and init() registers pageshow for bfcache restoration without a matching pagehide release (src/libs/ActiveClientManager/index.ts#L220-L230). When the tab navigates away (to /workspaces/ or an external bank OAuth redirect), the cached document retains activeClientLeader (blocking any open tab queued with requestLeaderLock(false)), and when broken by {steal: true}, its .catch() hits wasHoldingLeaderLock && error.name === 'AbortError' (src/libs/ActiveClientManager/index.ts#L171-L174) to issue an immediate requestLeaderLock(false) from the departing page — and on Safari, where document.visibilityState can remain 'visible' during suspension (src/libs/ActiveClientManager/index.ts#L178-L188, #L222-L223), even arms retry timers.

    2. A stalled {steal: true} lock request on the incoming page permanently wedges isStealingLeaderLock, isReady(), and SequentialQueue:
      In requestLeaderLock(true) (src/libs/ActiveClientManager/index.ts#L137-L140), isStealingLeaderLock is set to true and {steal: true} cannot carry an AbortSignal per the Web Locks spec. If the browser's LockManager stalls a {steal: true} request during same-tab document teardown/bfcache transition, savedSelfPromise (isReady(), src/libs/ActiveClientManager/index.ts#L29-L40) never settles to start Network.startMainQueue() (src/libs/Network/index.ts#L15-L26), and isStealingLeaderLock stays true forever so every subsequent init() exits at else if (!isStealingLeaderLock) (src/libs/ActiveClientManager/index.ts#L215-L218). Because OpenApp and ReconnectApp are persisted write commands (src/libs/actions/App.ts#L458-L462, #L518-L522) gated on isClientTheLeader() in SequentialQueue.flush() (src/libs/Network/SequentialQueue.ts#L678-L688), useIsAppLoadPending() (src/hooks/useInFlightRequests.ts#L49, #L193-L197) never clears the loading indicator on src/pages/workspace/WorkspacesListPage.tsx#L59-L60.

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

    In src/libs/ActiveClientManager/index.ts:

    1. Release the held Web Lock and silence retries on pagehide, while preserving open background tab handoff:

      • Replace return new Promise<void>(() => {}) inside the lock grant callback with a stored releaseHeldLeaderLock resolver (and release immediately if requestID !== leaderLockRequestID || isPageHidden).
      • Register a pagehide listener alongside pageshow that sets isPageHidden = true, increments leaderLockRequestID, clears retry/watchdog timers, aborts waitForLeaderLockController, clears isHoldingLeaderLock and isStealingLeaderLock, invokes releaseHeldLeaderLock?.(), and calls notifyIfBecameLeader(). Reset isPageHidden = false on pageshow and when init() runs in a visible document.
      • Return early in .catch() after resolveSavedSelfPromise() whenever isPageHidden is true, so departing/cached pages never re-request the lock (even on Safari when visibilityState stays 'visible'), whereas live background tabs (isPageHidden === false) still queue requestLeaderLock(false) on steal.
    2. Bound {steal: true} lock requests with a single tracked stealLeaderLockTimeout watchdog:
      When shouldSteal is true, arm a tracked timeout (cleared on any new request, grant, rejection, or pagehide) so a hung {steal: true} request cannot wedge startup or leadership forever:

    if (shouldSteal) {
        stealLeaderLockTimeout = setTimeout(() => {
            if (requestID !== leaderLockRequestID || !isStealingLeaderLock || isHoldingLeaderLock) {
                return;
            }
            isStealingLeaderLock = false;
            resolveSavedSelfPromise();
            if (!isPageHidden && document.visibilityState === 'visible') {
                requestLeaderLock(false);
            }
        }, STEAL_LEADER_LOCK_TIMEOUT_MS);
    }

    Bumping leaderLockRequestID on fallback ensures any late grant from the stalled request exits immediately without dual leadership, while clearing isStealingLeaderLock lets both the abortable requestLeaderLock(false) fallback and future init() calls recover leadership so SequentialQueue flushes OpenApp/ReconnectApp.

    1. Add unit tests in tests/unit/ActiveClientManagerTest.ts (including cleaning up pagehide listeners in afterEach) covering: (a) pagehide releasing a held lock to a waiting tab without retrying even if visibilityState is 'visible', followed by pageshow reacquiring leadership; and (b) a never-settling {steal: true} request resolving isReady(), clearing isStealingLeaderLock, and recovering leadership to flush SequentialQueue.

    What alternative solutions did you explore? (Optional)

    • Resolving isReady() on a timer inside init() alone: Unblocks MainQueue read requests, but leaves isStealingLeaderLock = true forever and isClientTheLeader() === false, so SequentialQueue still never processes OpenApp or ReconnectApp (WorkspacesListPage stays on its loading indicator) and repeated init() calls leak duplicate timers.
    • Modifying WorkspaceRouter.ts, normalizePath.ts, or AddPlaidBankAccount.tsx unmount cleanup: /workspaces/ is already parsed as a specific deep link to SCREENS.WORKSPACES_LIST in NavigationRoot.tsx, AddPlaidBankAccount is not mounted on /workspaces/, and React unmount cleanups do not run on full-document address-bar navigations.
  23. expensify-chore-bot commented on Dec 3, 2026

    @expensify-chore-bot

    @dmkt9 this issue is now 4 weeks old, please consider:

    • Finding a contributor to fix the bug
    • Closing the issue if BZ has been unable to add the issue to a VIP or Wave project
    • If you have any questions, don't hesitate to start a discussion in #expensify-open-source

    Thanks!

  24. ldc861117 commented on Dec 3, 2026

    @ldc861117

    Proposal

    What is the root cause of that problem?

    Starting bank account setup via the Login (Plaid) flow enqueues persisted bank-setup requests while mounting external Plaid Link resources, and then pasting /workspaces/ in the address bar triggers a same-tab full-document navigation where the departing document enters the back/forward cache (bfcache) instead of unloading cleanly.

    Even after PR #106881 removed synchronous microtask retry loops in src/libs/ActiveClientManager/index.ts, init() registers a pageshow listener (lines 224–229) for bfcache restoration without a symmetric pagehide release for the activeClientLeader Web Lock:

    1. Inside requestLeaderLock, the lock callback holds activeClientLeader indefinitely via return new Promise<void>(() => {}) (line 157). When the departing bank-setup page enters bfcache on same-tab URL navigation, that unresolved promise keeps holding activeClientLeader (or, when broken via {steal: true}, triggers .catch() at lines 171–188 where wasHoldingLeaderLock && error.name === 'AbortError' immediately queues requestLeaderLock(false) and Safari's still-'visible' suspended state schedules retry timers).
    2. On the incoming /workspaces/ document, OpenApp / ReconnectApp are persisted write commands in SequentialQueue gated on isClientTheLeader(). When cross-document {steal: true} handoff collides with the departing bfcache document's held lock or immediate re-request during teardown, leadership / isReady() (savedSelfPromise) fails to settle cleanly on the incoming page, SequentialQueue never flushes ReconnectApp, and src/pages/workspace/WorkspacesListPage.tsx (lines 59–60: shouldShowLoadingIndicator = isAppLoadPending && !isOffline) stays stuck on the loading indicator.

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

    Add symmetric pagehide Web Lock release and suspension gating in src/libs/ActiveClientManager/index.ts so departing documents relinquish activeClientLeader cleanly before entering bfcache, without introducing arbitrary {steal: true} timeouts:

    1. Store a lock-release resolver in requestLeaderLock (src/libs/ActiveClientManager/index.ts, around line 157):
      • Replace the anonymous new Promise<void>(() => {}) inside navigator.locks.request with a promise whose resolve callback is saved in a module-scoped releaseHeldLeaderLock reference (clearing it on lock exit, and resolving immediately if the page already entered pagehide while the lock grant was in flight).
    2. Release activeClientLeader synchronously on pagehide (src/libs/ActiveClientManager/index.ts, around lines 219–229):
      • Track a module-scoped isPageSuspended flag set to true in a window.addEventListener('pagehide', ...) listener and reset to false in pageshow.
      • On pagehide, clear leaderLockRetryTimeout, set isHoldingLeaderLock = false and isStealingLeaderLock = false, call notifyIfBecameLeader(), and invoke releaseHeldLeaderLock?.() so the browser's LockManager releases activeClientLeader immediately before the incoming /workspaces/ page requests it (pagehide only fires on document unload or bfcache entry—never on ordinary tab switches—so background multi-tab leadership stays intact).
    3. Prevent suspended bfcache pages from re-competing in .catch() and recover cleanly on pageshow (src/libs/ActiveClientManager/index.ts, lines 171–188 & 224–229):
      • Early-return in requestLeaderLock and its .catch() handler (before the AbortError requestLeaderLock(false) re-request at line 172 and retry timer at line 181) whenever isPageSuspended is true.
      • On pageshow (event.persisted), reset isPageSuspended = false and call init() when document.visibilityState === 'visible' (letting AppState / visibilitychange handle tabs restored in the background).
    4. Add unit tests in tests/unit/ActiveClientManagerTest.ts:
      • Verify pagehide resolves the held activeClientLeader Web Lock promise immediately, suppresses post-pagehide AbortError re-requests and retry timers, allows the incoming /workspaces/ client to acquire leadership and flush SequentialQueue without stalling useIsAppLoadPending(), and re-acquires leadership on pageshow (event.persisted = true).

    What alternative solutions did you explore? (Optional)

    • Adding a timeout fallback around {steal: true} or savedSelfPromise (isReady()): Rejected because Web Locks {steal: true} cannot accept an AbortSignal per spec, and force-resolving leadership or isReady() on a timer while another context still holds the Web Lock violates single-leader serialization over shared IndexedDB ONYXKEYS.PERSISTED_REQUESTS. Releasing the lock synchronously on pagehide eliminates the bfcache lock collision at its source.
    • Clearing Plaid or ONYXKEYS.REIMBURSEMENT_ACCOUNT loading flags on /workspaces/ mount: Rejected because WorkspacesListPage.tsx renders its spinner from useIsAppLoadPending() (IS_LOADING_APP / in-flight app-load requests), not from REIMBURSEMENT_ACCOUNT.isLoading.
  25. melvin-bot commented on Dec 3, 2026

    @melvin-bot

    📣 @ldc861117! 📣
    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>
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

BugDailyExternalHelp WantedOverdue

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions