Skip to content

Public Room - User is logged out after opening a public room - #70382

Merged
inimaga merged 10 commits into
Expensify:mainfrom
dukenv0307:fix/68719
Sep 17, 2025
Merged

inimaga merged 10 commits into
Expensify:mainfrom
dukenv0307:fix/68719

Conversation

@dukenv0307

@dukenv0307 dukenv0307 commented Sep 11, 2025 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Fixed Issues

$ #68719
PROPOSAL: #68719 (comment)

Tests

  1. Go to https://staging.new.expensify.com/
  2. Sign up with a Gmail address that includes a +
  3. Select Track and budget my expenses. Complete the onboarding flow (skip everything)
  4. Create a workspace
  5. Click FAB > Start Chat > Room
  6. Create a public room
  7. Go to the public room and click on its header.
  8. Click Share > Copy URL
  9. Leave the room
  10. Open a new tab, paste the URL, and press enter
  11. Verify that opening a public room should not log the user out.
  • Verify that no errors appear in the JS console

Offline tests

Same as above

QA Steps

Same as above

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Screen_Recording_2025-09-11_at_21.18.19.mov
Android: mWeb Chrome
Screen_Recording_2025-09-11_at_21.13.13.mov
iOS: Native
Screen_Recording_2025-09-11_at_21.21.59.mov
iOS: mWeb Safari
Screen_Recording_2025-09-11_at_21.14.31.mov
MacOS: Chrome / Safari
web-1.mov
MacOS: Desktop
Screen_Recording_2025-09-11_at_21.24.53.mov

@dukenv0307
dukenv0307 marked this pull request as ready for review September 13, 2025 04:53
@dukenv0307
dukenv0307 requested a review from a team as a code owner September 13, 2025 04:53
@melvin-bot
melvin-bot Bot requested review from rojiphil and removed request for a team September 13, 2025 04:53
@melvin-bot

melvin-bot Bot commented Sep 13, 2025

Copy link
Copy Markdown

@rojiphil Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@parasharrajat

Copy link
Copy Markdown
Member

We are migrating Onyx.Connect as much as possible. but I think waiting for onyx value to load could delay some other logic in that hook. We can create a HOC to deal with it but that will delay app rendering as Expensify is root component. I think it is better to stick with Onyx.connectWithoutView for this case. @dukenv0307

@parasharrajat

Copy link
Copy Markdown
Member

@dukenv0307 Can you please verify whether this PR solves all of these? I will check too.

#70435
#68719
#70172

@rojiphil rojiphil left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dukenv0307 I have left some comments. Please have a look. Thanks.

Comment thread src/Expensify.tsx Resolved
Comment thread src/Expensify.tsx Outdated

// Display a blank page until the onyx migration completes
if (!isOnyxMigrated) {
if (!isOnyxMigrated || isLoadingOnyxValue(sessionMetadata)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need to keep showing the blank page until we fetch session data? Wondering what problems we ran into here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We're using isAuthenticated to show PublicScreens or AuthScreens, so I think we should wait for session data to be loaded to avoid unexpected errors.

@rojiphil

Copy link
Copy Markdown
Contributor

I think it is better to stick with Onyx.connectWithoutView for this case.

@parasharrajat Since isAuthenticated is needed while rendering as well, connectWithoutView does not seem best to use here. What do you think?

Comment thread src/Expensify.tsx Outdated

// Display a blank page until the onyx migration completes
if (!isOnyxMigrated) {
if (!isOnyxMigrated || isLoadingOnyxValue(sessionMetadata)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we keep showing a blank page until we fetch session data?
I am on the fence about this.
@mountiny what do you think?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you describe the flow right now and what is proposed to do?

Also curious what caused this change? Previously we havent had this problem, as far as I know

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we were using WithOnyx HOC earlier.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @rojiphil here. We shouldn’t gate the whole app on session load. This issue is from acting before session state stabilises, not rendering.
Related to my earlier note on deep-link listener duplication: set up the listener once with cleanup, fetch the initial URL once and process it after session metadata finishes loading, while letting the loader/splasher render normally.

@parasharrajat

Copy link
Copy Markdown
Member

Since isAuthenticated is needed while rendering as well, connectWithoutView does not seem best to use here. What do you think?

Let's create HOC in that case to load session data.

@rojiphil

Copy link
Copy Markdown
Contributor

Can you describe the flow right now and what is proposed to do?

Regarding the flow right now, the RCA in the proposal looks accurate to me i.e. isAuthenticated is false briefly because the session data is not available yet. And this causes the openReport to be called without the auth token. The BE considered this as an anonymous user thereby causing the FE to sign out the user.

The proposed approach is to call the openReportfromDeeplink only once the session data is available. And that LGTM. However, I was concerned if showing blank page till session data is available is a good idea. On testing the fix though, I think it looks fine. Not sure how you look at this though @mountiny

70382-web-chrome-001.mp4

@rojiphil

Copy link
Copy Markdown
Contributor

Also curious what caused this change? Previously we havent had this problem, as far as I know

That’s a very good question. Seems like the problem existed for quite some time but surfaced only recently due to the side effect been triggered even before the session data was fetched. Not able to pinpoint exactly what caused this though.

@rojiphil

Copy link
Copy Markdown
Contributor

Let's create HOC in that case to load session data.

@parasharrajat I do not see any distinct advantage of using HOC here over the proposed solution. Or am I missing something here?

@parasharrajat

Copy link
Copy Markdown
Member

If we use the HOC the session data will be ready on first render of the component. It might be slightly delayed by few ms but we will have main data ready.

@rojiphil

Copy link
Copy Markdown
Contributor

The proposed solution here also has a similar effect. In that case, I think it would be better to avoid one more component and use the proposed solution here.

@mountiny

Copy link
Copy Markdown
Contributor

to me the second loading on your dev looks good to me, no issue there #70382 (comment)

cc @Expensify/design in case you would have any feedback

@rojiphil could you go ahead with the checklist please?

@rojiphil

rojiphil commented Sep 16, 2025 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
70382-android-native-001.mp4
Android: mWeb Chrome
70382-mweb-chrome-001.mp4
iOS: HybridApp
70382-ios-hybrid-001.mp4
iOS: mWeb Safari
70382-mweb-safari-001.mp4
MacOS: Chrome / Safari
70382-web-chrome-001.mp4
MacOS: Desktop
70382-desktop-001.mp4

@rojiphil rojiphil left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @dukenv0307 for the PR and updates.

@mountiny Changes LGTM and works well too.
All yours. Thanks.

@melvin-bot

melvin-bot Bot commented Sep 16, 2025

Copy link
Copy Markdown

We did not find an internal engineer to review this PR, trying to assign a random engineer to #68719 as well as to this PR... Please reach out for help on Slack if no one gets assigned!

@melvin-bot
melvin-bot Bot requested a review from inimaga September 16, 2025 07:41
Comment thread src/Expensify.tsx
};
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps -- we don't want this effect to run again
}, []);
}, [sessionMetadata?.status]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look good in terms of addressing the current problem, but I'm concerned we might introduce a new regression linked to deep-link listener duplication. Because the effect now re-runs on session metadata changes and re-adds the Linking 'url' listener without cleanup, therefore could cause multiple navigations/API calls.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could set up the Linking 'url' listener once in a single effect (and clean it up on unmount), avoiding any dependency on session metadata for its setup. Fetch the initial URL once, store it, and process it only after session metadata finishes loading, ensuring it’s handled exactly once (e.g., with a “processed” guard).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@inimaga I think we can keep the current approach and clear the listener in the cleanup function. Another fact, sessionMetadata?.status is only changed once and we skipped when the status is loading.

const linkingChangeListener = Linking.addEventListener('url', (state) => {
            Report.openReportFromDeepLink(state.url, currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports);
        });
return () => {
            if (!appStateChangeListener.current) {
                return;
            }
            appStateChangeListener.current.remove();
            linkingChangeListener.remove();
        };

@dukenv0307 dukenv0307 Sep 17, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I think that's fine, because

  1. We already had the logic to return early at the beginning of this hook
if (isLoadingOnyxValue(sessionMetadata)) {
            return;
        }

and sessionMetadata?.status only changes from loading to loaded, which means the Linking logic only triggers 1 time

  1. In this hook, we used isAuthenticated many times we should wait until the session data is loaded to prevent the same issue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point on the early return. It helps, but there are still end‑user flows where session status changes more than once (e.g., sign‑out then sign‑in, switching accounts, opening a public room first and then signing in). So wouldn't put too much faith in sessionMetadata?.status only changing once.

Comment thread src/Expensify.tsx Outdated

// Display a blank page until the onyx migration completes
if (!isOnyxMigrated) {
if (!isOnyxMigrated || isLoadingOnyxValue(sessionMetadata)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @rojiphil here. We shouldn’t gate the whole app on session load. This issue is from acting before session state stabilises, not rendering.
Related to my earlier note on deep-link listener duplication: set up the listener once with cleanup, fetch the initial URL once and process it after session metadata finishes loading, while letting the loader/splasher render normally.

@github-actions

github-actions Bot commented Sep 17, 2025 •

Copy link
Copy Markdown
Contributor

PR Summary

Fixed a bug where users were being logged out when opening a public room via a direct link. The issue was caused by improper session state handling during deep link navigation. The solution properly tracks authentication state and prevents unnecessary logout when accessing public rooms through links.

Changes

File Summary
src/Expensify.tsx Added proper session state tracking for deep links by creating a reference to the linking listener for cleanup, checking for loading Onyx values, and updating the effect dependency to include session metadata status. This prevents unnecessary logout when opening public rooms.
src/libs/actions/Report.ts Modified the openReportFromDeepLink function to accept an isAuthenticated parameter instead of calling hasAuthToken() internally. This ensures the authentication state is consistent when handling deep links to public rooms.

autogenerated by presubmit.ai

@mountiny

Copy link
Copy Markdown
Contributor

@dukenv0307 can you please address the PR comments with urgency?

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ LGTM!

Review Summary

Commits Considered (7)
Files Processed (2)
  • src/Expensify.tsx (6 hunks)
  • src/libs/actions/Report.ts (2 hunks)
Actionable Comments (0)
Skipped Comments (7)
  • src/Expensify.tsx [98-98]

    enhancement: "Session metadata extraction improves loading state detection"

  • src/Expensify.tsx [189-191]

    best practice: "Prevent premature initialization before session data loads"

  • src/Expensify.tsx [230-230]

    enhancement: "Authentication state now properly passed to deep link handler"

  • src/Expensify.tsx [248-248]

    possible issue: "Effect dependency on session status may be incomplete"

  • src/Expensify.tsx [283-283]

    enhancement: "Prevent rendering before session data loads"

  • src/libs/actions/Report.ts [226-226]

    possible issue: "Removed hasAuthToken import may affect other functions"

  • src/libs/actions/Report.ts [3399-3399]

    best practice: "Authentication state now passed as parameter improves function design"

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 Pull request needs attention.

Review Summary

Commits Considered (1)
  • 2ed1e46: remove isLoadingOnyxValue check
Files Processed (2)
  • src/Expensify.tsx (5 hunks)
  • src/libs/actions/Report.ts (2 hunks)
Actionable Comments (2)
  • src/Expensify.tsx [189-191]

    possible bug: "Potential memory leak with event listeners"

  • src/Expensify.tsx [248-248]

    performance: "Missing cleanup for event listeners on dependency change"

Skipped Comments (2)
  • src/Expensify.tsx [230-230]

    possible issue: "Potential race condition with authentication state"

  • src/libs/actions/Report.ts [226-226]

    possible issue: "Removed function from imports may affect other code"

Comment thread src/Expensify.tsx
Comment on lines +189 to +191
if (isLoadingOnyxValue(sessionMetadata)) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This early return prevents the effect from running when session metadata is still loading, but it doesn't properly clean up any previously set listeners. If the component re-renders while sessionMetadata is loading, the cleanup function won't be called. Consider moving the early return condition inside the timeout callback or restructuring the effect to ensure proper cleanup regardless of the loading state.

Comment thread src/Expensify.tsx
};
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps -- we don't want this effect to run again
}, []);
}, [sessionMetadata?.status]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The effect dependency is now set to sessionMetadata?.status, which means the effect will re-run whenever the session status changes. However, the effect contains event listeners that are being added without proper cleanup between re-runs. This could lead to duplicate event listeners and multiple executions of the same code when deep links are opened. Consider storing the event listener reference and removing it in the cleanup function to prevent memory leaks and duplicate handlers.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 Pull request needs attention.

Review Summary

Commits Considered (1)
Files Processed (1)
  • src/Expensify.tsx (5 hunks)
Actionable Comments (4)
  • src/Expensify.tsx [234-236]

    possible issue: "Potential memory leak with event listener"

  • src/Expensify.tsx [189-191]

    possible bug: "Early return prevents proper cleanup of effect resources"

  • src/Expensify.tsx [230-230]

    performance: "Passing entire object as dependency"

  • src/Expensify.tsx [235-235]

    performance: "Passing entire object in event handler"

Skipped Comments (0)

Comment thread src/Expensify.tsx Outdated
Comment on lines 234 to 236
const linkingChangeListener = Linking.addEventListener('url', (state) => {
Report.openReportFromDeepLink(state.url, currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports, isAuthenticated);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The event listener is correctly created and stored in a variable, but there's a potential issue with how it's cleaned up. While you've added linkingChangeListener.remove() to the cleanup function, this pattern could lead to memory leaks if the component re-renders while sessionMetadata is still loading.

Consider moving the event listener setup outside of the dependency array or ensuring it's properly cleaned up on each re-render by using a ref to track the listener:

// Store the listener in a ref
const linkingChangeListenerRef = useRef(null);

// Set up the listener
linkingChangeListenerRef.current = Linking.addEventListener('url', (state) => {
  Report.openReportFromDeepLink(state.url, currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports, isAuthenticated);
});

// Clean up in the return function
return () => {
  if (appStateChangeListener.current) {
    appStateChangeListener.current.remove();
  }
  if (linkingChangeListenerRef.current) {
    linkingChangeListenerRef.current.remove();
  }
};

Comment thread src/Expensify.tsx
Comment on lines +189 to +191
if (isLoadingOnyxValue(sessionMetadata)) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This early return prevents the effect from running when session metadata is still loading, but it doesn't properly clean up any previously set listeners. If the component re-renders while sessionMetadata is loading, the cleanup function won't be called.

Consider restructuring the effect to ensure proper cleanup regardless of the loading state:

useEffect(() => {
  // Only set up listeners if session metadata is loaded
  if (!isLoadingOnyxValue(sessionMetadata)) {
    const timeoutId = setTimeout(() => {
      // Existing timeout code
    }, 0);
    
    // Set up listeners only when not loading
    // ...
    
    // Return cleanup function that always runs
    return () => {
      clearTimeout(timeoutId);
      if (appStateChangeListener.current) {
        appStateChangeListener.current.remove();
      }
      if (linkingChangeListener) {
        linkingChangeListener.remove();
      }
    };
  }
  
  // Return empty cleanup when loading
  return () => {};
}, [sessionMetadata?.status]);


<!-- presubmit.ai: comment -->

Comment thread src/Expensify.tsx
Linking.getInitialURL().then((url) => {
setInitialUrl(url as Route);
Report.openReportFromDeepLink(url ?? '', currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports);
Report.openReportFromDeepLink(url ?? '', currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports, isAuthenticated);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This component is violating the [PERF-6] rule by passing the entire allReports object as a dependency to Report.openReportFromDeepLink(). Passing entire objects can cause unnecessary re-renders and performance issues.

Consider extracting only the specific properties needed from allReports or restructuring the function to accept more granular parameters:

// Extract only needed properties from allReports
const reportIds = useMemo(() => Object.keys(allReports || {}), [allReports]);

// Then pass specific properties instead of the entire object
Report.openReportFromDeepLink(url ?? '', currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, reportIds, isAuthenticated);

Comment thread src/Expensify.tsx
Linking.addEventListener('url', (state) => {
Report.openReportFromDeepLink(state.url, currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports);
const linkingChangeListener = Linking.addEventListener('url', (state) => {
Report.openReportFromDeepLink(state.url, currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports, isAuthenticated);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to the previous issue, this line also violates the [PERF-6] rule by passing the entire allReports object to the function. This can lead to performance issues, especially in event handlers that may be called frequently.

Extract only the necessary properties from allReports or restructure the function to accept more specific parameters to improve performance.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 Pull request needs attention.

Review Summary

Commits Considered (1)
Files Processed (1)
  • src/Expensify.tsx (4 hunks)
Actionable Comments (3)
  • src/Expensify.tsx [190-192]

    possible issue: "Early return prevents proper cleanup of event listeners"

  • src/Expensify.tsx [231-231]

    performance: "Passing entire object as dependency can cause performance issues"

  • src/Expensify.tsx [236-236]

    performance: "Passing entire object in event handler affects performance"

Skipped Comments (0)

Comment thread src/Expensify.tsx
Comment on lines +190 to +192
if (isLoadingOnyxValue(sessionMetadata)) {
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This early return prevents the effect from running when session metadata is still loading, but it doesn't properly clean up any previously set listeners. If the component re-renders while sessionMetadata is loading, the cleanup function won't be called.

Consider restructuring the effect to ensure proper cleanup regardless of the loading state:

useEffect(() => {
  let timeoutId: NodeJS.Timeout;
  
  // Only set up listeners if session metadata is loaded
  if (!isLoadingOnyxValue(sessionMetadata)) {
    timeoutId = setTimeout(() => {
      // Existing timeout code
    }, 0);
    
    // Set up listeners only when not loading
    // ...
  }
  
  // Return cleanup function that always runs
  return () => {
    if (timeoutId) clearTimeout(timeoutId);
    if (appStateChangeListener.current) {
      appStateChangeListener.current.remove();
    }
    if (linkingChangeListener.current) {
      linkingChangeListener.current.remove();
    }
  };
}, [sessionMetadata?.status]);

Comment thread src/Expensify.tsx
Linking.getInitialURL().then((url) => {
setInitialUrl(url as Route);
Report.openReportFromDeepLink(url ?? '', currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports);
Report.openReportFromDeepLink(url ?? '', currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports, isAuthenticated);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line violates the [PERF-6] rule by passing the entire allReports object to Report.openReportFromDeepLink(). Passing entire objects can cause unnecessary re-renders and performance issues when the dependency changes.

Consider extracting only the specific properties needed from allReports or restructuring the function to accept more granular parameters:

// Extract only needed properties from allReports
const reportIds = useMemo(() => Object.keys(allReports || {}), [allReports]);

// Then pass specific properties instead of the entire object
Report.openReportFromDeepLink(url ?? '', currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, reportIds, isAuthenticated);

Comment thread src/Expensify.tsx
Linking.addEventListener('url', (state) => {
Report.openReportFromDeepLink(state.url, currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports);
linkingChangeListener.current = Linking.addEventListener('url', (state) => {
Report.openReportFromDeepLink(state.url, currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports, isAuthenticated);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to the previous issue, this line also violates the [PERF-6] rule by passing the entire allReports object to the function. This can lead to performance issues, especially in event handlers that may be called frequently.

Extract only the necessary properties from allReports or restructure the function to accept more specific parameters to improve performance.

@inimaga

inimaga commented Sep 17, 2025

Copy link
Copy Markdown
Contributor

Hmmm, @dukenv0307 with the latest updates, the original issue still remains. We can still recreate the original bug as no early-return when sessionMetadata?.status is loading. Meaning it will execute with an unstable isAuthenticated value and re-run when loaded. See patch below on what I was suggesting earlier:

diff --git a/src/Expensify.tsx b/src/Expensify.tsx
index 8707567ac583..8e2011eda4c1 100644
--- a/src/Expensify.tsx
+++ b/src/Expensify.tsx
@@ -48,6 +48,7 @@ import * as ReportActionContextMenu from './pages/home/report/ContextMenu/Report
 import type {Route} from './ROUTES';
 import SplashScreenStateContext from './SplashScreenStateContext';
 import type {ScreenShareRequest} from './types/onyx';
+import isLoadingOnyxValue from '@src/types/utils/isLoadingOnyxValue';
 
 Onyx.registerLogger(({level, message, parameters}) => {
     if (level === 'alert') {
@@ -94,7 +95,7 @@ function Expensify() {
     const [hasAttemptedToOpenPublicRoom, setAttemptedToOpenPublicRoom] = useState(false);
     const {translate, preferredLocale} = useLocalize();
     const [account] = useOnyx(ONYXKEYS.ACCOUNT, {canBeMissing: true});
-    const [session] = useOnyx(ONYXKEYS.SESSION, {canBeMissing: true});
+    const [session, sessionMetadata] = useOnyx(ONYXKEYS.SESSION, {canBeMissing: true});
     const [lastRoute] = useOnyx(ONYXKEYS.LAST_ROUTE, {canBeMissing: true});
     const [userMetadata] = useOnyx(ONYXKEYS.USER_METADATA, {canBeMissing: true});
     const [isCheckingPublicRoom = true] = useOnyx(ONYXKEYS.IS_CHECKING_PUBLIC_ROOM, {initWithStoredValues: false, canBeMissing: true});
@@ -121,6 +122,10 @@ function Expensify() {
     }, [isCheckingPublicRoom]);
 
     const isAuthenticated = useIsAuthenticated();
+    const isAuthenticatedRef = useRef(isAuthenticated);
+    useEffect(() => {
+        isAuthenticatedRef.current = isAuthenticated;
+    }, [isAuthenticated]);
     const autoAuthState = useMemo(() => session?.autoAuthState ?? '', [session]);
 
     const isSplashReadyToBeHidden = splashScreenState === CONST.BOOT_SPLASH_STATE.READY_TO_BE_HIDDEN;
@@ -220,16 +225,23 @@ function Expensify() {
         appStateChangeListener.current = AppState.addEventListener('change', initializeClient);
 
         setIsAuthenticatedAtStartup(isAuthenticated);
-        // If the app is opened from a deep link, get the reportID (if exists) from the deep link and navigate to the chat report
+        // If the app is opened from a deep link, capture the initial URL for later processing
         Linking.getInitialURL().then((url) => {
             if (url) {
                setInitialUrl(url as Route);
            } else {
                Onyx.set(ONYXKEYS.IS_CHECKING_PUBLIC_ROOM, false);
            }
-            Report.openReportFromDeepLink(url ?? '', currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports);
         });
 
         // Open chat report from a deep link (only mobile native)
-        Linking.addEventListener('url', (state) => {
-            Report.openReportFromDeepLink(state.url, currentOnboardingPurposeSelected, currentOnboardingCompanySize, onboardingInitialPath, allReports);
-        });
+        const onURL = (state: {url: string}) => {
+            Report.openReportFromDeepLink(
+                state.url,
+                currentOnboardingPurposeSelected,
+                currentOnboardingCompanySize,
+                onboardingInitialPath,
+                allReports,
+                isAuthenticatedRef.current,
+            );
+        };
+        const urlSubscription = Linking.addEventListener('url', onURL);
         if (CONFIG.IS_HYBRID_APP) {
             HybridAppModule.onURLListenerAdded();
         }
@@ -239,10 +251,32 @@ function Expensify() {
                 return;
             }
             appStateChangeListener.current.remove();
+            // Clean up URL listener
+            urlSubscription?.remove?.();
         };
         // eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps -- we don't want this effect to run again
     }, []);
 
+    // Process the initial URL only after session metadata has finished loading
+    useEffect(() => {
+        if (!initialUrl) {
+            return;
+        }
+        if (isLoadingOnyxValue(sessionMetadata)) {
+            return;
+        }
+
+        Report.openReportFromDeepLink(
+            initialUrl ?? '',
+            currentOnboardingPurposeSelected,
+            currentOnboardingCompanySize,
+            onboardingInitialPath,
+            allReports,
+            isAuthenticatedRef.current,
+        );
+        setInitialUrl(null);
+    }, [initialUrl, sessionMetadata?.status]);
+
     // This is being done since we want to play sound even when iOS device is on silent mode, to align with other platforms.
     useEffect(() => {
         Audio.setAudioModeAsync({playsInSilentModeIOS: true});

And then:

diff --git a/src/libs/actions/Report.ts b/src/libs/actions/Report.ts
index 220bd884ed5f..5ebd4a4845e0 100644
--- a/src/libs/actions/Report.ts
+++ b/src/libs/actions/Report.ts
@@ -3396,9 +3396,10 @@ function openReportFromDeepLink(
     currentOnboardingCompanySize: OnyxEntry<OnboardingCompanySize>,
     onboardingInitialPath: OnyxEntry<string>,
     reports: OnyxCollection<Report>,
+    isAuthenticatedParam?: boolean,
 ) {
     const reportID = getReportIDFromLink(url);
-    const isAuthenticated = hasAuthToken();
+    const isAuthenticated = isAuthenticatedParam ?? hasAuthToken();
 
     if (reportID && !isAuthenticated) {
         // Call the OpenReport command to check in the server if it's a public room. If so, we'll open it as an anonymous user

Thoughts?

Comment thread src/Expensify.tsx Resolved
@inimaga
inimaga merged commit 3840bbc into Expensify:main Sep 17, 2025
@melvin-bot

melvin-bot Bot commented Sep 17, 2025

Copy link
Copy Markdown

@inimaga looks like this was merged without a test passing. Please add a note explaining why this was done and remove the Emergency label if this is not an emergency.

@inimaga

inimaga commented Sep 17, 2025

Copy link
Copy Markdown
Contributor

"Failing test" linked to automated review comments from review bot.

@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@github-actions

This comment has been minimized.

@github-actions

Copy link
Copy Markdown
Contributor

🚧 @mountiny has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

Copy link
Copy Markdown
Contributor

🧪🧪 Use the links below to test this adhoc build on Android, iOS, Desktop, and Web. Happy testing! 🧪🧪
Built from App PR #70382.

Android 🤖 iOS 🍎
⏩ SKIPPED ⏩ ⏩ SKIPPED ⏩
The build for Android was skipped The build for iOS was skipped
Desktop 💻 Web 🕸️
⏩ SKIPPED ⏩ https://70382.pr-testing.expensify.com
The build for Desktop was skipped Web

👀 View the workflow run that generated this build 👀

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/inimaga in version: 9.2.16-0 🚀

platform result
🖥 desktop 🖥 success ✅
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 failure ❌

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/roryabraham in version: 9.2.16-14 🚀

platform result
🖥 desktop 🖥 success ✅
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants