Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(mentions): stabilize people and document results while typing (#7198)

gbirman7751f82d316e
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx
new file mode 100644
index 0000000000..ea045321d3
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx
@@ -0,0 +1,104 @@
+import type { IUser } from '@core/user';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { createSignal, type ParentProps } from 'solid-js';
+import { afterEach, expect, it, vi } from 'vitest';
+import { createMenuOperations } from '../../../shared/inlineMenu';
+import { MentionsMenu } from './MentionsMenu';
+
+vi.mock('@app/lib/analytics/analytics-context', () => ({
+ useAnalytics: () => ({ track: vi.fn() }),
+}));
+vi.mock('@app/signal/splitLayout', () => ({ globalSplitManager: () => null }));
+vi.mock('@core/block', () => ({
+ useMaybeBlockId: () => undefined,
+ useMaybeBlockName: () => undefined,
+}));
+vi.mock('@core/constant/featureFlags', () => ({
+ enableCrm: {},
+ isFeatureEnabled: () => false,
+}));
+vi.mock('@core/context/quickAccess', () => ({
+ useQuickAccess: () => ({ useList: () => ({ items: () => [] }) }),
+}));
+vi.mock('@core/context/user', () => ({
+ useEmail: () => () => '[email protected]',
+}));
+vi.mock('@core/constant/allBlocks', () => ({
+ fileTypeToBlockName: () => 'md',
+}));
+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => false }));
+vi.mock('@core/util/dateSearch/useDateSearch', () => ({
+ useDateSearch: () => () => [],
+}));
+vi.mock('@core/component/ScopedPortal', () => ({
+ ScopedPortal: (props: ParentProps) => props.children,
+}));
+vi.mock('../../../directive/floatWithSelection', () => ({
+ floatWithSelection: vi.fn(),
+}));
+vi.mock('../../../directive/floatWithElement', () => ({
+ floatWithElement: vi.fn(),
+}));
+vi.mock('../../../plugins', () => ({ CLOSE_INLINE_SEARCH_COMMAND: {} }));
+vi.mock('./utils/mentionHandlers', () => ({ createItemHandler: vi.fn() }));
+vi.mock('./hooks/useEmailSearchMention', () => ({
+ useEmailSearchMention: vi.fn(),
+}));
+vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => null }));
+vi.mock('@ui', () => ({
+ Surface: (props: ParentProps) => <div>{props.children}</div>,
+ cn: (...classes: unknown[]) =>
+ classes.filter((c) => typeof c === 'string').join(' '),
+}));
+
+const originalScrollIntoView = Element.prototype.scrollIntoView;
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ Element.prototype.scrollIntoView = originalScrollIntoView;
+});
+
+it('keeps matching category and row nodes mounted across typing and updated people', async () => {
+ vi.useFakeTimers();
+ Element.prototype.scrollIntoView = vi.fn();
+ const seamus: IUser = {
+ id: 'macro|[email protected]',
+ name: 'Seamus Edson',
+ email: '[email protected]',
+ };
+ const [users, setUsers] = createSignal([seamus]);
+ const menu = createMenuOperations();
+ menu.setSearchTerm('sea');
+ menu.openMenu();
+ const onPick = vi.fn();
+ render(() => (
+ <MentionsMenu
+ menu={menu}
+ entities={() => []}
+ users={users}
+ sources={['users']}
+ anchor={document.createElement('div')}
+ onPick={onPick}
+ />
+ ));
+ const heading = screen.getByText('People');
+ const row = screen.getByTitle('Seamus Edson [email protected]');
+ for (const term of ['seam', 'seamu', 'seam', 'sea']) {
+ menu.setSearchTerm(term);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(screen.getByText('People')).toBe(heading);
+ expect(screen.getByTitle('Seamus Edson [email protected]')).toBe(row);
+ }
+ const updated = { ...seamus, name: 'Seamus Updated' };
+ setUsers([updated]);
+ expect(screen.getByText('People')).toBe(heading);
+ expect(screen.getByTitle('Seamus Updated [email protected]')).toBe(row);
+ fireEvent.click(row);
+ expect(onPick).toHaveBeenCalledWith(
+ expect.objectContaining({ data: updated })
+ );
+ expect(menu.isOpen()).toBe(false);
+});
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.tsx
index 41f242da81..a5c4600fe4 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
@@ -14,6 +14,7 @@ import { debouncedDependent } from '@core/util/debounce';
import { useIsKeyPressActive } from '@core/util/useIsKeyPressActive';
import type { EmailEntity } from '@entity';
import type { HistoryItem as Item } from '@queries/history/history';
+import { Key } from '@solid-primitives/keyed';
import { createLazyMemo } from '@solid-primitives/memo';
import { createVirtualizer } from '@tanstack/solid-virtual';
import { Surface } from '@ui';
@@ -55,7 +56,7 @@ import { useMentionsMenuController } from './MentionsMenuController';
import { createItemHandler } from './utils/mentionHandlers';
import { sortMobileMentions } from './utils/mobileSort';
-const MAX_ITEMS = 8;
+const TARGET_ITEMS = 8;
const VIRTUAL_ITEM_HEIGHT = 36;
// Height consumed by Surface's p-px border (2px) + py-2 padding (16px)
const PANEL_DECORATION_HEIGHT = 18;
@@ -382,7 +383,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {
const controller = useMentionsMenuController(bucketConfigs, {
ignoredIds: () => (blockId ? [blockId] : []),
- maxItems: MAX_ITEMS,
+ targetItems: TARGET_ITEMS,
});
const [escapeSpaceState, setEscapeSpaceState] = createSignal<
@@ -634,29 +635,33 @@ function MentionsMenuInner(props: MentionsMenuProps) {
}
>
<div>
- <For each={visibleBuckets()}>
+ <Key
+ each={visibleBuckets()}
+ by={(bucket) => bucket.config.id}
+ >
{(bucket, idx) => (
<>
<Show when={idx() > 0}>
<div class="w-full mt-4 border-b border-edge-muted mb-2" />
</Show>
<ItemBin
- label={bucket.config.label}
- binType={bucket.config.id}
- totalCount={bucket.config.getFullCount()}
- showingCount={bucket.bucketItems.length}
+ label={bucket().config.label}
+ binType={bucket().config.id}
+ totalCount={bucket().config.getFullCount()}
+ showingCount={bucket().bucketItems.length}
onViewAll={handleViewAll}
isSelected={
- controller.selectedCategory() === bucket.config.id
+ controller.selectedCategory() ===
+ bucket().config.id
}
>
- <For each={bucket.bucketItems}>
+ <Key each={bucket().bucketItems} by="id">
{(item, i) => (
<MentionsMenuItem
- item={item}
- index={bucket.startIndex + i()}
+ item={item()}
+ index={bucket().startIndex + i()}
selected={
- bucket.startIndex + i() ===
+ bucket().startIndex + i() ===
controller.selectedIndex()
}
itemAction={itemAction}
@@ -664,11 +669,11 @@ function MentionsMenuInner(props: MentionsMenuProps) {
setOpen={setMenuOpen}
/>
)}
- </For>
+ </Key>
</ItemBin>
</>
)}
- </For>
+ </Key>
</div>
</Show>
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.test.ts
new file mode 100644
index 0000000000..e40c777691
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.test.ts
@@ -0,0 +1,151 @@
+import type { UserItem } from '@core/context/quickAccess';
+import { createRoot, createSignal } from 'solid-js';
+import { expect, it } from 'vitest';
+import {
+ type BucketConfig,
+ useMentionsMenuController,
+} from './MentionsMenuController';
+
+const items = (prefix: string, count: number): UserItem[] =>
+ Array.from({ length: count }, (_, index) => ({
+ id: `${prefix}-${index}`,
+ kind: 'user',
+ bucket: 'person',
+ data: {
+ id: `${prefix}-${index}`,
+ name: prefix,
+ email: `${index}@test.com`,
+ },
+ searchText: prefix,
+ sortTimestamp: 0,
+ timestamps: {},
+ }));
+
+const bucket = (id: BucketConfig['id'], data: UserItem[]): BucketConfig => ({
+ id,
+ label: id,
+ getData: () => data,
+ getFullCount: () => data.length,
+});
+
+it('keeps the same people visible and selected as delayed categories arrive', () => {
+ createRoot((dispose) => {
+ const people = items('person', 7);
+ const [buckets, setBuckets] = createSignal([bucket('users', people)]);
+ const menu = useMentionsMenuController(buckets);
+ expect(menu.combinedItems()).toEqual(people.slice(0, 3));
+ menu.selectItem(2);
+
+ setBuckets([
+ bucket('users', people),
+ bucket('documents', items('doc', 74)),
+ bucket('channels', items('channel', 24)),
+ bucket('agentSessions', items('session', 3)),
+ bucket('companies', items('company', 8)),
+ bucket('emails', items('email', 3)),
+ ]);
+ expect(menu.combinedItems().slice(0, 3)).toEqual(people.slice(0, 3));
+ expect(menu.selectedItem()).toBe(people[2]);
+ expect(menu.selectedCategory()).toBe('users');
+ expect(menu.combinedItems()).toHaveLength(8);
+ dispose();
+ });
+});
+
+it('keeps all people accessible through View all and keyboard navigation', () => {
+ createRoot((dispose) => {
+ const people = items('person', 7);
+ const menu = useMentionsMenuController(() => [bucket('users', people)]);
+ expect(menu.canViewAllForCategory('users')).toBe(true);
+ menu.viewAll('users');
+ expect(menu.combinedItems()).toEqual(people);
+ menu.selectPrev();
+ expect(menu.selectedItem()).toBe(people[6]);
+ menu.exitViewAll();
+ expect(menu.combinedItems()).toEqual(people.slice(0, 3));
+ dispose();
+ });
+});
+
+it('keeps document preview slots stable when only total match counts change', () => {
+ createRoot((dispose) => {
+ const documents = items('doc', 74);
+ const [documentCount, setDocumentCount] = createSignal(15);
+ const menu = useMentionsMenuController(() => [
+ bucket('users', items('person', 7)),
+ bucket('documents', documents.slice(0, documentCount())),
+ bucket('channels', items('channel', 1)),
+ bucket('emails', items('email', 4)),
+ ]);
+ const initialBins = menu.bins();
+ const documentSlots = initialBins.documents;
+ expect(documentSlots).toBeGreaterThan(0);
+ expect(menu.combinedItems()).toHaveLength(8);
+ menu.selectItem(3 + documentSlots - 1);
+ for (const count of [11, 15, 74, 11]) {
+ setDocumentCount(count);
+ expect(menu.bins()).toEqual(initialBins);
+ expect(menu.combinedItems().slice(3, 3 + documentSlots)).toEqual(
+ documents.slice(0, documentSlots)
+ );
+ expect(menu.selectedItem()).toBe(documents[documentSlots - 1]);
+ }
+ menu.viewAll('documents');
+ expect(menu.combinedItems()).toHaveLength(11);
+ dispose();
+ });
+});
+
+it('allocates unused people slots to other categories and excludes ignored people', () => {
+ createRoot((dispose) => {
+ const people = items('person', 2);
+ const menu = useMentionsMenuController(
+ () => [bucket('users', people), bucket('documents', items('doc', 20))],
+ { ignoredIds: () => [people[0].id] }
+ );
+ expect(menu.bins()).toEqual({ users: 1, documents: 7 });
+ expect(menu.combinedItems()).toHaveLength(8);
+ expect(menu.combinedItems()[0]).toBe(people[1]);
+ dispose();
+ });
+});
+
+it('retains the full combined mobile list and entity-only allocation', () => {
+ createRoot((dispose) => {
+ const allItems = items('all', 12);
+ const menu = useMentionsMenuController(() => [bucket('all', allItems)]);
+ menu.viewAll('all');
+ expect(menu.combinedItems()).toEqual(allItems);
+ const entities = useMentionsMenuController(() => [
+ bucket('documents', items('doc', 20)),
+ bucket('channels', items('channel', 20)),
+ ]);
+ expect(entities.bins()).toEqual({ documents: 4, channels: 4 });
+ dispose();
+ });
+});
+
+it('keeps every category reachable when stable People rows exceed the preview target', () => {
+ createRoot((dispose) => {
+ const otherCategories: BucketConfig['id'][] = [
+ 'openTabs',
+ 'documents',
+ 'channels',
+ 'agentSessions',
+ 'companies',
+ 'emails',
+ 'dates',
+ ];
+ const menu = useMentionsMenuController(() => [
+ bucket('users', items('person', 7)),
+ ...otherCategories.map((id) => bucket(id, items(id, 10))),
+ ]);
+ expect(menu.bins().users).toBe(3);
+ for (const id of otherCategories) {
+ expect(menu.bins()[id]).toBe(1);
+ expect(menu.canViewAllForCategory(id)).toBe(true);
+ }
+ expect(menu.combinedItems()).toHaveLength(10);
+ dispose();
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
index 1e7daa1027..44a9e380ea 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
@@ -37,9 +37,13 @@ type SelectedCategory = string | null;
/** result of bin computation - how many items to show per bucket */
type MentionBins = Record<string, number>;
+const PEOPLE_PREVIEW_COUNT = 3;
+
class MentionsMenuController {
private buckets: Accessor<BucketConfig[]>;
- private maxItems: number;
+ // A soft preview budget: stable People rows and one row per other category
+ // take precedence so asynchronous results cannot hide a category.
+ private targetItems: number;
private ignoredIds: Accessor<string[]> = () => [];
private selectedIndexSignal: Signal<number>;
private viewAllModeSignal: Signal<ViewAllMode>;
@@ -47,12 +51,12 @@ class MentionsMenuController {
constructor(
buckets: Accessor<BucketConfig[]>,
options: {
- maxItems?: number;
+ targetItems?: number;
ignoredIds?: Accessor<string[]>;
} = {}
) {
this.buckets = buckets;
- this.maxItems = options.maxItems ?? 8;
+ this.targetItems = options.targetItems ?? 8;
this.ignoredIds = options.ignoredIds ?? (() => []);
this.selectedIndexSignal = createSignal(0);
@@ -98,7 +102,17 @@ class MentionsMenuController {
});
bins = createLazyMemo((): MentionBins => {
- return this.computeBins(this.rawBins(), this.maxItems);
+ const { users, ...otherBins } = this.rawBins();
+ if (users === undefined)
+ return this.computeBins(otherBins, this.targetItems);
+
+ // Keep people visible while asynchronous entity/email results arrive.
+ // Proportional allocation can otherwise remove the person under the pointer.
+ const peopleCount = Math.min(users, PEOPLE_PREVIEW_COUNT, this.targetItems);
+ return {
+ users: peopleCount,
+ ...this.computeBins(otherBins, this.targetItems - peopleCount),
+ };
});
combinedItems = createLazyMemo((): MentionItem[] => {
@@ -338,15 +352,15 @@ class MentionsMenuController {
return (config?.getFullCount() ?? 0) > abbreviatedCount;
}
- private computeBins(rawBins: MentionBins, maxItems: number): MentionBins {
+ private computeBins(rawBins: MentionBins, targetItems: number): MentionBins {
const total = Object.values(rawBins).reduce((sum, count) => sum + count, 0);
- // If total items fit in max, no scaling needed
- if (total <= maxItems) {
+ // If total items fit in the target, no scaling needed
+ if (total <= targetItems) {
return { ...rawBins };
}
- // Allocate items proportionally, ensuring each non-empty bin gets at least 1
+ // Give every non-empty category a preview before sharing spare slots.
const scaled: MentionBins = {};
const nonEmptyBins = Object.entries(rawBins).filter(
@@ -363,40 +377,18 @@ class MentionsMenuController {
}
}
- // Second pass: distribute remaining slots proportionally
- const remaining = maxItems - allocated;
-
- if (remaining > 0) {
- const nonEmptyTotal = nonEmptyBins.reduce((sum, [_, c]) => sum + c, 0);
- const remainders: Array<{ key: string; remainder: number }> = [];
- let totalFloorsAdded = 0;
-
+ // Share spare slots in category order. Total match counts can change on
+ // each keystroke or cache response even when the visible matches are the
+ // same; proportional allocation would hide/show those rows repeatedly.
+ while (allocated < targetItems) {
for (const [key, count] of nonEmptyBins) {
- const proportion = count / nonEmptyTotal;
- const raw = proportion * remaining;
- const floor = Math.floor(raw);
- const remainder = raw - floor;
-
- scaled[key] = (scaled[key] || 0) + floor;
- totalFloorsAdded += floor;
- remainders.push({ key, remainder });
- }
-
- // Distribute leftover items to bins with largest remainders
- const leftover = remaining - totalFloorsAdded;
- const sorted = remainders.sort((a, b) => b.remainder - a.remainder);
-
- for (let i = 0; i < leftover && i < sorted.length; i++) {
- const key = sorted[i].key;
- scaled[key] = (scaled[key] || 0) + 1;
+ if (allocated >= targetItems) break;
+ if (scaled[key] >= count) continue;
+ scaled[key] += 1;
+ allocated += 1;
}
}
- // Ensure we don't exceed actual bin counts
- for (const [key, count] of Object.entries(scaled)) {
- scaled[key] = Math.min(count, rawBins[key] || 0);
- }
-
return scaled;
}
}
@@ -404,12 +396,12 @@ class MentionsMenuController {
export function useMentionsMenuController(
buckets: Accessor<BucketConfig[]>,
options: {
- maxItems?: number;
+ targetItems?: number;
ignoredIds?: Accessor<string[]>;
} = {}
): MentionsMenuController {
return new MentionsMenuController(buckets, {
- maxItems: options.maxItems,
+ targetItems: options.targetItems,
ignoredIds: options.ignoredIds,
});
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.test.ts
new file mode 100644
index 0000000000..afd36a9d88
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.test.ts
@@ -0,0 +1,112 @@
+import type { UserItem } from '@core/context/quickAccess';
+import type { IUser } from '@core/user';
+import { createRoot, createSignal } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useUsersMention } from './useUsersMention';
+
+const mocks = vi.hoisted(() => ({
+ users: (): UserItem[] => [],
+}));
+vi.mock('@core/context/quickAccess', () => ({
+ useQuickAccess: () => ({ useList: () => ({ items: () => mocks.users() }) }),
+}));
+vi.mock('@core/context/user', () => ({
+ useEmail: () => () => '[email protected]',
+}));
+
+const seamus: IUser = {
+ id: 'macro|[email protected]',
+ name: 'Seamus Edson',
+ email: '[email protected]',
+};
+const alias: IUser = {
+ id: 'macro|[email protected]',
+ name: 'seamus+05',
+ email: '[email protected]',
+};
+const sean: IUser = {
+ id: 'macro|[email protected]',
+ name: 'Sean Aye',
+ email: '[email protected]',
+};
+const userItem = (user: IUser, lastInteraction?: Date): UserItem => ({
+ id: user.id,
+ data: user,
+ kind: 'user',
+ bucket: 'person',
+ searchText: `${user.name} | ${user.email}`,
+ sortTimestamp: lastInteraction?.getTime() ?? 0,
+ timestamps: { lastInteraction },
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-29T12:00:00Z'));
+ mocks.users = () => [
+ userItem(sean),
+ userItem(alias),
+ userItem(seamus, new Date()),
+ ];
+});
+afterEach(() => vi.useRealTimers());
+
+it('ranks shared people identically in body and discussion mention searches', () => {
+ createRoot((dispose) => {
+ const [searchTerm, setSearchTerm] = createSignal('sea');
+ const body = useUsersMention({ searchTerm });
+ const discussion = useUsersMention({
+ searchTerm,
+ users: () => [sean, alias, seamus],
+ });
+ for (const term of ['sea', 'seam', 'seamus']) {
+ setSearchTerm(term);
+ expect(discussion.users().map((item) => item.id)).toEqual(
+ body.users().map((item) => item.id)
+ );
+ expect(discussion.users()[0].id).toBe(seamus.id);
+ }
+ dispose();
+ });
+});
+
+it('keeps custom participant scope and display data when workspace data refreshes', () => {
+ createRoot((dispose) => {
+ const [workspace, setWorkspace] = createSignal<UserItem[]>([]);
+ mocks.users = workspace;
+ const customUser = {
+ ...seamus,
+ name: 'Custom Seamus',
+ photoUrl: 'avatar.png',
+ };
+ const mention = useUsersMention({
+ searchTerm: () => 'sea',
+ users: () => [customUser],
+ });
+ expect(mention.users().map((item) => item.id)).toEqual([seamus.id]);
+ setWorkspace([userItem(sean), userItem(seamus, new Date())]);
+ expect(mention.users().map((item) => item.id)).toEqual([seamus.id]);
+ expect(mention.users()[0].data).toBe(customUser);
+ expect(mention.users()[0].timestamps.lastInteraction).toEqual(new Date());
+ dispose();
+ });
+});
+
+it('uses supplied interaction history for people absent from the workspace list', () => {
+ mocks.users = () => [];
+ createRoot((dispose) => {
+ const mention = useUsersMention({
+ searchTerm: () => 'sea',
+ users: () => [sean, alias, { ...seamus, lastInteraction: new Date() }],
+ });
+ expect(mention.users()[0].id).toBe(seamus.id);
+ dispose();
+ });
+});
+
+it('preserves explicitly empty participant lists', () => {
+ createRoot((dispose) => {
+ const mention = useUsersMention({ searchTerm: () => '', users: () => [] });
+ expect(mention.users()).toEqual([]);
+ dispose();
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts
index a82ef75501..e45566a37a 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/hooks/useUsersMention.ts
@@ -41,6 +41,7 @@ export function useUsersMention(
): UseUsersMentionResult {
const { users: customUsers, searchTerm, isChannelBlock, blockId } = options;
const quickAccess = useQuickAccess();
+ const workspaceUsers = quickAccess.useList('person').items;
const currentUserEmail = useEmail();
const currentUserDomain = () => {
@@ -48,26 +49,27 @@ export function useUsersMention(
return email ? email.split('@')[1] : undefined;
};
- const usersList = createLazyMemo(() => {
- if (customUsers) {
- const users = customUsers;
- return () =>
- users().map(
- (user) =>
- ({
- id: user.id,
- data: user,
- kind: 'user' as const,
- bucket: 'person' as const,
- sortTimestamp: 0,
- timestamps: {},
- searchText: user.name
- ? user.name + ' | ' + user.email
- : user.email + ' | ' + user.email,
- }) as UserItem
- );
- }
- return quickAccess.useList('person').items;
+ const usersList = createLazyMemo((): UserItem[] => {
+ if (!customUsers) return workspaceUsers();
+
+ // Custom lists scope who can be mentioned, but should retain the same
+ // interaction ranking as the document body's workspace list.
+ const workspaceUsersById = new Map(
+ workspaceUsers().map((item) => [item.id, item])
+ );
+ return customUsers().map((user) => ({
+ id: user.id,
+ data: user,
+ kind: 'user',
+ bucket: 'person',
+ sortTimestamp: workspaceUsersById.get(user.id)?.sortTimestamp ?? 0,
+ timestamps: {
+ lastInteraction:
+ workspaceUsersById.get(user.id)?.timestamps.lastInteraction ??
+ user.lastInteraction,
+ },
+ searchText: `${user.name || user.email} | ${user.email}`,
+ }));
});
const userSearch = () => {
@@ -92,7 +94,7 @@ export function useUsersMention(
const users = createLazyMemo(() => {
const term = searchTerm();
- const list = usersList()();
+ const list = usersList();
return userSearch()(list, term).map(({ item }) => item);
});
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
index 6d099b8ab1..93d7e6d2f4 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
@@ -346,6 +346,60 @@ function renderRetainedList(
}
describe('Quick Access source integration', () => {
+ it('keeps cached document order and fuzzy matches stable across typing and backspacing', async () => {
+ const names = [
+ 'Seamus snip',
+ 'seamus todo',
+ '[email protected] taskium',
+ 'Some early afternoon music',
+ ];
+ mocks.history = names.map((name, index) => ({
+ id: `mention-${index}`,
+ name,
+ type: 'document',
+ fileType: 'md',
+ ownerId: 'owner',
+ }));
+ const results: SearchCachePage = {
+ documents: names.map((name, index) => ({
+ profile: 'quick-access-v1',
+ recordKey: `GraphqlSoupDocument:mention-${index}`,
+ bucket: 'note',
+ searchText: name.toLowerCase(),
+ timestampMs: 1,
+ sourceHash: 'hash',
+ })),
+ nextCursor: null,
+ };
+ mocks.search.mockResolvedValue(results);
+ const [query, setQuery] = createSignal('seam');
+ const snapshots: string[][] = [];
+ const list = setup((source) => {
+ const list = source.useList({ buckets: ['note'], searchTerm: query });
+ createRenderEffect(() => {
+ snapshots.push(list.items().map((item) => item.id));
+ });
+ return list;
+ });
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ const expected = mocks.history.map((item) => item.id);
+ expect(list.items().map((item) => item.id)).toEqual(expected);
+ snapshots.length = 0;
+
+ for (const term of ['seamu', 'seam', 'seamu']) {
+ const pending = Promise.withResolvers<SearchCachePage>();
+ mocks.search.mockReturnValueOnce(pending.promise);
+ setQuery(term);
+ expect(list.isLoading()).toBe(true);
+ expect(list.items().map((item) => item.id)).toEqual(expected);
+ pending.resolve(results);
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ expect(list.items().map((item) => item.id)).toEqual(expected);
+ }
+ expect(snapshots.length).toBeGreaterThan(0);
+ expect(snapshots.every((ids) => ids.join() === expected.join())).toBe(true);
+ });
+
it('lets initially empty cached channels populate during hydration and replays the last change', async () => {
const first = retainedQueryData.channels;
const latest = [{ ...first[0], name: 'Updated channel' }];
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
index 3775040067..8684176de6 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
@@ -39,7 +39,10 @@ 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 { searchQuickAccessItems } from './entity-search';
+import {
+ filterQuickAccessItems,
+ searchQuickAccessItems,
+} from './entity-search';
import { createProjectedList } from './projected-list';
import type {
Bucket,
@@ -956,6 +959,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {
enabled: () =>
projectedBuckets().length > 0 && options.enabled?.() !== false,
existingItems: localItems,
+ filterPreviousItems: filterQuickAccessItems,
materialize: async (documents) => {
const idOf = (recordKey: string) =>
recordKey.slice(recordKey.indexOf(':') + 1);
diff --git a/apps/web/src/lib/core/context/quickAccess/entity-search.test.ts b/apps/web/src/lib/core/context/quickAccess/entity-search.test.ts
new file mode 100644
index 0000000000..bb870ce389
--- /dev/null
+++ b/apps/web/src/lib/core/context/quickAccess/entity-search.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import { filterQuickAccessItems } from './entity-search';
+import type { UserItem } from './types';
+
+function items(...names: string[]): UserItem[] {
+ return names.map((name, index) => ({
+ id: String(index),
+ kind: 'user',
+ bucket: 'person',
+ searchText: name,
+ sortTimestamp: 0,
+ timestamps: {},
+ data: { id: String(index), name, email: `${index}@macro.com` },
+ }));
+}
+
+describe('pending Quick Access matches', () => {
+ it('keeps cache order and row identity even when the legacy ranker would reorder them', () => {
+ const ranked = items(
+ 'Seamus snip',
+ 'seamus todo',
+ '[email protected] taskium'
+ );
+ for (const query of ['seam', 'seamu', 'seamus', 'seamu']) {
+ const matches = filterQuickAccessItems(ranked, query);
+ expect(matches).toEqual(ranked);
+ expect(matches[0]).toBe(ranked[0]);
+ }
+ });
+
+ it.each([
+ ['Some early afternoon music', 'seamu', true],
+ ['Seamus snip', ' SNIP\tSEAMU ', true],
+ ['Seamus snip', 'seamux', false],
+ ['Seamus snip', 'suames', false],
+ ['a😀b🎵c', '😀🎵', true],
+ ['a😀b🎵c', '🎵😀', false],
+ ['Alpha', 'aa', true],
+ ['Alpha', 'aaa', false],
+ ])(
+ 'matches cache subsequence semantics for %s and %s',
+ (name, query, matches) => {
+ const ranked = items(name);
+ expect(filterQuickAccessItems(ranked, query)).toEqual(
+ matches ? ranked : []
+ );
+ }
+ );
+
+ it('preserves the full list when the query is cleared', () => {
+ const ranked = items('Seamus snip', 'other');
+ expect(filterQuickAccessItems(ranked, ' \t ')).toBe(ranked);
+ });
+});
diff --git a/apps/web/src/lib/core/context/quickAccess/entity-search.ts b/apps/web/src/lib/core/context/quickAccess/entity-search.ts
index c13c4ae195..dcf1fb05a2 100644
--- a/apps/web/src/lib/core/context/quickAccess/entity-search.ts
+++ b/apps/web/src/lib/core/context/quickAccess/entity-search.ts
@@ -8,6 +8,30 @@ const quickAccessSearch = createFreshSearch<QuickAccessItem>({
getTimestamp: (item) => item.timestamps,
});
+/** Filter a pending cache search without replacing its established ranking.
+ * Match tokens as ordered subsequences, as cache-core/search.rs does; uFuzzy's
+ * stricter matching would drop cached hits only to restore them on completion. */
+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;
+ });
+ });
+}
+
/** Fuzzy-ranks entity candidates using the existing mentions semantics. */
export function searchQuickAccessItems(
items: QuickAccessItem[],
diff --git a/apps/web/src/lib/core/context/quickAccess/projected-list.test.ts b/apps/web/src/lib/core/context/quickAccess/projected-list.test.ts
index 48e5e93d88..d2898b0782 100644
--- a/apps/web/src/lib/core/context/quickAccess/projected-list.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/projected-list.test.ts
@@ -55,6 +55,105 @@ function deferred<T>() {
}
describe('Quick Access local projection', () => {
+ it('retains matching rows until the next query commits, without retaining its cursor', async () => {
+ const [query, setQuery] = createSignal('sea');
+ const pending = deferred<SearchCachePage>();
+ const search = vi
+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
+ .mockResolvedValueOnce(page(['seamus', 'sean'], true))
+ .mockReturnValueOnce(pending.promise);
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision: () => 0,
+ searchTerm: query,
+ filterPreviousItems: (items, term) =>
+ items.filter((item) => item.id.includes(term)),
+ materialize,
+ })
+ );
+ await vi.waitFor(() => expect(list.items()).toHaveLength(2));
+ const retained = list.items()[0];
+ setQuery('seam');
+ expect(list.items()).toEqual([retained]);
+ expect(list.items()[0]).toBe(retained);
+ expect(list.isLoading()).toBe(true);
+ expect(list.hasMore()).toBe(false);
+ await list.loadMore();
+ expect(search).toHaveBeenCalledTimes(2);
+ expect(search.mock.calls[1][0].cursor).toBeUndefined();
+ pending.resolve(page(['seamus', 'seamless']));
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ expect(list.items()).toEqual([
+ { id: 'GraphqlSoupDocument:seamus' },
+ { id: 'GraphqlSoupDocument:seamless' },
+ ]);
+ });
+
+ it.each(['buckets', 'disable'] as const)(
+ 'does not retain matches when %s changes',
+ async (change) => {
+ const [buckets, setBuckets] = createSignal<Bucket[]>(['note']);
+ const [enabled, setEnabled] = createSignal(true);
+ const pending = deferred<SearchCachePage>();
+ const search = vi
+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
+ .mockResolvedValueOnce(page(['seamus']))
+ .mockReturnValueOnce(pending.promise);
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ get buckets() {
+ return buckets();
+ },
+ revision: () => 0,
+ enabled,
+ filterPreviousItems: (items) => items,
+ materialize,
+ })
+ );
+ await vi.waitFor(() => expect(list.items()).toHaveLength(1));
+ if (change === 'buckets') setBuckets(['task']);
+ else setEnabled(false);
+ expect(list.items()).toEqual([]);
+ }
+ );
+
+ it('removes nonmatches immediately and ignores an obsolete query completion', async () => {
+ const [query, setQuery] = createSignal('sea');
+ const obsolete = deferred<SearchCachePage>();
+ const latest = deferred<SearchCachePage>();
+ const search = vi
+ .fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
+ .mockResolvedValueOnce(page(['seamus']))
+ .mockReturnValueOnce(obsolete.promise)
+ .mockReturnValueOnce(latest.promise);
+ const list = root(() =>
+ createProjectedList({
+ host: { search },
+ buckets: ['note'],
+ revision: () => 0,
+ searchTerm: query,
+ filterPreviousItems: (items, term) =>
+ items.filter((item) => item.id.includes(term)),
+ materialize,
+ })
+ );
+ await vi.waitFor(() => expect(list.items()).toHaveLength(1));
+ setQuery('seam');
+ expect(list.items()).toHaveLength(1);
+ setQuery('xyz');
+ expect(list.items()).toEqual([]);
+ obsolete.resolve(page(['seamus']));
+ await obsolete.promise;
+ expect(list.items()).toEqual([]);
+ expect(list.isLoading()).toBe(true);
+ latest.resolve(page([]));
+ await vi.waitFor(() => expect(list.isLoading()).toBe(false));
+ expect(list.items()).toEqual([]);
+ });
+
it('follows the local browse cursor, deduplicates hits, and stops at the last page', async () => {
const search = vi
.fn<(args: SearchCacheArgs) => Promise<SearchCachePage>>()
diff --git a/apps/web/src/lib/core/context/quickAccess/projected-list.ts b/apps/web/src/lib/core/context/quickAccess/projected-list.ts
index 770ea2d746..5b8d35ce15 100644
--- a/apps/web/src/lib/core/context/quickAccess/projected-list.ts
+++ b/apps/web/src/lib/core/context/quickAccess/projected-list.ts
@@ -51,6 +51,8 @@ export function createProjectedList<T extends { id: string }>(options: {
enabled?: Accessor<boolean>;
/** Visible fallback rows; duplicates do not grow the combined menu. */
existingItems?: Accessor<readonly T[]>;
+ /** Keep already-materialized matches visible while a new query is pending. */
+ filterPreviousItems?: (items: T[], query: string) => T[];
materialize: (documents: SearchDocumentWire[]) => Promise<T[]>;
}) {
const buckets = () => {
@@ -170,7 +172,16 @@ export function createProjectedList<T extends { id: string }>(options: {
// obsolete responses and their queued refreshes.
current = undefined;
setHasMore(false);
- setItems([]);
+ const sameBuckets =
+ previous?.buckets.length === activeBuckets.length &&
+ previous.buckets.every(
+ (bucket, index) => bucket === activeBuckets[index]
+ );
+ setItems(
+ enabled && sameBuckets
+ ? (options.filterPreviousItems?.(untrack(items), query) ?? [])
+ : []
+ );
if (!enabled) {
setLoading('idle');
return;
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 12ca6983a6..75a7252cb0 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -563,6 +563,20 @@ preview replies per thread. Expand a thread to load its replies;
`Load earlier comments` pages backward. Live updates preserve unsent replies
and edits while updating the surrounding thread.
+When verifying `@` mentions, compare the same person query in the document body
+and the Discussion composer: shared contacts use the same recent-interaction
+ranking. The desktop menu keeps up to three People results visible while other
+result categories load; use **View all** for the remaining matches. Check that a
+person stays clickable after document and email results arrive. Type and
+backspace through a query that keeps the same matches: existing rows should
+stay mounted and the menu should not collapse while cached results refresh.
+Check document titles and their order as well as People: type and backspace
+between a name's prefixes and verify the top document does not disappear and
+return while the result count briefly drops.
+Changing the total number of matches should not change a category's preview
+slots when it still has enough rows to fill them; use **View all** for the full list.
+Clear the unsent draft after testing.
+
Select text and choose the comment action to create an anchored comment. These
threads appear beside their text in the margin (or in the active thread drawer
on phones) and never in the bottom Discussion, including after live updates or