[$250] Members - Removed user with secondary login is shown as "already a member" in search list
If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!
Version Number: v9.5.36-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from TestRail: https://github.com/Expensify/Expensify/issues/579751 Email or phone of affected tester (no customers): N/A Issue reported by: Applause Internal Team
Action Performed:
- Go to staging.new.expensify.com
- Go to workspace settings > Members.
- Invite a member using their secondary login.
- Click Invite member.
- Enter the secondary login of the invited member.
- Close the RHP.
- Remove the invited member.
- Click Invite member.
- Enter the secondary login of the invited member.
Expected Result:
The removed user will appear in the search list.
Actual Result:
The removed user does not appear in the search list. It shows that the removed user is already a member of the workspace when the user has been removed.
Workaround:
N/A
Platforms:
- [ ] Android: App
- [ ] Android: mWeb Chrome
- [ ] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [ ] Windows: Chrome
- [x] MacOS: Chrome / Safari
Screenshots/Videos
https://github.com/user-attachments/assets/3db9d799-a595-4207-afcd-5856a0087ee0
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022120517466941292149
- Upwork Job ID: 2120517466941292149
- Last Price Increase: 2026-12-01
Triggered auto assignment to Contributor-plus team member for initial proposal review - @FitseTLT (External)
Job added to Upwork: https://www.upwork.com/jobs/~022120517466941292149
🤖 Web test steps verification results: ⚠️ partial
Blocked on dev NewDot web: no account with a verified secondary login was available. No substitute email was invited, and no product failure was observed.
| Step | Status |
|---|---|
Open workspace settings > MembersCreated a workspace and reached its invite panel, but not Members settings.![]() |
⚠️ |
Invite a member using their secondary loginBlocked: verified secondary-login fixture unavailable. No invitation sent. |
⚠️ |
Click Invite member againNot executed because the invitation was blocked. |
⚠️ |
Search the invited secondary loginNot executed: required fixture unavailable. |
⚠️ |
Close the RHPNot executed in the requested post-search state. |
⚠️ |
Remove the invited memberNo fixture member was invited. |
⚠️ |
Click Invite member again after removalNot executed in the requested post-removal state. |
⚠️ |
Search the secondary login and verify reinvitation is availableBlocked by the missing fixture; behavior remains unverified. |
⚠️ |
Preliminary analysis
⚠️ Low confidence in the complete root cause. The code explains the displayed message, but not why the reported sequence leaves the offending state.
Likely mechanism: A secondary-login entry remains in the workspace’s employee list after removal. Invite search treats that entry as membership—even if its value is an empty object.
Code evidence and hypothesis challenge
- The exact “already a member” message comes from current employee-list exclusions, not a remembered search result: DynamicWorkspaceInvitePage.tsx:203–216.
- The exclusion helper accepts empty employee entries, skipping only pending deletions and entries with errors: members.ts:210–225. An existing test documents empty secondary-login artifacts: WorkspaceMembersTest.tsx:634–657.
- Counterevidence: The reported release already expands removal to include the secondary login when
primaryLoginsInvitedcontains its pairing: Member.ts:398–426. Simply adding alias cleanup would duplicate existing behavior. - No client-side mapping cleanup was found in the intermediate open/search/close flow. Server responses clearing the pairing or reintroducing an alias remain unverified alternatives.
Required confirmation: With a verified secondary-login fixture, capture employeeList, primaryLoginsInvited, and response Onyx updates before and after the intermediate search, removal, and final reopening. This distinguishes an alias that was never deleted from one restored afterward. A specific code fix is not yet justified.
Possibly related: Secondary login can not be removed from workspace members reports overlapping removal symptoms; duplication is not confirmed.
Next Steps: Provide the verified secondary-login fixture or a sanitized state/response trace to establish the missing causal step.
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a workspace member is invited using their secondary login and later removed from the workspace, searching for that secondary login in the "Invite member" search list does not show the user. Instead, the UI displays the message that the user is "already a member" of the workspace.
What is the root cause of that problem?
-
In
src/pages/workspace/DynamicWorkspaceInvitePage.tsx(lines 85–92):const ineligibleInvites = getIneligibleInvitees(policy?.employeeList); const excludedUsers = ineligibleInvites.reduce( (acc, login) => { acc[login] = true; return acc; }, {} as Record<string, boolean>, );The
excludedUsersmap for invite search is computed directly fromgetIneligibleInvitees(policy?.employeeList). When typing in the search box, lines 210–213 evaluate:} else if ( excludedUsers[parsePhoneNumber(appendCountryCode(searchValue, countryCode)).possible ? addSMSDomainIfPhoneNumber(appendCountryCode(searchValue, countryCode)) : searchValue] ) { headerMessage = translate('messages.userIsAlreadyMember', searchValue, policyName); }and
usePersonalDetailSearchSelectorsuppresses the user from the available options viaexcludeLogins: excludedUsers. -
In
src/libs/PolicyUtils/members.ts(lines 210–226):function getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] { const policyEmployeeList = employeeList ?? {}; const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS]; for (const email of Object.keys(policyEmployeeList)) { const policyEmployee = policyEmployeeList?.[email]; // Policy members that are pending delete or have errors are not valid and we should show them in the invite options (don't exclude them). if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) { continue; } if (!email) { continue; } memberEmailsToExclude.push(email); } return memberEmailsToExclude; }getIneligibleInviteesloops through all keys inpolicyEmployeeListand only skips entries ifpendingAction === 'delete'or if errors exist. -
When a member is invited using a secondary login, the backend associates the membership under their primary login, leaving an empty object / nullified artifact
{pendingAction: null}under the secondary email inpolicy.employeeList(as documented inWorkspaceMembersTest.tsx:634–657and handled inuseWorkspaceMembers.ts:30–35). -
Similarly, when members are removed (
Member.removeMembers),successMembersState[email] = nullis merged into Onyx. -
In
getIneligibleInvitees:- For an empty employee artifact (
{},{pendingAction: null}, ornull),policyEmployee?.pendingActionisnull/undefined(not'delete') anderrorsis empty. - Crucially,
getIneligibleInviteesdoes not checkisEmptyValueObject(policyEmployee)or!policyEmployee?.role(unlikeuseWorkspaceMembers.tswhich skipsisEmptyValueObject(policyEmployee), orPolicyUtils/members.ts:42which requiresemployee.role). - Consequently,
memberEmailsToExclude.push(email)pushes the secondary login (or any empty/nullified artifact), marking it as an active member and triggering the "user is already a member" message.
- For an empty employee artifact (
-
Furthermore, in
src/libs/actions/Policy/Member.ts(removeMembers, lines 554–576):primaryLoginsInvited: nullis only pushed tooptimisticDataand omitted fromsuccessData.- When only one of multiple secondary-invited members is deleted, individual entries in
policy.primaryLoginsInvitedare never cleared. remainingLoginsfilters onselectedMemberEmailsinstead ofselectedMemberEmailsWithDuplicates, failing to discount the paired secondary login.
What changes do you think we should make in order to solve the problem?
-
In
src/libs/PolicyUtils/members.ts:- Import
isEmptyValueObjectfrom@src/types/utils/EmptyObject. - In
getIneligibleInvitees, skip entries that are empty value objects or do not have an activerole:
--- a/src/libs/PolicyUtils/members.ts +++ b/src/libs/PolicyUtils/members.ts @@ -11,7 +11,7 @@ import CONST from '@src/CONST'; import type {PersonalDetailsList, Policy, PolicyEmployeeList} from '@src/types/onyx'; import type PolicyEmployee from '@src/types/onyx/PolicyEmployee'; -import {isEmptyObject} from '@src/types/utils/EmptyObject'; +import {isEmptyObject, isEmptyValueObject} from '@src/types/utils/EmptyObject'; import type {OnyxCollection, OnyxEntry} from 'react-native-onyx'; @@ -212,7 +212,12 @@ function getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] { const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS]; for (const email of Object.keys(policyEmployeeList)) { const policyEmployee = policyEmployeeList?.[email]; - // Policy members that are pending delete or have errors are not valid and we should show them in the invite options (don't exclude them). - if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) { + // Policy members that are pending delete, empty artifacts, without an assigned role, or have errors + // are not valid active members and we should show them in the invite options (don't exclude them). + if ( + isEmptyValueObject(policyEmployee) || + !policyEmployee?.role || + policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || + Object.keys(policyEmployee?.errors ?? {}).length > 0 + ) { continue; } if (!email) { - Import
-
In
src/libs/actions/Policy/Member.ts(removeMembers):- Use
selectedMemberEmailsWithDuplicatesto computeremainingLogins. - Explicitly clear the removed member's secondary login from
primaryLoginsInvitedin bothoptimisticDataandsuccessData. - Also include
primaryLoginsInvited: nullinsuccessDatawhen all secondary-invited members have been removed.
- Use
-
Add unit test coverage in
tests/unit/PolicyUtilsTest.tsforgetIneligibleInvitees:- Verifying that active members and Expensify team emails are excluded from invites.
- Verifying that members pending delete or with errors are not excluded.
- Verifying that empty employee objects (
{}),{pendingAction: null}, and entries without aroleare not excluded from invites.
Proposal
Please re-state the problem that we are trying to solve in this issue.
When an admin invites a user to a workspace using their secondary login ([email protected]), removes that member from the workspace, and then opens Invite member and searches for the user's secondary login again, the removed user does not appear in the search list and instead displays the message that [email protected] is already a member of the workspace (messages.userIsAlreadyMember).
What is the root cause of that problem?
There is a two-part root cause across buildAddMembersToWorkspaceOnyxData / removeMembers (src/libs/actions/Policy/Member.ts) and getIneligibleInvitees (src/libs/PolicyUtils/members.ts):
-
How inviting by secondary login leaves an empty
{pendingAction: null}entry inpolicy.employeeList[secondaryLogin]:- When
addMembersToWorkspace(src/libs/actions/Policy/Member.ts:898-952) invitessecondaryLogin,optimisticDatamergesemployeeList: {[secondaryLogin]: {email: secondaryLogin, pendingAction: 'add', role: ...}}andsuccessDatamergesemployeeList: {[secondaryLogin]: {pendingAction: null}}(line 906). - On the backend,
AddMembersToWorkspaceresolvessecondaryLoginto the user's primary login (primaryLogin), addsemployeeList[primaryLogin] = {email: primaryLogin, role: 'user', ...}, and setsemployeeList[secondaryLogin] = nullto clear the secondary login key. - However, because
API.writeappliessuccessDataafter the server responseonyxData,successData'sOnyx.METHOD.MERGE(employeeList: {[secondaryLogin]: {pendingAction: null}}) re-createspolicy.employeeList[secondaryLogin]as{pendingAction: null}(an empty-value object with noroleoremail, as documented insrc/hooks/useWorkspaceMembers.ts:32-34).
- When
-
Why
secondaryLoginremains inpolicy.employeeListand is marked ineligible ingetIneligibleInviteesafter the member is removed:- In
DynamicWorkspaceInvitePage.tsx:85-92, 210-213,excludedUsersis built exclusively fromgetIneligibleInvitees(policy?.employeeList). Whensections.length === 0andexcludedUsers[searchValue]istrue, the page displaystranslate('messages.userIsAlreadyMember', searchValue, policyName). - In
src/libs/PolicyUtils/members.ts:210-226,getIneligibleInviteesiterates overObject.keys(policyEmployeeList)and only skips entries wherepolicyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0. UnlikeuseWorkspaceMembers.ts:35(which skipsisEmptyValueObject(policyEmployee)) andgetEligibleBankAccountShareRecipientEmails(src/libs/PolicyUtils/members.ts:42, which checks!employee.role),getIneligibleInviteestreats the{pendingAction: null}artifact atpolicy.employeeList[secondaryLogin]as an active workspace member. - When the member is removed in Step 7 (
removeMembersinsrc/libs/actions/Policy/Member.ts:406-427),selectedMemberEmailsonly contains[primaryLogin](becauseuseWorkspaceMembers.ts:35hid the emptysecondaryLoginentry from the Members table).removeMembersonly expandsselectedMemberEmailsWithDuplicatestosecondaryLoginifpolicy?.primaryLoginsInvitedcurrently mapssecondaryLogin -> primaryLogin. WheneverprimaryLoginsInvitedis absent, cleared (e.g. viadismissAddedWithPrimaryLoginMessages), or not populated on the policy whenremoveMembersruns (and even whenprimaryLoginsInvitedis present, line 557 filtersremainingLoginsagainstselectedMemberEmailsinstead ofselectedMemberEmailsWithDuplicatesand only clearsprimaryLoginsInvitedinoptimisticDatarather thansuccessData),policy.employeeList[secondaryLogin]({pendingAction: null}) is left behind in Onyx andgetIneligibleInviteescontinues to returnsecondaryLoginas an existing member.
- In
What changes do you think we should make in order to solve the problem?
-
Skip empty/role-less ghost entries in
getIneligibleInvitees(src/libs/PolicyUtils/members.ts:210-226) while still respecting activeprimaryLoginsInvitedpairings:- In
getIneligibleInvitees, skip anypolicyEmployeeentry that is an empty-value object (isEmptyValueObject(policyEmployee) || !policyEmployee?.role), matching the guard inuseWorkspaceMembers.ts:35andsrc/libs/PolicyUtils/members.ts:42. - Note on Step 5 (searching
secondaryLoginwhile the user is still an active member of the workspace): when the user searchessecondaryLogininDynamicWorkspaceInvitePage,searchUserInServer(debouncedSearchTerm)(DynamicWorkspaceInvitePage.tsx:232) returns the user'spersonalDetailskeyed by theiraccountIDwithlogin: primaryLogin. BecauseprimaryLoginis an active member inexcludedUsers,usePersonalDetailSearchSelectorexcludes thatpersonalDetailsoption, and ifsecondaryLoginis also excluded while its pairedprimaryLoginis an active member (or ifgetIneligibleInvitees/DynamicWorkspaceInvitePageincludessecondaryLoginfrompolicy?.primaryLoginsInvitedonly while its mappedprimaryLoginis an active member inpolicy.employeeList), Step 5 continues to show "already a member" while the user is in the workspace, and Step 9 (afterprimaryLoginis removed) no longer excludessecondaryLogin:
function getIneligibleInvitees(policyEmployeeList?: PolicyEmployeeList, primaryLoginsInvited?: Record<string, string>): string[] { const policyEmployeeEmailsToExclude: string[] = []; for (const [email, policyEmployee] of Object.entries(policyEmployeeList ?? {})) { // Policy members that are pending delete or have errors aren't valid members so we shouldn't exclude them. // Also skip empty employeeList entries ({pendingAction: null}) left behind after inviting a secondary login. if ( isEmptyValueObject(policyEmployee) || !policyEmployee?.role || policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0 ) { continue; } if (!email) { continue; } policyEmployeeEmailsToExclude.push(email); } // If a secondary login was invited and its resolved primary login is currently an active member, exclude the secondary login too if (primaryLoginsInvited) { const activeEmails = new Set(policyEmployeeEmailsToExclude); for (const [secondaryLogin, primaryLogin] of Object.entries(primaryLoginsInvited)) { if (activeEmails.has(primaryLogin) && !activeEmails.has(secondaryLogin)) { policyEmployeeEmailsToExclude.push(secondaryLogin); } } } return policyEmployeeEmailsToExclude; }And pass
policy?.primaryLoginsInvitedwheregetIneligibleInvitees(policy?.employeeList, policy?.primaryLoginsInvited)is called insrc/pages/workspace/DynamicWorkspaceInvitePage.tsx:85. - In
-
Clean up orphaned empty
{pendingAction: null}entries andprimaryLoginsInvitedinremoveMembers(src/libs/actions/Policy/Member.ts:406-427, 554-576):- In
removeMembers, in addition to expandingselectedMemberEmailsWithDuplicatesviaprimaryLoginsInvited, also sweep any empty-value entry (isEmptyValueObject(employee)) inpolicy.employeeListintosuccessMembersState[email] = nullso stale{pendingAction: null}keys do not linger inpolicy.employeeList. - At line 557 of
src/libs/actions/Policy/Member.ts, filterremainingLoginsusingselectedMemberEmailsWithDuplicates(and excludeisEmptyValueObjectentries), and clear the removed member's entry fromprimaryLoginsInvitedin bothoptimisticDataandsuccessData.
- In
What alternative solutions did you explore? (Optional)
We also considered omitting successMembersState[email] = {pendingAction: null} in buildAddMembersToWorkspaceOnyxData (src/libs/actions/Policy/Member.ts:906). However, for normal primary-login invites, successData needs to clear the optimistic pendingAction: 'add' flag on employeeList[email] if the backend response does not overwrite pendingAction. Filtering isEmptyValueObject(policyEmployee) || !policyEmployee?.role in getIneligibleInvitees (paired with active primaryLoginsInvited lookup and removeMembers cleanup) safely handles the {pendingAction: null} secondary-login artifact without breaking primary-login optimistic pendingAction cleanup.
Contributor details
- Your Expensify account email: [email protected]
- Upwork Profile Link: https://www.upwork.com/freelancers/~013d295f05a578824b
— submitted with Antigravity on the contributor's behalf
Proposal
Please re-state the problem that we are trying to solve in this issue.
In Workspace Members, after inviting a user using their secondary login, closing the panel, and then removing that invited member, re-inviting with the same secondary login fails because the search list incorrectly reports that the user is "already a member of the workspace".
What is the root cause of that problem?
In src/libs/actions/Policy/Member.ts (removeMembers) and src/libs/PolicyUtils/members.ts (getIneligibleInvitees):
- In
src/libs/actions/Policy/Member.ts(lines 556–575): When removing members,remainingLoginsis computed as:const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmails.includes(email));It checks!selectedMemberEmails.includes(email)instead ofselectedMemberEmailsWithDuplicates. When a member invited via secondary login is removed,selectedMemberEmailsonly contains one of the logins (primary or secondary), while the paired login was added toselectedMemberEmailsWithDuplicates. BecauseremainingLoginsstill contains the paired login, the cleanup condition!remainingLogins.some(...)evaluates tofalse, andpolicy.primaryLoginsInvitedis never cleared. - Additionally, in
src/pages/workspace/DynamicWorkspaceInvitePage.tsx(lines 85–92 and 210–213) andgetIneligibleInvitees:excludedUserscheckspolicy.employeeListandpolicy.primaryLoginsInvited. When the member is removed, ifprimaryLoginsInvitedretains thesecondaryLogin -> primaryLoginmapping or ifemployeeList[secondaryLogin]is not cleaned up in successData,excludedUsers[searchValue]evaluates totrue, triggeringmessages.userIsAlreadyMember.
What changes do you think we should make in order to solve the problem?
- In
src/libs/actions/Policy/Member.ts(removeMembers):- In lines 557–575, compute
remainingLoginsusingselectedMemberEmailsWithDuplicates:const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmailsWithDuplicates.includes(email)); - Explicitly delete the removed secondary login from
policy.primaryLoginsInvitedin bothoptimisticDataandsuccessData:primaryLoginsInvited: {[secondaryLogin]: null}so stale mappings do not persist after member deletion.
- In lines 557–575, compute
- In
src/libs/PolicyUtils/members.ts(getIneligibleInvitees):- Ensure that if a primary login is deleted or pending delete (
CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE), any associated secondary login fromprimaryLoginsInvitedis also excluded fromineligibleInvitees.
- Ensure that if a primary login is deleted or pending delete (
What alternative solutions did you explore? (Optional)
Clearing the entire primaryLoginsInvited object whenever any member is deleted, which would inadvertently discard valid mappings for other members who were invited via secondary logins.
Proposal
What is the root cause of that problem?
There are two interacting root causes across member invitation data persistence, member deletion cleanup, and invitee exclusion filtering:
-
Orphaned
{pendingAction: null}secondary login entry inpolicy.employeeList:- In
buildAddMembersToWorkspaceOnyxData(src/libs/actions/Policy/Member.ts:898-906), inviting a member with a secondary login setsoptimisticMembersState[secondaryLogin] = {email: secondaryLogin, pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD, role: ...}andsuccessMembersState[secondaryLogin] = {pendingAction: null}. - When the backend responds, the backend stores the user under their primary login in
employeeList[primaryLogin], stores the secondary-to-primary mapping inpolicy.primaryLoginsInvited, and nulls the secondary login key. - However, when
successDatamerges,successMembersState[secondaryLogin] = {pendingAction: null}leaves an empty-value placeholder{pendingAction: null}inpolicy.employeeList[secondaryLogin]. - In
getIneligibleInvitees(src/libs/PolicyUtils/members.ts:210-226):for (const email of Object.keys(policyEmployeeList)) { const policyEmployee = policyEmployeeList?.[email]; if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) { continue; } if (!email) { continue; } memberEmailsToExclude.push(email); }getIneligibleInviteesonly checks forpendingAction === 'delete'or errors; it does not checkisEmptyValueObject(policyEmployee)or!policyEmployee?.role(unlikesrc/hooks/useWorkspaceMembers.ts:35, which explicitly ignoresisEmptyValueObject(policyEmployee)to prevent rendering duplicate rows). As a result, the orphaned{pendingAction: null}entry is treated as an active member and added tomemberEmailsToExclude.
- In
-
Incomplete member removal and missing
primaryLoginsInvitedcleanup insuccessData:- In
removeMembers(src/libs/actions/Policy/Member.ts:554-575), line 557 computes remaining logins usingselectedMemberEmailsinstead ofselectedMemberEmailsWithDuplicates:
Because the members table only renders the primary login (due toconst remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmails.includes(email));useWorkspaceMembers),selectedMemberEmailscontains only[primaryLogin]. Thus,remainingLoginscontinues to containsecondaryLogin, causingremainingLogins.some((remainingLogin) => !!invitedPrimaryToSecondaryLogins[remainingLogin])to evaluate totrue. - Furthermore, lines 568-574 only push
primaryLoginsInvited: nulltooptimisticDataand never tosuccessData. WhenDeleteMembersFromWorkspacecompletes and mergessuccessData, stale secondary-to-primary mappings remain in Onyx. - On reopening the invite flow (
DynamicWorkspaceInvitePage.tsx:210-213),excludedUsers[searchValue]evaluates totrue, displayingmessages.userIsAlreadyMember.
- In
What changes do you think we should make in order to solve the problem?
1. Filter out empty-value placeholder entries and check active primary members in getIneligibleInvitees (src/libs/PolicyUtils/members.ts:210-226)
Skip placeholder entries (isEmptyValueObject(policyEmployee) or missing role), and forward primaryLoginsInvited so secondary logins are excluded only when their paired primary login is an active member:
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import {isEmptyValueObject} from '@src/types/utils/EmptyObject';
import CONST from '@src/CONST';
function getIneligibleInvitees(employeeList?: PolicyEmployeeList, primaryLoginsInvited?: Record<string, string>): string[] {
const policyEmployeeList = employeeList ?? {};
const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS];
for (const email of Object.keys(policyEmployeeList)) {
const policyEmployee = policyEmployeeList?.[email];
// Policy members that are pending delete, have errors, or are empty placeholder entries (e.g. secondary logins) are not valid active members
if (isEmptyValueObject(policyEmployee) || !policyEmployee?.role || policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) {
continue;
}
if (!email) {
continue;
}
memberEmailsToExclude.push(email);
}
if (primaryLoginsInvited) {
for (const [secondaryLogin, primaryLogin] of Object.entries(primaryLoginsInvited)) {
const primaryEmployee = policyEmployeeList?.[primaryLogin];
if (primaryEmployee && !isEmptyValueObject(primaryEmployee) && !!primaryEmployee.role && primaryEmployee.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE && Object.keys(primaryEmployee.errors ?? {}).length === 0) {
memberEmailsToExclude.push(secondaryLogin);
}
}
}
return memberEmailsToExclude;
}
2. Pass policy?.primaryLoginsInvited in DynamicWorkspaceInvitePage.tsx:85
const ineligibleInvites = getIneligibleInvitees(policy?.employeeList, policy?.primaryLoginsInvited);
3. Update removeMembers in src/libs/actions/Policy/Member.ts to clean up paired secondary logins and sync primaryLoginsInvited in both optimisticData and successData
if (!isEmptyObject(policy?.primaryLoginsInvited ?? {})) {
const employeeListEmails = Object.keys(policy?.employeeList ?? {});
const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmailsWithDuplicates.includes(email));
const invitedPrimaryToSecondaryLogins: Record<string, string> = {};
if (policy?.primaryLoginsInvited) {
for (const key of Object.keys(policy.primaryLoginsInvited)) {
invitedPrimaryToSecondaryLogins[policy.primaryLoginsInvited?.[key] ?? ''] = key;
}
}
const removedSecondaryLogins: Record<string, null> = {};
for (const [secondaryLogin, primaryLogin] of Object.entries(primaryLoginsInvited)) {
if (selectedMemberEmailsWithDuplicates.includes(secondaryLogin) || selectedMemberEmailsWithDuplicates.includes(primaryLogin)) {
removedSecondaryLogins[secondaryLogin] = null;
}
}
if (!remainingLogins.some((remainingLogin) => !!invitedPrimaryToSecondaryLogins[remainingLogin])) {
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: policyKey,
value: {
primaryLoginsInvited: null,
},
});
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: policyKey,
value: {
primaryLoginsInvited: null,
},
});
} else if (!isEmptyObject(removedSecondaryLogins)) {
optimisticData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: policyKey,
value: {
primaryLoginsInvited: removedSecondaryLogins,
},
});
successData.push({
onyxMethod: Onyx.METHOD.MERGE,
key: policyKey,
value: {
primaryLoginsInvited: removedSecondaryLogins,
},
});
}
}
What alternative solutions did you explore? (Optional)
- Only filtering
isEmptyValueObjectingetIneligibleInvitees: LeavingprimaryLoginsInviteduncleared insuccessDatawould leave stale secondary-to-primary mapping references in Onyx and could cause re-invitations or workspace arrangement helpers (WorkArrangementUtils.ts:30) to resolve against nonexistent primary members. - Clearing all
primaryLoginsInvitedunconditionally: Would inadvertently delete valid mappings for other workspace members who were invited via secondary logins and remain active in the workspace. Updating onlyremovedSecondaryLoginsensures fine-grained precision.
What automated tests can you add to prevent this from re-occurring?
In tests/actions/PolicyMemberTest.ts:
Add a unit test verifying that when a member invited with a secondary login is removed via removeMembers:
- Both
primaryEmailandsecondaryEmailentries are removed frompolicy.employeeList. - The mapping in
policy.primaryLoginsInvitedis cleared in both optimistic and success Onyx data. getIneligibleInvitees(policy.employeeList, policy.primaryLoginsInvited)no longer containssecondaryEmail.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
When an admin invites a user to a workspace using their secondary login ([email protected]), searches that secondary login in Invite member, closes the RHP, removes the invited member from the workspace, and then opens Invite member and searches for [email protected] again, the removed user does not appear in the search list and the UI displays the message that [email protected] is already a member of the workspace (messages.userIsAlreadyMember).
What is the root cause of that problem?
The bug is caused by the interaction of three concrete mechanisms across the invitation flow, the intermediate Invite member RHP search (Steps 4–6), the member removal flow (Step 7), and the invite exclusion check (Steps 8–9):
-
Inviting via secondary login leaves a role-less
{pendingAction: null}ghost entry atpolicy.employeeList[secondaryLogin](src/libs/actions/Policy/Member.ts:898-952):- In
buildAddMembersToWorkspaceOnyxData,optimisticDatamergesemployeeList: {[secondaryLogin]: {email: secondaryLogin, pendingAction: 'add', role: ...}}andsuccessDatamergesemployeeList: {[secondaryLogin]: {pendingAction: null}}(src/libs/actions/Policy/Member.ts:898-906). - On the server,
AddMembersToWorkspaceresolvessecondaryLoginto the user's primary login (primaryLogin), addsemployeeList[primaryLogin] = {email: primaryLogin, role: 'user', ...}, setspolicy.primaryLoginsInvited = {[secondaryLogin]: primaryLogin}, and returnsemployeeList[secondaryLogin] = nullin the command'sonyxData. - Because
Onyx.updateapplies the request'ssuccessDataafter the server'sonyxData,successData'sOnyx.METHOD.MERGE(employeeList: {[secondaryLogin]: {pendingAction: null}}) re-createspolicy.employeeList[secondaryLogin]as{pendingAction: null}(an empty-value object with noroleoremail, as explicitly documented insrc/hooks/useWorkspaceMembers.ts:32-35andtests/ui/WorkspaceMembersTest.tsx:635-657).
- In
-
Why
removeMembersin Step 7 fails to removepolicy.employeeList[secondaryLogin](and why Steps 4–6 matter):- On the Workspace Members page,
useWorkspaceMembers(src/hooks/useWorkspaceMembers.ts:35) hides anypolicyEmployeewhereisEmptyValueObject(policyEmployee)istrue, so only theprimaryLoginrow is rendered and selectable. When the admin removes the member in Step 7,selectedMemberEmailsis[primaryLogin]. - In
removeMembers(src/libs/actions/Policy/Member.ts:406-418),selectedMemberEmailsWithDuplicatesonly expandsprimaryLogintosecondaryLoginifpolicy?.primaryLoginsInvitedstill contains[secondaryLogin]: primaryLoginat the momentremoveMembersis called. - However,
policy.primaryLoginsInvitedis cleared wheneverdismissAddedWithPrimaryLoginMessages(policyID)runs (src/libs/actions/Policy/Policy.ts:4650-4652) or when the policy object is refreshed byopenWorkspaceInvitePage/openWorkspaceMembersPagein Steps 4–6 withoutprimaryLoginsInvited. OnceprimaryLoginsInvitedis absent/cleared,selectedMemberEmailsWithDuplicatescontains only[primaryLogin], leavingpolicy.employeeList[secondaryLogin]({pendingAction: null}) untouched in Onyx! - Even when
policy.primaryLoginsInvitedis present duringremoveMembers,src/libs/actions/Policy/Member.ts:557filtersremainingLoginsagainstselectedMemberEmailsinstead ofselectedMemberEmailsWithDuplicates(const remainingLogins = employeeListEmails.filter((email) => !selectedMemberEmails.includes(email))), and only mergesprimaryLoginsInvited: nullintooptimisticData(omittingsuccessDataand never clearing individual entries when other secondary-invited members remain).
- On the Workspace Members page,
-
Why
getIneligibleInviteestreats the empty{pendingAction: null}artifact as an active member in Step 9 (src/libs/PolicyUtils/members.ts:210-226):- In
src/pages/workspace/DynamicWorkspaceInvitePage.tsx:85-92, 210-213,excludedUsersis built fromgetIneligibleInvitees(policy?.employeeList). - In
src/libs/PolicyUtils/members.ts:210-226:
Unlikefunction getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] { const policyEmployeeList = employeeList ?? {}; const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS]; for (const email of Object.keys(policyEmployeeList)) { const policyEmployee = policyEmployeeList?.[email]; if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) { continue; } if (!email) { continue; } memberEmailsToExclude.push(email); } return memberEmailsToExclude; }useWorkspaceMembers.ts:35(which skipsisEmptyValueObject(policyEmployee)) andgetEligibleBankAccountShareRecipientEmails(src/libs/PolicyUtils/members.ts:42, which checks!employee.role),getIneligibleInviteesdoes not skip empty-value objects (isEmptyValueObject(policyEmployee)). As a result, the leftover{pendingAction: null}entry undersecondaryLoginis added tomemberEmailsToExclude(excludedUsers[secondaryLogin] = true), which suppressesgetUserToInviteOptioninusePersonalDetailSearchSelectorand causesDynamicWorkspaceInvitePage.tsx:213to displaytranslate('messages.userIsAlreadyMember', searchValue, policyName).
- In
What changes do you think we should make in order to solve the problem?
-
Skip empty-value employee artifacts in
getIneligibleInviteeswhile still excludingsecondaryLoginwhile its pairedprimaryLoginis an active member (src/libs/PolicyUtils/members.ts&src/pages/workspace/DynamicWorkspaceInvitePage.tsx):- Note why we must also check
primaryLoginsInvitedfor active members: in Step 5 (while the invited user is still an active member underprimaryLogin), typingsecondaryLogincallssearchUserInServer, which returnspersonalDetailskeyed byaccountIDwithlogin: primaryLogin. WhilepersonalDetailsOptionsexcludes that contact becauseexcludedUsers[primaryLogin]istrue,filterUserToInvite(src/libs/PersonalDetailOptionsListUtils/index.ts:199-235, 427-434) checksloginsToExclude[searchValue](loginsToExclude[secondaryLogin]). IfsecondaryLoginwere not inexcludedUserswhileprimaryLoginis an active member,filterUserToInvitewould create a fallbackuserToInviteoption forsecondaryLoginin Step 5 instead of showing"already a member". - Therefore, in
getIneligibleInvitees(employeeList?: PolicyEmployeeList, primaryLoginsInvited?: Record<string, string>):- Skip any
policyEmployeewhereisEmptyValueObject(policyEmployee)istrue(matchinguseWorkspaceMembers.ts:35). - For each
[secondaryLogin, primaryLogin]inprimaryLoginsInvited, includesecondaryLogininmemberEmailsToExcludeonly ifprimaryLoginis currently an active (non-empty, non-pending-delete, error-free) member inpolicyEmployeeList.
- Skip any
--- a/src/libs/PolicyUtils/members.ts +++ b/src/libs/PolicyUtils/members.ts @@ -11,7 +11,7 @@ import CONST from '@src/CONST'; import type {PersonalDetailsList, Policy, PolicyEmployeeList} from '@src/types/onyx'; import type PolicyEmployee from '@src/types/onyx/PolicyEmployee'; -import {isEmptyObject} from '@src/types/utils/EmptyObject'; +import {isEmptyObject, isEmptyValueObject} from '@src/types/utils/EmptyObject'; @@ -210,10 +210,15 @@ function getAccountIDForSubmitManagerEmail( /** * Get login list that we should not show in the workspace invite options */ -function getIneligibleInvitees(employeeList?: PolicyEmployeeList): string[] { +function getIneligibleInvitees(employeeList?: PolicyEmployeeList, primaryLoginsInvited?: Record<string, string>): string[] { const policyEmployeeList = employeeList ?? {}; const memberEmailsToExclude: string[] = [...CONST.EXPENSIFY_EMAILS]; for (const email of Object.keys(policyEmployeeList)) { const policyEmployee = policyEmployeeList?.[email]; // Policy members that are pending delete, have errors, or are empty secondary-login artifacts are not valid members - if (policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || Object.keys(policyEmployee?.errors ?? {}).length > 0) { + if ( + isEmptyValueObject(policyEmployee) || + policyEmployee?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE || + Object.keys(policyEmployee?.errors ?? {}).length > 0 + ) { continue; } if (!email) { continue; } memberEmailsToExclude.push(email); } + + if (primaryLoginsInvited) { + const activeMemberEmails = new Set(memberEmailsToExclude); + for (const [secondaryLogin, primaryLogin] of Object.entries(primaryLoginsInvited)) { + if (activeMemberEmails.has(primaryLogin) && !activeMemberEmails.has(secondaryLogin)) { + memberEmailsToExclude.push(secondaryLogin); + } + } + } return memberEmailsToExclude; }- Update
getExcludedUsersinsrc/libs/PolicyUtils/members.ts:231and the call site insrc/pages/workspace/DynamicWorkspaceInvitePage.tsx:85to passpolicy?.primaryLoginsInvited:const ineligibleInvites = getIneligibleInvitees(policy?.employeeList, policy?.primaryLoginsInvited);
- Note why we must also check
-
Clean up empty
{pendingAction: null}employeeList artifacts andprimaryLoginsInvitedentries inremoveMembers(src/libs/actions/Policy/Member.ts:406-427, 554-576):- In
removeMembers, sweep any empty-value entry (isEmptyValueObject(employeeList[email])) intosuccessMembersState[email] = nullso orphaned{pendingAction: null}keys do not accumulate in Onyx. - At line 557, compute
remainingLoginsusingselectedMemberEmailsWithDuplicates(excludingisEmptyValueObjectentries), and clear removed secondary-login mappings fromprimaryLoginsInvitedin bothoptimisticDataandsuccessData.
- In
What alternative solutions did you explore? (Optional)
- Removing
successMembersState[email] = {pendingAction: null}frombuildAddMembersToWorkspaceOnyxData(src/libs/actions/Policy/Member.ts:906): Not sufficient on its own because for normal primary-login invitations or offline-to-online transitions where the server response does not overwritependingAction,successDatamust clearpendingAction: 'add'. SkippingisEmptyValueObject(policyEmployee)ingetIneligibleInvitees(paired with activeprimaryLoginsInvitedresolution andremoveMemberscleanup) alignsgetIneligibleInviteeswithuseWorkspaceMembers.ts:35and handles both Step 5 (while active) and Step 9 (after removal).
I can not reproduce this
I investigated the secondary-login invite bug and prepared a candidate fix and a proposal draft using Expensify's official proposal template.
- Proposal draft + draft PR (in my fork, not upstream): https://github.com/HamzaZahid172/App/pull/1
- Fix branch: https://github.com/HamzaZahid172/App/tree/fix/106630-secondary-login-invite
The proposed root cause is that a role-less employeeList placeholder left after inviting a secondary login is mistaken for an active member by getIneligibleInvitees. The candidate patch filters those placeholders while continuing to exclude a secondary login when its paired primary login is active. Four regression test cases were added.
Status: This is a proposal draft, not an official proposal submission or an upstream PR. I have not reproduced the complete nine-step scenario with a verified secondary-login account or run the full repository test suite. I also see that other proposals overlap with this approach.
Since the issue does not currently have a Help Wanted label and the contribution guidelines say not to submit proposals beforehand or open upstream PRs before acceptance, I am holding off on both. Could the assigned reviewer please confirm whether new proposals are being accepted and whether a verified secondary-login fixture or sanitized Onyx state trace can be provided? I can then validate the full flow and address any mapping-cleanup gaps before formal submission.
My Expensify/Upwork contributor details have already been registered in this issue.
📣 @HamzaZahid172! 📣 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:
- Make sure you've read and understood the contributing guidelines.
- 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.
- 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.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0190813b8dab33818c
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
@FitseTLT Still overdue 6 days?! Let's take care of this!
Not overdue
@MelvinBot proposal for this ?
Proposal — preliminary, not ready for acceptance
What is the root cause of that problem?
A leftover secondary-login entry can incorrectly count as workspace membership, even when its value is {pendingAction: null}.
However, the complete reported sequence remains unverified: member removal already deletes both logins when their pairing is available. We still need to establish why the secondary entry survives.
Code evidence and important counterevidence
- members.ts:210–225 excludes empty employee entries from invitation search.
- Member.ts:424–453 already removes the paired secondary login.
- Policy.ts:4649–4654 clears that pairing when its informational message is dismissed. This establishes a possible failure path, but not that opening/searching/closing Invite triggers it.
What changes do you think we should make in order to solve the problem?
A specific fix is not justified yet. Capture employeeList, primaryLoginsInvited, and response updates immediately before and after removal using a verified secondary-login account.
This must establish whether the alias was never deleted or was restored afterward. Any eventual fix must also keep the secondary login blocked while its primary account remains a member—simply ignoring empty entries could break that behavior.
Blocker: No verified secondary-login reproduction or sanitized state trace is available in the thread. Source review alone does not close that gap.
@MelvinBot What I can reproduce is when I delete it offline and search, it says it is already member but this doesn't happen for normal members only with the secondary login? Why?
@FitseTLT Here is why this happens specifically for a secondary login (and not for normal members), even offline:
- Normal members:
selectedMemberEmailscontains their only login inpolicy.employeeList, sodeleteMembersFromWorkspacesetsemployeeList[email] = {pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE}optimistically right away, andgetIneligibleInviteesskips any entry withpendingAction === DELETE. - Secondary login: When you invite by secondary login, the backend stores the member under their primary login, while the secondary login entry also remains in
policy.employeeList(with{pendingAction: null}). When you remove the member in the UI,selectedMemberEmailsonly contains theprimaryLogin. deleteMembersFromWorkspace(Member.ts#L432-L444) only expandsselectedMemberEmailsWithDuplicatesto includesecondaryLoginif the pairing is still present inpolicy?.primaryLoginsInvited. WheneverprimaryLoginsInvitedhas been cleared or is missing (e.g. after dismissing the invite flow / Onyx refresh),deleteMembersFromWorkspaceonly marksprimaryLoginaspendingAction: DELETE, leavingemployeeList[secondaryLogin]untouched (pendingAction: null), sogetIneligibleInviteesstill treatssecondaryLoginas an active member and shows"already a member".