Skip to content

[$250] Spend - Stale user data appearing in admin account #96862

Closed

Description

@izarutskaya

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: Needs Reproduction (Reproduction is blocked)
Reproducible in staging?: Needs Reproduction (Reproduction is blocked)
Reproducible in production?: Needs Reproduction (Reproduction is blocked)
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: @RachCHopkins
Slack conversation (hyperlinked to channel name): #expensify_bugs

Action Performed:

Prerequisites: The account was once an admin and domain admin for a different business.

  1. Sign in to New Expensify
  2. Go to Spend > Expenses (or Reports)
  3. Open the “From” / “To” filter dropdown

Expected Result:

Only relevant users (current workspace/report members or former members with accessible expense/report data) for Company A/Domain A appear as filter options.

Actual Result:

Company B/Domain B users appear as selectable filter options even though the user no longer shares any workspace/reports with them (the two companies split ~2 years ago). Filtering by them returns zero results. They sometimes disappear and then reappear. Support (supportal) only sees one Company B user; the affected user sees at least 10-20

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

Please check the OP for the details

View all open jobs on GitHub

Upwork Automation - Do Not Edit

Activity

  1. added
    Daily
    Bug
    Needs Reproduction
    on Jul 23, 2026
  2. exfy-zapier commented on Jul 23, 2026

    @exfy-zapier

    This has been labelled "Needs Reproduction". Follow the steps here: https://stackoverflowteams.com/c/expensify/questions/16989

  3. added
    Bug
    and removed
    Bug
    on Jul 23, 2026
  4. MelvinBot commented on Jul 23, 2026

    @MelvinBot
    Contributor

    Proposal

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

    In Search → Spend (Expenses/Reports), the From / To filter dropdown offers stale users as selectable options — e.g. people from a business the account split from ~2 years ago (Company B) — even though the current user no longer shares any workspace, domain, or report with them. Filtering by them returns zero results, and they intermittently disappear then reappear. Supportal sees only 1 such user while the affected user sees 10–20.

    What is the root cause of that problem?

    The From/To filter option list is built from the entire locally-cached ONYXKEYS.PERSONAL_DETAILS_LIST, with no filter restricting it to people the user currently shares a workspace/domain/report with.

    Both consumers pull from the full personal-details map:

    Both funnel into createOptionList (PersonalDetailOptionsListUtils/index.ts:435-465), which loops over every entry in PERSONAL_DETAILS_LIST (a report/workspace link is only looked up to decorate the option, never to include/exclude it), and getValidOptions (:264) which applies only cosmetic filters (login exists, not a domain email, not an Expensify-team/AM login, not the current user, search-term match). There is no "do we currently share anything with this account" check.

    Because PERSONAL_DETAILS_LIST is populated additively via Onyx.merge from many API responses and rarely pruned, historical Company B accountIDs linger in the local cache and stay selectable. The intermittent disappear/reappear and the supportal-vs-user count gap are consistent with this: a cache clear/fresh load shows fewer, then subsequent responses re-merge the stale accountIDs back in, and different accounts have accumulated different local caches.

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

    Scope the personal-details option universe to accountIDs the current user actually shares a workspace/domain/report with, rather than emitting every cached entry.

    • Add a relationship filter in getValidOptions (or upstream in createOptionList / usePersonalDetailOptions) so an option is only included when the account is a member of one of the current user's policies, shares a domain, or appears on a report the user has access to.
    • Ensure the change covers both the RHP UserSelector path and the inline useAutocompleteSuggestions path, since they share this data source.
    One thing worth confirming with logs

    I couldn't determine from code alone whether the backend still returns these ~10–20 Company B accountIDs in the user's OpenApp/ReconnectApp/Search personalDetails payloads, or whether they are purely leftover local Onyx cache. Inspecting one of the affected user's request payloads for the personalDetailsList keys would settle this. Either way the selectable-list bug is in App (frontend) — but if the backend is still emitting them, a backend change to stop returning unrelated accountIDs would be the more complete fix, and the frontend scoping above is still valuable as a guard.

    What alternative solutions did you explore? (Optional)

    Pruning PERSONAL_DETAILS_LIST when relationships end was considered but is riskier — personal details are legitimately shared across many surfaces (chat history, past reports), so deleting them could break unrelated UI. Scoping at the option-building layer is safer and localized.


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/96862) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.

  5. added
    External
    on Jul 23, 2026
  6. added
    Help Wanted
    on Jul 23, 2026
  7. ahmdshrif commented on Jul 23, 2026

    @ahmdshrif
    Contributor

    Proposal

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

    The Search From/To filter dropdown offers users from a company the admin split from ~2 years ago. Filtering by them returns zero results, they flap in and out of the list, and the user sees 10–20 of them while supportal sees only one.

    What is the root cause of that problem?

    The From/To filter renders the raw personalDetailsList Onyx cache with no relevance gate, and that cache is append-only on the client — so anyone the account has ever interacted with stays a selectable filter option forever.

    The chain:

    1. UserSelector (the component behind both the From and To filters) feeds the list straight from the full personalDetailsList collection:
      const personalDetails = usePersonalDetails();
    2. createOptionList turns every entry into an option — its only gate is a missing accountID:
      for (const personalDetail of Object.values(personalDetails)) {
      if (!personalDetail?.accountID) {
      continue;
      }
      const reportID = accountIDToReportIDMap[personalDetail.accountID];
      const report = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
      const reportAttributes = report?.reportID ? reportAttributesDerived?.[report.reportID] : undefined;
      const isReportArchived = privateIsArchivedMap[reportID];
      const option = createOption(personalDetail, report, formatPhoneNumber, config, reportAttributes, isReportArchived);
    3. getValidOptions only excludes Expensify-team emails, domain emails, and the current user — there is no "does this user still share anything with me" predicate:
      const loginsToExclude: Record<string, boolean> = {
      [CONST.EMAIL.NOTIFICATIONS]: true,
      ...excludeLogins,
      [currentUserLogin]: !includeCurrentUser,
      };
    4. personalDetailsList is written exclusively with Onyx.merge (server onyxData and optimistic writers alike, e.g.
      Onyx.merge(ONYXKEYS.PERSONAL_DETAILS_LIST, {
      ). Merge never deletes keys and nothing reconciles the cache against the server's canonical list, so details merged 2 years ago persist indefinitely.

    This is the structural cause: a read surface that mirrors an append-only cache. It explains every symptom detail:

    • Zero results when filtering — the server has no accessible expenses for those users; only the client-side option list thinks they're relevant.
    • Supportal sees 1, the user sees 10–20 — supportal reads the server's canonical (cleaned) list; the client shows the historical union from merge-only writes.
    • Disappear/reappear — a cache clear/fresh sign-in starts from the server's trimmed set, then old chat reports and reconnect paging re-merge stale details back in.

    All affected paths (every one renders from the same unfiltered source):

    • Advanced-filters From/To — narrow-layout popup and RHP page both mount the same UserSelector via the shared filter mapping, which also routes Assignee and Attendee here (same bug):
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.ASSIGNEE:
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.ATTENDEE:
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.TO:
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM:
      return (
      <UserSelector
    • Search-router from:/to: autocomplete builds suggestions from the same full personalDetails:
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.TO:
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM:
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.PAYER:
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.ATTENDEE:
      case CONST.SEARCH.SYNTAX_FILTER_KEYS.EXPORTER: {
      // Soft-exclude Expensify-team logins (current and former AMs/Guides) from user filter suggestions. Users can still type any email manually because the search bar accepts free text.
      const memberExclusions = getExpensifyTeamExclusions(personalDetails, policies, currentUserEmail);
      const participants = getSearchOptions({
      options,
      draftComments,
      betas: betas ?? [],
      isUsedInChatFinder: true,
      includeReadOnly: true,
      searchQuery: autocompleteValue,
      maxResults: 10,
      includeUserToInvite: false,
      includeRecentReports: false,
      includeCurrentUser: true,
      countryCode,
      loginList,
      shouldShowGBR: true,
      visibleReportActionsData,
      policyCollection: policies,
      currentUserAccountID,
      currentUserEmail,
      personalDetails,
      sortedActions,
      conciergeReportID,
      excludeFromSuggestionsOnly: memberExclusions,
      isTrackIntentUser,
      }).options.personalDetails.filter((participant) => participant.text && !alreadyAutocompletedKeys.has(participant.text.toLowerCase()));

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

    Add a relevance gate at the two convergence points, reusing the exclusion mechanism the code already has for Expensify-team members (getExpensifyTeamExclusions → excludeFromSuggestionsOnly,

    const expensifyTeamExclusions = getExpensifyTeamExclusions(personalDetails, policies, currentUserPersonalDetails.email);
    const {searchTerm, setSearchTerm, availableOptions, totalOptionsCount, toggleSelection, areOptionsInitialized} = usePersonalDetailSearchSelector({
    selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI,
    initialSelected: initialSelectedAccountIDs,
    excludeLogins: CONST.EXPENSIFY_EMAILS_OBJECT,
    excludeFromSuggestionsOnly: expensifyTeamExclusions,
    ).

    Add a sibling helper (next to getExpensifyTeamExclusions in PolicyUtils):

    function getIrrelevantUserExclusions(personalDetails, reports, policies): Record<string, boolean> {
        // login -> true for details whose accountID is not a participant of any report
        // in Onyx AND whose login is not in any policy employeeList
    }

    A user passes the gate if they are a member of any of the admin's workspaces or a participant of any accessible report — exactly the issue's Expected Result ("current workspace/report members or former members with accessible expense/report data"): former members with still-accessible expense reports stay listed because those reports and their participants are in Onyx.

    Wire it in at both surfaces:

    1. UserSelector.tsx — merge into excludeFromSuggestionsOnly at L51 (policies is already subscribed on L34).
    2. useAutocompleteSuggestions.ts — merge into the existing memberExclusions at L237.

    Regression safety in one sentence: excludeFromSuggestionsOnly only hides rows from the suggestion list — typing a full email still works via includeUserToInvite (L52), already-applied/saved-search values still render via shouldKeepSelectedInAvailableOptions (L57), and no other consumer of personalDetailsList or getValidOptions changes behavior.

    Why the obvious spot-fix does NOT work: "just prune the stale keys out of the Onyx personalDetailsList" fails twice. First, every write path is Onyx.merge — the next ReconnectApp/OpenApp page-in or opening any 2-year-old chat re-merges the deleted details, reproducing the exact "disappear then reappear" flapping the reporter describes. Second, nearly 200 files read personalDetailsList for avatars/display names in still-accessible old chat history; deleting entries degrades those to "Hidden". The fix must be a read-side gate at the filter surfaces, not a cache mutation. (The one server-side stale user supportal sees is a backend data artifact, but a backend cleanup alone cannot fix the 10–20 entries already persisted in client caches — the App-side gate above is what actually resolves the report.)

    What alternative solutions did you explore? (Optional)

    1. Prune personalDetailsList on full reconnect (Onyx.set with the server response) — rejected: reverted by the next merge, and it breaks name/avatar rendering across old chats.
    2. Backend-only: clean stale shares server-side — needed for the one user supportal sees, but it can't reach already-populated client caches; noted for BZ, not the fix here.
    3. Gate on the existing accountIDToReportIDMap — rejected: that map is built only from 1:1 DM chats (usePersonalDetailOptions.ts), so it would wrongly hide workspace members the admin never chatted with.
  8. mukhrr commented on Jul 23, 2026

    @mukhrr
    Contributor

    Proposal

    What is the root cause of that problem?

    The Search from/to suggestion list is a direct projection of the entire personalDetailsList, with no check that the current user is actually connected to those accounts.

    UserSelector feeds the whole personal details list into the selector and applies exactly one soft exclusion — Expensify staff:

    function UserSelector({value = [], selectionListTextInputStyle, selectionListStyle, autoFocus, ready = true, footer, onChange}: UserSelectorProps) {
    const styles = useThemeStyles();
    const {translate} = useLocalize();
    const personalDetails = usePersonalDetails();
    const currentUserPersonalDetails = useCurrentUserPersonalDetails();
    const shouldFocusInputOnScreenFocus = autoFocus && canFocusInputOnScreenFocus();
    const [isSearchingForReports] = useOnyx(ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS);
    const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
    const initialSelectedAccountIDs = value.reduce<Set<string>>((acc, id) => {
    const participant = personalDetails?.[id];
    if (!participant) {
    return acc;
    }
    acc.add(id);
    return acc;
    }, new Set<string>());
    const expensifyTeamExclusions = getExpensifyTeamExclusions(personalDetails, policies, currentUserPersonalDetails.email);
    const {searchTerm, setSearchTerm, availableOptions, totalOptionsCount, toggleSelection, areOptionsInitialized} = usePersonalDetailSearchSelector({
    selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI,
    initialSelected: initialSelectedAccountIDs,
    excludeLogins: CONST.EXPENSIFY_EMAILS_OBJECT,
    excludeFromSuggestionsOnly: expensifyTeamExclusions,
    includeUserToInvite: true,
    includeCurrentUser: false,
    includeRecentReports: false,
    shouldInitialize: ready,
    onSelectionChange: onChange,
    shouldKeepSelectedInAvailableOptions: true,
    });

    The options themselves come from createOptionList(), which emits one option per hydrated personal-detail entry unconditionally. A related report is only used to decorate an option, so having no shared report does not exclude anyone:

    function createOptionList(
    currentUserAccountID: number,
    personalDetails: OnyxEntry<PersonalDetailsList>,
    accountIDToReportIDMap: Record<number, string>,
    reports: OnyxCollection<Report>,
    reportAttributesDerived: ReportAttributesDerivedValue['reports'] | undefined,
    privateIsArchivedMap: PrivateIsArchivedMap,
    formatPhoneNumber: LocaleContextProps['formatPhoneNumber'],
    config?: PreviewConfig,
    ) {
    if (isEmptyObject(personalDetails)) {
    return {
    currentUserOption: undefined,
    options: [],
    };
    }
    const currentUserRef = {
    current: undefined as OptionData | undefined,
    };
    const allPersonalDetailsOptions = [] as OptionData[];
    for (const personalDetail of Object.values(personalDetails)) {
    if (!personalDetail?.accountID) {
    continue;
    }
    const reportID = accountIDToReportIDMap[personalDetail.accountID];
    const report = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
    const reportAttributes = report?.reportID ? reportAttributesDerived?.[report.reportID] : undefined;
    const isReportArchived = privateIsArchivedMap[reportID];
    const option = createOption(personalDetail, report, formatPhoneNumber, config, reportAttributes, isReportArchived);
    allPersonalDetailsOptions.push(option);
    if (option.accountID === currentUserAccountID) {
    currentUserRef.current = option;
    }
    }
    return {
    currentUserOption: currentUserRef.current,
    options: allPersonalDetailsOptions,
    };
    }

    And the only exclusion helper in play matches @expensify.com / @team.expensify.com logins. Ordinary users retained from a former workspace or domain relationship are never excluded:

    App/src/libs/PolicyUtils.ts

    Lines 916 to 952 in a4b6ddf

    function getExpensifyTeamExclusions(personalDetails: OnyxEntry<PersonalDetailsList>, policies: OnyxCollection<Policy>, currentUserLogin: string | undefined): Record<string, boolean> {
    if (!currentUserLogin || isExpensifyTeam(currentUserLogin)) {
    return {};
    }
    const lowerCurrentUserLogin = currentUserLogin.toLowerCase();
    const allowedExpensifyTeamLogins = new Set<string>();
    for (const policy of Object.values(policies ?? {})) {
    if (!policy?.owner || !policy.employeeList || !isExpensifyTeam(policy.owner)) {
    continue;
    }
    const currentUserIsInPolicy = Object.keys(policy.employeeList).some((email) => email.toLowerCase() === lowerCurrentUserLogin);
    if (!currentUserIsInPolicy) {
    continue;
    }
    for (const email of Object.keys(policy.employeeList)) {
    const lowerEmail = email.toLowerCase();
    if (isExpensifyTeam(lowerEmail)) {
    allowedExpensifyTeamLogins.add(lowerEmail);
    }
    }
    }
    const exclusion: Record<string, boolean> = {};
    for (const details of Object.values(personalDetails ?? {})) {
    const login = details?.login?.toLowerCase();
    if (!login || !isExpensifyTeam(login)) {
    continue;
    }
    if (allowedExpensifyTeamLogins.has(login)) {
    continue;
    }
    exclusion[login] = true;
    }
    return exclusion;
    }

    I want to correct something explicitly, because it is easy to misread the history here: this is not a regression. getNonWorkspaceMemberExclusions (a workspace-members-only rule) was added and then replaced with the narrower Expensify-team rule inside PR #88921's own branch, so it never existed on main — git log --first-parent -S "getNonWorkspaceMemberExclusions" origin/main -- src/libs/PolicyUtils.ts returns nothing. The connectivity rule was deliberately scoped out of that PR, which is why this gap is still open.

    I reproduced this locally. On a fresh account the From filter listed only me and the one peer I share a report with. I then seeded three @company-b.com personal details into Onyx — no shared policy, no shared report, exactly the reported leftover state — reloaded, and all three rendered as selectable From options.

    This also explains the two details in the report. Because the list is a pure projection of whatever is currently hydrated, entries come and go as different API responses rehydrate personal details — matching "they sometimes disappear and then reappear". And a supportal session starts with a much smaller hydrated set than an account that has been accumulating personal details for years, which matches support seeing one Company B user while the affected user sees 10–20.

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

    I think we should add getSearchFilterUserExclusions() to PolicyUtils and apply it only to the from/to filters, by passing filterKey down into UserSelector. The helper builds an allow-list of accounts the current user is still connected to, and soft-excludes everything else:

    • every login in any visible policy's employeeList (current workspace members);
    • ownerAccountID / managerID of any accessible report (former members whose expense data is still searchable);
    • every participants key of any report (1:1 DM partners and other non-workspace contacts);
    • the current user;
    • any already-selected accountIDs.

    The last two bullets are load-bearing, and they are why I would not restore the old workspace-members-only rule. getValidOptions applies excludeFromSuggestionsOnly to the very personalDetails list that UserSelector renders:

    const filteringFunction = (personalDetail: OptionData) => {
    if (
    !personalDetail.login ||
    !personalDetail.accountID ||
    !!personalDetail.isOptimisticPersonalDetail ||
    (!includeDomainEmail && Str.isDomainEmail(personalDetail.login)) ||
    // Exclude the account executive (and its legacy "Setup Specialist" login) from the list of personal details as it's a fallback if guide is not assigned
    personalDetail.login === CONST.ACCOUNT_EXECUTIVE_LOGIN ||
    personalDetail.login === CONST.ACCOUNT_EXECUTIVE_LEGACY_LOGIN ||
    // Exclude any recent options from the personal details
    recentOptionsByAccountID.has(personalDetail.accountID)
    ) {
    return false;
    }
    if (loginsToExcludeFromSuggestions[personalDetail.login]) {
    return false;
    }
    return matchesSearchTerms(personalDetail, searchTerms);
    };
    personalDetailsOptions = optionsOrderBy(options, personalDetailsComparator, maxElements, filteringFunction, true).options;

    So a members-only rule would hide 1:1 chat partners (Search covers personal expenses and DMs, not just workspace data) and would strip an already-selected row from a saved search like from:someone@old-co.com, so the chip would no longer render as checked. Including report participants and selected accountIDs avoids both.

    Scoping matters too, because the same component serves four filters:

    case CONST.SEARCH.SYNTAX_FILTER_KEYS.ASSIGNEE:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.ATTENDEE:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.TO:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM:
    return (
    <UserSelector
    value={typeof value === 'object' ? value : undefined}
    key={filterKey}
    selectionListTextInputStyle={selectionListTextInputStyle}
    selectionListStyle={selectionListStyle}
    autoFocus={autoFocus}
    ready={ready}
    footer={footer}
    onChange={onChange}
    />

    attendee and assignee are not limited to the current user's own data, so passing filterKey lets us apply the rule to from/to and leave those two on the existing broad behaviour.

    The illustrative change in UserSelector:

    +const isParticipantScopedFilter = filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM || filterKey === CONST.SEARCH.SYNTAX_FILTER_KEYS.TO;
    +const searchFilterUserExclusions = isParticipantScopedFilter
    +    ? getSearchFilterUserExclusions(personalDetails, policies, connectedAccountReports, currentUserPersonalDetails.email, initialSelectedAccountIDs)
    +    : CONST.EMPTY_OBJECT;
    +
     usePersonalDetailSearchSelector({
    -    excludeFromSuggestionsOnly: expensifyTeamExclusions,
    +    excludeFromSuggestionsOnly: {...expensifyTeamExclusions, ...searchFilterUserExclusions},

    The reports collection is read through a lean selector that keeps only ownerAccountID, managerID and participants, so we are not pulling full reports into a filter component.

    These stay suggestion-only exclusions, so includeUserToInvite still lets anyone type an address manually — we only stop suggesting accounts that can never match a result.

    I implemented and verified this. Unit tests in PolicyUtilsTest cover a current workspace member, a former member reachable via an accessible expense report, a 1:1 participant, an unrelated stale entry, an already-selected value, and case-insensitive matching. In the browser, with the three stale entries still present in Onyx storage and the list confirmed rendered, they no longer appear in From, while the legitimate peer still does.

    What alternative solutions did you explore? (Optional)

    I explored restoring the workspace-members-only helper from PR #88921's branch. I rejected it for the two concrete reasons above: it hides 1:1 chat partners, and because soft exclusions are applied to the rendered list it silently drops already-selected rows from saved searches.

    I also considered pruning stale entries out of personalDetailsList itself. I would avoid that — the same list backs mentions, chat and report rendering, so deleting entries risks unresolved names elsewhere; scoping the suggestion list is the narrower and safer change.

  9. melvin-bot commented on Jul 23, 2026

    @melvin-bot

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

  10. wildan-m commented on Jul 23, 2026

    @wildan-m
    Contributor

    Proposal

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

    In Search (Spend > Expenses/Reports), the From / To filter dropdown offers users the account has no relationship with anymore — people from a different company/domain the account parted ways with about two years ago. Selecting one of them returns zero results. The list is also inconsistent: the entries sometimes disappear and then come back, and support (via supportal) sees only one of these accounts while the affected user sees 10–20.

    What is the root cause of that problem?

    The From/To filter renders UserSelector:

    case CONST.SEARCH.SYNTAX_FILTER_KEYS.ASSIGNEE:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.ATTENDEE:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.TO:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM:
    return (
    <UserSelector
    value={typeof value === 'object' ? value : undefined}
    key={filterKey}
    selectionListTextInputStyle={selectionListTextInputStyle}
    selectionListStyle={selectionListStyle}
    autoFocus={autoFocus}
    ready={ready}
    footer={footer}
    onChange={onChange}
    />
    );

    and UserSelector builds its option list through usePersonalDetailSearchSelector:

    const {searchTerm, setSearchTerm, availableOptions, totalOptionsCount, toggleSelection, areOptionsInitialized} = usePersonalDetailSearchSelector({
    selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI,
    initialSelected: initialSelectedAccountIDs,
    excludeLogins: CONST.EXPENSIFY_EMAILS_OBJECT,
    excludeFromSuggestionsOnly: expensifyTeamExclusions,
    includeUserToInvite: true,
    includeCurrentUser: false,
    includeRecentReports: false,
    shouldInitialize: ready,
    onSelectionChange: onChange,
    shouldKeepSelectedInAvailableOptions: true,
    });

    That hook gets its raw options from usePersonalDetailOptions, which passes the whole personalDetailsList Onyx value into createOptionList:

    const accountIDToReportIDMap = generateAccountIDToReportIDMap(reports, accountID);
    const privateIsArchivedMap = filterRNVPs(reportNameValuePairs, reportIDsSet);
    const filteredReportAttributes = filterReportAttributes(reportAttributes, reportIDsSet);
    const optionsData = !isLoading
    ? createOptionList(accountID, personalDetails, accountIDToReportIDMap, reports, filteredReportAttributes, privateIsArchivedMap, formatPhoneNumber, {
    shouldStoreReportErrors,
    shouldShowBrickRoadIndicator,
    })

    createOptionList then turns every single entry of that cached list into a selectable option. It looks up a report for the account, but a missing report is not a reason to drop the entry — the option is pushed either way, just without report data:

    for (const personalDetail of Object.values(personalDetails)) {
    if (!personalDetail?.accountID) {
    continue;
    }
    const reportID = accountIDToReportIDMap[personalDetail.accountID];
    const report = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
    const reportAttributes = report?.reportID ? reportAttributesDerived?.[report.reportID] : undefined;
    const isReportArchived = privateIsArchivedMap[reportID];
    const option = createOption(personalDetail, report, formatPhoneNumber, config, reportAttributes, isReportArchived);
    allPersonalDetailsOptions.push(option);
    if (option.accountID === currentUserAccountID) {
    currentUserRef.current = option;
    }
    }

    The last chance to drop them is the personal-details filter inside getValidOptions, but that filter only removes optimistic entries, domain emails, the Expensify/notifications/account-executive logins, and accounts already shown in the recent-reports bucket. There is no check for whether the current user still shares a report, workspace, or any accessible data with the account:

    const filteringFunction = (personalDetail: OptionData) => {
    if (
    !personalDetail.login ||
    !personalDetail.accountID ||
    !!personalDetail.isOptimisticPersonalDetail ||
    (!includeDomainEmail && Str.isDomainEmail(personalDetail.login)) ||
    // Exclude the account executive (and its legacy "Setup Specialist" login) from the list of personal details as it's a fallback if guide is not assigned
    personalDetail.login === CONST.ACCOUNT_EXECUTIVE_LOGIN ||
    personalDetail.login === CONST.ACCOUNT_EXECUTIVE_LEGACY_LOGIN ||
    // Exclude any recent options from the personal details
    recentOptionsByAccountID.has(personalDetail.accountID)
    ) {
    return false;
    }
    if (loginsToExcludeFromSuggestions[personalDetail.login]) {
    return false;
    }
    return matchesSearchTerms(personalDetail, searchTerms);
    };

    So the option list is exactly "everything that has ever been written into the local personalDetailsList cache". That key is only ever written with merge semantics — entries are added and updated, never removed — so accounts the backend stopped returning long ago (the Company B / Domain B people) stay in the cache indefinitely and keep showing up as filter options. Because the backend search knows nothing about them, filtering by one returns zero results.

    This also explains the two confusing symptoms in the report. Supportal starts from a clean client state, so it only sees what the backend actually returns today (one account), while the affected user sees the accumulated local cache (10–20). And the entries "disappear and reappear" because whenever the local cache is cleared or rebuilt the stale names go away, then partially come back as older data is re-merged.

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

    Scope the personal-detail options used by the Search From/To (and the other participant filters wired to the same component: To, Assignee, Attendee) to accounts the current user actually has a relationship with, instead of the entire cached personal-details list.

    Concretely:

    1. Add an opt-in option to the options builder in PersonalDetailOptionsListUtils — something like "only include accounts the user is related to". When it is on, the personal-details filtering function additionally requires that the account is related to the current user, meaning either the account has an associated report in the reports collection (this is already computed as the account-to-report map in usePersonalDetailOptions and surfaces on the option as its report ID), or the account appears in the employeeList of one of the policies the current user is a member of. Everything else in the cache is orphaned data with no report and no shared workspace — precisely the entries that produce zero search results today.

    2. Thread that option through usePersonalDetailSearchSelector as a new config flag, and turn it on only from UserSelector. Keeping it opt-in means the other consumers of the same hook (invite to workspace, new chat, assign task, split participants, etc.) are untouched — those flows legitimately need to offer people you do not share anything with yet.

    3. Keep any account IDs that are already selected in the filter visible regardless of the new check, so an existing saved search or an in-progress filter never silently drops its chips. UserSelector already passes the current value in as the initially selected set and asks for selected options to be kept in the available options, so this is a matter of exempting selected IDs from the new relationship check.

    This keeps the expected behaviour from the report intact: current workspace members and anyone you share a report with (including former colleagues whose expense/report data you can still open, because that data implies a report) continue to appear, while accounts that only exist as leftovers in the local cache stop being offered. It also keeps the fix purely on the client, where the stale data is actually being displayed.

    Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/96862-scope-search-participant-filter?expand=1

    What alternative solutions did you explore? (Optional)

    Prune the cached personal-details list instead of filtering at render time. Rather than scoping the filter, we could reconcile personalDetailsList on app open so accounts that the backend no longer returns are deleted from the local cache. This would fix the symptom everywhere at once, but it is much riskier: the key is written with merge semantics on purpose, many flows depend on holding on to personal details for accounts whose reports are not currently loaded, and deleting entries that were merely absent from a partial response would make names render as unknown across the app. The relationship check at the option-building layer is the narrower and safer change.

    Filter only by the presence of a report ID on the option. This is a one-line version of the same idea, but it would wrongly hide workspace members you have not started a chat with, so it needs the policy employeeList half as well.

  11. 10 remaining items

  12. github-actions commented on Jul 24, 2026

    @github-actions
    Contributor

    ⚠️ @lorretheboy Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  13. Dip-G-Git commented on Jul 24, 2026

    @Dip-G-Git

    Proposal

    Reviewing the code and preparing a detailed root-cause analysis — this comment will be updated with the full proposal shortly.

  14. nabi-ebrahimi commented on Jul 24, 2026

    @nabi-ebrahimi
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-07-24 10:45:59 UTC.

    Proposal

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

    The Spend From and To filters suggest users who have no relevant expenses or reports accessible to the current user. Selecting one produces zero search results.

    What is the root cause of that problem?

    From, To, Assignee, and Attendee share the generic UserSelector component. UserSelector builds its options from the complete PERSONAL_DETAILS_LIST via createOptionList(), which creates an option for every personal detail with an accountID. getValidOptions() applies only generic exclusions — no Spend-specific relevance check exists.

    The critical distinction from prior proposals: From and To are not symmetric filters, and they do not share the same candidate set. Search derives them from different roles that do not map to report.participants:

    • Transaction From (SearchUIUtils.ts:2145): reportAction?.actorAccountID ?? report?.ownerAccountID — the money-request action actor, falling back to report owner.
    • Report From (SearchUIUtils.ts:2966): report.ownerAccountID.
    • Transaction To (SearchUIUtils.ts:1708-1726): For PAY actions, the report owner. For IOUs, the payer/receiver selected by getIOUPayerAndReceiver based on amount sign. Otherwise, report.managerID.

    A single "users who share a report or workspace" gate is therefore incorrect: it includes arbitrary chat participants who have no From/To value in any accessible Spend result, while excluding owners/managers who are valid filter values but absent from report.participants.

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

    Create a Search-specific helper that derives suggestion exclusions with separate candidate sets for FROM and TO.

    Common allowed accounts (both From and To):

    • Members of workspaces accessible to the current user (via getMemberAccountIDsForWorkspace).
    • The current user.
    • Account IDs already selected in the filter (saved searches and existing chips).

    From-specific allowed accounts:

    • ownerAccountID from accessible Expense, IOU, and Invoice reports.
    • actorAccountID from money-request actions, when Search uses the actor as the transaction's From value.

    To-specific allowed accounts:

    • managerID from accessible Spend reports.
    • IOU payer/receiver accounts, using getIOUPayerAndReceiver direction logic.
    • The report owner for PAY actions.

    Return an exclusion map via excludeFromSuggestionsOnly — not excludeLogins — so already-selected values remain and users can enter an exact email manually.

    Apply to both surfaces:

    1. The advanced-filter UserSelector (RHP panel).
    2. Inline query autocomplete for from: and to: keys in the search bar.

    Pass filterKey to UserSelector and enable this only for FROM and TO. Do not change Assignee, Attendee, Payer, Exporter, invitation, or IOU participant selectors.

    Use lean Onyx selectors and memoize derived sets. Place the helper in a Search-specific module (e.g., SearchUserFilterUtils), not PolicyUtils.

    What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

    • An unrelated personal detail does not appear in From or To.
    • A current workspace member remains visible.
    • A report owner not in report.participants appears in From.
    • A report manager not in report.participants appears in To.
    • A money-request action actor appears in From when the actor differs from the owner.
    • IOU payer/receiver direction produces the correct To option.
    • A PAY action renders the report owner as To, not the manager.
    • An already-selected unrelated account continues to render.
    • Advanced-filter and inline-autocomplete suggestions are consistent.
    • Assignee and Attendee behavior remains unchanged.
    • Exact manual email input remains possible.
    • The selector works with offline or partially hydrated Onyx data.

    What alternative solutions did you explore? (Optional)

    A single "users related to the current user" exclusion gate (workspace members + report participants) is simpler but incorrect. It includes arbitrary chat participants who have no From/To value in Spend results while excluding report owners and managers who are valid filter values but absent from report.participants. The role-specific FROM/TO candidate separation is required to match the actual search rendering logic.

    Pruning PERSONAL_DETAILS_LIST is unsafe because it is shared state used by chat, IOU, invitation, and other features. The available evidence does not prove the cache contents are invalid.

    A backend-provided list of valid From/To facets would be most authoritative and would handle incomplete client hydration, but requires an API change. The proposed role-based projection is a smaller fix structured so server-provided facets can replace it later.

  15. github-actions commented on Jul 24, 2026

    @github-actions
    Contributor

    ⚠️ @nabi-ebrahimi Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  16. x-dev90 commented on Jul 24, 2026

    @x-dev90
    Contributor

    Proposal

    What is the root cause of that problem?

    The From and To filters (along with Assignee and Attendee) all render the same UserSelector component, and it builds its option list from the entire client-side PERSONAL_DETAILS_LIST with no check for whether the account still shares a workspace or report with the current user.

    UserSelector sources its options from usePersonalDetails() — the whole PERSONAL_DETAILS_LIST — and passes it into the search selector, requesting only Expensify/system-email exclusions. There is no accessibility scoping here:

    const personalDetails = usePersonalDetails();
    const currentUserPersonalDetails = useCurrentUserPersonalDetails();
    const shouldFocusInputOnScreenFocus = autoFocus && canFocusInputOnScreenFocus();
    const [isSearchingForReports] = useOnyx(ONYXKEYS.RAM_ONLY_IS_SEARCHING_FOR_REPORTS);
    const [policies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
    const initialSelectedAccountIDs = value.reduce<Set<string>>((acc, id) => {
    const participant = personalDetails?.[id];
    if (!participant) {
    return acc;
    }
    acc.add(id);
    return acc;
    }, new Set<string>());
    const expensifyTeamExclusions = getExpensifyTeamExclusions(personalDetails, policies, currentUserPersonalDetails.email);
    const {searchTerm, setSearchTerm, availableOptions, totalOptionsCount, toggleSelection, areOptionsInitialized} = usePersonalDetailSearchSelector({
    selectionMode: CONST.SEARCH_SELECTOR.SELECTION_MODE_MULTI,
    initialSelected: initialSelectedAccountIDs,
    excludeLogins: CONST.EXPENSIFY_EMAILS_OBJECT,
    excludeFromSuggestionsOnly: expensifyTeamExclusions,
    includeUserToInvite: true,
    includeCurrentUser: false,
    includeRecentReports: false,
    shouldInitialize: ready,
    onSelectionChange: onChange,
    shouldKeepSelectedInAvailableOptions: true,
    });

    That list is produced by createOptionList, which turns every personal-details entry that has an accountID into a selectable option — a shared report is only attached to enrich the option, never used to drop an account that shares nothing:

    for (const personalDetail of Object.values(personalDetails)) {
    if (!personalDetail?.accountID) {
    continue;
    }
    const reportID = accountIDToReportIDMap[personalDetail.accountID];
    const report = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
    const reportAttributes = report?.reportID ? reportAttributesDerived?.[report.reportID] : undefined;
    const isReportArchived = privateIsArchivedMap[reportID];
    const option = createOption(personalDetail, report, formatPhoneNumber, config, reportAttributes, isReportArchived);
    allPersonalDetailsOptions.push(option);
    if (option.accountID === currentUserAccountID) {
    currentUserRef.current = option;
    }
    }

    getValidOptions then filters that list, but only removes entries with no login/accountID, optimistic details, domain emails, the account-executive logins, and search-term mismatches. It never checks shared policy or report membership:

    const filteringFunction = (personalDetail: OptionData) => {
    if (
    !personalDetail.login ||
    !personalDetail.accountID ||
    !!personalDetail.isOptimisticPersonalDetail ||
    (!includeDomainEmail && Str.isDomainEmail(personalDetail.login)) ||
    // Exclude the account executive (and its legacy "Setup Specialist" login) from the list of personal details as it's a fallback if guide is not assigned
    personalDetail.login === CONST.ACCOUNT_EXECUTIVE_LOGIN ||
    personalDetail.login === CONST.ACCOUNT_EXECUTIVE_LEGACY_LOGIN ||
    // Exclude any recent options from the personal details
    recentOptionsByAccountID.has(personalDetail.accountID)
    ) {
    return false;
    }
    if (loginsToExcludeFromSuggestions[personalDetail.login]) {
    return false;
    }
    return matchesSearchTerms(personalDetail, searchTerms);
    };

    So the causal chain is: the client's PERSONAL_DETAILS_LIST retains accounts encountered in the past (the Company B / Domain B users from before the split ~2 years ago) and is never pruned → createOptionList makes an option for each of them → getValidOptions has no shared-workspace/report rule to drop them → they render as selectable From / To options even though the user shares no workspace or report with them, and filtering by them returns zero results because there is no accessible data. This is longstanding behavior (the option-building loop was last touched by a general refactor in #83310, not introduced as a regression). It also explains why supportal, on a fresh session, sees only the one still-shared Company B user while the affected user — whose local Onyx cache has accumulated stale accounts — sees 10–20.

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

    Approach: scope the From / To option list to accounts the current user still has a relationship with — members of any policy the user belongs to, plus participants of any report available to the user — while always keeping any accountIDs already present in the applied filter value. This matches the Expected Result (current workspace/report members and former members with accessible expense/report data) and drops accounts, like the split-off Company B users, that share neither.

    Implementation: in UserSelector, derive an "accessible accountID" set from data already synced on the client — policy member accountIDs via getMemberAccountIDsForWorkspace over the policies the current user belongs to, plus participant accountIDs from the reports in the REPORT collection the user can access — then restrict the rendered personal-details options to accountIDs in that set, unioned with the initialSelectedAccountIDs already computed in the component so saved-search chips keep rendering. Because UserSelector is the single component behind the From, To, Assignee, and Attendee filters, this fixes all four consistently. The set is derived purely from already-synced Onyx data, so it works offline with no new API calls.

    Regression test: render the From filter with a PERSONAL_DETAILS_LIST that contains an account which is neither a member of any of the current user's policies nor a participant in any accessible report, and assert it does not appear as an option; assert that an account sharing a policy or report does appear; and assert that an accountID already present in the filter value still renders even when it shares neither.

    What alternative solutions did you explore? (Optional)

    Prune stale entries from PERSONAL_DETAILS_LIST itself. The evidence (supportal on a fresh session sees only one Company B user, and the entries "disappear and reappear") points to the client cache accumulating accounts that are never cleaned up, so fixing the data at the source would help every surface, not just this filter. Trade-off: deciding which accounts are safe to drop and how they re-hydrate is a data-layer/backend concern that is larger and riskier than a targeted filter, and it must still retain former-but-accessible members, so it does not remove the need for correct scoping in the selector.

    Add an accessibility-scoping option to getValidOptions / usePersonalDetailSearchSelector and opt the search filter into it. Trade-off: reusable for other selectors, but it changes a shared util used by many flows (IOU participant pickers, member invites) that intentionally show the full contact list, increasing the regression surface versus keeping the logic local to UserSelector.

  17. github-actions commented on Jul 24, 2026

    @github-actions
    Contributor

    ⚠️ @x-dev90 Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  18. nabi-ebrahimi commented on Jul 24, 2026

    @nabi-ebrahimi
    Contributor

    This proposal is distinct from ahmdshrif's in three specific ways:

    1. FROM/TO are not symmetric. ahmdshrif uses a single "related users" gate for both. This proposal builds separate candidate sets because SearchUIUtils.ts:2145 derives From from actorAccountID ?? ownerAccountID, while SearchUIUtils.ts:1708-1726 derives To from managerID / IOU direction / PAY action owner — different roles, different users.
    2. Report participants are insufficient. ahmdshrif includes report.participants. A report owner (ownerAccountID) is often absent from participants but is a valid From value. This proposal keys on ownerAccountID, managerID, actorAccountID, and IOU direction logic instead.
    3. Money-request actor and PAY action. No prior proposal accounts for delegated submissions (reportAction.actorAccountID at line 2145) or the PAY-action special case where To becomes the owner (line 1708), not the manager.
  19. melvin-bot commented on Jul 28, 2026

    @melvin-bot

    @bernhardoj Eep! 4 days overdue now. Issues have feelings too...

  20. yusufdeveloper2903 commented on Jul 29, 2026

    @yusufdeveloper2903
    Contributor

    Proposal

    What is the root cause of that problem?

    The "From" / "To" (and Assignee / Attendee) advanced filter is rendered by UserSelector, which every one of those filter keys maps to:

    case CONST.SEARCH.SYNTAX_FILTER_KEYS.ASSIGNEE:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.ATTENDEE:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.TO:
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.FROM:
    return (
    <UserSelector
    value={typeof value === 'object' ? value : undefined}
    key={filterKey}
    selectionListTextInputStyle={selectionListTextInputStyle}
    selectionListStyle={selectionListStyle}
    autoFocus={autoFocus}
    ready={ready}
    footer={footer}
    onChange={onChange}
    />
    );
    case CONST.SEARCH.SYNTAX_FILTER_KEYS.POLICY_ID:

    UserSelector builds its option pool from usePersonalDetails(), which is bound directly to the Onyx PERSONAL_DETAILS_LIST collection — OnyxListItemProvider.tsx:13. That map is then fed through usePersonalDetailSearchSelector → usePersonalDetailOptions → createOptionList(accountID, personalDetails, …), which turns every entry in the map into a selectable option. The only entry it skips is one missing an accountID:

    for (const personalDetail of Object.values(personalDetails)) {
    if (!personalDetail?.accountID) {
    continue;
    }
    const reportID = accountIDToReportIDMap[personalDetail.accountID];
    const report = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`];
    const reportAttributes = report?.reportID ? reportAttributesDerived?.[report.reportID] : undefined;
    const isReportArchived = privateIsArchivedMap[reportID];
    const option = createOption(personalDetail, report, formatPhoneNumber, config, reportAttributes, isReportArchived);
    allPersonalDetailsOptions.push(option);
    if (option.accountID === currentUserAccountID) {
    currentUserRef.current = option;
    }
    }

    The accountIDToReportIDMap / reports arguments here are used only to decorate an option with a report for display — they are not a membership gate. A user you no longer share any report with simply gets reportID = undefined and is still pushed into the list.

    Downstream, getValidOptions filters that pool, but not by relevance. Its personal-details filteringFunction drops an entry only when it has no login/accountID, is an optimistic detail, is a domain email, is an account-executive login, is a recent-report duplicate, is an explicitly-excluded login (the Expensify-team logins UserSelector passes), or fails the search string:

    const filteringFunction = (personalDetail: OptionData) => {
    if (
    !personalDetail.login ||
    !personalDetail.accountID ||
    !!personalDetail.isOptimisticPersonalDetail ||
    (!includeDomainEmail && Str.isDomainEmail(personalDetail.login)) ||
    // Exclude the account executive (and its legacy "Setup Specialist" login) from the list of personal details as it's a fallback if guide is not assigned
    personalDetail.login === CONST.ACCOUNT_EXECUTIVE_LOGIN ||
    personalDetail.login === CONST.ACCOUNT_EXECUTIVE_LEGACY_LOGIN ||
    // Exclude any recent options from the personal details
    recentOptionsByAccountID.has(personalDetail.accountID)
    ) {
    return false;
    }
    if (loginsToExcludeFromSuggestions[personalDetail.login]) {
    return false;
    }
    return matchesSearchTerms(personalDetail, searchTerms);
    };

    There is no check for whether the account still shares a current workspace or an accessible report with the viewer. UserSelector compounds this by passing includeRecentReports: false, so the list is never even scoped to people you have recent reports with.

    Why the stale accounts are still in the cache to begin with: PERSONAL_DETAILS_LIST is not an evictable Onyx key — setup/index.ts:41-47 lists only report-action collections — and member removal never writes PERSONAL_DETAILS_LIST (removeMembers touches employeeList, reports and room members only). So once a personal detail is seeded from an old workspace/domain relationship, it lives in the local cache indefinitely — including the Company B / Domain B users from ~2 years ago — and each one is offered as a filter option.

    This matches the report precisely: filtering by these accounts "returns zero results" because they share no accessible report/transaction with the user, and supportal — reading the server's authoritative data — sees only the one still-relevant Company B account, while the client's stale cache surfaces 10-20. The intermittent disappear/reappear is consistent with an OpenApp/ReconnectApp refresh momentarily dropping entries the backend no longer returns, then those same accountIDs being re-seeded from still-cached reports that reference them — but the stable defect is the missing relevance gate above.

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

    The mention suggester already builds its list from the same PERSONAL_DETAILS_LIST, and in a workspace/group context it keys relevance on the exact two predicates the From/To filter is missing — policy.employeeList[detail.login] and isReportParticipant(detail.accountID, currentReport):

    const shouldWeightDetails = isGroupChat(currentReport) || doesReportBelongToWorkspace(currentReport, policyID, conciergeReportID);
    let personalDetailsParam: PersonalDetailsList | SuggestionPersonalDetailsList | undefined;
    if (!shouldWeightDetails) {
    personalDetailsParam = personalDetails;
    } else {
    const isPolicyEmployee = (detail: PersonalDetails): boolean => {
    if (!detail.login || detail.accountID === currentUserPersonalDetails.accountID) {
    return false;
    }
    const policyEmployee = policy?.employeeList?.[detail.login];
    return !!policyEmployee && isEmptyObject(policyEmployee.errors);
    };
    // Smaller weight means higher order in suggestion list
    const getPersonalDetailsWeight = (detail: PersonalDetails): number => {
    if (isReportParticipant(detail.accountID, currentReport)) {
    return 0;
    }
    if (isPolicyEmployee(detail)) {
    return 1;
    }
    return 2;
    };
    personalDetailsParam = lodashMapValues(personalDetails, (detail) => (detail ? {...detail, weight: getPersonalDetailsWeight(detail)} : null));

    We should apply that same membership relevance to the From/To filter, as a hard gate rather than a weight. Concretely:

    1. In UserSelector, compute the set of accountIDs the viewer still shares data with — members of every policy in policies (via getMemberAccountIDsForWorkspace) unioned with the participants of the reports the client has access to — and pass it as a new optional relevantAccountIDs config to usePersonalDetailSearchSelector.

    2. Thread relevantAccountIDs into the getValidOptions call (base.ts:215-231) and add one clause to the personal-details filteringFunction:

    // when a relevance set is provided, only suggest people the viewer still shares data with
    // (already-selected values are kept so an applied filter chip is never dropped)
    if (relevantAccountIDs && !relevantAccountIDs.has(personalDetail.accountID) && !personalDetail.isSelected) {
        return false;
    }

    Only UserSelector passes relevantAccountIDs; when it is omitted the filter behaves exactly as today.

    This is safe because:

    • Already-applied filter values survive: UserSelector passes shouldKeepSelectedInAvailableOptions: true and the new clause exempts isSelected, so a stale account you have already selected as a filter is never removed from the list.
    • Typed addresses still work: includeUserToInvite: true builds the userToInvite option independently of the personal-details filteringFunction, so you can still enter any email/phone that isn't in the suggestion set.
    • Every other consumer of this shared hook — the workspace-invite, delegate, task-assignee and approval selectors — omits relevantAccountIDs, so their intentionally-broad contact lists are unchanged.
    • The excluded accounts share no accessible report and no current workspace with the viewer, so filtering by them returns zero results regardless — the gate removes only options that could never match anything.
    • The predicates (policy.employeeList membership + report participation) are already trusted for this exact purpose in the mention suggester.

    Note: the relevance set must be the union of report participation and policy membership, not the narrow accountIDToReportIDMap that usePersonalDetailOptions already computes — that map is built from only 1:1 chats and self-DMs, so reusing it would wrongly drop legitimate From/To candidates you share an expense report or a workspace with but no 1:1 chat. A former member with accessible expense/report data still appears because they remain a participant of a report the client can access.

    We can also apply the same relevance set to the typed from: / to: autocomplete, which draws from the same unfiltered pool through SearchAutocompleteList → OptionsListUtils.getSearchOptions.

    What alternative solutions did you explore? (Optional)

    Purge PERSONAL_DETAILS_LIST when a member/domain relationship ends (evict the key or clear entries in removeMembers). Rejected: it cannot retroactively clean the reporter's already-stale cache (2 years of accumulated entries), the personal detail is still legitimately needed to render historical reports/transactions that reference the accountID, and the observed flicker shows entries get re-seeded from those references anyway. The filter should present a relevance-bounded list regardless of what the local cache happens to hold.

  21. github-actions commented on Jul 29, 2026

    @github-actions
    Contributor

    ⚠️ @yusufdeveloper2903 Your proposal is a duplicate of an already existing proposal and has been automatically withdrawn to prevent spam. Please review the existing proposals before submitting a new one.

  22. trjExpensify commented on Jul 29, 2026

    @trjExpensify
    Contributor

    Closing in favour of an improvement.

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

Metadata

Metadata

Assignees

Labels

BugDailyExternalHelp WantedNeeds Reproduction

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions