Skip to content

Reinitialize Pusher during delegate account transitions - #93265

Merged
iwiznia merged 29 commits into
Expensify:mainfrom
nabi-ebrahimi:fix/delegate-switch-pusher-reinitialization
Jul 1, 2026
Merged

Reinitialize Pusher during delegate account transitions#93265
iwiznia merged 29 commits into
Expensify:mainfrom
nabi-ebrahimi:fix/delegate-switch-pusher-reinitialization

Conversation

@nabi-ebrahimi

@nabi-ebrahimi nabi-ebrahimi commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

This change improves delegate account switching by ensuring Pusher is reinitialized with the correct account context after a delegate connect or disconnect flow. That keeps the app subscribed to the newly active account’s private user channel instead of staying attached to the previous account’s live updates.

During the investigation, it also became clear that the delegate transition and the normal app startup should share the same Pusher bootstrap path. src/libs/Navigation/AppNavigator/AuthScreensInitHandler.tsx now registers a reusable reinitialize handler, and src/libs/actions/Delegate.ts calls requestPusherReinitialize(...) after openApp() with the account details returned by the switch response. That keeps the Pusher setup and user-event subscription logic centralized and avoids relying only on SESSION timing.

To address this, the PR keeps the change focused on the Pusher initialization flow. The updated logic now:

  • disconnects Pusher before clearing delegate-transition state in src/libs/actions/Delegate.ts
  • reinitializes Pusher after openApp() using requestPusherReinitialize(...)
  • passes the switched account’s accountID and email explicitly during delegate connect and disconnect
  • falls back to the current session values in src/libs/Navigation/AppNavigator/AuthScreensInitHandler.tsx when explicit values are not provided
  • logs a warning in src/libs/requestPusherReinitialize.ts when no handler is registered, so missing setup is easier to diagnose

Overall, these changes make delegate switching more reliable by reconnecting live updates through one shared initialization path and ensuring Pusher resubscribes with the correct account information.

Fixed Issues

$ #90694
PROPOSAL: #90694 (comment)

Tests

Preconditions

  • User A has access to a delegated account/User B.
  • User A is logged into the app.
  • Pusher connection is active.
  1. Open the app while logged in as User A.
  2. Switch/connect to the delegated account (User B).
  3. Navigate to any report/chat in the delegated account.
  4. From another device/account, send a new message or trigger an update for the delegated account.
  5. Observe whether the update is received in real time.
  6. Observe that the app should unsubscribe from User A’s pusher channel and subscribe to User B’s pusher channel
  • Verify that no errors appear in the JS console

Offline tests

QA Steps

  1. Sign in to an account that has delegated access configured.
  2. Use the delegate connect flow to switch into a delegator account.
  3. Verify that the app finishes loading and remains subscribed to live updates for the newly active account.
  4. Send a new message or make a report change from the switched account and confirm it appears in the other session.
  5. Switch back using the delegate disconnect flow.
  6. Verify that live updates continue to work after switching back to the original account.
  7. Repeat the same flow on a slower network, such as 3G, to confirm the Pusher reinitialization still happens after the account switch.
  • 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
  • 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 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
    • 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 new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • 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
Screenrecorder-2026-05-21-19-11-24-229.mp4
Android: mWeb Chrome
Screenrecorder-2026-05-22-18-29-02-482.mp4
iOS: Native
IOS.NATIVE.mp4
iOS: mWeb Safari
iosweb.mov
MacOS: Chrome / Safari
Screen.Recording.2026-05-20.at.11.43.33.PM.mov

@nabi-ebrahimi
nabi-ebrahimi requested review from a team as code owners June 11, 2026 08:56
@melvin-bot
melvin-bot Bot requested review from huult and joekaufmanexpensify and removed request for a team June 11, 2026 08:56
@melvin-bot

melvin-bot Bot commented Jun 11, 2026

Copy link
Copy Markdown

@huult 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]

@melvin-bot
melvin-bot Bot requested review from a team and iwiznia and removed request for a team June 11, 2026 08:56
@melvin-bot

melvin-bot Bot commented Jun 11, 2026

Copy link
Copy Markdown

@iwiznia 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]

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 683b5e321a

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/libs/actions/Delegate.ts Outdated
return openApp().then(() => {
if (!CONFIG.IS_HYBRID_APP || !policyID) {
return openApp()
.then(() => initializePusherForDelegateTransition())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid blocking delegate switch on Pusher connection

In delegate transitions launched through DelegatorConnectGate, the returned connect() promise is used to suspend the UI until it resolves, and in HybridApp this chain also gates switchAccount(). Because initializePusherForDelegateTransition() waits on Pusher.init(), which only resolves after a successful Pusher connected event and does not reject on connection/auth failures, users whose Pusher websocket is blocked or unavailable after openApp() succeeds can remain stuck on the loading gate and never complete the account switch. Keep the Pusher reinitialization fire-and-forget or add a timeout/fallback before resolving the delegate transition.

Useful? React with 👍 / 👎.

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.

Hi @huult, thank you for taking the time and review this.
I tried reproducing this by using a delegate transition URL with delegatorEmail and blocking the Pusher websocket in Chrome DevTools, but I couldn’t reproduce the stuck loading state locally.

@huult

huult commented Jun 12, 2026

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
  • 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 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 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)
  • 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)
  • 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.
  • 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
Screen.Recording.2026-06-04.at.10.53.44.mov
Android: mWeb Chrome
Screen.Recording.2026-06-04.at.10.32.20.mov
iOS: HybridApp
Screen.Recording.2026-06-04.at.10.47.45.mov
iOS: mWeb Safari
Screen.Recording.2026-06-04.at.10.51.00.mov
MacOS: Chrome / Safari
Screen.Recording.2026-06-04.at.10.11.27.mov

@huult

huult commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot It looks like the unit test is failing due to an issue unrelated to this PR. Do you have any suggestions on how we should address it?

@MelvinBot

Copy link
Copy Markdown
Contributor

You're right — this failure is unrelated to your PR and looks like a flaky test, not something your changes introduced.

What's failing: OnyxUpdateManagerTest (both the tests/actions and tests/unit copies), with assertions like expect(App.getMissingOnyxUpdates).toHaveBeenCalledTimes(1) getting Received number of calls: 0.

Why it's not your PR: Your PR only touches initializePusher.ts, Delegate.ts, AuthScreensInitHandler.tsx, and InitializePusherTest.ts — none of which are imported by OnyxUpdateManagerTest. Jest isolates modules per test file, so there's no path for these changes to affect that suite. The OnyxUpdateManager tests themselves haven't been modified on main since April.

Suggested way to address it:

  1. Don't change anything in your PR for this — the fix isn't in code you touched.
  2. Re-run the failed test (job 1) and test (job 5) jobs. This suite relies on intricate promise sequencing (queryPromise / beforeValidateAndApplyDeferredUpdates / getMissingOnyxUpdates ordering), which is timing-sensitive and intermittently fails. A re-run usually goes green.
  3. Merge latest main into your branch first, then push, so the re-run happens on the freshest base.
  4. If it still fails after a clean re-run, flag the flaky test in #expensify-open-source (or open a flaky-test issue) so the OnyxUpdateManager maintainers can stabilize it — but that shouldn't block your PR.
Evidence
  • PR changed files: src/libs/actions/initializePusher.ts, src/libs/actions/Delegate.ts, src/libs/Navigation/AppNavigator/AuthScreensInitHandler.tsx, tests/actions/InitializePusherTest.ts.
  • Failing assertions are async call-count checks (getMissingOnyxUpdates/applyUpdates call timing) — a classic flaky pattern, not a deterministic logic break.
  • Multiple unrelated PRs failed the Jest Unit Tests workflow over the same June 11–12 window, several on different tests (e.g. TranslateTest), indicating general suite flakiness during that period rather than a regression specific to this PR.
  • OnyxUpdateManagerTest source is unchanged on main since 2026-04-28.

@huult

huult commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

@iwiznia It's the same flaky test that Melvin mentioned. I think we should create a ticket to track it. Do you have any recommendations on how we should proceed?

@huult huult 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.

@joekaufmanexpensify joekaufmanexpensify 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.

Good for product 👍

@nabi-ebrahimi

Copy link
Copy Markdown
Contributor Author

@iwiznia It's the same flaky test that Melvin mentioned. I think we should create a ticket to track it. Do you have any recommendations on how we should proceed?

Hi @iwiznia, could you please take a look at this comment, when you have a chance? Thanks!

@iwiznia

iwiznia commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Hmmmm but I retried it several times and it failed in all of them, are you sure it's a flakey test and not something we actually broke?

2 similar comments
@iwiznia

iwiznia commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Hmmmm but I retried it several times and it failed in all of them, are you sure it's a flakey test and not something we actually broke?

@iwiznia

iwiznia commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Hmmmm but I retried it several times and it failed in all of them, are you sure it's a flakey test and not something we actually broke?

@huult

huult commented Jun 18, 2026

Copy link
Copy Markdown
Contributor

@nabi-ebrahimi Could you update the code as shown below so we can test it?

await Onyx.clear();
await Onyx.set(ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT, 1);
await Onyx.set(ONYX_KEY, initialData);

+      await Onyx.set(ONYXKEYS.IS_LOADING_APP, false);
        await Onyx.set(ONYXKEYS.ONYX_UPDATES_LAST_UPDATE_ID_APPLIED_TO_CLIENT, 1);
        await Onyx.set(ONYX_KEY, initialData);
+      await waitForBatchedUpdates();

@nabi-ebrahimi

Copy link
Copy Markdown
Contributor Author

Hi @huult, thank you for the review. We are still testing this approach locally to confirm the delegate Pusher reinitialization behaves correctly across different network conditions. I will share the updated results once verification is complete.

iwiznia
iwiznia previously approved these changes Jun 30, 2026
@huult

huult commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

@nabi-ebrahimi Thanks! Let me know when it’s ready

@nabi-ebrahimi

Copy link
Copy Markdown
Contributor Author

@nabi-ebrahimi Thanks! Let me know when it’s ready

Hi @huult, I tested this PR across different devices and network conditions, and it worked as expected. Thanks.

@huult

huult commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

@nabi-ebrahimi Please update the PR description based on the latest changes.

@nabi-ebrahimi You haven't updated the explanation to reflect the latest changes. Could you please update it?

@huult

huult commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

@nabi-ebrahimi Please update the QA steps.

Comment thread src/libs/requestPusherReinitialize.ts Outdated
@huult

huult commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

@nabi-ebrahimi I've left a few minor comments. Could you address them today? I'll approve the PR once those are addressed.

@nabi-ebrahimi

Copy link
Copy Markdown
Contributor Author

@huult, thank you. I’ve addressed all of your feedback.

@huult

huult commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

@iwiznia all yours

@iwiznia
iwiznia merged commit cdecccf into Expensify:main Jul 1, 2026
35 checks passed
@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

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

@OSBotify

OSBotify commented Jul 1, 2026

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.

@m-natarajan

Copy link
Copy Markdown

@nabi-ebrahimi @iwiznia How to configure a delegated access?

@OSBotify

OSBotify commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/iwiznia in version: 9.4.26-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 Help site review: no changes required.

This PR is a purely internal fix to how the Pusher (real-time updates) connection is reinitialized during Copilot/delegate account transitions. It changes only the connection-management infrastructure in three src/libs files — it does not add, remove, or change any user-facing feature, setting, tab, label, button, or workflow.

The public help articles that cover this area document the workflow (assigning and switching to delegated accounts), not the underlying real-time connection behavior:

  • new-expensify/settings/Delegate-when-out-of-office.md
  • expensify-classic/copilots-and-delegates/Assign-or-remove-a-Copilot.md
  • expensify-classic/copilots-and-delegates/Delegate-when-out-of-office.md

From a reader's perspective the documented behavior is unchanged — this fix simply ensures live updates keep working after a switch, which is already the implicitly expected behavior. So there's nothing to update, and no draft PR was created.

If you feel a specific article's wording should change as a result of this fix, reply with the article and what you'd like updated and I'll open a draft PR.

@iwiznia

iwiznia commented Jul 2, 2026

Copy link
Copy Markdown
Contributor

@nabi-ebrahimi @iwiznia How to configure a delegated access?

Go to Account > Copilot
image

@OSBotify

OSBotify commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/grgia in version: 9.4.27-2 🚀

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

Bundle Size Analysis (Sentry):

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.

8 participants