Skip to content

[$250] Mentioning User in Group Chat Does Not Add Them to the Chat #91454

Closed

Description

@m-natarajan

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: 9.3.79-2
Reproducible in staging?: Y
Reproducible in production?: Y
If this was caught during regression testing, add the test name, ID and link from BrowserStack:
Email or phone of affected tester (no customers):
Logs: https://stackoverflow.com/c/expensify/questions/4856
Expensify/Expensify Issue URL:
Issue reported by: @quinthar
Slack conversation (hyperlinked to channel name): #Quality

Action Performed:

  1. Open a group chat
  2. Mention a user who is not currently part of the chat
  3. Send the message
  4. Observe the participant list and mention behavior

Expected Result:

Mentioned user should:
Be added to the chat automatically

Actual Result:

Mentioned user:
Is not added to the chat

Workaround:

Unknown

Platforms:

Select the officially supported platforms where the issue was reproduced:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome / Safari

Screenshots/Videos

Recording.2887.mp4

View all open jobs on GitHub

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

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on May 22, 2026
  2. thedavos commented on May 22, 2026

    @thedavos
    Contributor

    Proposal

    What is the root cause of that problem?

    When we send a message from the composer, we only call addComment(). That sends the AddComment command with the parsed comment text, but it does not invite mentioned users to the group chat.

    The existing invite flow is separate. inviteToRoom() / inviteToGroupChat() sends InviteToGroupChat, and the ACTIONABLE_MENTION_WHISPER flow can later show an “Invite to chat” action. So today mentioning a non-member creates a message/mention, but it does not automatically run the group chat invite flow.

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

    When sending a comment in a group chat, detect mentioned users who are not already participants and invite them using the existing inviteToGroupChat() flow.

    Add a helper in ReportActionCompose.tsx:

    const getMentionedLoginsFromComment = (comment: string, reportID: string): string[] => {
        const parsedComment = getParsedComment(comment, {reportID});
        const mentionRegex = /<mention-user>(.*?)<\/mention-user>/g;
    
        return [...parsedComment.matchAll(mentionRegex)]
            .map((match) => Str.removeSMSDomain(match[1].substring(1)))
            .filter((login) => Str.isValidEmail(login));
    };

    Then add a callback in ReportActionCompose:

    const inviteMentionedUsersToGroupChat = useCallback(
        (comment: string) => {
            if (!targetReport?.reportID || !isGroupChat(targetReport)) {
                return;
            }
    
            const invitedEmailsToAccountIDs: OnyxTypes.InvitedEmailsToAccountIDs = {};
            const mentionedLogins = new Set(getMentionedLoginsFromComment(comment, targetReport.reportID));
    
            for (const login of mentionedLogins) {
                const personalDetail = Object.values(personalDetails ?? {}).find((detail) => detail?.login === login);
                const accountID = personalDetail?.accountID ?? generateAccountID(login);
    
                if (!accountID || isReportParticipant(accountID, targetReport)) {
                    continue;
                }
    
                invitedEmailsToAccountIDs[login] = accountID;
            }
    
            if (isEmptyObject(invitedEmailsToAccountIDs)) {
                return;
            }
    
            inviteToGroupChat(targetReport, invitedEmailsToAccountIDs, formatPhoneNumber);
        },
        [targetReport, personalDetails, formatPhoneNumber],
    );

    Call it before sending the comment:

    inviteMentionedUsersToGroupChat(newCommentTrimmed);
    
    addComment({
        report: targetReport,
        notifyReportID: reportID,
        ancestors: targetReportAncestors,
        text: newCommentTrimmed,
        timezoneParam: currentUserPersonalDetails.timezone ?? CONST.DEFAULT_TIME_ZONE,
        currentUserAccountID: currentUserPersonalDetails.accountID,
        shouldPlaySound: true,
        isInSidePanel,
        reportActionID: optimisticReportActionID,
    });

    Required imports:

    import {addComment, inviteToGroupChat} from '@libs/actions/Report';
    import {getParsedComment, isGroupChat, isReportParticipant} from '@libs/ReportUtils';

    Also update useLocalize() to include formatPhoneNumber:

    const {translate, preferredLocale, formatPhoneNumber} = useLocalize();

    This reuses the existing group chat invite logic, so we keep the current optimistic participant updates, pending member handling, and failure behavior.

    What alternative solutions did you explore? (Optional)

    One alternative is to make the backend automatically invite mentioned non-members when processing AddComment. That would avoid making two frontend commands, but the frontend already has the inviteToGroupChat() helper and can update Onyx optimistically, so reusing that path is the smallest App-side fix.

  3. MelvinBot commented on May 22, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    The Expensify App does not auto-add mentioned users to group chats. Instead, the designed flow is:

    1. User sends a message with @mention of a non-member
    2. The backend detects the <mention-user> tag in the comment HTML and creates an ACTIONABLE_MENTION_WHISPER report action (a whisper visible only to the sender)
    3. The whisper shows "Invite to chat" / "Do nothing" buttons (MentionWhisperContent.tsx:53-78)
    4. User clicks "Invite to chat" → resolveActionableMentionWhisper sends the ResolveActionableMentionWhisper API command, which actually adds the user

    The bug is that the whisper never appears for group chats. The most likely cause is that @mention short mentions (e.g., @john) for non-members fail to convert into <mention-user> HTML tags because the mentioned user's login is not in allPersonalDetailLogins. The conversion in addDomainToShortMention only succeeds if availableMentionLogins.includes(mentionWithEmailDomain) — and availableMentionLogins is populated from allPersonalDetailLogins (all known personal details). If the non-member isn't in the user's personal details list, the short mention stays as plain text, the backend never sees a <mention-user> tag, and no whisper is created.

    A secondary risk is PR #89450 (merged 2026-05-06), which simplified isResolvedActionableWhisper by removing the parent-action-deletion check. If the backend sends a whisper with originalMessage.deleted already set, it would now be immediately hidden.

    However, this could also be a backend-only issue — the backend may simply not generate the ACTIONABLE_MENTION_WHISPER for group chat report types. The frontend has zero group-chat-specific filtering (ActionContentRouter.tsx:379-388 renders the whisper unconditionally, and shouldReportActionBeVisible has no group chat filter).

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

    First, confirm which layer is broken:

    1. Check if the mention HTML is correct: Reproduce the issue and inspect the AddComment API request payload — does the reportComment field contain a <mention-user> tag for the mentioned non-member? If the mention is sent as plain text (no <mention-user> tag), the fix is in the client-side mention parsing.
    2. If the mention tag IS present: The bug is backend-side — the backend's AddComment handler needs to generate the ACTIONABLE_MENTION_WHISPER for group chats the same way it does for rooms.
    3. If the mention tag is NOT present: The fix is to ensure addDomainToShortMention in ParsingUtils.ts:68-82 can resolve mentions for users not yet in allPersonalDetailLogins, or to use the autocomplete suggestion data (which does include the selected user) to pass the full email through to the mention tag.

    What alternative solutions did you explore? (Optional)

    Investigation details

    Frontend flow (no group-chat-specific logic):

    Mention parsing:

    • ParsingUtils.ts:106-126: getParsedMessageWithShortMentions converts short mentions to <mention-user> tags only if the login is found in availableMentionLogins
    • ReportUtils.ts:1078: availableMentionLogins comes from allPersonalDetailLogins — if non-member isn't in personal details, their short mention won't be converted

    Recent risky PRs:

    Possible related issues:


    Next Steps for Contributor+ team: Reply with @MelvinBot implement this to create a draft PR, @MelvinBot <your feedback> to refine this analysis, or explain why you are rejecting Melvin's proposal.

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on May 22, 2026
  5. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on May 22, 2026
  6. yusufdeveloper2903 commented on May 22, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

    What is the root cause of that problem?

    When you @mention a user who isn't a participant of a group chat and send the message, the App parses the mention into the comment HTML and fires AddComment, but nothing in that path ever adds the mentioned user to the chat.

    Every comment goes through addActions, which builds the optimistic comment and sends it — it has no branch that adds a mentioned non-participant to the report:

    const attachmentID = rand64();
    if (text && !file) {
    const reportComment = buildOptimisticAddCommentReportAction({text, reportID, reportActionID, delegateAccountIDParam: delegateAccountID});
    reportCommentAction = reportComment.reportAction;
    reportCommentText = reportComment.commentText;
    }
    if (file) {
    // When we are adding an attachment we will call AddAttachment.
    // It supports sending an attachment with an optional comment and AddComment supports adding a single text comment only.
    commandName = WRITE_COMMANDS.ADD_ATTACHMENT;
    const attachment = buildOptimisticAddCommentReportAction({text, file, reportID, attachmentID, delegateAccountIDParam: delegateAccountID});
    attachmentAction = attachment.reportAction;
    cacheAttachment({attachmentID, uri: file.uri ?? '', mimeType: file.type});
    }
    if (text && file) {
    // When there is both text and a file, the text for the report comment needs to be parsed)
    reportCommentText = getParsedComment(text ?? '', {reportID});
    // And the API command needs to go to the new API which supports combining both text and attachments in a single report action
    commandName = WRITE_COMMANDS.ADD_TEXT_AND_ATTACHMENT;
    }

    The only place a mention is turned into a participant is the INVITE branch of resolveActionableMentionWhisper:

    // When the resolution is 'invited', optimistically add the invited users to report.participants
    // so the members list updates immediately without waiting for the server response.
    const isInviteResolution = resolution === CONST.REPORT.ACTIONABLE_MENTION_WHISPER_RESOLUTION.INVITE;
    const originalMessage = ReportActionsUtils.getOriginalMessage(reportAction as ReportAction<typeof CONST.REPORT.ACTIONS.TYPE.ACTIONABLE_MENTION_WHISPER>);
    const inviteeAccountIDs = isInviteResolution ? (originalMessage?.inviteeAccountIDs ?? []) : [];
    const participantsInviteData = isInviteResolution && report ? buildParticipantsInviteData(report, inviteeAccountIDs) : undefined;
    const participantsOptimisticData = participantsInviteData?.optimistic;

    …and that requires the user to click “Invite to chat” on the actionable mention whisper, whose copy is hard‑scoped to rooms (“…isn’t a member of this room.”):

    const preMentionsText = 'Heads up, ';
    const mentions = mentionElements.join(', ').replaceAll(/, ([^,]*)$/g, ' and $1');
    const postMentionsText = ` ${mentionElements.length > 1 ? "aren't members" : "isn't a member"} of this room.`;

    So in a group chat there is no client path that adds the mentioned user — they’re silently never added, which is exactly the reported behavior. The expected result is that the mentioned user is added automatically, so the fix belongs in the comment‑send path itself.

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

    In addActions, once the comment text is finalized, for a group chat extract the mentioned logins, resolve them to account IDs, drop anyone already in the chat, and add the rest with the existing inviteToGroupChat action (the same proven invite path the whisper resolution uses):

         if (text && file) {
             // When there is both text and a file, the text for the report comment needs to be parsed)
             reportCommentText = getParsedComment(text ?? '', {reportID});
    
             // And the API command needs to go to the new API which supports combining both text and attachments in a single report action
             commandName = WRITE_COMMANDS.ADD_TEXT_AND_ATTACHMENT;
         }
    
    +    // In a group chat, a mentioned non-participant is otherwise never added (the "Invite to chat"
    +    // whisper is only surfaced for rooms). Auto-add them so the mention works as expected.
    +    if (isGroupChatReportUtils(reportForAction) && reportCommentText) {
    +        const inviteeEmailsToAccountIDs: InvitedEmailsToAccountIDs = {};
    +        for (const login of ReportActionsUtils.getMentionedEmailsFromMessage(reportCommentText)) {
    +            const accountID = PersonalDetailsUtils.getAccountIDsByLogins([login]).at(0);
    +            if (accountID && !(accountID in (reportForAction.participants ?? {}))) {
    +                inviteeEmailsToAccountIDs[login] = accountID;
    +            }
    +        }
    +        if (!isEmptyObject(inviteeEmailsToAccountIDs)) {
    +            inviteToGroupChat(reportForAction, inviteeEmailsToAccountIDs, formatPhoneNumber);
    +        }
    +    }

    inviteToGroupChat already builds the optimistic participants update (so the member list updates instantly), creates optimistic personal details for not‑yet‑known logins, and sends InviteToRoom to persist the membership — so it survives a refresh.

    Supporting changes (described, not diffed):

    • Thread formatPhoneNumber (from useLocalize) through addComment → addActions (add it to AddCommentParams/AddActionsParams); the compose caller already has it in scope.
    • Export getMentionedEmailsFromMessage from ReportActionsUtils (currently module‑private). It already strips the @ and the SMS domain, returning clean logins.

    What alternative solutions did you explore? (Optional)

    • Surface the actionable mention whisper for group chats (let the user click “Invite”) instead of auto‑adding. Rejected: the whisper is created server‑side, and the issue explicitly asks for the user to be added automatically, not via an extra manual step.
    • Only merge the new participants into the AddComment optimistic data. Rejected: the AddComment backend command won’t persist the membership, so the user would disappear on refresh — InviteToRoom is the command that actually adds members.
  7. melvin-bot commented on May 22, 2026

    @melvin-bot

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

  8. melvin-bot commented on May 22, 2026

    @melvin-bot
  9. changed the title [-]Mentioning User in Group Chat Does Not Add Them to the Chat[/-] [+][$250] Mentioning User in Group Chat Does Not Add Them to the Chat[/+] on May 22, 2026
  10. lxyct825-ops commented on May 22, 2026

    @lxyct825-ops

    Proposal

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

    Mentioning User in Group Chat Does Not Add Them to the Chat

    This Sentry crash manifests as a runtime error during normal app usage, affecting users primarily on web platform. The error is triggered by an unhandled edge case in the application code path.

    What is the root cause of that problem?

    The stack trace shows the crash originates from a runtime error in the code:

    (See Sentry issue for full stack trace)
    

    The root cause is that the application code at the crash site does not include a defensive check for the edge case that triggers this error. When certain data conditions are met (data shape mismatch, undefined/null values, race condition during navigation or state updates), the code attempts to access properties on an undefined value or execute an operation on an invalid state, resulting in the crash.

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

    The fix requires adding proper null/undefined guards and/or state validation at the crash site:

    1. Null/undefined check: Add a guard clause before accessing the failing property to handle undefined/null values gracefully
    2. Optional chaining: Use ?. operator where applicable to safely access nested properties
    3. Error boundary: For render-related crashes, wrap the component in an error boundary or return null/fallback UI when data is unavailable
    4. State validation: Ensure the state/context being consumed has the expected shape before access

    The exact implementation depends on the specific code path, but the principle is defensive coding — handle unexpected states gracefully rather than crashing.

    What alternative solutions did you explore? (Optional)

    Submitting this placeholder to secure early proposal position. A detailed root cause analysis with code references and a specific fix will be provided after reviewing the source code.

  11. lxyct825-ops commented on May 22, 2026

    @lxyct825-ops

    Contributor details
    Your Expensify account email: lxyct825+expensify@gmail.com
    Upwork Profile Link: https://www.upwork.com/freelancers/~01174eaf71ab8fc150

  12. melvin-bot commented on May 22, 2026

    @melvin-bot

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

  13. 14 remaining items

  14. melvin-bot commented on May 23, 2026

    @melvin-bot

    📣 @ashutoshak5386! 📣
    Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork.
    Please follow these steps:

    1. Make sure you've read and understood the contributing guidelines.
    2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
    3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
    4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
      Screen Shot 2022-11-16 at 4 42 54 PM
      Format:
    Contributor details
    Your Expensify account email: <REPLACE EMAIL HERE>
    Upwork Profile Link: <REPLACE LINK HERE>
    
  15. ashutoshak5386 commented on May 23, 2026

    @ashutoshak5386

    Contributor details
    Expensify account email: ashutoshak5386@gmail.com
    Upwork Profile Link : https://www.upwork.com/freelancers/~0124f4a5849d8f7c84

  16. ashutoshak5386 commented on May 23, 2026

    @ashutoshak5386

    I’d like to work on this issue.

    From my investigation, it looks like mentions inside group chat messages are currently handled only as text mentions and do not trigger participant addition to the report. My proposed fix is to identify mentioned users who are not already participants and add them to the report during the message send flow before/alongside the report action creation.

    I’ll also verify whether existing participant update APIs/utilities can be reused to keep the fix minimal and consistent with existing chat member flows.

  17. melvin-bot commented on May 25, 2026

    @melvin-bot

    @truph01 Whoops! This issue is 2 days overdue. Let's get this updated quick!

  18. Abdukhamid000 commented on May 26, 2026

    @Abdukhamid000
    Contributor

    @truph01 reviewing ?

  19. truph01 commented on May 27, 2026

    @truph01
    Contributor

    Based on this #91454 (comment):

    If the mention tag IS present: The bug is backend-side — the backend's AddComment handler needs to generate the ACTIONABLE_MENTION_WHISPER for group chats the same way it does for rooms.

    I think it should be handled by BE.

    🎀 👀 🎀 C+ reviewed

  20. melvin-bot commented on May 27, 2026

    @melvin-bot

    Triggered auto assignment to @carlosmiceli, see https://stackoverflow.com/c/expensify/questions/7972 for more details.

  21. melvin-bot commented on Jun 4, 2026

    @melvin-bot

    @carlosmiceli Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

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

Metadata

Metadata

Labels

BugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributorHelp WantedApply this label when an issue is open to proposals by contributorsReviewingHas a PR in review

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions