App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Statements-Page loads infinitely when navigating to /statements/<YYYYMM>

Open unzig21 opened this issue 3 weeks ago • 27 comments

If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!


Version Number: v9.5.35-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/106332 Email or phone of affected tester (no customers): N/A Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Windows 11 / Chrome App Component: Other

Action Performed:

Preconditions:

  • logged in to any account that has expensify card enabled but no card activity in current month
  • Send this link on any chat https://staging.new.expensify.com/statements/202611

Steps:

  1. Navigate to the chat where the link in sent
  2. Copy and paste the deeplink to the address bar

Expected Result:

Statement page should loads and shows the "Submit expense", "Pay someone", and "Split expense" links.

Actual Result:

The page loads infinitely (if we wait longer, the chrome becomes unresponsive)

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

https://github.com/user-attachments/assets/03bc9502-9cc8-4dd6-8b55-22e18a15f74e

View all open jobs on GitHub

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

unzig21 avatar Nov 10 '26 08:11 unzig21

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

melvin-bot[bot] avatar Nov 10 '26 08:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 10 '26 08:11 melvin-bot[bot]

🤖 Web test steps verification results: ⚠️ partial

Verified on dev NewDot web: November statement link was sent and located in Concierge chat. Both November and October opened statement dialogs but failed inside the iframe; the current-month issue could not be isolated.

October statement dialog with the same iframe failure
Step Status
Send and locate /statements/202611 in chatThe message and clickable November statement link were confirmed.
✅
November statement loads with Submit expense, Pay someone, Split expenseThe dialog opened, but its iframe displayed a hostname-lookup failure instead of statement content. This did not reproduce the reported infinite loading or Chrome unresponsiveness.

Preliminary analysis — low confidence: App embeds the OldDot statement page and clears its spinner only when the iframe fires its load event; there is no loading timeout (WalletStatementModal:69–86). A stalled embedded page could therefore explain indefinite loading, but this does not establish why Chrome becomes unresponsive.

The current month is explicitly permitted, and this App code does not branch on card activity (WalletStatementPage:50–65).
November statement dialog with iframe loading failure
❌
Compare October statementOctober produced the same iframe failure, preventing isolation of a current-month defect.

Alternative considered: the listener change in Only handle wallet statement messages sent by the statement iframe. Its registration effect neither updates state nor reloads the iframe, so a listener-driven render loop is not demonstrated (WalletStatementModal:33–67). Discovery during that PR’s QA does not establish causation.
October statement dialog with the same iframe failure
✅
Paste November route into address barBlocked by the permitted browser-command surface. Only chat-link navigation was tested, so the issue’s exact hard-navigation sequence remains unverified.
❌
Account prerequisitesSigned-in state was confirmed; the required card-enabled/no-current-month-activity combination was not independently verified.

Required evidence before recommending a fix: reproduce with the specified account state, capture the statement document’s redirect chain and load event, and collect a Chrome performance trace during the hang. This distinguishes network/authentication failure from embedded-page CPU work or repeated navigation. Redact authentication tokens.

Production-log access was unavailable. The root cause remains unconfirmed; neither reverting the listener security checks nor adding a timeout is justified as the solution yet.
❌

view run

MelvinBot avatar Nov 10 '26 08:11 MelvinBot

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

Proposal

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

When navigating to the wallet statement route (e.g. copying and pasting https://staging.new.expensify.com/statements/202611 or /statements/202611/ into the browser address bar, or opening the statement modal on Web), the page remains stuck on an infinite loading state and within moments the Chrome browser tab becomes completely unresponsive (100% CPU lock).

What is the root cause of that problem?

The issue is caused by a compounding selector reference instability and infinite render loop in WalletStatementModal/index.tsx (introduced in PR #106332), combined with missing route parameter sanitization in WalletStatementPage.tsx:

  1. Infinite Re-render Loop via Selector Object Reference Instability: In src/components/WalletStatementModal/index.tsx:30:

    const [conciergePersonalDetails] = usePersonalDetailsByIDs([CONST.ACCOUNT_ID.CONCIERGE]);
    

    An inline array literal [CONST.ACCOUNT_ID.CONCIERGE] is allocated on every single render. Inside src/hooks/usePersonalDetails.ts:29-35:

    function usePersonalDetailsByIDs<TReturn>(accountIDs: Array<number | undefined> | undefined, selector?: (personalDetails: PersonalDetailsList) => TReturn) {
        const personalDetailsByIDsSelector = (personalDetailsList: OnyxEntry<PersonalDetailsList>) => {
            const personalDetails = personalDetailsListSelector(accountIDs)(personalDetailsList);
            return selector ? selector(personalDetails) : personalDetails;
        };
        return useOnyx(ONYXKEYS.PERSONAL_DETAILS_LIST, {selector: personalDetailsByIDsSelector});
    }
    

    personalDetailsByIDsSelector is re-created every render capturing the new accountIDs array. It calls getPersonalDetailsListByIDs, which in src/libs/PersonalDetailsUtils.ts:61-74 returns a newly allocated object {} on every invocation:

    accountIDs?.reduce(...) ?? {}
    

    Because useOnyx receives a new selector function and the selector computes a new object reference on every call, useOnyx detects that the snapshot changed (prev !== next) and schedules an immediate component re-render.

  2. Synchronous Main-Thread Event Listener Churn: In src/components/WalletStatementModal/index.tsx:38-62:

    const navigate = (event: MessageEvent<WalletStatementMessage>) => { ... };
    
    useEffect(() => {
        window.addEventListener('message', navigate);
        return () => {
            window.removeEventListener('message', navigate);
        };
    }, [navigate]);
    

    navigate is not wrapped in useCallback or stored in a ref. Every render allocates a new navigate function reference, which triggers useEffect cleanup (removeEventListener) and re-registration (addEventListener). Combined with the selector re-render loop above, this creates an unbounded synchronous render and event listener thrash on the JavaScript main thread. This starves the browser's event loop, prevents the embedded iframe from completing its paint and firing its load event (leaving isLoading stuck at true), and locks up the Chrome tab until the browser flags it as unresponsive. (Note: in tests/ui/WalletStatementModalTest.tsx, usePersonalDetailsByIDs was mocked as () => [undefined, {status: 'loaded'}], so this runtime render loop was bypassed during automated test execution).

  3. Route Parameter Trailing Slash Handling: In src/pages/wallet/WalletStatementPage.tsx:44-55: When users paste URLs from chat or address bars that include a trailing slash (e.g. /statements/202611/), yearMonth carries the trailing slash. Parsing Number(month) - 1 results in NaN, which causes date-fns format() to throw RangeError: Invalid time value, or causes yearMonth.length !== 6 to fail and immediately dismiss the modal unexpectedly.

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

  1. Stabilize WalletStatementModal references and event listener (src/components/WalletStatementModal/index.tsx):

    • Define const CONCIERGE_ACCOUNT_IDS = [CONST.ACCOUNT_ID.CONCIERGE]; at module scope outside the component so usePersonalDetailsByIDs receives a stable array reference across renders.
    • Decouple the message event listener from inline function churn by storing navigate in a ref (navigateRef.current = navigate) and attaching the listener once on mount with an empty dependency array []:
      const navigateRef = useRef(navigate);
      navigateRef.current = navigate;
      
      useEffect(() => {
          const handleMessage = (event: MessageEvent<WalletStatementMessage>) => {
              navigateRef.current(event);
          };
          window.addEventListener('message', handleMessage);
          return () => {
              window.removeEventListener('message', handleMessage);
          };
      }, []);
      
    • Memoize statementPageOrigin with useMemo(() => new URL(statementPageURL).origin, [statementPageURL]) to avoid redundant string parsing on every render.
  2. Sanitize yearMonth parameter in WalletStatementPage (src/pages/wallet/WalletStatementPage.tsx):

    • Strip any trailing slashes from route.params.yearMonth:
      const rawYearMonth = route.params.yearMonth ?? null;
      const yearMonth = rawYearMonth?.replace(/\/$/, '') ?? null;
      
    • Validate that yearMonth matches the 6-digit ^\d{6}$ format before calculating the date to prevent any RangeError during formatting.
  3. Automated Regression Tests (tests/ui/WalletStatementModalTest.tsx):

    • Add a test verifying that WalletStatementModal does not tear down or recreate its window message listener across parent component re-renders.
    • Add unit tests verifying WalletStatementPage mounts correctly and parses yearMonth with or without a trailing slash.

What alternative solutions did you explore? (Optional)

  • Wrapping navigate in useCallback with full dependencies [conciergeReportID, introSelected, session?.accountID, isSelfTourViewed, hasCompletedGuidedSetupFlow, conciergePersonalDetails, delegateAccountID, statementPageOrigin]. While this stabilizes the function when dependencies don't change, using the useRef listener pattern is superior because it guarantees zero window listener re-registration while always forwarding the freshest Onyx and session state to handleWalletStatementNavigation, matching Expensify's standard pattern for window-level message handlers.

— submitted with Antigravity on the contributor's behalf

HindsightWise avatar Nov 10 '26 09:11 HindsightWise

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

melvin-bot[bot] avatar Nov 10 '26 09:11 melvin-bot[bot]

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

Proposal

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

When navigating to a wallet statement URL (e.g. https://staging.new.expensify.com/statements/202611 or /statements/202611/), the statement modal gets stuck in an infinite loading state and within seconds locks up the browser tab (100% CPU freeze / unresponsive tab).

What is the root cause of that problem?

This is a regression introduced in PR #106332 (WalletStatementModal/index.tsx) involving unstable dependencies and an infinite render loop:

  1. Unstable inline array in usePersonalDetailsByIDs: In src/components/WalletStatementModal/index.tsx:

    const [conciergePersonalDetails] = usePersonalDetailsByIDs([CONST.ACCOUNT_ID.CONCIERGE]);
    

    An inline array literal [CONST.ACCOUNT_ID.CONCIERGE] is instantiated on every render. usePersonalDetailsByIDs passes this array into personalDetailsByIDsSelector, which calls getPersonalDetailsListByIDs. Because accountIDs is a new reference each time, getPersonalDetailsListByIDs returns a new object reference {}. useOnyx detects a changed selector snapshot and immediately triggers a re-render.

  2. Synchronous listener thrash via unmemoized navigate in useEffect: In src/components/WalletStatementModal/index.tsx:

    const navigate = (event: MessageEvent<WalletStatementMessage>) => { ... };
    
    useEffect(() => {
        window.addEventListener('message', navigate);
        return () => {
            window.removeEventListener('message', navigate);
        };
    }, [navigate]);
    

    navigate is not wrapped in useCallback or held in a ref. Every render allocates a new navigate function instance, causing useEffect to constantly tear down and recreate the window event listener. Coupled with the re-render loop above, the main thread enters an unbounded synchronous execution loop, blocking the browser event loop, preventing the iframe's load event from ever resolving isLoading, and crashing Chrome with "Page Unresponsive".

  3. Trailing slash handling in WalletStatementPage.tsx: Navigating to URLs with a trailing slash (e.g. /statements/202611/) leaves route.params.yearMonth with length 7 instead of 6, leading to unexpected date calculation errors or premature route dismissals.

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

  1. Stabilize WalletStatementModal/index.tsx:

    • Hoist the Concierge account ID array outside the component to keep a constant reference:
      const CONCIERGE_ACCOUNT_IDS = [CONST.ACCOUNT_ID.CONCIERGE];
      
      And use:
      const [conciergePersonalDetails] = usePersonalDetailsByIDs(CONCIERGE_ACCOUNT_IDS);
      
    • Use the useRef pattern for the window message listener so the event listener is attached once on mount and never thrashed across renders:
      const navigateRef = useRef(navigate);
      navigateRef.current = navigate;
      
      useEffect(() => {
          const handleMessage = (event: MessageEvent<WalletStatementMessage>) => {
              navigateRef.current(event);
          };
          window.addEventListener('message', handleMessage);
          return () => {
              window.removeEventListener('message', handleMessage);
          };
      }, []);
      
    • Memoize statementPageOrigin with useMemo(() => new URL(statementPageURL).origin, [statementPageURL]).
  2. Sanitize yearMonth in src/pages/wallet/WalletStatementPage.tsx:

    • Sanitize yearMonth by stripping any trailing slashes:
      const yearMonth = route.params.yearMonth?.replace(/\/+$/, '') ?? null;
      
  3. Regression Tests in tests/ui/WalletStatementModalTest.tsx:

    • Add unit test verifying that WalletStatementModal does not thrash event listeners or re-render infinitely when mounted.
    • Verify WalletStatementPage correctly parses yearMonth with and without a trailing slash.

What alternative solutions did you explore? (Optional)

  • Wrapping navigate in useCallback with all its dependencies was explored, but the useRef listener pattern is superior and standard across Expensify because it ensures the window-level listener is attached exactly once while always executing with the latest state and Onyx data.

jmquero92 avatar Nov 10 '26 10:11 jmquero92

:warning: Unable to store contributor details

Details
Auth SetContributorDetails returned an error
401 Contributor details already exist

melvin-bot[bot] avatar Nov 10 '26 10:11 melvin-bot[bot]

Proposal

What is the root cause of that problem?

This is a compounding regression introduced in PR #106332 (WalletStatementModal/index.tsx) involving unstable selector dependencies, synchronous event listener thrashing, and unmapped cold-launch navigation state:

  1. Infinite Re-render Loop via Selector Object Reference Instability: In src/components/WalletStatementModal/index.tsx:30:

    const [conciergePersonalDetails] = usePersonalDetailsByIDs([CONST.ACCOUNT_ID.CONCIERGE]);
    

    An inline array literal [CONST.ACCOUNT_ID.CONCIERGE] is instantiated on every single render. usePersonalDetailsByIDs passes this array into personalDetailsByIDsSelector, which calls getPersonalDetailsListByIDs. Because accountIDs is a new reference each time, getPersonalDetailsListByIDs returns a new object reference {}. useOnyx detects that the selector snapshot changed (prev !== next) and immediately schedules a component re-render.

  2. Synchronous Main-Thread Event Listener Churn: In src/components/WalletStatementModal/index.tsx:38-62:

    const navigate = (event: MessageEvent<WalletStatementMessage>) => { ... };
    
    useEffect(() => {
        window.addEventListener('message', navigate);
        return () => {
            window.removeEventListener('message', navigate);
        };
    }, [navigate]);
    

    navigate is not wrapped in useCallback or stored in a ref. Every render allocates a new navigate function reference, which triggers useEffect cleanup (removeEventListener) and re-registration (addEventListener). Combined with the selector re-render loop above, this creates an unbounded synchronous render and event listener thrash on the JavaScript main thread. This starves the browser's event loop, prevents the embedded iframe from completing its paint and firing its load event (leaving isLoading stuck at true), and locks up the Chrome tab until the browser flags it as unresponsive.

  3. Route Parameter Trailing Slash Handling: In src/pages/wallet/WalletStatementPage.tsx:44-55: When users navigate with a trailing slash (e.g. /statements/202611/), route.params.yearMonth has length 7 instead of 6, leading to date calculation errors or premature route dismissals.

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

  1. Stabilize WalletStatementModal references and event listener (src/components/WalletStatementModal/index.tsx):

    • Define const CONCIERGE_ACCOUNT_IDS = [CONST.ACCOUNT_ID.CONCIERGE]; at module scope outside the component so usePersonalDetailsByIDs receives a stable array reference across renders.
    • Decouple the message event listener from inline function churn by storing navigate in a ref (navigateRef.current = navigate) and attaching the listener once on mount with an empty dependency array []:
      const navigateRef = useRef(navigate);
      navigateRef.current = navigate;
      
      useEffect(() => {
          const handleMessage = (event: MessageEvent<WalletStatementMessage>) => {
              navigateRef.current(event);
          };
          window.addEventListener('message', handleMessage);
          return () => {
              window.removeEventListener('message', handleMessage);
          };
      }, []);
      
    • Memoize statementPageOrigin with useMemo(() => new URL(statementPageURL).origin, [statementPageURL]).
  2. Sanitize yearMonth in WalletStatementPage (src/pages/wallet/WalletStatementPage.tsx):

    • Strip any trailing slashes from route.params.yearMonth:
      const rawYearMonth = route.params.yearMonth ?? null;
      const yearMonth = rawYearMonth?.replace(/\/+$/, '') ?? null;
      
  3. Automated Regression Tests (tests/ui/WalletStatementModalTest.tsx):

    • Add a unit test verifying that WalletStatementModal does not tear down or recreate its window message listener across parent component re-renders.
    • Add unit tests verifying WalletStatementPage correctly parses yearMonth with and without a trailing slash.

What alternative solutions did you explore? (Optional)

Wrapping navigate in useCallback with all its dependencies was explored, but the useRef listener pattern is superior and standard across Expensify because it ensures the window-level listener is attached exactly once while always executing with the latest state and Onyx data.

Tests

  1. Send /statements/202611 and /statements/202611/ in chat.
  2. Click the link to open the statement modal.
  3. Verify that the modal loads without freezing the browser tab or pegging CPU at 100%.
  4. Copy and paste the link directly into the browser address bar (cold launch) and verify that the page loads properly.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 10 '26 11:11 kevinjosh10

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

melvin-bot[bot] avatar Nov 10 '26 11:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 10 '26 11:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 10 '26 12:11 melvin-bot[bot]

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

Proposal

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

Navigating to /statements/<YYYYMM> in Workspace/User Settings causes an infinite loading spinner instead of displaying the monthly billing statement.

What is the root cause of that problem?

In src/pages/settings/Subscription/StatementsPage.tsx: When navigating directly to a statement by month URL, the page expects statement data in Onyx under ONYXKEYS.SUBSCRIPTION_STATEMENTS. If the statement for that specific month does not exist or has not finished loading, the loading state check isLoadingOnyxValue(statements) remains indefinitely true because no fallback or empty resolution is triggered when the API returns an empty set.

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

  1. In src/pages/settings/Subscription/StatementsPage.tsx:
    • Refactor loading check to verify if statements API request has completed (statementsResult.status !== 'loading').
    • If the statement for the requested <YYYYMM> is not found in Onyx after fetch completion, render an informative EmptyState or redirect to the primary statements list rather than looping the loading indicator.

What alternative solutions did you explore? (Optional)

Infinite retry of the fetch call, but if the statement doesn't exist (e.g. future or pre-account date), it causes infinite network requests.

Automated Tests

Add unit test in tests/unit/StatementsPageTest.tsx:

  • Verify page displays statement details when data exists.
  • Verify page renders empty state or error message when statement does not exist, without infinite loading.

TassioSales avatar Nov 11 '26 13:11 TassioSales

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

melvin-bot[bot] avatar Nov 11 '26 13:11 melvin-bot[bot]

I looked into this on staging (Windows 11, Chrome 157) and it does not look like an App-side problem.

What I see when opening https://staging.new.expensify.com/statements/202611 directly:

  • The app loads normally and opens the "November 2026 Statement" RHP. The splash hides in about 6 seconds and there is no render loop in the console logs.
  • The iframe request https://staging.expensify.com/statement.php?period=202611 returns HTTP 200 with an empty (0 byte) body, so the panel stays blank.
  • The same request for other months (period=202610, period=202601) returns the statement normally in the same panel, with the same account and session.
  • Navigating to the route inside an already loaded app gives the same blank panel, so it is not specific to a cold load.

So the only difference is the period, and the empty response comes from statement.php for the current month. This looks like a backend issue rather than something in WalletStatementPage / WalletStatementModal.

Screenshots: November 2026 (blank) and October 2026 (works).

step2f step3-1

tarunkauxhik avatar Nov 11 '26 19:11 tarunkauxhik

📣 @tarunkauxhik! 📣 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 11 '26 19:11 melvin-bot[bot]

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

tarunkauxhik avatar Nov 11 '26 19:11 tarunkauxhik

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

melvin-bot[bot] avatar Nov 11 '26 19:11 melvin-bot[bot]

@thesahindia Still overdue 6 days?! Let's take care of this!

@thesahindia 8 days overdue is a lot. Should this be a Weekly issue? If so, feel free to change it!

@thesahindia 12 days overdue now... This issue's end is nigh!