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(user): add same domain and dm recency boost to user search fields (#1134)
Seamusfbe8b54d6b9c
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsxindex c3752d931b..f6a11dbc46 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu.tsx@@ -5,7 +5,10 @@ import {} from '@core/block';import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';import { BozzyBracketInnerSibling } from '@core/component/BozzyBracket';-import { useChannelsContext } from '@core/context/channels';+import {+ useChannelsContext,+ useDmActivityByUserId,+} from '@core/context/channels';import { EntityIcon } from '@core/component/EntityIcon';import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';import { UserIcon } from '@core/component/UserIcon';@@ -16,8 +19,9 @@ import {type IUser,useContacts,} from '@core/user';+import { useEmail } from '@core/context/user';import { getDateSuggestions } from '@core/util/dateParser';-import { createFreshSearch } from '@core/util/freshSort';+import { createFreshSearch, FreshSearchPresets } from '@core/util/freshSort';import ClockIcon from '@icon/regular/clock.svg';import EmailIcon from '@icon/regular/envelope.svg';import UsersIcon from '@icon/regular/users.svg';@@ -455,9 +459,25 @@ function MentionsMenuInner(props: {const contacts = useContacts();+ const dmActivityByUserId = useDmActivityByUserId();+const users = createMemo(() => {const list = props.users?.() ?? contacts();- return list.map(entityMapper('user')).filter(allItemFilter);+ const dmActivity = dmActivityByUserId();++ return list+ .map(entityMapper('user'))+ .map((entity) => {+ const dmTimestamp = dmActivity.get(entity.id);+ if (dmTimestamp) {+ return {+ ...entity,+ lastInteraction: dmTimestamp,+ };+ }+ return entity;+ })+ .filter(allItemFilter);});let channels: Accessor<Entity<'channel'>[]>;@@ -648,8 +668,17 @@ function MentionsMenuInner(props: {return [...tabResults, ...otherResults];});+ const currentUserEmail = useEmail();+ const currentUserDomain = createMemo(() => {+ const email = currentUserEmail();+ return email ? email.split('@')[1] : undefined;+ });+const userSearch = createFreshSearch<Entity<'user'>>(- { timeWeight: 0, brevityWeight: 0.3 },+ FreshSearchPresets.baseUserSearch(+ currentUserDomain,+ (item) => item.data.email+ ),getItemSearchText);@@ -1038,7 +1067,7 @@ function MentionsMenuInner(props: {</button></div></div>- <div class="max-h-64 overflow-y-auto">+ <div class="max-h-64 overflow-y-auto scrollbar-hidden"><For each={allItems}>{(item, i) => (<MentionsMenuItemdiff --git a/js/app/packages/core/component/RecipientSelector.tsx b/js/app/packages/core/component/RecipientSelector.tsxindex 3a222b0f98..c75d8240af 100644--- a/js/app/packages/core/component/RecipientSelector.tsx+++ b/js/app/packages/core/component/RecipientSelector.tsx@@ -26,7 +26,9 @@ import {} from '@kobalte/core/combobox';import type { Channel } from '@service-comms/generated/models/channel';import { useEmail, useUserId } from '@core/context/user';+import { useDmActivityByUserId } from '@core/context/channels';import { debounce } from '@solid-primitives/scheduled';+import { createFreshSearch, FreshSearchPresets } from '@core/util/freshSort';import * as EmailValidator from 'email-validator';import {type Accessor,@@ -323,9 +325,27 @@ export function RecipientSelector<K extends CombinedRecipientKind>((props.triedToSubmit?.() ?? false) && props.selectedOptions.length === 0);+ const currentUserEmail = useEmail();+ const currentUserDomain = createMemo(() => {+ const email = currentUserEmail();+ return email ? email.split('@')[1] : undefined;+ });++ const dmActivityByUserId = useDmActivityByUserId();++ // Create search function for recipients+ const recipientSearch = createFreshSearch<CombinedRecipientItem>(+ FreshSearchPresets.baseUserSearch(currentUserDomain, (item) =>+ item.kind === 'user' ? item.data.email : undefined+ ),+ getRecipientOptionTextValue+ );+const options = createMemo(() => {const emailSet = new Set<string>();+ const dmActivity = dmActivityByUserId();+ // Filter and augment options with DM activityconst optionsList: CombinedRecipientItem<K>[] = [];for (const option of props.options()) {const item = option as CombinedRecipientItem;@@ -343,6 +363,19 @@ export function RecipientSelector<K extends CombinedRecipientKind>(if (email) {emailSet.add(email.toLowerCase());}++ // Augment user items with DM activity timestamp+ if (item.kind === 'user') {+ const dmTimestamp = dmActivity.get(item.id);+ if (dmTimestamp) {+ optionsList.push({+ ...option,+ lastInteraction: dmTimestamp,+ } as CombinedRecipientItem<K>);+ continue;+ }+ }+optionsList.push(option);}@@ -370,7 +403,14 @@ export function RecipientSelector<K extends CombinedRecipientKind>(allOptions.push(customEntity);}- return allOptions;+ // Always apply freshSort ranking - with search term for filtering, without for time-based ranking+ const searchResults = recipientSearch(+ allOptions as CombinedRecipientItem[],+ currentUserInput ?? ''+ );+ return searchResults.map(+ (result) => result.item+ ) as CombinedRecipientItem<K>[];});const [scrollToItem, setScrollToItem] = createSignal<(key: string) => void>(diff --git a/js/app/packages/core/context/channels.ts b/js/app/packages/core/context/channels.tsindex 0105bb11a6..78dee24d91 100644--- a/js/app/packages/core/context/channels.ts+++ b/js/app/packages/core/context/channels.ts@@ -7,6 +7,7 @@ import { useListChannelsQuery } from '@queries/channel/channels';import { useChannelsActivityQuery } from '@queries/channel/activity';import { queryReadyGate } from '@queries/gate';import { createAssertedContextProvider } from './createContext';+import { useUserId } from './user';type ChannelsContextValue = {channels: Accessor<ApiChannelWithLatest[]>;@@ -68,3 +69,39 @@ export function useChannelActivity(channelId: string) {const ctx = useChannelsContext();return createMemo(() => ctx.activityByChannelId()[channelId]);}++/**+ * Get a reactive map of userId -> Unix timestamp for the most recent DM+ * activity with that user. Useful for ranking/sorting users by recency of+ * interaction.+ */+export function useDmActivityByUserId(): Accessor<Map<string, number>> {+ const { channels } = useChannelsContext();+ const currentUserId = useUserId();++ return createMemo(() => {+ const currentUser = currentUserId();+ if (!currentUser) return new Map<string, number>();++ const allChannels = channels();+ const map = new Map<string, number>();++ for (const channel of allChannels) {+ if (channel.channel_type !== 'direct_message') continue;++ const otherParticipant = channel.participants.find(+ (p) => p.user_id !== currentUser+ );+ if (!otherParticipant) continue;++ const timestamp = channel.updated_at;+ if (timestamp) {+ const date = new Date(timestamp);+ const unixTimestamp = Math.floor(date.getTime() / 1000);+ map.set(otherParticipant.user_id, unixTimestamp);+ }+ }++ return map;+ });+}diff --git a/js/app/packages/core/util/freshSort.test.ts b/js/app/packages/core/util/freshSort.test.tsindex 412573b007..156cdc2df0 100644--- a/js/app/packages/core/util/freshSort.test.ts+++ b/js/app/packages/core/util/freshSort.test.ts@@ -257,3 +257,303 @@ describe('freshSort with all exact matches', () => {expect(results[0].item.type).toBe('channel');});});++describe('boostFn functionality', () => {+ interface MockItemWithEmail extends MockItem {+ email?: string;+ }++ it('applies per-item boost correctly', () => {+ const now = Date.now();+ const items: MockItemWithEmail[] = [+ {+ id: '1',+ name: 'Alice Johnson',+ type: 'item',+ email: '[email protected]',+ viewedAt: now - 1000,+ },+ {+ id: '2',+ name: 'Bob Smith',+ type: 'item',+ email: '[email protected]',+ viewedAt: now - 5000, // Older than Alice+ },+ {+ id: '3',+ name: 'Charlie Brown',+ type: 'item',+ email: '[email protected]',+ viewedAt: now - 3000,+ },+ ];++ const currentUserDomain = 'macro.com';+ const search = createFreshSearch<MockItemWithEmail>(+ {+ fuzzyWeight: 0.8,+ timeWeight: 0.2,+ boostFn: (item) => {+ const itemDomain = item.email?.split('@')[1];+ return itemDomain === currentUserDomain ? 1.0 : 0; // 100% boost for same domain+ },+ },+ (item) => item.name+ );++ const results = search(items, 'o'); // All three match with 'o' in their names++ // Bob should be boosted to the top despite being older, because of same domain boost+ expect(results[0].item.id).toBe('2');+ });++ it('boostFn works with search query', () => {+ const now = Date.now();+ const items: MockItemWithEmail[] = [+ {+ id: '1',+ name: 'Alice Johnson',+ type: 'item',+ email: '[email protected]',+ viewedAt: now - 1000,+ },+ {+ id: '2',+ name: 'Alicia Smith',+ type: 'item',+ email: '[email protected]',+ viewedAt: now - 1000,+ },+ ];++ const currentUserDomain = 'macro.com';+ const search = createFreshSearch<MockItemWithEmail>(+ {+ fuzzyWeight: 0.8,+ timeWeight: 0.2,+ boostFn: (item) => {+ const itemDomain = item.email?.split('@')[1];+ return itemDomain === currentUserDomain ? 0.5 : 0;+ },+ },+ (item) => item.name+ );++ const results = search(items, 'Ali');++ // Both match the query, but Alicia should rank higher due to domain boost+ expect(results).toHaveLength(2);+ expect(results[0].item.id).toBe('2');+ });++ it('handles boostFn returning 0 for no boost', () => {+ const now = Date.now();+ const items: MockItemWithEmail[] = [+ { id: '1', name: 'Alice', type: 'item', viewedAt: now - 1000 },+ { id: '2', name: 'Bob', type: 'item', viewedAt: now - 2000 },+ ];++ const search = createFreshSearch<MockItemWithEmail>(+ {+ fuzzyWeight: 0.5,+ timeWeight: 0.5,+ boostFn: () => 0, // No boost+ },+ (item) => item.name+ );++ const results = search(items, '');++ // Should sort by recency (Alice more recent)+ expect(results[0].item.id).toBe('1');+ });++ it('combines boostFn with channelBoost', () => {+ const now = Date.now();+ const items: MockItemWithEmail[] = [+ {+ id: '1',+ name: 'Design Doc',+ type: 'item',+ email: '[email protected]',+ viewedAt: now - 1000,+ },+ {+ id: '2',+ name: 'Design Channel',+ type: 'channel',+ email: '[email protected]',+ viewedAt: now - 1000,+ },+ ];++ const search = createFreshSearch<MockItemWithEmail>(+ {+ fuzzyWeight: 0.5,+ timeWeight: 0.5,+ channelBoost: 1.5,+ boostFn: (item) => {+ const itemDomain = item.email?.split('@')[1];+ return itemDomain === 'macro.com' ? 0.3 : 0;+ },+ },+ (item) => item.name+ );++ const results = search(items, 'Design');++ // With both boosts combined, channel may still win depending on weights+ expect(results).toHaveLength(2);+ });++ it('works without boostFn (undefined)', () => {+ const now = Date.now();+ const items: MockItemWithEmail[] = [+ { id: '1', name: 'Alice', type: 'item', viewedAt: now - 1000 },+ { id: '2', name: 'Bob', type: 'item', viewedAt: now - 2000 },+ ];++ const search = createFreshSearch<MockItemWithEmail>(+ {+ fuzzyWeight: 0.5,+ timeWeight: 0.5,+ // boostFn is undefined+ },+ (item) => item.name+ );++ const results = search(items, '');++ // Should sort normally by recency+ expect(results[0].item.id).toBe('1');+ });+});++describe('DM activity timestamps for user ranking', () => {+ interface UserWithInteraction extends MockItem {+ email: string;+ lastInteraction?: number;+ }++ it('ranks users with recent DM activity higher', () => {+ const now = Date.now();+ const users: UserWithInteraction[] = [+ {+ id: '1',+ name: 'Alice Johnson',+ type: 'item',+ email: '[email protected]',+ lastInteraction: now / 1000 - 86400, // 1 day ago (unix timestamp in seconds)+ },+ {+ id: '2',+ name: 'Bob Smith',+ type: 'item',+ email: '[email protected]',+ lastInteraction: now / 1000 - 3600, // 1 hour ago+ },+ {+ id: '3',+ name: 'Charlie Brown',+ type: 'item',+ email: '[email protected]',+ // No DM activity+ },+ ];++ const search = createFreshSearch<UserWithInteraction>(+ {+ fuzzyWeight: 0.6,+ timeWeight: 0.3,+ brevityWeight: 0.1,+ },+ (item) => item.name+ );++ const results = search(users, '');++ // Bob should rank highest (most recent interaction)+ // Then Alice (older interaction)+ // Then Charlie (no interaction)+ expect(results[0].item.id).toBe('2');+ expect(results[1].item.id).toBe('1');+ expect(results[2].item.id).toBe('3');+ });++ it('combines DM activity with fuzzy search', () => {+ const now = Date.now();+ const users: UserWithInteraction[] = [+ {+ id: '1',+ name: 'Alice Anderson',+ type: 'item',+ email: '[email protected]',+ lastInteraction: now / 1000 - 86400, // 1 day ago+ },+ {+ id: '2',+ name: 'Alicia Martinez',+ type: 'item',+ email: '[email protected]',+ lastInteraction: now / 1000 - 3600, // 1 hour ago+ },+ {+ id: '3',+ name: 'Bob Wilson',+ type: 'item',+ email: '[email protected]',+ lastInteraction: now / 1000 - 60, // 1 minute ago+ },+ ];++ const search = createFreshSearch<UserWithInteraction>(+ {+ fuzzyWeight: 0.6,+ timeWeight: 0.3,+ brevityWeight: 0.1,+ },+ (item) => item.name+ );++ const results = search(users, 'Ali');++ // Both Alice and Alicia match, but Alicia has more recent interaction+ expect(results).toHaveLength(2);+ expect(results[0].item.id).toBe('2');+ expect(results[1].item.id).toBe('1');+ });++ it('handles users without lastInteraction gracefully', () => {+ const users: UserWithInteraction[] = [+ {+ id: '1',+ name: 'Alice',+ type: 'item',+ email: '[email protected]',+ // No lastInteraction+ },+ {+ id: '2',+ name: 'Bob',+ type: 'item',+ email: '[email protected]',+ // No lastInteraction+ },+ ];++ const search = createFreshSearch<UserWithInteraction>(+ {+ fuzzyWeight: 0.6,+ timeWeight: 0.3,+ brevityWeight: 0.1,+ },+ (item) => item.name+ );++ const results = search(users, '');++ // Should not throw, and should return both users+ expect(results).toHaveLength(2);+ });+});diff --git a/js/app/packages/core/util/freshSort.ts b/js/app/packages/core/util/freshSort.tsindex 31b8d55b7d..36b4f0de17 100644--- a/js/app/packages/core/util/freshSort.ts+++ b/js/app/packages/core/util/freshSort.ts@@ -2,6 +2,7 @@* Wrap the fuzzy library in some addition utils for ranking by fuzzy match score* alongside freshness.*/+import type { Accessor } from 'solid-js';import type { FilterResult } from 'fuzzy';import fuzzy from 'fuzzy';import { fuzzyScoreCommaSpaceSeparated } from './fuzzy';@@ -25,6 +26,8 @@ export interface FreshSortConfig {channelBoost?: number;/** Enable comma-separated matching for channel names. When enabled, query "a,b" matches channel name "a,c,b". Default: false */commaSeparatedChannelMatch?: boolean;+ /** Function to calculate per-item boost. Returns a boost multiplier (e.g., 0.2 for +20% boost). Default: undefined */+ boostFn?: <T extends TimestampedItem>(item: T) => number;}export interface TimestampedItem {@@ -47,7 +50,7 @@ export interface FreshSortResult<T> {fuzzyResult?: FilterResult<T>;}-const DEFAULT_CONFIG: Required<FreshSortConfig> = {+const DEFAULT_CONFIG = {fuzzyWeight: 0.7,timeWeight: 0.3,brevityWeight: 0.0,@@ -57,6 +60,13 @@ const DEFAULT_CONFIG: Required<FreshSortConfig> = {useViewedAt: false,channelBoost: 1.0,commaSeparatedChannelMatch: false,+ boostFn: undefined,+} as const;++type FreshSortConfigWithDefaults = Required<+ Omit<FreshSortConfig, 'boostFn'>+> & {+ boostFn: FreshSortConfig['boostFn'];};function extractTimestamp(@@ -108,7 +118,7 @@ function isChannelItem(item: TimestampedItem): boolean {function calculateTimeScore(timestamp: number,- config: Required<FreshSortConfig>+ config: FreshSortConfigWithDefaults): number {const now = Date.now();const itemTime = timestamp * 1000;@@ -149,7 +159,10 @@ export function freshSort<T extends TimestampedItem>(filterResults: FilterResult<T>[],config: FreshSortConfig = {}): FreshSortResult<T>[] {- const finalConfig = { ...DEFAULT_CONFIG, ...config };+ const finalConfig = {+ ...DEFAULT_CONFIG,+ ...config,+ } as FreshSortConfigWithDefaults;const totalWeight =finalConfig.fuzzyWeight +finalConfig.timeWeight +@@ -183,12 +196,18 @@ export function freshSort<T extends TimestampedItem>(? finalConfig.channelBoost: 1.0;+ // Apply per-item boost if boostFn is provided+ const itemBoost = finalConfig.boostFn+ ? finalConfig.boostFn(result.original)+ : 0;+const combinedScore =(normalizedFuzzyWeight * fuzzyScore +normalizedTimeWeight * timeScore +normalizedBrevityWeight * brevityScore) *fuzzyPenalty *- channelMultiplier;+ channelMultiplier *+ (1 + itemBoost);return {item: result.original,@@ -210,6 +229,7 @@ export function createFreshSearch<T extends TimestampedItem>() {return (items: T[], query: string): FreshSortResult<T>[] => {const finalConfig = { ...DEFAULT_CONFIG, ...config };+const hasComma = query.includes(',');const hasSpace = query.includes(' ');const useMultiTermChannelMatch =@@ -253,3 +273,44 @@ export function createFreshSearch<T extends TimestampedItem>(return freshSort(fuzzyResults, config);};}++/**+ * Creates a boost function that gives a bonus to items with emails matching the current user's domain.+ * @param currentUserDomain - Accessor returning the current user's email domain (e.g., "example.com")+ * @param boost - The boost multiplier to apply (default: 0.5 for +50% boost)+ * @param getEmail - Function to extract email from item (default: assumes item.data.email)+ */+export function createSameDomainBoostFn<T extends TimestampedItem>(+ currentUserDomain: Accessor<string | undefined>,+ boost: number = 0.5,+ getEmail: (item: T) => string | undefined = (item) =>+ (item as { data?: { email?: string } }).data?.email+): (item: T) => number {+ return (item: T) => {+ const userDomain = currentUserDomain();+ if (!userDomain) return 0;+ const email = getEmail(item);+ const itemDomain = email?.split('@')[1];+ return itemDomain === userDomain ? boost : 0;+ };+}++/**+ * Preset configurations for common fresh search use cases.+ */+export const FreshSearchPresets = {+ /**+ * Base user search - balances fuzzy matching with recency, includes same-domain boost.+ * Good for recipient selectors, user pickers, and @mention menus.+ */+ baseUserSearch: <T extends TimestampedItem>(+ currentUserDomain: Accessor<string | undefined>,+ getEmail: (item: T) => string | undefined = (item) =>+ (item as { data?: { email?: string } }).data?.email+ ): Omit<FreshSortConfig, 'boostFn'> & { boostFn: (item: T) => number } => ({+ fuzzyWeight: 0.5,+ timeWeight: 0.4,+ brevityWeight: 0.1,+ boostFn: createSameDomainBoostFn(currentUserDomain, 0.5, getEmail),+ }),+} as const;