Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(command): discover CRM contacts in Command-K (#7648)
gbirman546d8f32de2b
diff --git a/apps/web/src/features/command/CommandItem.tsx b/apps/web/src/features/command/CommandItem.tsxindex b51d58b96c..8489bf0111 100644--- a/apps/web/src/features/command/CommandItem.tsx+++ b/apps/web/src/features/command/CommandItem.tsx@@ -1,7 +1,7 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';import { UserIcon } from '@core/component/UserIcon';import { hasValidHotkey } from '@core/hotkey/utils';-import { Entity, type EntityData } from '@entity';+import { type CrmContactEntity, Entity, type EntityData } from '@entity';import SearchIcon from '@phosphor/magnifying-glass.svg';import PlusIcon from '@phosphor/plus.svg';import WideStar from '@phosphor/sparkle.svg';@@ -153,6 +153,25 @@ function EntityDisplay(props: { entity: EntityData }) {);}+function ContactDisplay(props: { contact: CrmContactEntity }) {+ const showEmail = () =>+ Boolean(props.contact.name) && props.contact.name !== props.contact.email;++ return (+ <div class="flex items-center gap-2 flex-1 min-w-0">+ <div class="size-5 p-0.5 flex items-center justify-center text-ink-muted shrink-0">+ <Entity.Icon entity={props.contact} />+ </div>+ <span class="truncate">+ <Show when={showEmail()} fallback={props.contact.email}>+ {props.contact.name}+ <span class="ml-[0.5em] opacity-50">{props.contact.email}</span>+ </Show>+ </span>+ </div>+ );+}+function UserDisplay(props: { item: UserItem }) {const name = () => props.item.data.name;const email = () => props.item.data.email;@@ -226,6 +245,15 @@ function ItemDisplay(props: { item: CommandMenuItem }) {<Match when={isCommandItem(props.item) && props.item}>{(item) => <CommandDisplay item={item()} />}</Match>+ <Match+ when={+ isEntityItem(props.item) &&+ props.item.data.type === 'crm_contact' &&+ props.item.data+ }+ >+ {(contact) => <ContactDisplay contact={contact()} />}+ </Match><Match when={isEntityItem(props.item) && props.item}>{(item) => <EntityDisplay entity={item().data} />}</Match>diff --git a/apps/web/src/features/command/CommandMenu.tsx b/apps/web/src/features/command/CommandMenu.tsxindex 83c94a95fe..865abd3d9a 100644--- a/apps/web/src/features/command/CommandMenu.tsx+++ b/apps/web/src/features/command/CommandMenu.tsx@@ -1,5 +1,6 @@import { isListViewID } from '@app/constants/list-views';import { openChatWithMessage } from '@app/features/chat/ChatWithAgentButton';+import { useCrmContactDiscovery } from '@app/features/crm/record-adapter';import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-presets';import { getSearchSplit } from '@app/features/next-soup/soup-view/search-controllers';import { useAnalytics } from '@app/lib/analytics/analytics-context';@@ -27,6 +28,7 @@ import { type EntityData, isGithubPrEntity } from '@entity';import { EntitySelectionBadge } from '@entity/components/EntitySelectionBadge';import Macro from '@icon/macro-logo.svg';import ArrowLeft from '@phosphor/arrow-left.svg';+import { useGetOrCreateDirectMessageMutation } from '@queries/channel/get-or-create-dm';import { useDatabaseDiscoverySync } from '@queries/storage/databases';import {Badge,@@ -66,6 +68,7 @@ import {isCommandItem,isEntityItem,isSearchItem,+ isUserItem,type PaginationControls,useCommandItems,} from './useCommandItems';@@ -181,6 +184,7 @@ export function CommandMenuInner(props: {? undefined: useCommandItems(query, categoryFilter, {searchActive: CommandState.isOpen,+ contactDiscovery: useCrmContactDiscovery,});const filteredItems = props.items ?? defaultCommandItems!.items;const pagination = defaultCommandItems?.pagination;@@ -200,17 +204,34 @@ export function CommandMenuInner(props: {}});+ // Skip past the search row only onto a real result — when the query has+ // no results the rows below are fallbacks (ask AI), and the search row+ // should stay the default.+ const resultFollowsSearchRow = () => {+ const items = filteredItems();+ return Boolean(+ items[0] && isSearchItem(items[0]) && items[1] && !isAskAiItem(items[1])+ );+ };createEffect(on([query, categoryFilter], () => {- const items = filteredItems();- const firstIsSearch = items[0] && isSearchItem(items[0]);- // Skip past the search row only onto a real result — when the query has- // no results the rows below are fallbacks (ask AI), and the search row- // should stay the default.- const secondIsResult = items[1] && !isAskAiItem(items[1]);- listController.setSelectedIndex(firstIsSearch && secondIsResult ? 1 : 0);+ listController.setSelectedIndex(resultFollowsSearchRow() ? 1 : 0);}));+ // Results fetched from the server (CRM contacts outside the cache, projects)+ // can appear after the query changes; the first one takes the default+ // selection the search row held until then.+ createEffect(+ on(+ resultFollowsSearchRow,+ (hasResult, hadResult) => {+ if (hasResult && !hadResult && CommandState.selectedIndex() === 0) {+ listController.setSelectedIndex(1);+ }+ },+ { defer: true }+ )+ );const selectedItem = () => {const items = filteredItems();@@ -241,7 +262,10 @@ export function CommandMenuInner(props: {};const selectedIsEntity = () => {const item = selectedItem();- return item && (isEntityItem(item) || item.kind === 'initiative');+ return (+ item &&+ (isEntityItem(item) || isUserItem(item) || item.kind === 'initiative')+ );};const selectedIsSearch = () => {const item = selectedItem();@@ -252,6 +276,29 @@ export function CommandMenuInner(props: {return item && isAskAiItem(item);};+ const getOrCreateDirectMessage = useGetOrCreateDirectMessageMutation();+ // A person without a conversation yet: open one, as the user card does.+ const openDirectMessage = async (+ recipientId: string,+ openInNewSplit: boolean+ ) => {+ try {+ const { channel_id } = await getOrCreateDirectMessage.mutateAsync({+ recipient_id: recipientId,+ });+ openWithSplit(+ { type: 'channel', id: channel_id },+ {+ referredFrom: 'kommand-menu',+ preferNewSplit: openInNewSplit,+ reopen: 'latest',+ }+ );+ } catch {+ toast.failure('Unable to open conversation. Please try again.');+ }+ };+function handleItemAction(item: CommandMenuItem, openInNewSplit = false) {if (!item) return;if (@@ -382,6 +429,13 @@ export function CommandMenuInner(props: {return;}+ if (isUserItem(item)) {+ void openDirectMessage(item.id, openInNewSplit);+ CommandState.close();+ CommandState.setQuery('');+ return;+ }+if (isAskAiItem(item)) {// Opens a new agent session and sends the query when ready.void openChatWithMessage(item.query);diff --git a/apps/web/src/features/command/contact-items.ts b/apps/web/src/features/command/contact-items.tsnew file mode 100644index 0000000000..4dbeea6b88--- /dev/null+++ b/apps/web/src/features/command/contact-items.ts@@ -0,0 +1,55 @@+import type {+ EntityItem,+ QuickAccessItem,+ UserItem,+} from '@core/context/quickAccess';+import {+ resolveContactPeople,+ toCrmContactItem,+} from '@core/context/quickAccess/crm-contacts';+import type { CrmContactEntity } from '@entity';++function directMessagesByUser(+ directMessages: readonly QuickAccessItem[],+ viewerId: string | undefined+) {+ const byUser = new Map<string, EntityItem>();+ for (const item of directMessages) {+ if (item.kind !== 'entity' || item.data.type !== 'channel') continue;+ if (item.data.channelType !== 'direct_message') continue;+ const others = (item.data.participantIds ?? []).filter(+ (id) => id !== viewerId+ );+ if (others.length === 1) byUser.set(others[0], item);+ }+ return byUser;+}++/**+ * One People row per discovered contact email. A contact who is a Macro user+ * becomes that person's direct message: the existing conversation when the+ * viewer has one, else the user, whose selection opens one. The contact's+ * name stays searchable on that row so a CRM-only alias still ranks it.+ */+export function contactCommandItems(options: {+ contacts: readonly CrmContactEntity[];+ users: readonly UserItem[];+ directMessages: readonly QuickAccessItem[];+ viewerId: string | undefined;+}): (EntityItem | UserItem)[] {+ const conversations = directMessagesByUser(+ options.directMessages,+ options.viewerId+ );+ return resolveContactPeople(+ options.contacts.map(toCrmContactItem),+ options.users+ ).map(({ contact, user }) => {+ if (!user) return contact;+ const conversation = conversations.get(user.id) ?? user;+ return {+ ...conversation,+ searchText: `${conversation.searchText} | ${contact.searchText}`,+ };+ });+}diff --git a/apps/web/src/features/command/rank-command-search-items.test.ts b/apps/web/src/features/command/rank-command-search-items.test.tsindex 2a3686fcd8..e372fd4df1 100644--- a/apps/web/src/features/command/rank-command-search-items.test.ts+++ b/apps/web/src/features/command/rank-command-search-items.test.ts@@ -134,4 +134,27 @@ describe('command menu search ranking', () => {];expect(ids(items, 'qtr')).toEqual(['direct-match', 'project']);});++ it('keeps server-matched people the fuzzy matcher misses, without the cache projection', () => {+ const person: CommandMenuItem = {+ id: 'macro|[email protected]',+ kind: 'user',+ bucket: 'person',+ searchText: 'Asher Smith | [email protected]',+ sortTimestamp: NOW,+ timestamps: {},+ data: {+ id: 'macro|[email protected]',+ email: '[email protected]',+ name: 'Asher Smith',+ },+ };+ const items = [person, channel('unrelated', 'Planning')];+ expect(+ rankCommandSearchItems(items, 'hckrnn', {+ preserveAdditionalEntityMatches: false,+ preservedIds: new Set([person.id]),+ }).map((item) => item.id)+ ).toEqual([person.id]);+ });});diff --git a/apps/web/src/features/command/rank-command-search-items.ts b/apps/web/src/features/command/rank-command-search-items.tsindex 2f6fcf228e..59af0ca5f6 100644--- a/apps/web/src/features/command/rank-command-search-items.ts+++ b/apps/web/src/features/command/rank-command-search-items.ts@@ -25,7 +25,12 @@ function compareRecency(left: CommandMenuItem, right: CommandMenuItem) {export function rankCommandSearchItems(items: CommandMenuItem[],query: string,- options: { preserveAdditionalEntityMatches: boolean }+ options: {+ preserveAdditionalEntityMatches: boolean;+ /** Rows a server search already matched, kept even when the menu's+ * fuzzy matcher would not match them. */+ preservedIds?: ReadonlySet<string>;+ }): CommandMenuItem[] {const ranked = search(items, query).sort(@@ -34,17 +39,18 @@ export function rankCommandSearchItems(compareRecency(left.item, right.item)).map(({ item }) => item);- if (!options.preserveAdditionalEntityMatches) return ranked;+ const preserved = (item: CommandMenuItem) =>+ options.preservedIds?.has(item.id) ||+ (options.preserveAdditionalEntityMatches &&+ (item.kind === 'entity' || item.kind === 'initiative'));+ if (!options.preserveAdditionalEntityMatches && !options.preservedIds?.size)+ return ranked;// Cache search accepts broader subsequences than the menu's fuzzy matcher.// Keep these additional matches reachable after the regular ranked results.const matchedIds = new Set(ranked.map((item) => item.id));const additional = items- .filter(- (item) =>- (item.kind === 'entity' || item.kind === 'initiative') &&- !matchedIds.has(item.id)- )+ .filter((item) => preserved(item) && !matchedIds.has(item.id)).sort(compareRecency);return [...ranked, ...additional];}diff --git a/apps/web/src/features/command/state.test.ts b/apps/web/src/features/command/state.test.tsindex c3f1cb3bc6..3e56c5dc7a 100644--- a/apps/web/src/features/command/state.test.ts+++ b/apps/web/src/features/command/state.test.ts@@ -17,3 +17,12 @@ describe('command menu hint', () => {expect(run).not.toHaveBeenCalled();});});++describe('command menu query', () => {+ it('does not carry a closed search into the next opening', () => {+ CommandState.onMenuOpen();+ CommandState.setQuery('kappelhoff');+ CommandState.onMenuClose();+ expect(CommandState.query()).toBe('');+ });+});diff --git a/apps/web/src/features/command/state.ts b/apps/web/src/features/command/state.tsindex b5d52bc37b..f97d7631de 100644--- a/apps/web/src/features/command/state.ts+++ b/apps/web/src/features/command/state.ts@@ -176,6 +176,9 @@ function createCommandState(): ICommandState {function onMenuClose() {setLastClosedTime(Date.now());setHint(undefined);+ // Opening clears the query too late for a menu that mounts reading it, and+ // the previous search's results would briefly reappear.+ clearQuery();clearCommandScopeCommands();clearEntityActionEntities();}diff --git a/apps/web/src/features/command/useCommandItems.contacts.test.ts b/apps/web/src/features/command/useCommandItems.contacts.test.tsnew file mode 100644index 0000000000..c0356c31f7--- /dev/null+++ b/apps/web/src/features/command/useCommandItems.contacts.test.ts@@ -0,0 +1,251 @@+import type {+ Bucket,+ EntityItem,+ QuickAccessItem,+ QuickAccessList,+ UserItem,+} from '@core/context/quickAccess/types';+import type { CrmContactEntity } from '@entity';+import { type Accessor, createRoot, createSignal } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { CategoryFilter } from './types';+import { type CommandContactSource, useCommandItems } from './useCommandItems';++const VIEWER = 'macro|[email protected]';++const mocks = vi.hoisted(() => ({+ lists: {} as Record<string, () => QuickAccessItem[]>,+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: false, loading: false }),+}));+vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'macro|[email protected]',+}));+vi.mock('../projects/project-search', () => ({+ useProjectSearchQuery: () => ({+ rows: () => undefined,+ error: () => undefined,+ }),+}));+vi.mock('@app/constants/hotkeys', () => ({+ GO_TO_COMMAND_SCOPE: 'go-to',+ GO_TO_LEADER_KEY: 'g',+}));+vi.mock('@core/context/quickAccess', () => ({+ useQuickAccess: () => ({+ useList: (first: Bucket | { buckets: readonly Bucket[] }) => {+ const key = typeof first === 'string' ? first : 'category';+ const items = () => mocks.lists[key]?.() ?? [];+ return {+ items,+ totalCount: () => items().length,+ hasMore: () => false,+ isLoading: () => false,+ isLoadingMore: () => false,+ loadMore: async () => {},+ } satisfies QuickAccessList;+ },+ usesRecordSelection: () => false,+ usesSearchProjection: () => false,+ }),+}));+vi.mock('@core/context/quickAccess/types', () => ({+ exclude: () => ['dm', 'note'],+}));+vi.mock('@core/hotkey/getCommands', () => ({+ getActiveCommandsFromScope: () => [],+}));+vi.mock('@core/hotkey/state', () => ({+ activeScope: () => 'global',+ hotkeyScopeTree: new Map(),+}));+vi.mock('./recency', () => ({ getCommandLastUsedAt: () => undefined }));+vi.mock('./state', () => ({+ CommandState: {+ commandScopeCommands: () => [],+ isEntityActionMode: () => false,+ },+}));++const contact = (+ id: string,+ name: string,+ email: string+): CrmContactEntity => ({+ type: 'crm_contact',+ id,+ ownerId: 'team',+ companyId: 'company',+ name,+ email,+ hidden: false,+ lastInteraction: '2026-09-01T00:00:00Z',+});++const user = (email: string, name: string): UserItem => ({+ kind: 'user',+ bucket: 'person',+ id: `macro|${email}`,+ searchText: `${name} | ${email}`,+ sortTimestamp: 0,+ timestamps: {},+ data: { id: `macro|${email}`, email, name },+});++const directMessage = (+ id: string,+ name: string,+ other: string+): EntityItem => ({+ kind: 'entity',+ bucket: 'dm',+ id,+ searchText: name,+ sortTimestamp: 1,+ timestamps: {},+ data: {+ type: 'channel',+ id,+ name,+ ownerId: VIEWER,+ channelType: 'direct_message',+ participantIds: [VIEWER, other],+ },+});++let dispose: (() => void) | undefined;+afterEach(() => {+ dispose?.();+ mocks.lists = {};+});++function setup(initialCategory: CategoryFilter = 'dms') {+ return createRoot((cleanup) => {+ dispose = cleanup;+ const [query, setQuery] = createSignal('');+ const [category, setCategory] = createSignal(initialCategory);+ const [contacts, setContacts] = createSignal<CrmContactEntity[]>([]);+ const [users, setUsers] = createSignal<UserItem[]>([]);+ const [dms, setDms] = createSignal<EntityItem[]>([]);+ const [hasMore, setHasMore] = createSignal(false);+ const [loading, setLoading] = createSignal(false);+ mocks.lists = { person: users, dm: dms };+ const discovery = {+ search: undefined as Accessor<string> | undefined,+ active: undefined as Accessor<boolean> | undefined,+ loadMore: vi.fn(async () => {}),+ };+ const result = useCommandItems(query, category, {+ searchActive: () => true,+ contactDiscovery: (search, active): CommandContactSource => {+ discovery.search = search;+ discovery.active = active;+ return {+ contacts: () => (active() ? contacts() : []),+ isLoading: loading,+ hasMore,+ isLoadingMore: () => false,+ loadMore: discovery.loadMore,+ };+ },+ });+ return {+ result,+ discovery,+ ids: () => result.items().map((item) => item.id),+ setQuery,+ setCategory,+ setContacts,+ setUsers,+ setDms,+ setHasMore,+ setLoading,+ };+ });+}++describe('command menu contact discovery', () => {+ it('lists contacts beyond the cached seed under People for a typed query', () => {+ const t = setup('dms');+ t.setContacts([+ contact('crm-asher', 'Asher at HackerNoon', '[email protected]'),+ ]);+ expect(t.discovery.active?.()).toBe(false);+ expect(t.ids()).toEqual([]);++ t.setQuery('asher');+ expect(t.discovery.active?.()).toBe(true);+ expect(t.discovery.search?.()).toBe('asher');+ expect(t.ids()).toEqual(['search:dms:asher', 'crm-asher']);+ });++ it('adds contacts to a typed All search but keeps blank All on recency', () => {+ const t = setup('all');+ t.setContacts([contact('crm-pat', 'Pat Doe', '[email protected]')]);+ expect(t.discovery.active?.()).toBe(false);+ expect(t.ids()).not.toContain('crm-pat');+ t.setQuery('pat doe');+ expect(t.ids()).toContain('crm-pat');+ });++ it('keeps contacts out of unrelated categories', () => {+ const t = setup('documents');+ t.setQuery('asher');+ t.setContacts([contact('crm-asher', 'Asher', '[email protected]')]);+ expect(t.discovery.active?.()).toBe(false);+ expect(t.ids()).not.toContain('crm-asher');+ t.setCategory('people');+ expect(t.discovery.active?.()).toBe(true);+ });++ it('prefers the Macro user sharing the email even when only the CRM name matched', () => {+ const t = setup('dms');+ const asher = user('[email protected]', 'Asher Smith');+ t.setUsers([asher]);+ t.setContacts([+ contact('crm-asher', 'Asher at HackerNoon', ' [email protected]'),+ contact('crm-plus', 'Asher Press', '[email protected]'),+ ]);+ t.setQuery('hackernoon');+ const items = t.result.items();+ // The plus alias is a different address, so it stays a contact.+ expect(items.map((item) => item.id)).toEqual([+ 'search:dms:hackernoon',+ asher.id,+ 'crm-plus',+ ]);+ expect(items[1].kind).toBe('user');+ expect(items.some((item) => item.id === 'crm-asher')).toBe(false);+ });++ it("opens the person's existing conversation instead of a second row", () => {+ const t = setup('dms');+ const asher = user('[email protected]', 'Asher Smith');+ const dm = directMessage('dm-asher', 'Asher Smith', asher.id);+ // People already lists the conversation; only the CRM name matches.+ mocks.lists.category = () => [dm];+ t.setUsers([asher]);+ t.setDms([dm]);+ t.setContacts([+ contact('crm-asher', 'Asher at HackerNoon', asher.data.email),+ ]);+ t.setQuery('hackernoon');+ expect(t.ids()).toEqual(['search:dms:hackernoon', 'dm-asher']);++ t.setQuery('asher');+ expect(t.ids().filter((id) => id === 'dm-asher')).toHaveLength(1);+ });++ it('pages contacts with the rest of the menu and reports their loading', async () => {+ const t = setup('dms');+ t.setQuery('pat');+ expect(t.result.pagination.hasMore()).toBe(false);+ t.setHasMore(true);+ expect(t.result.pagination.hasMore()).toBe(true);+ await t.result.pagination.loadMore();+ expect(t.discovery.loadMore).toHaveBeenCalledOnce();+ t.setLoading(true);+ expect(t.result.isLoadingEntities()).toBe(true);+ });+});diff --git a/apps/web/src/features/command/useCommandItems.ts b/apps/web/src/features/command/useCommandItems.tsindex a4e20e7b9c..c137f7b46b 100644--- a/apps/web/src/features/command/useCommandItems.ts+++ b/apps/web/src/features/command/useCommandItems.ts@@ -12,6 +12,7 @@ import {// QuickAccessProvider, which cycles back here, and `exclude` runs at module// evaluation time below.import { exclude } from '@core/context/quickAccess/types';+import { useUserId } from '@core/context/user';import { HotkeyTags } from '@core/hotkey/constants';import {type CommandWithInfo,@@ -22,7 +23,9 @@ import { TOKENS } from '@core/hotkey/tokens';import type { HotkeyCommand } from '@core/hotkey/types';import type { TimestampedItem } from '@core/util/freshSort';import { mergeSortedArrays } from '@core/util/list';+import type { CrmContactEntity } from '@entity';import { type Accessor, createMemo } from 'solid-js';+import { contactCommandItems } from './contact-items';import {type CreateProjectCommandItem,newProjectCommand,@@ -85,6 +88,12 @@ export type PaginationControls = {loadMore: () => Promise<void>;};+/** CRM contacts matching a typed query, beyond those Quick Access holds. */+export type CommandContactSource = PaginationControls & {+ contacts: Accessor<CrmContactEntity[]>;+ isLoading: Accessor<boolean>;+};+function isCommandItem(item: CommandMenuItem): item is CommandItem {return item.kind === 'command';}@@ -347,7 +356,7 @@ const QUICK_ACCESS_BUCKETS_BY_CATEGORY: Partial<> = {// Projects come from the command menu's own server search. CRM contacts// have no view history, so a no-query list would surface the whole team's- // contacts; they are reached through their company instead.+ // contacts; typed queries find them through contact discovery instead.all: exclude('person', 'initiative', 'crm_contact'),channels: ['channel'],dms: ['dm'],@@ -358,6 +367,13 @@ const QUICK_ACCESS_BUCKETS_BY_CATEGORY: Partial<people: ['person'],};+/** Categories listing people, where a typed query also finds CRM contacts. */+const CONTACT_CATEGORIES: ReadonlySet<CategoryFilter> = new Set([+ 'all',+ 'dms',+ 'people',+]);+/** Creates only the Quick Access list needed by the active category. */function useQuickAccessCategory(categoryFilter: Accessor<CategoryFilter>,@@ -425,6 +441,11 @@ export function useCommandItems(commandScopeCommands?: Accessor<CommandWithInfo[]>;/** Whether this menu should drive cache-backed Quick Access search. */searchActive?: Accessor<boolean>;+ /** Finds CRM contacts for typed People and All queries. */+ contactDiscovery?: (+ search: Accessor<string>,+ active: Accessor<boolean>+ ) => CommandContactSource;}) {const showSearchRow = options?.showSearchRow ?? true;@@ -445,15 +466,55 @@ export function useCommandItems(!CommandState.isEntityActionMode() &&(categoryFilter() === 'all' || categoryFilter() === 'projects');const projects = useProjectCommandItems(scopedSearchTerm, projectEnabled);- const categoryItems = () => [- ...category.items(),- ...projects.items(),- // All/Commands already include the registered Create project command.- // The Projects category excludes general commands, so keep its shortcut.- ...(projects.enabled() && categoryFilter() === 'projects'- ? [newProjectCommand]- : []),- ];+ const contactsActive = () =>+ searchActive() &&+ commandScopeCommands().length === 0 &&+ !CommandState.isEntityActionMode() &&+ CONTACT_CATEGORIES.has(categoryFilter()) &&+ query().trim().length > 0;+ const contacts = options?.contactDiscovery?.(+ scopedSearchTerm,+ contactsActive+ );+ const contactPeople = contacts+ ? {+ users: quickAccess.useList('person').items,+ directMessages: quickAccess.useList('dm').items,+ viewerId: useUserId(),+ }+ : undefined;+ const contactItems = createMemo((): CommandMenuItem[] =>+ contacts && contactPeople && contactsActive()+ ? contactCommandItems({+ contacts: contacts.contacts(),+ users: contactPeople.users(),+ directMessages: contactPeople.directMessages(),+ viewerId: contactPeople.viewerId(),+ })+ : []+ );+ const contactItemIds = createMemo(+ () => new Set(contactItems().map((item) => item.id))+ );+ const categoryItems = () => {+ const items = [+ ...category.items(),+ ...projects.items(),+ // All/Commands already include the registered Create project command.+ // The Projects category excludes general commands, so keep its shortcut.+ ...(projects.enabled() && categoryFilter() === 'projects'+ ? [newProjectCommand]+ : []),+ ];+ // A contact's row keeps its CRM name searchable, so it replaces the same+ // conversation listed under its own name.+ const contactIds = contactItemIds();+ if (contactIds.size === 0) return items;+ return [+ ...items.filter((item) => !contactIds.has(item.id)),+ ...contactItems(),+ ];+ };const rankItems = (items: CommandMenuItem[],@@ -463,6 +524,7 @@ export function useCommandItems(return rankCommandSearchItems(items, queryText, {preserveAdditionalEntityMatches:quickAccess.usesRecordSelection() || quickAccess.usesSearchProjection(),+ preservedIds: contactItemIds(),});};@@ -519,15 +581,23 @@ export function useCommandItems(return {items: filteredItems,isLoadingEntities: () =>- category.isLoadingEntities() || projects.isLoading(),+ category.isLoadingEntities() ||+ projects.isLoading() ||+ (contacts?.isLoading() ?? false),pagination: {- hasMore: () => category.pagination.hasMore() || projects.hasMore(),+ hasMore: () =>+ category.pagination.hasMore() ||+ projects.hasMore() ||+ (contacts?.hasMore() ?? false),isLoadingMore: () =>- category.pagination.isLoadingMore() || projects.isLoadingMore(),+ category.pagination.isLoadingMore() ||+ projects.isLoadingMore() ||+ (contacts?.isLoadingMore() ?? false),loadMore: async () => {await Promise.all([category.pagination.loadMore(),projects.loadMore(),+ contacts?.loadMore(),]);},},diff --git a/apps/web/src/features/crm/core/contact-discovery.test.ts b/apps/web/src/features/crm/core/contact-discovery.test.tsnew file mode 100644index 0000000000..a005e01de7--- /dev/null+++ b/apps/web/src/features/crm/core/contact-discovery.test.ts@@ -0,0 +1,80 @@+import type { CrmContactEntity } from '@entity';+import { describe, expect, it } from 'vitest';+import { mergeDiscoveredContacts } from './contact-discovery';++const contact = (+ id: string,+ overrides: Partial<CrmContactEntity> = {}+): CrmContactEntity => ({+ type: 'crm_contact',+ id,+ ownerId: 'team',+ teamId: 'team',+ companyId: 'company',+ name: id,+ email: `${id}@example.com`,+ hidden: false,+ lastInteraction: '2026-01-01T00:00:00Z',+ ...overrides,+});++describe('contact discovery merging', () => {+ it('collapses cross-team records by normalized full email, keeping plus aliases and original IDs', () => {+ const cached = [+ contact('team-a-asher', {+ email: '[email protected]',+ teamId: 'a',+ lastInteraction: '2026-02-01T00:00:00Z',+ }),+ ];+ const server = [+ contact('team-b-asher', {+ email: ' [email protected] ',+ teamId: 'b',+ lastInteraction: '2026-03-01T00:00:00Z',+ }),+ contact('alias', { email: '[email protected]' }),+ ];+ expect(mergeDiscoveredContacts(cached, server).map(({ id }) => id)).toEqual(+ ['team-b-asher', 'alias']+ );+ });++ it('picks the same representative regardless of which source or page delivered it', () => {+ const tied = '2026-03-01T00:00:00Z';+ const low = contact('0190-a', {+ email: '[email protected]',+ lastInteraction: tied,+ });+ const high = contact('0190-b', {+ email: '[email protected]',+ lastInteraction: tied,+ });+ expect(mergeDiscoveredContacts([low], [high])).toEqual([high]);+ expect(mergeDiscoveredContacts([high], [low])).toEqual([high]);+ expect(mergeDiscoveredContacts([], [high, low])).toEqual([high]);+ });++ it('takes the server facts for a contact the cache also holds', () => {+ const stale = contact('pat', { name: 'Pat (old)' });+ const fresh = contact('pat', {+ name: 'Pat Doe',+ lastInteraction: '2026-05-01T00:00:00Z',+ });+ expect(mergeDiscoveredContacts([stale], [fresh])).toEqual([fresh]);+ });++ it('drops hidden records and orders by latest interaction', () => {+ const merged = mergeDiscoveredContacts(+ [+ contact('older', { lastInteraction: '2025-01-01T00:00:00Z' }),+ contact('hidden', {+ hidden: true,+ lastInteraction: '2027-01-01T00:00:00Z',+ }),+ ],+ [contact('newer', { lastInteraction: '2026-06-01T00:00:00Z' })]+ );+ expect(merged.map(({ id }) => id)).toEqual(['newer', 'older']);+ });+});diff --git a/apps/web/src/features/crm/core/contact-discovery.ts b/apps/web/src/features/crm/core/contact-discovery.tsnew file mode 100644index 0000000000..0d6e1b44b5--- /dev/null+++ b/apps/web/src/features/crm/core/contact-discovery.ts@@ -0,0 +1,23 @@+import {+ type ContactRepresentative,+ deduplicatePeople,+ interactionTime,+} from './people';++type DiscoveredContact = ContactRepresentative & { name?: string | null };++/** Server pages carry the freshest facts for a record the cache also holds;+ * one visible record per email remains, most recent interaction first. */+export function mergeDiscoveredContacts<T extends DiscoveredContact>(+ cached: readonly T[],+ server: readonly T[]+): T[] {+ const byId = new Map<string, T>();+ for (const contact of cached) byId.set(contact.id, contact);+ for (const contact of server) byId.set(contact.id, contact);+ return deduplicatePeople([...byId.values()]).sort(+ (left, right) =>+ interactionTime(right) - interactionTime(left) ||+ (right.id > left.id ? 1 : right.id < left.id ? -1 : 0)+ );+}diff --git a/apps/web/src/features/crm/core/people.ts b/apps/web/src/features/crm/core/people.tsindex 507e0c39c7..95be8fed52 100644--- a/apps/web/src/features/crm/core/people.ts+++ b/apps/web/src/features/crm/core/people.ts@@ -7,19 +7,31 @@ export type PeopleSort =| 'lastInteraction'| 'firstInteraction';-/** A representative can change between server pages; keep one visible row per email. */-export function deduplicatePeople(people: CrmPerson[]): CrmPerson[] {- const byEmail = new Map<string, CrmPerson>();+/** The fields that choose one visible record for a contact email. */+export type ContactRepresentative = {+ id: string;+ email: string;+ hidden: boolean;+ lastInteraction?: string | null;+};++export const interactionTime = (contact: ContactRepresentative) =>+ Date.parse(contact.lastInteraction ?? '') || 0;++/** A representative can change between server pages; keep one visible row per+ * email: the latest interaction, then the greatest record id. */+export function deduplicatePeople<T extends ContactRepresentative>(+ people: T[]+): T[] {+ const byEmail = new Map<string, T>();for (const person of people) {if (person.hidden) continue;const email = person.email.trim().toLowerCase();const previous = byEmail.get(email);if (!previous ||- Date.parse(person.lastInteraction) >- Date.parse(previous.lastInteraction) ||- (Date.parse(person.lastInteraction) ===- Date.parse(previous.lastInteraction) &&+ interactionTime(person) > interactionTime(previous) ||+ (interactionTime(person) === interactionTime(previous) &&person.id > previous.id)) {byEmail.set(email, person);diff --git a/apps/web/src/features/crm/primitives/contact-discovery.test.ts b/apps/web/src/features/crm/primitives/contact-discovery.test.tsnew file mode 100644index 0000000000..3da9cde430--- /dev/null+++ b/apps/web/src/features/crm/primitives/contact-discovery.test.ts@@ -0,0 +1,271 @@+import type { CrmContactEntity } from '@entity';+import { batch, createRoot, createSignal } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createContactDiscovery, type ServerAnswer } from './contact-discovery';++const contact = (+ id: string,+ overrides: Partial<CrmContactEntity> = {}+): CrmContactEntity => ({+ type: 'crm_contact',+ id,+ ownerId: 'team',+ companyId: 'company',+ name: id,+ email: `${id}@example.com`,+ hidden: false,+ lastInteraction: '2026-01-01T00:00:00Z',+ ...overrides,+});++let dispose: (() => void) | undefined;+afterEach(() => dispose?.());++function setup() {+ return createRoot((cleanup) => {+ dispose = cleanup;+ const [query, setQuery] = createSignal('');+ const [serverQuery, setServerQuery] = createSignal('');+ const [active, setActive] = createSignal(true);+ const [cached, setCached] = createSignal<CrmContactEntity[]>([]);+ const [answer, setAnswer] = createSignal<ServerAnswer>();+ const [error, setError] = createSignal<Error>();+ const [loadingMore, setLoadingMore] = createSignal(false);+ const queuedPages: CrmContactEntity[][] = [];+ const nextPage = () =>+ setAnswer((loaded) =>+ loaded+ ? {+ query: loaded.query,+ contacts: [...loaded.contacts, ...(queuedPages.shift() ?? [])],+ }+ : loaded+ );+ const serverLoadMore = vi.fn(async () => {+ setLoadingMore(true);+ await Promise.resolve();+ batch(() => {+ nextPage();+ setLoadingMore(false);+ });+ });+ const refresh = vi.fn(async () => {});+ const discovery = createContactDiscovery({+ query,+ active,+ cached: {+ contacts: cached,+ isLoading: () => false,+ hasMore: () => false,+ isLoadingMore: () => false,+ loadMore: async () => {},+ },+ server: {+ query: serverQuery,+ answer,+ error,+ isLoading: () => answer() === undefined,+ hasMore: () => queuedPages.length > 0,+ isLoadingMore: loadingMore,+ loadMore: serverLoadMore,+ refresh,+ },+ });+ const search = (text: string) =>+ batch(() => {+ setQuery(text);+ setServerQuery(text);+ });+ return {+ discovery,+ ids: () => discovery.contacts().map(({ id }) => id),+ setQuery,+ setServerQuery,+ search,+ setActive,+ setCached,+ setAnswer,+ setError,+ nextPage,+ queuedPages,+ serverLoadMore,+ refresh,+ };+ });+}++describe('contact discovery', () => {+ it('shows cached matches at once and adds uncached server contacts once the query settles', () => {+ const t = setup();+ t.setCached([contact('cached-asher', { name: 'Asher' })]);+ t.setQuery('asher');+ expect(t.ids()).toEqual(['cached-asher']);+ expect(t.discovery.isLoading()).toBe(false);++ batch(() => {+ t.setServerQuery('asher');+ t.setAnswer({+ query: 'asher',+ contacts: [+ contact('cached-asher', {+ name: 'Asher',+ lastInteraction: '2026-04-01T00:00:00Z',+ }),+ contact('beyond-seed', {+ name: 'Asher Two',+ lastInteraction: '2025-01-01T00:00:00Z',+ }),+ ],+ });+ });+ expect(t.ids()).toEqual(['cached-asher', 'beyond-seed']);+ expect(t.discovery.contacts()[0].lastInteraction).toBe(+ '2026-04-01T00:00:00Z'+ );+ });++ it('reports loading instead of an empty result while the server query is still settling', () => {+ const t = setup();+ t.setQuery('ash');+ expect(t.discovery.contacts()).toEqual([]);+ expect(t.discovery.isLoading()).toBe(true);+ batch(() => {+ t.setServerQuery('ash');+ t.setAnswer({ query: 'ash', contacts: [] });+ });+ expect(t.discovery.isLoading()).toBe(false);+ });++ it('never shows or pages an earlier answer the live query no longer matches', async () => {+ const t = setup();+ t.search('ash');+ t.setAnswer({+ query: 'ash',+ contacts: [+ contact('ashley', { name: 'Ashley' }),+ contact('asher', { name: 'Asher' }),+ ],+ });+ t.queuedPages.push([contact('ash-page-2', { name: 'Ash Two' })]);+ expect(t.ids()).toEqual(['ashley', 'asher']);++ t.setQuery('asher');+ expect(t.ids()).toEqual(['asher']);+ expect(t.discovery.hasMore()).toBe(false);+ await t.discovery.loadMore();+ expect(t.serverLoadMore).not.toHaveBeenCalled();++ // The settled query's first page is pending: keep rows that still match.+ batch(() => {+ t.setServerQuery('asher');+ t.setAnswer(undefined);+ });+ expect(t.ids()).toEqual(['asher']);+ t.setAnswer({+ query: 'asher',+ contacts: [contact('asher-b', { name: 'Asher B' })],+ });+ expect(t.ids()).toEqual(['asher-b']);++ t.setQuery('bob');+ expect(t.ids()).toEqual([]);+ });++ it('judges pages by the query they answer, not the query that is settling', () => {+ const t = setup();+ t.search('ash');+ t.setAnswer({+ query: 'ash',+ contacts: [+ contact('ashley', { name: 'Ashley' }),+ contact('asher', { name: 'Asher' }),+ ],+ });+ // The debounced query advances before the query cache swaps its pages.+ t.search('asher');+ expect(t.ids()).toEqual(['asher']);+ });++ it('exposes nothing while inactive and does not resurface the closed search', async () => {+ const t = setup();+ t.search('asher');+ t.setAnswer({+ query: 'asher',+ contacts: [contact('asher', { name: 'Asher' })],+ });+ t.setError(new Error('boom'));+ t.queuedPages.push([contact('next')]);+ t.setActive(false);+ expect(t.ids()).toEqual([]);+ expect(t.discovery.error()).toBeUndefined();+ expect(t.discovery.hasMore()).toBe(false);+ await t.discovery.loadMore();+ await t.discovery.refresh();+ expect(t.serverLoadMore).not.toHaveBeenCalled();+ expect(t.refresh).not.toHaveBeenCalled();++ // Reopened with a different query before the server catches up.+ batch(() => {+ t.setActive(true);+ t.setQuery('zed');+ });+ expect(t.ids()).toEqual([]);+ });++ it('loads past pages holding only duplicates without overlapping requests', async () => {+ const t = setup();+ t.search('pat');+ t.setAnswer({+ query: 'pat',+ contacts: [contact('pat', { email: '[email protected]' })],+ });+ t.queuedPages.push(+ [+ contact('pat-other-team', {+ email: ' [email protected]',+ lastInteraction: '2024-01-01T00:00:00Z',+ }),+ ],+ [contact('patricia', { email: '[email protected]' })]+ );+ expect(t.discovery.hasMore()).toBe(true);++ await Promise.all([t.discovery.loadMore(), t.discovery.loadMore()]);+ expect(t.serverLoadMore).toHaveBeenCalledTimes(2);+ expect(t.ids()).toEqual(['patricia', 'pat']);+ expect(t.discovery.hasMore()).toBe(false);+ });++ it('stops paging the earlier query once the query changes', async () => {+ const t = setup();+ t.search('pat');+ t.setAnswer({ query: 'pat', contacts: [contact('pat')] });+ t.queuedPages.push([contact('pat')], [contact('pat-2')]);+ t.serverLoadMore.mockImplementationOnce(async () => {+ t.setQuery('patr');+ t.nextPage();+ });+ await t.discovery.loadMore();+ expect(t.serverLoadMore).toHaveBeenCalledTimes(1);+ });++ it('surfaces server failures and refreshes only while active', async () => {+ const t = setup();+ t.search('pat');+ const failure = new Error('CRM unavailable');+ t.setError(failure);+ expect(t.discovery.error()).toBe(failure);+ await t.discovery.refresh();+ expect(t.refresh).toHaveBeenCalledOnce();+ });++ it('does not refetch an earlier or empty search while the query settles', async () => {+ const t = setup();+ t.setQuery('pat');+ await t.discovery.refresh();+ expect(t.refresh).not.toHaveBeenCalled();+ t.setServerQuery('pat');+ await t.discovery.refresh();+ expect(t.refresh).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/features/crm/primitives/contact-discovery.ts b/apps/web/src/features/crm/primitives/contact-discovery.tsnew file mode 100644index 0000000000..241fe6c266--- /dev/null+++ b/apps/web/src/features/crm/primitives/contact-discovery.ts@@ -0,0 +1,143 @@+import { matchesTokenSubsequences } from '@core/util/string';+import type { CrmContactEntity } from '@entity';+import { type Accessor, createMemo } from 'solid-js';+import { mergeDiscoveredContacts } from '../core/contact-discovery';++/** Contacts the local cache matches for the live query. */+export type CachedContactMatches = {+ contacts: Accessor<CrmContactEntity[]>;+ isLoading: Accessor<boolean>;+ hasMore: Accessor<boolean>;+ isLoadingMore: Accessor<boolean>;+ loadMore: () => Promise<void>;+};++/** Loaded server rows and the query they answer. */+export type ServerAnswer = { query: string; contacts: CrmContactEntity[] };++/** Authorized server pages for `query`, which trails the live query. */+export type ServerContactPages = {+ query: Accessor<string>;+ /** Loaded pages and the query they answer, read from the pages themselves;+ * undefined until a first page settles. */+ answer: Accessor<ServerAnswer | undefined>;+ error: Accessor<Error | undefined>;+ isLoading: Accessor<boolean>;+ hasMore: Accessor<boolean>;+ isLoadingMore: Accessor<boolean>;+ loadMore: () => Promise<void>;+ refresh: () => Promise<void>;+};++/** Rows answering an earlier query show only while the cache's matching+ * semantics still match them against the live query by name or email. */+const stillMatches = (contact: CrmContactEntity, query: string) =>+ matchesTokenSubsequences(`${contact.name} | ${contact.email}`, query);++const NO_ANSWER: ServerAnswer = { query: '', contacts: [] };++// Bounds one request for more rows when consecutive pages hold only+// duplicates of contacts already shown.+const MAX_PAGES_PER_LOAD = 5;++/**+ * Contacts matching a typed query: cached matches immediately, server pages+ * for contacts the cache has not seen. Nothing is exposed or paged while+ * inactive, and rows from an earlier query only show while they still match.+ */+export function createContactDiscovery(options: {+ query: Accessor<string>;+ active: Accessor<boolean>;+ cached: CachedContactMatches;+ server: ServerContactPages;+}) {+ const query = () => options.query().trim();+ const searching = () => options.active() && query().length > 0;+ const serverSettled = () => options.server.query() === query();++ // A newer query's first page replaces the last answer only once it lands,+ // so typing does not blank rows that still match.+ const serverAnswer = createMemo<ServerAnswer>(+ (previous) =>+ searching() ? (options.server.answer() ?? previous) : NO_ANSWER,+ NO_ANSWER+ );++ const serverContacts = () => {+ const answer = serverAnswer();+ return answer.query === query()+ ? answer.contacts+ : answer.contacts.filter((contact) => stillMatches(contact, query()));+ };++ const contacts = createMemo<CrmContactEntity[]>(() =>+ searching()+ ? mergeDiscoveredContacts(options.cached.contacts(), serverContacts())+ : []+ );++ const canLoadServer = () =>+ searching() && serverSettled() && options.server.hasMore();+ const canLoadCached = () => searching() && options.cached.hasMore();+ const hasMore = () => canLoadServer() || canLoadCached();++ const loadPage = async () => {+ await Promise.all([+ canLoadServer() && !options.server.isLoadingMore()+ ? options.server.loadMore()+ : undefined,+ canLoadCached() && !options.cached.isLoadingMore()+ ? options.cached.loadMore()+ : undefined,+ ]);+ };++ const loadUntilNewContact = async () => {+ const startQuery = query();+ const startCount = contacts().length;+ for (let page = 0; page < MAX_PAGES_PER_LOAD; page++) {+ await loadPage();+ if (+ query() !== startQuery ||+ !hasMore() ||+ contacts().length > startCount+ )+ return;+ }+ };++ let pending: Promise<void> | undefined;+ const loadMore = async () => {+ if (pending) return pending;+ if (!hasMore()) return;+ pending = loadUntilNewContact();+ try {+ await pending;+ } finally {+ pending = undefined;+ }+ };++ return {+ contacts,+ isLoading: () =>+ searching() &&+ contacts().length === 0 &&+ (!serverSettled() ||+ options.server.isLoading() ||+ options.cached.isLoading()),+ error: () => (searching() ? options.server.error() : undefined),+ hasMore,+ isLoadingMore: () =>+ searching() &&+ (options.server.isLoadingMore() || options.cached.isLoadingMore()),+ loadMore,+ // A query still settling fetches fresh pages once it does; refreshing+ // now would refetch the previous (possibly empty, unfiltered) search.+ refresh: async () => {+ if (searching() && serverSettled()) await options.server.refresh();+ },+ };+}++export type ContactDiscovery = ReturnType<typeof createContactDiscovery>;diff --git a/apps/web/src/features/crm/queries/contact-suggestions.ts b/apps/web/src/features/crm/queries/contact-suggestions.tsindex 6e37d27a83..1fbd405fc9 100644--- a/apps/web/src/features/crm/queries/contact-suggestions.ts+++ b/apps/web/src/features/crm/queries/contact-suggestions.ts@@ -22,13 +22,17 @@ export function useCrmContactsQuery(enabled: enabled(),staleTime: 60_000,initialPageParam: null as string | null,- queryFn: ({ pageParam, signal }) =>- fetchCrmContacts({+ // Each page names the search it answers, so a consumer reading+ // pages during a key change cannot attribute them to the new search.+ queryFn: async ({ pageParam, signal }) => ({+ ...(await fetchCrmContacts({cursor: pageParam,search: searchTerm,limit,signal,- }),+ })),+ search: searchTerm,+ }),getNextPageParam: (page) => page.nextCursor,};},diff --git a/apps/web/src/features/crm/record-adapter.ts b/apps/web/src/features/crm/record-adapter.tsindex 926b750ee6..5d35306947 100644--- a/apps/web/src/features/crm/record-adapter.ts+++ b/apps/web/src/features/crm/record-adapter.ts@@ -1,10 +1,15 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableCrm } from '@core/constant/featureFlags';import type { EntityItem } from '@core/context/quickAccess';+import { useQuickAccess } from '@core/context/quickAccess/context';+import { toCrmContactItem } from '@core/context/quickAccess/crm-contacts';+import { debouncedDependent } from '@core/util/debounce';+import { isCrmContactEntity } from '@entity/types/entity';import { queryReadyGate } from '@queries/gate';import { storageServiceClient } from '@service-storage/client';import { useQueryClient } from '@tanstack/solid-query';import { type Accessor, createMemo } from 'solid-js';+import { createContactDiscovery } from './primitives/contact-discovery';import { useSetCompanyHiddenMutation as createHiddenMutation } from './queries/companies';import {useQuickAccessCrmContactsQuery as createContactSuggestions,@@ -57,18 +62,9 @@ export function useCrmContactMentionSource(const entities = createMemo<EntityItem[]>(() =>queryReadyGate(query)? query.data.pages.flatMap((page) =>- page.contacts.map((record) => {- const contact = toCrmContactEntity(record);- return {- kind: 'entity' as const,- bucket: 'crm_contact' as const,- id: contact.id,- data: contact,- searchText: `${contact.name} | ${contact.email}`,- sortTimestamp: Date.parse(record.lastInteraction),- timestamps: { lastInteraction: record.lastInteraction },- };- })+ page.contacts.map((record) =>+ toCrmContactItem(toCrmContactEntity(record))+ )): []);@@ -83,3 +79,67 @@ export function useCrmContactMentionSource(},};}++const CONTACT_SEARCH_DEBOUNCE_MS = 250;++/** Contacts matching a typed query: cached matches at once, then authorized+ * server pages across the viewer's CRM-enabled teams beyond the cached rows. */+export function useCrmContactDiscovery(+ search: Accessor<string>,+ active: Accessor<boolean>+) {+ const flag = useFeatureFlag(enableCrm);+ const query = () => search().trim();+ const enabled = () => flag().enabled && active() && query().length > 0;+ const serverQuery = debouncedDependent(query, CONTACT_SEARCH_DEBOUNCE_MS);+ const cached = useQuickAccess().useList({+ buckets: ['crm_contact'],+ searchTerm: query,+ enabled,+ });+ const server = useCrmContactsQuery(+ { client: useQueryClient() },+ () => enabled() && serverQuery().length > 0,+ serverQuery+ );+ return createContactDiscovery({+ query,+ active: enabled,+ cached: {+ contacts: () =>+ cached+ .items()+ .flatMap((item) =>+ item.kind === 'entity' && isCrmContactEntity(item.data)+ ? [item.data]+ : []+ ),+ isLoading: cached.isLoading,+ hasMore: cached.hasMore,+ isLoadingMore: cached.isLoadingMore,+ loadMore: cached.loadMore,+ },+ server: {+ query: serverQuery,+ answer: () =>+ queryReadyGate(server)+ ? {+ query: server.data.pages[0]?.search ?? '',+ contacts: server.data.pages.flatMap((page) =>+ page.contacts.map(toCrmContactEntity)+ ),+ }+ : undefined,+ error: () => server.error ?? undefined,+ isLoading: () => server.isLoading,+ hasMore: () => server.hasNextPage,+ isLoadingMore: () => server.isFetchingNextPage,+ loadMore: async () => {+ await server.fetchNextPage();+ },+ refresh: async () => {+ await server.refetch({ throwOnError: true });+ },+ },+ });+}diff --git a/apps/web/src/features/entity/types/entity.ts b/apps/web/src/features/entity/types/entity.tsindex 63b7315dab..9afb8dce2f 100644--- a/apps/web/src/features/entity/types/entity.ts+++ b/apps/web/src/features/entity/types/entity.ts@@ -616,6 +616,10 @@ export const isCrmContactEntity = (return entity.type === 'crm_contact';};+/** The full-email identity shared by CRM contacts and Macro users. Plus+ * aliases stay distinct, as in the backend's authorized contact deduplication. */+export const crmContactEmailKey = (email: string) => email.trim().toLowerCase();+export const isDocumentEntity = (entity: EntityData): entity is DocumentEntity => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/people-mentions.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/people-mentions.tsindex 6dfe110869..303a3da233 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/people-mentions.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/people-mentions.ts@@ -1,35 +1,30 @@import type { EntityItem, UserItem } from '@core/context/quickAccess';-import { deduplicateContactItems } from '@core/context/quickAccess/entity-search';-import type { CrmContactEntity } from '@entity';+import { resolveContactPeople } from '@core/context/quickAccess/crm-contacts';+import { crmContactEmailKey } from '@entity/types/entity';import type { GroupMentionItem } from '../../../../utils/mentionsUtils';-const emailKey = (email: string) => email.trim().toLowerCase();-/** Preserve real user mentions; CRM duplicates retain one navigable team record. */export function mergePeopleMentions(usersAndGroups: (UserItem | GroupMentionItem)[],contacts: EntityItem[],availableUsers: UserItem[]): (UserItem | GroupMentionItem | EntityItem)[] {- const usersByEmail = new Map(- availableUsers.map((user) => [emailKey(user.data.email), user])- );const seen = new Set(usersAndGroups.flatMap((item) =>- item.kind === 'user' ? [emailKey(item.data.email)] : []+ item.kind === 'user' ? [crmContactEmailKey(item.data.email)] : []));const result: (UserItem | GroupMentionItem | EntityItem)[] = [...usersAndGroups,];- const ordered = deduplicateContactItems(contacts).filter(- (item) => item.data.type === 'crm_contact'- );- for (const contact of ordered) {- const key = emailKey((contact.data as CrmContactEntity).email);+ for (const { contact, user } of resolveContactPeople(+ contacts,+ availableUsers+ )) {+ const key = crmContactEmailKey(contact.data.email);if (seen.has(key)) continue;seen.add(key);- result.push(usersByEmail.get(key) ?? contact);+ result.push(user ?? contact);}return result;}diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsxindex 4e90462b58..0dc811ad5f 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx@@ -55,8 +55,8 @@ import { formatDocumentName } from '@service-storage/util/filename';import { createLazyMemo } from '@solid-primitives/memo';import { toDate } from 'date-fns';import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js';+import { deduplicateContactItems, toCrmContactItem } from './crm-contacts';import {- deduplicateContactItems,filterQuickAccessItems,searchQuickAccessItems,} from './entity-search';@@ -285,12 +285,6 @@ function getCrmCompanyVersion(return `${company.name}|${domains}|${company.updatedAt}|${viewedAt}`;}-function getCrmContactSearchText(contact: CrmContactEntity): string {- return contact.name === contact.email- ? contact.email- : `${contact.name} | ${contact.email}`;-}-function getCrmContactVersion(contact: CrmContactEntity): string {return `${contact.name}|${contact.email}|${contact.hidden}|${contact.updatedAt}|${contact.lastInteraction}`;}@@ -691,27 +685,16 @@ export function createQuickAccessValue(): QuickAccessContextValue {if (contact.hidden || hidden.has(contact.id)) continue;const version = getCrmContactVersion(contact);const cached = itemCache.get(contact.id);- const sortTimestamp = toTimestamp(- contact.lastInteraction ?? contact.updatedAt- );- if (!cached || cached.version !== version) {- itemCache.set(contact.id, {- version,- item: {- kind: 'entity',- id: contact.id,- bucket: 'crm_contact',- searchText: getCrmContactSearchText(contact),- sortTimestamp,- timestamps: {- lastInteraction: contact.lastInteraction ?? contact.updatedAt,- createdAt: contact.createdAt,- },- data: contact,- },- });- }- allEntries.push({ id: contact.id, bucket: 'crm_contact', sortTimestamp });+ const item =+ cached && cached.version === version+ ? cached.item+ : toCrmContactItem(contact);+ if (item !== cached?.item) itemCache.set(contact.id, { version, item });+ allEntries.push({+ id: contact.id,+ bucket: 'crm_contact',+ sortTimestamp: item.sortTimestamp,+ });}return sortIndexEntries(allEntries);});@@ -1242,25 +1225,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {];}const contact = contactsById.get(id);- if (contact) {- return [- {- kind: 'entity',- id,- bucket: 'crm_contact',- searchText: getCrmContactSearchText(contact),- sortTimestamp: toTimestamp(- contact.lastInteraction ?? contact.updatedAt- ),- timestamps: {- lastInteraction:- contact.lastInteraction ?? contact.updatedAt,- createdAt: contact.createdAt,- },- data: contact,- },- ];- }+ if (contact) return [toCrmContactItem(contact)];const company = companiesById.get(id);if (company) {return [diff --git a/apps/web/src/lib/core/context/quickAccess/crm-contacts.ts b/apps/web/src/lib/core/context/quickAccess/crm-contacts.tsnew file mode 100644index 0000000000..c6c7b22928--- /dev/null+++ b/apps/web/src/lib/core/context/quickAccess/crm-contacts.ts@@ -0,0 +1,83 @@+import type { CrmContactEntity } from '@entity';+import { crmContactEmailKey } from '@entity/types/entity';+import { toDate } from 'date-fns';+import type { EntityItem, QuickAccessItem, UserItem } from './types';++function getCrmContactSearchText(contact: CrmContactEntity): string {+ return contact.name === contact.email+ ? contact.email+ : `${contact.name} | ${contact.email}`;+}++/** The Quick Access row for a contact, ordered by its latest interaction. */+export function toCrmContactItem(+ contact: CrmContactEntity+): EntityItem<CrmContactEntity> {+ const lastInteraction = contact.lastInteraction ?? contact.updatedAt;+ return {+ kind: 'entity',+ id: contact.id,+ bucket: 'crm_contact',+ searchText: getCrmContactSearchText(contact),+ sortTimestamp: lastInteraction ? toDate(lastInteraction).getTime() : 0,+ timestamps: { lastInteraction, createdAt: contact.createdAt },+ data: contact,+ };+}++function isCrmContactItem(+ item: QuickAccessItem+): item is EntityItem<CrmContactEntity> {+ return item.kind === 'entity' && item.data.type === 'crm_contact';+}++/** Collapse cached team records while retaining the selected result's ranking. */+export function deduplicateContactItems<T extends QuickAccessItem>(+ items: T[]+): T[] {+ const winners = new Map<string, T>();+ for (const item of items) {+ if (!isCrmContactItem(item) || item.data.hidden) continue;+ const email = crmContactEmailKey(item.data.email);+ const previous = winners.get(email);+ if (+ !previous ||+ item.sortTimestamp > previous.sortTimestamp ||+ (item.sortTimestamp === previous.sortTimestamp && item.id > previous.id)+ ) {+ winners.set(email, item);+ }+ }+ return items.filter(+ (item) =>+ !isCrmContactItem(item) ||+ winners.get(crmContactEmailKey(item.data.email)) === item+ );+}++export type ContactPerson = {+ contact: EntityItem<CrmContactEntity>;+ /** The Macro user with the contact's email, which takes the contact's place. */+ user?: UserItem;+};++/** One entry per visible contact email, paired with its Macro user when the+ * viewer can see one — even when only the contact's CRM name matched. */+export function resolveContactPeople(+ contacts: QuickAccessItem[],+ users: readonly UserItem[]+): ContactPerson[] {+ const usersByEmail = new Map(+ users.map((user) => [crmContactEmailKey(user.data.email), user])+ );+ return deduplicateContactItems(contacts).flatMap((item) =>+ isCrmContactItem(item)+ ? [+ {+ contact: item,+ user: usersByEmail.get(crmContactEmailKey(item.data.email)),+ },+ ]+ : []+ );+}diff --git a/apps/web/src/lib/core/context/quickAccess/entity-search.ts b/apps/web/src/lib/core/context/quickAccess/entity-search.tsindex 181d1ac3b5..0b1bbf74b3 100644--- a/apps/web/src/lib/core/context/quickAccess/entity-search.ts+++ b/apps/web/src/lib/core/context/quickAccess/entity-search.ts@@ -1,4 +1,5 @@import { createFreshSearch } from '@core/util/freshSort';+import { matchesTokenSubsequences } from '@core/util/string';import type { EntityItem, QuickAccessItem } from './types';const quickAccessSearch = createFreshSearch<QuickAccessItem>({@@ -15,21 +16,10 @@ export function filterQuickAccessItems(items: QuickAccessItem[],query: string): QuickAccessItem[] {- const tokens = query.toLowerCase().trim().split(/\s+/).filter(Boolean);- if (tokens.length === 0) return items;-- return items.filter((item) => {- const text = item.searchText.toLowerCase();- return tokens.every((token) => {- let position = 0;- for (const character of token) {- const next = text.indexOf(character, position);- if (next === -1) return false;- position = next + character.length;- }- return true;- });- });+ if (!query.trim()) return items;+ return items.filter((item) =>+ matchesTokenSubsequences(item.searchText, query)+ );}/** Fuzzy-ranks entity candidates using the existing mentions semantics. */@@ -48,29 +38,3 @@ export function searchQuickAccessEntities(): EntityItem[] {return searchQuickAccessItems(items, query) as EntityItem[];}--/** Collapse cached team records while retaining the selected result's ranking. */-export function deduplicateContactItems<T extends QuickAccessItem>(- items: T[]-): T[] {- const winners = new Map<string, T>();- for (const item of items) {- if (item.kind !== 'entity' || item.data.type !== 'crm_contact') continue;- if (item.data.hidden) continue;- const email = item.data.email.trim().toLowerCase();- const previous = winners.get(email);- if (- !previous ||- item.sortTimestamp > previous.sortTimestamp ||- (item.sortTimestamp === previous.sortTimestamp && item.id > previous.id)- ) {- winners.set(email, item);- }- }- return items.filter(- (item) =>- item.kind !== 'entity' ||- item.data.type !== 'crm_contact' ||- winners.get(item.data.email.trim().toLowerCase()) === item- );-}diff --git a/apps/web/src/lib/core/util/string.ts b/apps/web/src/lib/core/util/string.tsindex 4972571f71..5f09bcda9f 100644--- a/apps/web/src/lib/core/util/string.ts+++ b/apps/web/src/lib/core/util/string.ts@@ -104,3 +104,19 @@ export function isEmojiOnly(text: string): boolean {if (trimmed.length === 0) return false;return EMOJI_ONLY_REGEX.test(trimmed);}++/** Whether every query token appears in `text` as an ordered character+ * subsequence, case-insensitively. Mirrors cache-core/search.rs matching. */+export function matchesTokenSubsequences(text: string, query: string) {+ const tokens = query.toLowerCase().trim().split(/\s+/).filter(Boolean);+ const haystack = text.toLowerCase();+ return tokens.every((token) => {+ let position = 0;+ for (const character of token) {+ const next = haystack.indexOf(character, position);+ if (next === -1) return false;+ position = next + character.length;+ }+ return true;+ });+}diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex 7bcecd007e..62b755d786 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -688,6 +688,23 @@ notifications. External contacts insert a link to their original CRM record;they do not invite or notify that email address. Assignee and other user-onlypickers continue to list Macro users only.+Cmd+K **People** and a typed **All** query also find CRM contacts, using the same+accessible-team search, hidden-record exclusions, and full-email collapsing as+mentions. Cached contacts appear at once; the server search starts about 250 ms+after typing stops and pages 100 contacts at a time, so contacts beyond the first+500 cached records are found too. An empty query keeps People and All on their+usual recency lists without contacts. A contact whose email belongs to a Macro user+appears as that person instead, even when only the CRM name matched: their existing+direct message when you have one, otherwise the person, and selecting them opens a+direct message. Other contacts show their email and open the contact page; Enter and+click open in place, Shift+Enter in a new split. A server match that arrives after+typing takes the default selection from the Search for… row. Global Search does not+list CRM contacts; Search for… from People still opens the Channels search. Verify+a contact outside the cached rows, an email-only query, rapid query changes (rows+from an earlier query must disappear unless they still match), scrolling or Down+past the last row to load more, and that Files/Tasks/Channels/Agents never show+contacts.+Cmd+K merges cached and locally available items before applying recency order.An empty query prefers when an item was last viewed, falling back to its updatetime; equal timestamps have a stable entity-type and ID order. Searching retains the menu's