Skip to content

Guard pending chat members against missing account IDs - #96747

Merged
mountiny merged 6 commits into
Expensify:mainfrom
wildan-m:wildan/95348-pending-chat-members-undefined-toString
Aug 4, 2026
Merged

Guard pending chat members against missing account IDs#96747
mountiny merged 6 commits into
Expensify:mainfrom
wildan-m:wildan/95348-pending-chat-members-undefined-toString

Conversation

@wildan-m

@wildan-m wildan-m commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

A crash reaches Sentry from the report route as an unhandled promise rejection: TypeError: undefined is not an object (evaluating 'p.toString'). The helper that assembles a report's pending chat members converts each incoming account ID to a string without first checking that the ID is there. Its parameter is declared as a list of numbers, but nothing enforces that at runtime — the member add and remove flows derive those IDs from personal-detail lookups, and an entry that has not finished loading contributes a missing value. Converting that missing value throws, and because the member actions are dispatched from optimistic-update code the throw surfaces as an unhandled rejection instead of a render error, which is why the production stack has no useful frame.

Dropping the missing IDs before the conversion removes the only expression that can throw, and it also keeps a member entry with an empty account ID out of the report's metadata — the alternative of falling back to an empty string would have stored one. Putting the guard in the shared helper rather than at each call site covers the room invite and removal flows and the workspace member flows uniformly, and it leaves behavior for well-formed input unchanged.

Fixed Issues

$ #95348
PROPOSAL: #95348 (comment)

Tests

The Sentry report has no reproduction steps — the failure depends on a personal-detail entry that has not finished loading, so it cannot be triggered on demand. The unit tests added in this PR cover the missing-ID case directly (they throw the same TypeError without this change). The steps below confirm the member flows that call the helper are unaffected:

  1. Sign in, open Workspaces, select a workspace, and open Members.
  2. Click Invite member, select any contact, click Next, then Invite.
  3. Verify the invited member appears in the list, the total member count increases, and no error appears in the JS console.
  4. Tick the invited member's checkbox, open the selection dropdown, choose Remove member, and confirm.
  5. Verify the member disappears from the list, the workspace chat reports the member as removed, and no error appears in the JS console.
  6. Open a room from the Inbox, open its member list, invite and then remove a member, and verify the list updates the same way with a clean console.

Direct check of the guard (console script)

Because the crash depends on runtime data that cannot be produced on demand through the UI, this script calls the real bundled getPendingChatMembers out of the running dev build and hands it a missing account ID. It is the same script on both branches — only the result differs. It must be run against a local dev build (npm run web): minified staging/production bundles omit the module cache and mangle export names, so the script cannot reach the function there and will say so rather than fail silently.

Open any chat (so ReportUtils is loaded), then paste this into the DevTools console:

(() => {
    const candidates = Object.keys(window).filter((k) => /^(rspack|webpack)Chunk/.test(k) && Array.isArray(window[k]));
    if (!candidates.length) {
        return 'FAILED: no bundler registry on this page. Run against a local dev build (npm run web).';
    }
    let fn = null;
    let sawModuleCache = false;
    for (const key of candidates) {
        let req;
        try {
            window[key].push([['probe_' + Math.random()], {}, (r) => { req = r; }]);
        } catch (e) {
            continue;
        }
        // Minified staging/production builds expose the require fn but omit the module cache.
        // Browser extensions register their own chunk globals too, so try every candidate.
        if (!req || !req.c) {
            continue;
        }
        sawModuleCache = true;
        for (const id of Object.keys(req.c)) {
            const ex = req.c[id] && req.c[id].exports;
            if (!ex) continue;
            try {
                if (typeof ex.getPendingChatMembers === 'function') { fn = ex.getPendingChatMembers; break; }
            } catch (e) { /* some exports are getters that throw */ }
        }
        if (fn) break;
    }
    if (!fn) {
        return sawModuleCache
            ? 'FAILED: getPendingChatMembers is not loaded yet. Open any chat, then re-run.'
            : 'FAILED: no module cache on this page, so this is a minified build (staging or production) — export names are mangled there. Run against a local dev build: npm run web.';
    }
    const run = (ids) => {
        try { return JSON.stringify(fn(ids, [], 'add')); } catch (e) { return e.name + ': ' + e.message; }
    };
    const control = run([101, 102]);
    const missing = run([101, undefined, 102]);
    const crashed = missing.indexOf('TypeError') === 0;
    console.log('control [101, 102]            -> ' + control);
    console.log('repro   [101, undefined, 102] -> ' + missing);
    return crashed ? 'CRASHES — unpatched (this is main)' : 'NO CRASH — guard present (this is the PR branch)';
})()

On main it returns CRASHES — unpatched (this is main) and logs:

control [101, 102]            -> [{"accountID":"101","pendingAction":"add"},{"accountID":"102","pendingAction":"add"}]
repro   [101, undefined, 102] -> TypeError: Cannot read properties of undefined (reading 'toString')

On this branch it returns NO CRASH — guard present (this is the PR branch) and logs:

control [101, 102]            -> [{"accountID":"101","pendingAction":"add"},{"accountID":"102","pendingAction":"add"}]
repro   [101, undefined, 102] -> [{"accountID":"101","pendingAction":"add"},{"accountID":"102","pendingAction":"add"}]

The control case passing on both builds is the point — the only behavioural difference is the missing-ID case. The TypeError text above is Chrome's wording; Safari words the same error undefined is not an object (evaluating 'p.toString'), which is the form recorded in Sentry.

Scope note: this exercises the guard directly by passing the value in. It does not demonstrate the app producing that state on its own, and the reporting Sentry stack is minified, so it is not proof that this helper is the frame that crashed for the reporter.

Platform scope — the console script is web-only. It reaches the function through the dev build's bundler module registry, which only a local web dev build exposes. It will not run on Android or iOS native (those bundle through Metro, with no such registry), and it will not run against staging or production (minified builds omit the module cache and mangle export names — the script detects this and says so rather than failing silently).

Nothing about the change is platform-specific: it is a single null check in shared TypeScript that executes identically on every platform, with no UI, styling, or native code involved. So on the other platforms there is nothing extra to reproduce — the numbered steps above are the whole check. Invite a member and then remove one, and confirm the member list and the workspace chat's system message still behave exactly as they do today. The unit tests added in this PR cover the missing-ID case itself on every platform, since they run in the shared Jest suite.

  • Verify that no errors appear in the JS console

Offline tests

The change touches only the optimistic pending-member list and adds no network calls. Inviting or removing a member while offline queues the action and shows the member in the pending state exactly as it did before.

QA Steps

Do not run the console script from the Tests section — that is a developer-only check that needs a local dev build. For QA this is purely a regression check on the member flows, since the change is a defensive guard with no visible behaviour of its own:

  1. Sign in, open Workspaces and select a workspace, then open Members.
  2. Click Invite member, select any contact, click Next, then Invite.
  3. Verify the invited member appears in the list with the correct role and the total member count increases.
  4. Tick that member's checkbox, open the selection dropdown, choose Remove member, and confirm.
  5. Verify the member disappears from the list, the total count returns to its previous value, and the workspace chat reports the member as removed.
  6. Open a room from the Inbox, open its member list, invite and then remove a member, and verify the list updates the same way.

Everything above should behave exactly as it does on production — there is no user-visible change to look for.

  • 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 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 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)
  • 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.
  • 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
Kapture.2026-07-26.at.16.26.28.mp4
Android: mWeb Chrome
Kapture.2026-07-26.at.16.26.28.mp4
iOS: Native
Kapture.2026-07-26.at.00.15.59.mp4
iOS: mWeb Safari
Kapture.2026-07-26.at.00.17.22.mp4
MacOS: Chrome / Safari
Kapture.2026-07-25.at.23.18.52-compressed.mp4

@wildan-m
wildan-m marked this pull request as ready for review July 26, 2026 09:34
@wildan-m
wildan-m requested review from a team as code owners July 26, 2026 09:34
@melvin-bot

melvin-bot Bot commented Jul 26, 2026

Copy link
Copy Markdown

@eVoloshchak 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 removed request for a team and JmillsExpensify July 26, 2026 09:34

@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: 01e11450b2

ℹ️ 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/ReportUtils.ts
*/
function getPendingChatMembers(accountIDs: number[], previousPendingChatMembers: PendingChatMember[], pendingAction: PendingAction): PendingChatMember[] {
const pendingChatMembers = accountIDs.map((accountID) => ({accountID: accountID.toString(), pendingAction}));
const pendingChatMembers = accountIDs.filter((accountID) => accountID != null).map((accountID) => ({accountID: accountID.toString(), pendingAction}));

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 Filter missing IDs before building room updates

When a room/group-chat invite contains the runtime undefined value this change is intended to tolerate, filtering only inside getPendingChatMembers is too late: buildInviteToRoomOnyxData has already written that value as the "undefined" participant key, and the missing invitee receives no pending-member entry that can later carry an API error. The action now proceeds instead of throwing, leaving malformed optimistic participant data and no visible failure feedback for the affected invitee; sanitize the invite mapping/account-ID list before any optimistic data is constructed.

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.

Good catch — fixed in e7ee2f2.

You're right that the helper-level filter ran too late: participantsAfterInvitation is built before getPendingChatMembers, and a missing account ID lands in the participants map as the literal "undefined" key. Worth noting the sharper version of this — before this PR the throw aborted the whole action so nothing was persisted, whereas afterwards the write proceeds, so the fix would have newly persisted that malformed key.

The invitee account IDs are now filtered where they're derived, before any optimistic data is constructed. This covers group chats too, since inviteToGroupChat delegates to inviteToRoom. I deliberately left inviteeEmails untouched so the invite still reaches the server and the real account ID gets reconciled — filtering the emails as well would have silently dropped the invitee instead, which trades malformed data for a missing invite.

The guard inside the helper stays as defence in depth for the other callers.

@eVoloshchak

Copy link
Copy Markdown
Contributor

LGTM!
@wildan-m, looks like Android screen recording is missing, could you include it too please?

@wildan-m

Copy link
Copy Markdown
Contributor Author

@eVoloshchak slipped that one. added.

@eVoloshchak

eVoloshchak commented Jul 30, 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 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
    • 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
    • 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 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-20260802-234210-1785706876834.mp4
Android: mWeb Chrome
Screen.Recording.2026-08-02.at.23.33.06.mov
iOS: HybridApp
Screen.Recording.2026-08-02.at.23.30.53.mov
iOS: mWeb Safari
Screen.Recording.2026-08-02.at.23.28.48.mov
Screen.Recording.2026-08-02.at.23.28.04.mov
MacOS: Chrome / Safari
Screen.Recording.2026-08-02.at.23.26.51.mov

@eVoloshchak eVoloshchak 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!

@melvin-bot
melvin-bot Bot requested a review from mountiny August 2, 2026 21:43
@mountiny
mountiny merged commit 7979c09 into Expensify:main Aug 4, 2026
36 of 37 checks passed
@github-actions

github-actions Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

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

@OSBotify

OSBotify commented Aug 4, 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.

@OSBotify

OSBotify commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 9.4.50-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor

🤖 No help site changes required.

I reviewed the changes in this PR against the help articles under docs/articles, and no documentation updates are needed — so I did not create a draft PR.

Why: This is a purely defensive bug fix with no user-visible behavior change. It adds an accountID != null guard in two spots so a not-yet-loaded personal detail can no longer contribute a missing account ID:

  • getPendingChatMembers in ReportUtils.ts filters out missing IDs before .toString().
  • buildInviteToRoomOnyxData in actions/Report/index.ts drops missing account IDs before building optimistic participant data.

The PR description confirms it: "there is no user-visible change to look for" and "Everything above should behave exactly as it does on production." The invite-member and remove-member flows for both workspaces and rooms behave identically to today. The help site documents customer-facing features and workflows, none of which change here, so there is nothing to add or amend.

If you believe a specific article's described behavior is affected, let me know which one and I'll take another look.

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.

5 participants