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(mentions): rank projects alongside cached search results (#9069)
gbirmaneea8c49ae301
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 5e86142bc9..c4c1e31412 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -81,6 +81,13 @@ Gate event notes and document Share meeting-link controls withon in dev and uses PostHog in production.See `docs/agent-guide/calendar.md` at the repo root.+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.+Channel composer draft persistence has a backend-free browser regression:`bunx playwright test --config src/features/channel/Input/browser-test/playwright.config.ts`.It types a draft, remounts the composer over it, and checks the blank lines survive.diff --git a/apps/web/src/features/channel/Input/browser-test/mention-ranking.browser.e2e.ts b/apps/web/src/features/channel/Input/browser-test/mention-ranking.browser.e2e.tsnew file mode 100644index 0000000000..44fad0ac7f--- /dev/null+++ b/apps/web/src/features/channel/Input/browser-test/mention-ranking.browser.e2e.ts@@ -0,0 +1,78 @@+import { expect, test } from '@playwright/test';++for (const mobile of [false, true]) {+ test(`project ranks above cached tasks and inserts a mention on ${mobile ? 'phone' : 'desktop'}`, async ({+ browser,+ }, testInfo) => {+ const context = await browser.newContext({+ viewport: mobile+ ? { width: 390, height: 844 }+ : { width: 1280, height: 900 },+ isMobile: mobile,+ hasTouch: mobile,+ });+ const page = await context.newPage();+ const errors: string[] = [];+ page.on('pageerror', (error) => errors.push(error.message));+ await page.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (+ url.hostname === 'localhost' &&+ !url.pathname.startsWith('/__macro_dev/')+ ) {+ await route.continue();+ } else {+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: '{"responses":[]}',+ });+ }+ });+ await page.routeWebSocket('**/*', (socket) => socket.close());+ await page.goto(+ `http://localhost:${process.env.CHANNEL_DRAFT_TEST_PORT ?? '3006'}/src/features/channel/Input/browser-test/mention-ranking.html`+ );+ const editor = page.locator('[data-markdown-editable]');+ await expect(editor).toBeVisible({ timeout: 60_000 });+ await editor.click();+ await page.keyboard.type('@');+ await expect(page.locator('.menu-surface')).toBeVisible({+ timeout: 15_000,+ });+ await page.keyboard.type('task');+ const menu = page.locator('.menu-surface');+ const project = menu.getByText('Task planning', { exact: true });+ await expect(project).toBeVisible();+ // The first visible result must be the project even in the unexpanded preview.+ await expect(menu.locator('.group').first()).toContainText('Task planning');+ if (!mobile) {+ await page.keyboard.press('ArrowRight');+ await expect(menu.getByText('Back to everything')).toBeVisible();+ await expect(menu.locator('.group').first()).toContainText(+ 'Task planning'+ );+ }+ await page.screenshot({+ path: testInfo.outputPath(+ `mention-ranking-${mobile ? 'phone' : 'desktop'}.png`+ ),+ });+ if (mobile) await project.tap();+ else await page.keyboard.press('Enter');+ await expect(menu).toHaveCount(0);+ await expect(editor).toContainText('Task planning');+ await expect(editor).not.toContainText('@task');+ const chip = editor.locator('[data-document-mention][data-document-id]');+ await expect(chip).toHaveAttribute('data-document-id', 'project');+ await expect(chip).toHaveAttribute('data-block-name', 'initiative');+ await expect(page.getByTestId('draft')).toContainText(+ '<m-document-mention>'+ );+ await expect(page.getByTestId('draft')).toContainText(+ '\"blockName\":\"initiative\"'+ );+ expect(errors).toEqual([]);+ await context.close();+ });+}diff --git a/apps/web/src/features/channel/Input/browser-test/mention-ranking.html b/apps/web/src/features/channel/Input/browser-test/mention-ranking.htmlnew file mode 100644index 0000000000..1cb59feb17--- /dev/null+++ b/apps/web/src/features/channel/Input/browser-test/mention-ranking.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Project mention ranking</title></head>+ <body><div id="root"></div><script type="module" src="./mention-ranking.tsx"></script></body>+</html>diff --git a/apps/web/src/features/channel/Input/browser-test/mention-ranking.tsx b/apps/web/src/features/channel/Input/browser-test/mention-ranking.tsxnew file mode 100644index 0000000000..610c2d4b31--- /dev/null+++ b/apps/web/src/features/channel/Input/browser-test/mention-ranking.tsx@@ -0,0 +1,149 @@+import '@app/index.css';+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';+import { PosthogProvider } from '@app/lib/analytics/posthog';+import { DocumentMentionStatic } from '@core/component/LexicalMarkdown/component/decorator/DocumentMention';+import { ChannelsContextProvider } from '@core/context/channels';+import { EmailLinksContextProvider } from '@core/context/emailLinks';+import { QuickAccessContextProvider } from '@core/context/quickAccess/context';+import { filterQuickAccessItems } from '@core/context/quickAccess/entity-search';+import type {+ Bucket,+ EntityItem,+ QuickAccessContextValue,+ QuickAccessListOptions,+} from '@core/context/quickAccess/types';+import { UserContextProvider } from '@core/context/user';+import { useHotKeyRoot } from '@core/hotkey/hotkeys';+import { EntityProvider } from '@entity';+import { DocumentMentionNode } from '@macro-inc/lexical-core';+import { setDecorator } from '@macro-inc/lexical-core/decoratorRegistry';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { createSignal, onCleanup } from 'solid-js';+import { render } from 'solid-js/web';+import { ChannelInput } from '../ChannelInput';+import { makeInputValuePersistenceKey } from '../utils/persistence';++const CHANNEL_ID = 'mention-fixture-channel';+// Render the stored chip without a backend preview or app navigation host.+setDecorator(DocumentMentionNode, DocumentMentionStatic);+const ITEMS: EntityItem[] = [+ ...Array.from(+ { length: 500 },+ (_, index): EntityItem => ({+ id: `task-${index}`,+ kind: 'entity',+ bucket: 'task',+ searchText: `Track task changes ${index}`,+ sortTimestamp: Date.now(),+ timestamps: { viewedAt: new Date() },+ data: {+ type: 'document',+ id: `task-${index}`,+ name: `Track task changes ${index}`,+ ownerId: 'owner',+ fileType: 'md',+ subType: { type: 'task' },+ },+ })+ ),+ {+ id: 'project',+ kind: 'entity',+ bucket: 'initiative',+ searchText: 'Task planning',+ sortTimestamp: 0,+ timestamps: {},+ data: {+ type: 'initiative',+ id: 'project',+ name: 'Task planning',+ ownerId: 'owner',+ },+ },+];++// Reproduce the production merge: cached tasks first, the project appended.+// Query filtering stays source-owned; the real menu owns all ranking/selection.+const QUICK_ACCESS: QuickAccessContextValue = {+ useList: ((...args: Bucket[] | [QuickAccessListOptions]) => {+ const first = args[0];+ const options = typeof first === 'object' ? first : undefined;+ const buckets =+ options?.buckets ??+ args.filter((bucket): bucket is Bucket => typeof bucket === 'string');+ const items = () =>+ filterQuickAccessItems(+ ITEMS.filter(+ (item) => !buckets.length || buckets.includes(item.bucket)+ ),+ options?.searchTerm?.() ?? ''+ );+ return {+ items,+ totalCount: () => items().length,+ hasMore: () => false,+ isLoading: () => false,+ isLoadingMore: () => false,+ error: () => undefined,+ loadMore: async () => {},+ };+ }) as QuickAccessContextValue['useList'],+ usesRecordSelection: () => false,+ usesSearchProjection: () => true,+ isLoading: () => false,+ refresh: () => {},+ getById: (id) => ITEMS.find((item) => item.id === id),+};++/** Real channel composer and mention menu over a controlled Quick Access source. */+function Fixture() {+ useHotKeyRoot();+ const [draft, setDraft] = createSignal('');+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ onCleanup(() => client.clear());+ return (+ <QueryClientProvider client={client}>+ <AnalyticsContextProvider>+ <PosthogProvider>+ <EntityProvider>+ <UserContextProvider>+ <EmailLinksContextProvider>+ <ChannelsContextProvider>+ <QuickAccessContextProvider value={QUICK_ACCESS}>+ <main class="min-h-screen bg-page p-4 text-ink space-y-4 flex flex-col justify-end">+ <h1>Project mention ranking</h1>+ <output data-testid="draft" hidden>+ {draft()}+ </output>+ <ChannelInput+ onChange={(snapshot) => {+ setDraft(snapshot.value);+ }}+ input={{+ mode: 'channel',+ id: `channel-input-${CHANNEL_ID}`,+ placeholder: 'Message #planning',+ }}+ participants={() => []}+ bots={() => []}+ persistenceKey={makeInputValuePersistenceKey({+ channelId: CHANNEL_ID,+ })}+ />+ </main>+ </QuickAccessContextProvider>+ </ChannelsContextProvider>+ </EmailLinksContextProvider>+ </UserContextProvider>+ </EntityProvider>+ </PosthogProvider>+ </AnalyticsContextProvider>+ </QueryClientProvider>+ );+}++const root = document.getElementById('root');+if (!root) throw new Error('Fixture root missing');+render(() => <Fixture />, root);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex 2aad243d0d..a0050b8ef3 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -388,7 +388,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {...(sourceEnabled('calendarEvents') ? calendarEvents() : []),...(sourceEnabled('dates') ? (dates() ?? []) : []),];- return sortMobileMentions(combined, searchTerm(), users);+ return sortMobileMentions(combined, searchTerm(), users, true);});const bucketConfigs = createLazyMemo((): BucketConfig[] => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.test.tsindex f425160c98..203fcc5444 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.test.ts@@ -1,9 +1,10 @@-import { createRoot } from 'solid-js';+import type { EntityItem } from '@core/context/quickAccess';+import { createRoot, createSignal } from 'solid-js';import { expect, it, vi } from 'vitest';-import { useEntityMention } from './useEntityMention';+import { useEntityMention, useEntityMentionFromList } from './useEntityMention';const list = vi.hoisted(() => ({- items: () => [],+ items: vi.fn<() => EntityItem[]>(() => []),totalCount: () => 50,hasMore: () => true,isLoading: () => false,@@ -30,3 +31,67 @@ it('exposes pagination from search projections, not just legacy record selectionexpect(list.loadMore).toHaveBeenCalledOnce();dispose();});++it('ranks local projects together with cached hits and reranks new pages', () => {+ const recentTask: EntityItem = {+ id: 'task',+ kind: 'entity',+ bucket: 'task',+ searchText: 'Track task changes',+ sortTimestamp: Date.now(),+ timestamps: { viewedAt: new Date() },+ data: {+ id: 'task',+ name: 'Track task changes',+ type: 'document',+ ownerId: 'owner',+ fileType: 'md',+ subType: { type: 'task' },+ },+ };+ const project: EntityItem = {+ id: 'project',+ kind: 'entity',+ bucket: 'initiative',+ searchText: 'Task planning',+ sortTimestamp: 0,+ timestamps: {},+ data: {+ id: 'project',+ name: 'Task planning',+ type: 'initiative',+ ownerId: 'owner',+ },+ };+ const exactTask: EntityItem = {+ ...recentTask,+ id: 'exact',+ searchText: 'Task',+ data: { ...recentTask.data, id: 'exact', name: 'Task' },+ };+ const [rows, setRows] = createSignal([recentTask, project]);+ list.items.mockImplementation(rows);+ const { mention, custom, dispose } = createRoot((dispose) => ({+ mention: useEntityMention({+ buckets: ['task', 'initiative'],+ searchTerm: () => 'task',+ }),+ custom: useEntityMentionFromList({+ items: rows,+ buckets: ['task', 'initiative'],+ searchTerm: () => 'task',+ }),+ dispose,+ }));+ try {+ expect(mention.entities()).toEqual([project, recentTask]);+ expect(custom.entities()).toEqual([project, recentTask]);+ setRows([recentTask, project, exactTask]);+ expect(mention.entities()).toEqual([exactTask, project, recentTask]);+ expect(custom.entities()).toEqual([exactTask, project, recentTask]);+ expect(mention.hasMore()).toBe(true);+ } finally {+ dispose();+ list.items.mockReturnValue([]);+ }+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.tsindex b993ca6ffd..ab221a4ddb 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useEntityMention.ts@@ -4,9 +4,9 @@ import {type QuickAccessList,useQuickAccess,} from '@core/context/quickAccess';-import { searchQuickAccessEntities } from '@core/context/quickAccess/entity-search';import { createLazyMemo } from '@solid-primitives/memo';import type { Accessor } from 'solid-js';+import { rankMentions } from '../utils/mention-ranking';type UseEntityMentionOptions = {buckets: EntityBucket[];@@ -36,10 +36,9 @@ export function useEntityMention(}) as QuickAccessList<EntityItem>;const usesRankedList = () =>quickAccess.usesRecordSelection() || quickAccess.usesSearchProjection();- const entities = createLazyMemo(() => {- if (usesRankedList()) return entityList.items();- return searchQuickAccessEntities(entityList.items(), options.searchTerm());- });+ const entities = createLazyMemo(() =>+ rankMentions(entityList.items(), options.searchTerm(), usesRankedList())+ );return {entities,@@ -76,7 +75,7 @@ export function useEntityMentionFromList();const entities = createLazyMemo(() =>- searchQuickAccessEntities(entitiesList(), searchTerm())+ rankMentions(entitiesList(), searchTerm()));return {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.test.tsnew file mode 100644index 0000000000..2e6b3e5c75--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.test.ts@@ -0,0 +1,104 @@+import type { EntityItem } from '@core/context/quickAccess';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { rankMentions } from './mention-ranking';+import { sortMobileMentions } from './mobileSort';++const NOW = new Date('2026-10-01T12:00:00Z');+const OLD = new Date('2026-08-01T12:00:00Z');++function item(+ id: string,+ name: string,+ bucket: 'task' | 'initiative',+ viewedAt = NOW+): EntityItem {+ return {+ id,+ kind: 'entity',+ bucket,+ searchText: name,+ sortTimestamp: viewedAt.getTime(),+ timestamps: { viewedAt },+ data:+ bucket === 'initiative'+ ? { id, name, ownerId: 'owner', type: 'initiative' }+ : {+ id,+ name,+ ownerId: 'owner',+ type: 'document',+ fileType: 'md',+ subType: { type: 'task' },+ },+ };+}++afterEach(() => vi.useRealTimers());++describe('mention ranking', () => {+ it('promotes an old project appended after hundreds of recent cached tasks', () => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+ const tasks = Array.from({ length: 500 }, (_, index) =>+ item(`task-${index}`, `Track task changes ${index}`, 'task')+ );+ const project = item('project', 'Task planning', 'initiative', OLD);+ const source = [...tasks, project];++ for (const query of ['task', ' TASK ', 'task p', 'task planning']) {+ expect(rankMentions(source, query, true)[0]).toBe(project);+ expect(sortMobileMentions(source, query, [], true)[0]).toBe(project);+ }+ expect(source.at(-1)).toBe(project);+ });++ it('lets an exact task name beat a project that only partially matches', () => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+ const task = item('task', 'Release', 'task', OLD);+ const project = item('project', 'Release planning', 'initiative');+ expect(rankMentions([project, task], 'release')[0]).toBe(task);+ });++ it('uses a project boost for equally strong name matches', () => {+ const task = item('task', 'Roadmap', 'task');+ const project = item('project', 'Roadmap', 'initiative');+ expect(rankMentions([task, project], 'road')[0]).toBe(project);+ });++ it('uses viewed recency when browsing and when name matches are equal', () => {+ vi.useFakeTimers();+ vi.setSystemTime(NOW);+ const old = item('old', 'Task planning', 'initiative', OLD);+ const recent = item('recent', 'Task planning', 'task');+ expect(rankMentions([old, recent], '')[0]).toBe(recent);+ const olderTask = item('older-task', 'Task planning', 'task', OLD);+ expect(rankMentions([olderTask, recent], 'task')[0]).toBe(recent);+ });++ it('preserves broader cache matches and their identity without admitting unrelated custom items', () => {+ const broad = item('broad', 'Some early afternoon music', 'task');+ const direct = item('direct', 'Seamu notes', 'initiative');+ expect(rankMentions([broad, direct], 'seamu')).toEqual([direct]);+ expect(rankMentions([broad, direct], 'seamu', true)).toEqual([+ direct,+ broad,+ ]);+ expect(sortMobileMentions([broad, direct], 'seamu', [], true)).toEqual([+ direct,+ broad,+ ]);+ });++ it('keeps equal scores stable as another source page arrives', () => {+ const first = item('first', 'Task update', 'task');+ const second = item('second', 'Task update', 'task');+ const third = item('third', 'Task update', 'task');+ expect(rankMentions([first, second], 'task')).toEqual([first, second]);+ expect(rankMentions([first, second, third], 'task')).toEqual([+ first,+ second,+ third,+ ]);+ });+});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.tsnew file mode 100644index 0000000000..f59bb1ccfc--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mention-ranking.ts@@ -0,0 +1,99 @@+import type { EntityBucket } from '@core/context/quickAccess';+import { createFreshSearch, type FreshSortConfig } 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.+ * `initiative` is a task project; `project` is a Drive folder. */+export const MENTION_RANKING_CONFIG: Record<+ 'query' | 'browse',+ MentionRankingProfile+> = {+ query: {+ search: {+ 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 },+ bucketBoosts: {+ initiative: 0.6,+ project: 0.2,+ database: 0.2,+ snippet: 0.15,+ },+ exactNameBoost: 2,+ prefixNameBoost: 0.25,+ },+ browse: {+ search: {+ useViewedAt: true,+ fuzzyWeight: 0,+ timeWeight: 0.9,+ minFuzzyThreshold: 0,+ dmBoost: 1.2,+ },+ kindBoosts: { user: 0.2, group: 0.1 },+ bucketBoosts: {},+ exactNameBoost: 0,+ prefixNameBoost: 0,+ },+};++function getMentionName(item: MentionItem): string {+ if (item.kind === 'date') return item.data.displayText;+ if (item.kind === 'group') return item.data.groupAlias;+ if (item.kind === 'bookingLink' || item.kind === 'calendarEvent')+ return item.data.title;+ if (item.kind === 'externalChat') return item.data.name;+ return item.searchText;+}++function getMentionTimestamps(item: MentionItem) {+ return 'timestamps' in item ? item.timestamps : {};+}++/** Rank all loaded sources together before the menu takes its preview rows.+ * Preserve source matches when cache/server matching is broader than uFuzzy. */+export function rankMentions<T extends MentionItem>(+ items: T[],+ query: string,+ preserveMatches = false+): T[] {+ const term = query.trim().toLocaleLowerCase();+ const profile = MENTION_RANKING_CONFIG[term ? 'query' : 'browse'];+ const search = createFreshSearch<T>({+ config: {+ ...profile.search,+ boostFn: (item) => {+ 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,+ isDmItem: (item) => item.kind === 'entity' && item.bucket === 'dm',+ getTimestamp: getMentionTimestamps,+ });+ const ranked = search(items, query.trim()).map(({ item }) => item);+ if (!preserveMatches) return ranked;++ const rankedIds = new Set(ranked.map((item) => item.id));+ return [...ranked, ...items.filter((item) => !rankedIds.has(item.id))];+}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.test.tsindex 0c99d8240a..9f4a9b450e 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.test.ts@@ -208,14 +208,14 @@ describe('sortMobileMentions', () => {expect(result[0].id).toBe('d1');});- test('groups appear when matched by query but stay below users with stronger boost', () => {+ test('an exact group alias beats a partial user-name match', () => {const now = new Date();const here = groupItem('here');const user = userItem('u1', 'here-user', now);const result = sortMobileMentions([here, user], 'here');- expect(result.indexOf(user)).toBeLessThan(result.indexOf(here));+ expect(result.indexOf(here)).toBeLessThan(result.indexOf(user));});test('items with no timestamp (groups, dates) sink without a query', () => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.tsindex eed7fb2f09..48407a1ef0 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mobileSort.ts@@ -1,62 +1,5 @@-import { createFreshSearch, type FreshSortConfig } from '@core/util/freshSort';import type { MentionItem } from '../../../../utils/mentionsUtils';--function getMentionName(item: MentionItem): string {- if (item.kind === 'date') return item.data.displayText;- if (item.kind === 'group') return item.data.groupAlias;- if (item.kind === 'bookingLink' || item.kind === 'calendarEvent')- return item.data.title;- if (item.kind === 'externalChat') return item.data.name;- return item.searchText;-}--function getMentionTimestamps(item: MentionItem) {- if (- item.kind === 'date' ||- item.kind === 'group' ||- item.kind === 'bookingLink' ||- item.kind === 'calendarEvent' ||- item.kind === 'externalChat'- )- return {};- return item.timestamps;-}--function isDmItem(item: MentionItem): boolean {- return item.kind === 'entity' && item.bucket === 'dm';-}--/**- * Per-kind boost. With a query, the user is usually targeting a specific- * person, so users beat group DMs/channels that merely contain that name —- * the command menu sidesteps this by excluding persons from its "all" view,- * but the mention menu must include them. Without a query we keep the boost- * small so freshness dominates.- */-function mentionBoost(hasQuery: boolean) {- return (item: MentionItem): number => {- if (item.kind === 'user') return hasQuery ? 0.4 : 0.2;- if (item.kind === 'group') return hasQuery ? 0.2 : 0.1;- return 0;- };-}--function createMobileSearchConfig(- hasQuery: boolean-): FreshSortConfig<MentionItem> {- return {- useViewedAt: true,- fuzzyWeight: hasQuery ? 0.5 : 0,- timeWeight: hasQuery ? 0.4 : 0.9,- brevityWeight: hasQuery ? 0.1 : 0,- minFuzzyThreshold: hasQuery ? 0.1 : 0,- dmBoost: hasQuery ? 1.4 : 1.2,- commaSeparatedChannelMatch: true,- gapPenaltyWeight: hasQuery ? 0.4 : 0,- startBonusDecay: hasQuery ? 0.4 : 0,- boostFn: mentionBoost(hasQuery),- };-}+import { rankMentions } from './mention-ranking';/*** How many entries from {@link topUserCandidates} get pinned above the rest@@ -70,21 +13,15 @@ const TOP_USERS = 2;export function sortMobileMentions(items: MentionItem[],query: string,- topUserCandidates: MentionItem[] = []+ topUserCandidates: MentionItem[] = [],+ preserveMatches = false): MentionItem[] {const pinned = topUserCandidates.slice(0, TOP_USERS);const pinnedIds = new Set(pinned.map((item) => item.id));- const hasQuery = query.trim().length > 0;- const search = createFreshSearch<MentionItem>({- config: createMobileSearchConfig(hasQuery),- getName: getMentionName,- isDmItem,- getTimestamp: getMentionTimestamps,- });- const rest = search(items, query)- .map(({ item }) => item)- .filter((item) => !pinnedIds.has(item.id));+ const rest = rankMentions(items, query, preserveMatches).filter(+ (item) => !pinnedIds.has(item.id)+ );return [...pinned, ...rest];}diff --git a/docs/agent-guide/media/mentions/project-ranking-desktop.png b/docs/agent-guide/media/mentions/project-ranking-desktop.pngnew file mode 100644index 0000000000..269f968004Binary files /dev/null and b/docs/agent-guide/media/mentions/project-ranking-desktop.png differdiff --git a/docs/agent-guide/media/mentions/project-ranking-phone.png b/docs/agent-guide/media/mentions/project-ranking-phone.pngnew file mode 100644index 0000000000..d049195194Binary files /dev/null and b/docs/agent-guide/media/mentions/project-ranking-phone.png differdiff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex 5c82194358..365e8691a0 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -1211,6 +1211,18 @@ between buckets must still appear without retyping in every affected view.Older cache runtimes without bucket metadata, mutations, and identity resetsrefresh 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 together+before 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`.+Broader cache/server matches remain reachable even when the local fuzzy matcher+would 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+preview rows and stay near the top in **View all**. Select it with Enter or a+phone tap and confirm a project mention is inserted.+Counts describe loaded results, not the full server corpus. Scans throughincomplete or already-visible cache hits are bounded per action; continuenavigating/scrolling, or narrow the query, to resume from the saved cursor.