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
fix(command): rank exact and prefix name matches first in Cmd+K (#9111)
gbirmana9e245226a22
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 419011ef87..3f19197854 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -122,12 +122,22 @@ upload failure have desktop, phone, and tablet browser coverage:Keep the shared uploader from restoring removed attachments or publishing afterthe composer is disposed. The Share button and shortcut use the same upload guard.-Mention menus rank loaded entity sources together with `MENTION_RANKING_CONFIG`-in `MentionsMenu/utils/mention-ranking.ts`: name relevance, viewed recency,-brevity, and explicit type/name boosts. Task projects use the `initiative`-bucket; `project` means a Drive folder. Preserve broader cache/server matches-and the existing People preview/pinning. The channel browser suite below also-checks project ranking and insertion on desktop and phone.+Menus that find entities by typed name (Command-K, mobile name search, @+mentions) rank with `NAME_MATCH_RANKING` in `@core/util/freshSort`: names equal+to the query first, then names starting with it, then other matches, with tight+matches near the start scoring higher. Each menu's recency weights and type+boosts (Cmd+K's channel and DM boosts) order rows within those groups and never+lift a row past a better name match. The one exception: Cmd+K then keeps Macro+users and DMs ahead of CRM contacts across the people positions, whatever their+match. Tune name relevance there for every menu.+Name groups and match position use the row's label (`getDisplayName`), so search+text can add emails, aliases, or command keywords before or after it. Mention+menus rank loaded entity sources together with `MENTION_RANKING_CONFIG` in+`MentionsMenu/utils/mention-ranking.ts`: name relevance, viewed recency,+brevity, and type boosts. Task projects use the `initiative` bucket; `project`+means a Drive folder. Preserve broader cache/server matches and the existing+People preview/pinning. The channel browser suite below also checks project+ranking and insertion on desktop and phone.Channel composer draft persistence has a backend-free browser regression:`bunx playwright test --config src/features/channel/Input/browser-test/playwright.config.ts`.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 ebfe6b6ab0..69d23cbe13 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@@ -57,6 +57,18 @@ function project(id: string, name: string, updatedAt = NOW): CommandMenuItem {};}+function note(id: string, name: string, viewedAt = NOW): EntityItem {+ return {+ id,+ kind: 'entity',+ bucket: 'note',+ searchText: name,+ sortTimestamp: viewedAt,+ timestamps: { viewedAt: new Date(viewedAt) },+ data: { id, type: 'document', name, ownerId: 'owner', fileType: 'md' },+ };+}+function contact(id: string,name: string,@@ -143,6 +155,49 @@ describe('command menu search ranking', () => {).toEqual(['recent-project', 'command', 'old-project']);});+ it.each([false, true])(+ 'ranks an exact project name above recently viewed documents that contain it with GraphQL %s',+ (cacheEnabled) => {+ const items = [+ note('scattered', 'Launch: share the updated plan with partners'),+ note('retro', 'Team launch plan retro'),+ note('review', 'Launch plan review notes'),+ project('project', 'Launch plan', NOW - 20 * DAY),+ ];+ expect(ids(items, 'launch plan', cacheEnabled).slice(0, 2)).toEqual([+ 'project',+ 'review',+ ]);+ }+ );++ it('scores exact names against the label when search text adds emails or command keywords', () => {+ const items = [+ note('notes', 'Avery Morgan notes'),+ {+ ...contact('contact', 'Avery Morgan'),+ searchText: 'Avery Morgan | [email protected]',+ },+ ];+ expect(ids(items, 'avery morgan')[0]).toBe('contact');++ const create = {+ ...command('create', 'Create', NOW - DAY),+ searchText: 'new make add Create',+ };+ expect(ids([note('plan', 'Create plan'), create], 'create')[0]).toBe(+ 'create'+ );+ });++ it('ranks an exact project name above a recently viewed channel that starts with it', () => {+ const items = [+ channel('channel', 'Launch plan rollout'),+ project('project', 'Launch plan', NOW - 20 * DAY),+ ];+ expect(ids(items, 'launch plan')).toEqual(['project', 'channel']);+ });+it('keeps ranking independent of whether a match came from cached or local results', () => {const cached = channel('cached', 'Planning', NOW - DAY);const local = channel('local', 'Planning', NOW);diff --git a/apps/web/src/features/command/rank-command-search-items.ts b/apps/web/src/features/command/rank-command-search-items.tsindex ec10cde163..59df39936a 100644--- a/apps/web/src/features/command/rank-command-search-items.ts+++ b/apps/web/src/features/command/rank-command-search-items.ts@@ -1,6 +1,26 @@-import { createFreshSearch } from '@core/util/freshSort';+import { createFreshSearch, NAME_MATCH_RANKING } from '@core/util/freshSort';+import { match } from 'ts-pattern';import type { CommandMenuItem } from './useCommandItems';+/** The label a row shows; its search text can add emails, aliases, or command keywords. */+function displayName(item: CommandMenuItem): string {+ return match(item)+ .with({ kind: 'entity' }, { kind: 'user' }, (row) => row.data.name)+ .with({ kind: 'initiative' }, (row) => row.name)+ .with({ kind: 'command' }, ({ data }) =>+ typeof data.description === 'function'+ ? data.description()+ : data.description+ )+ .with(+ { kind: 'search' },+ { kind: 'ask-ai' },+ { kind: 'new-project' },+ (row) => row.searchText+ )+ .exhaustive();+}+function compareRecency(left: CommandMenuItem, right: CommandMenuItem) {return (right.sortTimestamp - left.sortTimestamp || left.id.localeCompare(right.id)@@ -43,6 +63,7 @@ export function rankCommandSearchItems<T extends CommandMenuItem>(): T[] {const search = createFreshSearch<T>({config: {+ ...NAME_MATCH_RANKING,useViewedAt: true,channelBoost: 3,dmBoost: 1.8,@@ -51,6 +72,7 @@ export function rankCommandSearchItems<T extends CommandMenuItem>(minFuzzyThreshold: 0.1,},getName: (item) => item.searchText,+ getDisplayName: displayName,isChannelItem: (item) => item.bucket === 'channel' || item.bucket === 'dm',isDmItem: (item) => item.bucket === 'dm',getTimestamp: (item) => item.timestamps,@@ -59,6 +81,7 @@ export function rankCommandSearchItems<T extends CommandMenuItem>(const ranked = search(items, query).sort((left, right) =>+ right.nameMatchRank - left.nameMatchRank ||right.combinedScore - left.combinedScore ||compareRecency(left.item, right.item))diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.tsindex f59bb1ccfc..dc58bb5499 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.ts@@ -1,13 +1,15 @@import type { EntityBucket } from '@core/context/quickAccess';-import { createFreshSearch, type FreshSortConfig } from '@core/util/freshSort';+import {+ createFreshSearch,+ type FreshSortConfig,+ NAME_MATCH_RANKING,+} from '@core/util/freshSort';import type { MentionItem } from '../../../../utils/mentionsUtils';type MentionRankingProfile = {search: FreshSortConfig<MentionItem>;kindBoosts: Partial<Record<MentionItem['kind'], number>>;bucketBoosts: Partial<Record<EntityBucket, number>>;- exactNameBoost: number;- prefixNameBoost: number;};/** Additive boosts: 0.5 means a 1.5x multiplier on the blended score.@@ -18,12 +20,11 @@ export const MENTION_RANKING_CONFIG: Record<> = {query: {search: {+ ...NAME_MATCH_RANKING,useViewedAt: true,fuzzyWeight: 0.7,timeWeight: 0.2,brevityWeight: 0.1,- gapPenaltyWeight: 0.4,- startBonusDecay: 0.2,dmBoost: 1.4,},kindBoosts: { user: 0.6, group: 0.2 },@@ -33,8 +34,6 @@ export const MENTION_RANKING_CONFIG: Record<database: 0.2,snippet: 0.15,},- exactNameBoost: 2,- prefixNameBoost: 0.25,},browse: {search: {@@ -46,8 +45,6 @@ export const MENTION_RANKING_CONFIG: Record<},kindBoosts: { user: 0.2, group: 0.1 },bucketBoosts: {},- exactNameBoost: 0,- prefixNameBoost: 0,},};@@ -60,6 +57,12 @@ function getMentionName(item: MentionItem): string {return item.searchText;}+/** Entity and user search text can add emails or aliases after the name. */+function getMentionDisplayName(item: MentionItem): string {+ if (item.kind === 'entity' || item.kind === 'user') return item.data.name;+ return getMentionName(item);+}+function getMentionTimestamps(item: MentionItem) {return 'timestamps' in item ? item.timestamps : {};}@@ -71,8 +74,7 @@ export function rankMentions<T extends MentionItem>(query: string,preserveMatches = false): T[] {- const term = query.trim().toLocaleLowerCase();- const profile = MENTION_RANKING_CONFIG[term ? 'query' : 'browse'];+ const profile = MENTION_RANKING_CONFIG[query.trim() ? 'query' : 'browse'];const search = createFreshSearch<T>({config: {...profile.search,@@ -80,14 +82,11 @@ export function rankMentions<T extends MentionItem>(let boost = profile.kindBoosts[item.kind] ?? 0;if (item.kind === 'entity')boost += profile.bucketBoosts[item.bucket] ?? 0;- const name = getMentionName(item).trim().toLocaleLowerCase();- if (term && name === term) boost += profile.exactNameBoost;- else if (term && name.startsWith(term))- boost += profile.prefixNameBoost;return boost;},},getName: getMentionName,+ getDisplayName: getMentionDisplayName,isDmItem: (item) => item.kind === 'entity' && item.bucket === 'dm',getTimestamp: getMentionTimestamps,});diff --git a/apps/web/src/lib/core/util/freshSort.test.ts b/apps/web/src/lib/core/util/freshSort.test.tsindex 5ef1d437b0..a1883d1345 100644--- a/apps/web/src/lib/core/util/freshSort.test.ts+++ b/apps/web/src/lib/core/util/freshSort.test.ts@@ -387,6 +387,91 @@ describe('freshSort with all exact matches', () => {});});+describe('name match ranking', () => {+ it('ranks exact names, then prefixes, then other matches, ignoring case and outer spaces', () => {+ const viewedAt = new Date();+ const items: MockItem[] = [+ { id: 'contains', name: 'Team launch plan', type: 'item', viewedAt },+ { id: 'prefix', name: 'Launch plan review', type: 'item', viewedAt },+ { id: 'exact', name: 'Launch Plan', type: 'item', viewedAt },+ ];+ const search = createFreshSearch<MockItem>({+ config: { rankNameMatchesFirst: true },+ getName: (item) => item.name,+ getTimestamp: (item) => ({ viewedAt: item.viewedAt }),+ });++ expect(+ search(items, ' launch PLAN ').map((result) => result.item.id)+ ).toEqual(['exact', 'prefix', 'contains']);+ const browseScores = search(items, '').map(+ (result) => result.combinedScore+ );+ expect(new Set(browseScores).size).toBe(1);+ });++ it('keeps an exact name ahead of a boosted channel that only starts with it', () => {+ const items: MockItem[] = [+ {+ id: 'channel',+ name: 'Planning',+ type: 'channel',+ viewedAt: new Date(),+ },+ {+ id: 'exact',+ name: 'Plan',+ type: 'item',+ viewedAt: new Date(Date.now() - 20 * 24 * 60 * 60 * 1000),+ },+ ];+ const search = createFreshSearch<MockItem>({+ config: {+ rankNameMatchesFirst: true,+ useViewedAt: true,+ channelBoost: 3,+ },+ getName: (item) => item.name,+ isChannelItem: (item) => item.type === 'channel',+ getTimestamp: (item) => ({ viewedAt: item.viewedAt }),+ });++ expect(search(items, 'plan').map((result) => result.item.id)).toEqual([+ 'exact',+ 'channel',+ ]);+ });++ it('measures match position on the label when search text puts keywords first', () => {+ const now = Date.now();+ const items: MockItem[] = [+ {+ id: 'plan',+ name: 'Create plan',+ type: 'item',+ viewedAt: new Date(now - 24 * 60 * 60 * 1000),+ },+ { id: 'command', name: 'Create', type: 'item', viewedAt: new Date(now) },+ ];+ const search = createFreshSearch<MockItem>({+ config: {+ rankNameMatchesFirst: true,+ startBonusDecay: 0.2,+ useViewedAt: true,+ },+ getName: (item) =>+ item.id === 'command' ? `new make add ${item.name}` : item.name,+ getDisplayName: (item) => item.name,+ getTimestamp: (item) => ({ viewedAt: item.viewedAt }),+ });++ expect(search(items, 'cre').map((result) => result.item.id)).toEqual([+ 'command',+ 'plan',+ ]);+ });+});+describe('boostFn functionality', () => {interface MockItemWithEmail extends MockItem {email?: string;diff --git a/apps/web/src/lib/core/util/freshSort.ts b/apps/web/src/lib/core/util/freshSort.tsindex 1ca39072fb..167ae5bc6f 100644--- a/apps/web/src/lib/core/util/freshSort.ts+++ b/apps/web/src/lib/core/util/freshSort.ts@@ -58,6 +58,8 @@ export interface FreshSortConfig<T = unknown> {gapPenaltyWeight?: number;/** How much to penalize matches that start later in the string. Higher values penalize later starts more. Default: 0 */startBonusDecay?: number;+ /** Rank names equal to the query first, then names starting with it, then other matches, ignoring case; the blended score orders each group. Default: false */+ rankNameMatchesFirst?: boolean;}type FreshSortConfigWithDefaults = Required<FreshSortConfig<unknown>>;@@ -74,6 +76,8 @@ export interface FreshSortResult<T> {timeScore: number;brevityScore: number;combinedScore: number;+ /** 2 for an exact name, 1 for a name starting with the query, else 0; always 0 unless `rankNameMatchesFirst`. */+ nameMatchRank: number;}const DEFAULT_CONFIG = {@@ -90,6 +94,7 @@ const DEFAULT_CONFIG = {boostFn: undefined,gapPenaltyWeight: 0,startBonusDecay: 0,+ rankNameMatchesFirst: false,} as const;function extractTimestamp(@@ -138,6 +143,35 @@ export function normalizeFuzzyScore(return Math.max(0, Math.min(1, fuzzyScore / maxPossibleScore));}+function calculateNameMatchRank(name: string, term: string): number {+ if (!term) return 0;+ const normalizedName = name.trim().toLocaleLowerCase();+ if (normalizedName === term) return 2;+ if (normalizedName.startsWith(term)) return 1;+ return 0;+}++type MatchPosition = { start: number; ranges: number[] | undefined };++/** Where the query matches each label, for rows whose search text adds more than the label. */+function labelMatchPositions(+ labels: string[],+ query: string,+ idxs: number[]+): Map<number, MatchPosition> {+ const positions = new Map<number, MatchPosition>();+ const labelIdxs = uf.filter(labels, query, idxs);+ if (!labelIdxs || labelIdxs.length === 0) return positions;+ const info = uf.info(labelIdxs, labels, query);+ info.idx.forEach((labelIdx, infoIdx) => {+ positions.set(labelIdx, {+ start: info.start[infoIdx] ?? 0,+ ranges: info.ranges[infoIdx],+ });+ });+ return positions;+}+function calculateBrevityScore(text: string): number {if (!text || text.length === 0) return 0;const maxLength = 100;@@ -148,6 +182,7 @@ function calculateBrevityScore(text: string): number {function ufuzzyFilter<T>(items: T[],getName: NameFn<T>,+ getDisplayName: NameFn<T>,query: string,gapPenaltyWeight: number,startBonusDecay: number@@ -162,10 +197,19 @@ function ufuzzyFilter<T>(if (!order || order.length === 0) return [];+ // Score where the query falls in the label when it matches there, so+ // aliases or keywords placed before the label don't count as a late start.+ const labelPositions =+ getDisplayName === getName+ ? undefined+ : labelMatchPositions(items.map(getDisplayName), query, idxs);+const queryLen = query.length;return order.map((orderIdx) => {const haystackIdx = info.idx[orderIdx];- const ranges = info.ranges[orderIdx];+ const labelPosition = labelPositions?.get(haystackIdx);+ const ranges = labelPosition ? labelPosition.ranges : info.ranges[orderIdx];+ const start = labelPosition ? labelPosition.start : info.start[orderIdx];let matchSpan = queryLen;if (ranges && ranges.length >= 2) {@@ -176,8 +220,7 @@ function ufuzzyFilter<T>(const clampedStartDecay = Math.max(0, startBonusDecay);const rawGapPenalty = matchSpan > 0 ? queryLen / matchSpan : 1;const gapPenalty = 1 - (1 - rawGapPenalty) * clampedGapWeight;- const startBonus =- 1 / (1 + (info.start[orderIdx] ?? 0) * clampedStartDecay);+ const startBonus = 1 / (1 + (start ?? 0) * clampedStartDecay);const score = gapPenalty * startBonus * 100;return {@@ -190,6 +233,7 @@ function ufuzzyFilter<T>(function freshSort<T>(filterResults: FuzzyFilterResult<T>[],+ getNameMatchRank: (item: T) => number,config: FreshSortConfig<T> = {},isChannelItem: BooleanFn<T>,isDmItem: BooleanFn<T>,@@ -257,16 +301,22 @@ function freshSort<T>(timeScore,brevityScore,combinedScore,+ nameMatchRank: getNameMatchRank(result.original),};});- scoredResults.sort((a, b) => b.combinedScore - a.combinedScore);+ scoredResults.sort(+ (a, b) =>+ b.nameMatchRank - a.nameMatchRank || b.combinedScore - a.combinedScore+ );return scoredResults;}interface CreateFreshSearchArgs<T> {config?: FreshSortConfig<T>;getName: NameFn<T>;+ /** The label people see, for name-match ranking and match position when `getName` adds aliases, emails, or keywords. Default: getName */+ getDisplayName?: NameFn<T>;isChannelItem?: BooleanFn<T>;isDmItem?: BooleanFn<T>;getTimestamp: TimestampFn<T>;@@ -275,6 +325,7 @@ interface CreateFreshSearchArgs<T> {export function createFreshSearch<T>({config = {},getName,+ getDisplayName = getName,isChannelItem = () => false,isDmItem = () => false,getTimestamp,@@ -282,6 +333,11 @@ export function createFreshSearch<T>({return (items: T[], query: string): FreshSortResult<T>[] => {const finalConfig = { ...DEFAULT_CONFIG, ...config };const trimmedQuery = query.trim();+ const term = trimmedQuery.toLocaleLowerCase();+ const getNameMatchRank = (item: T) =>+ finalConfig.rankNameMatchesFirst+ ? calculateNameMatchRank(getDisplayName(item), term)+ : 0;const hasComma = trimmedQuery.includes(',');const hasSpace = trimmedQuery.includes(' ');@@ -296,6 +352,7 @@ export function createFreshSearch<T>({}));return freshSort(allResults,+ getNameMatchRank,config,isChannelItem,isDmItem,@@ -326,6 +383,7 @@ export function createFreshSearch<T>({const nonChannelResults = ufuzzyFilter(nonChannelItems,getName,+ getDisplayName,trimmedQuery,finalConfig.gapPenaltyWeight,finalConfig.startBonusDecay@@ -333,6 +391,7 @@ export function createFreshSearch<T>({const allResults = [...channelResults, ...nonChannelResults];return freshSort(allResults,+ getNameMatchRank,config,isChannelItem,isDmItem,@@ -343,12 +402,14 @@ export function createFreshSearch<T>({const fuzzyResults = ufuzzyFilter(items,getName,+ getDisplayName,query,finalConfig.gapPenaltyWeight,finalConfig.startBonusDecay);return freshSort(fuzzyResults,+ getNameMatchRank,config,isChannelItem,isDmItem,@@ -377,6 +438,18 @@ function createSameDomainBoostFn<T>(};}+/**+ * How closely a typed query matches an item's name: exact names, then names+ * starting with the query, then tight matches near the start. Menus that find+ * entities by name (Command-K, mobile name search, @ mentions) share this and+ * keep their own recency weights and type boosts.+ */+export const NAME_MATCH_RANKING = {+ gapPenaltyWeight: 0.4,+ startBonusDecay: 0.2,+ rankNameMatchesFirst: true,+} as const satisfies FreshSortConfig;+/*** Preset configurations for common fresh search use cases.*/diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex 3506faff11..cd1baa6153 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -1227,10 +1227,13 @@ refresh conservatively. For an empty search, scroll toward the end (or useDown); mentions offer **View all** for a category and then load more local pages.The @ menu ranks loaded projects and cached document/task matches togetherbefore choosing preview rows, with the same ranking on desktop and phone.-Exact and prefix name matches get boosts, task projects get a type boost, and-viewed recency and shorter names contribute. Empty-query browsing remains-recency-led; existing People preview slots and phone pinning remain. Tuning lives-in `MENTION_RANKING_CONFIG` in the mention menu's `utils/mention-ranking.ts`.+Names equal to the query rank first and names starting with it next; within+those groups task projects get a type boost, and viewed recency and shorter+names contribute. Empty-query browsing remains+recency-led; existing People preview slots and phone pinning remain. Name-match+tuning is shared with Cmd+K in `NAME_MATCH_RANKING` (`@core/util/freshSort`);+recency weights and type boosts live in `MENTION_RANKING_CONFIG` in the mention+menu's `utils/mention-ranking.ts`.Broader cache/server matches remain reachable even when the local fuzzy matcherwould omit them. To verify, type `@task` with a project named `Task planning`and many recent tasks containing “task”: the project should appear in the first@@ -1315,8 +1318,14 @@ 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. Typed searches givechannels (including DMs) the same 3x boost as the main search view, with the menu'sadditional 1.8x DM boost; relevance and viewed recency still order those results.-This shared ranking also applies to mobile name search. Verify an older matching-channel stays above recent CRM contacts and agent sessions in All, and remains+Relevance uses the same name-match ranking as the @ menu: names equal to the+query come first, then names starting with it, then other matches, and matches+that are spread out or start late in the name score lower. The channel and DM+boosts and recency order rows within each group. Verify that typing a project's+full name puts it above recently viewed documents, tasks, and channels that+only contain or start with those words. This shared ranking also applies to mobile name search.+Verify an older matching channel stays above recent CRM contacts and agent+sessions in All, and remainsfindable in Channels while its cache entry is absent. Refreshing the cache orreopening the menu with unchanged data must not reorder results or duplicate achannel when its cache entry arrives. Hydration must also refresh ownership,