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(search): find conversations by participant names in any order (#9378)

gbirman453b80915306
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 7ad149b213..b6604e5801 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -143,6 +143,18 @@ 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.
+Cmd+K and mobile name search widen the first group: a query equal to the first
+word of a DM or person name counts as exact, so a person's first name reaches
+their full-name DM. `commaSeparatedChannelMatch` (Cmd+K, mobile name search,
+Quick Access, and Soup search including the Chat sidebar) matches channels and
+DMs by terms in any order, adding to uFuzzy's in-order matches, because names
+are generated from participants and people type them in any order. It also
+ranks a conversation whose participants the query names, by name prefixes,
+right after exact names. Each participant needs a term of their own, so a group
+with more people than the query names stays below it.
+Commas separate query terms like spaces in the cache search
+(`cache-core/search.rs`, mirrored by `matchesTokenSubsequences`) and in the
+server's channel name search; keep the three together.
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
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.ts
index d42da3b688..2a47958852 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
@@ -316,10 +316,10 @@ describe('command menu search ranking', () => {
channel('dm', 'Jackson Kustec', NOW - 60 * DAY, 'dm'),
];
- expect(ids(items, 'jack', cacheEnabled)).toEqual(['dm', 'jack', 'crm']);
+ expect(ids(items, 'jack', cacheEnabled)).toEqual(['jack', 'dm', 'crm']);
expect(ids([...items].reverse(), 'jack', cacheEnabled)).toEqual([
- 'dm',
'jack',
+ 'dm',
'crm',
]);
}
@@ -331,7 +331,7 @@ describe('command menu search ranking', () => {
contact('older-crm', 'Jack CRM', NOW - 10 * DAY),
command('command', 'Jack command', NOW - 5 * DAY),
channel('channel-slot', 'Jack channel', NOW - 15 * DAY),
- person('jack', 'Jack Smith'),
+ person('jack', 'Jackie Smith'),
channel('old-dm', 'Jack old', NOW - 60 * DAY, 'dm'),
channel('recent-dm', 'Jack recent', NOW - DAY, 'dm'),
];
@@ -370,4 +370,150 @@ describe('command menu search ranking', () => {
}).map((item) => item.id)
).toEqual(['jack', 'crm']);
});
+
+ describe('participant names in any order', () => {
+ const pair = channel('pair', 'Avery Morgan, Blair Chen', NOW - 20 * DAY);
+ const group = channel(
+ 'group',
+ 'Casey Reed, Avery Morgan, Blair Chen, Drew Fox',
+ NOW
+ );
+
+ it.each([
+ 'Avery, Blair',
+ 'Blair, Avery',
+ 'blair avery',
+ 'Blair, aver',
+ 'chen, morgan',
+ 'Blair Chen, Avery Morgan',
+ ])('ranks the exact pair above a newer larger group for %s', (query) => {
+ expect(ids([group, pair], query, true)).toEqual(['pair', 'group']);
+ expect(ids([group, pair], query, false)).toEqual(['pair', 'group']);
+ });
+
+ it('ranks the exact pair above a note and a project that loosely match', () => {
+ const items = [
+ note('note', 'Blair and Avery kickoff'),
+ project('project', 'Avery Blair launch'),
+ pair,
+ ];
+ expect(ids(items, 'Blair, Avery')[0]).toBe('pair');
+ });
+
+ it('does not treat a query that leaves a participant unnamed as the exact pair', () => {
+ const items = [note('note', 'Blair Chen notes'), pair];
+ expect(ids(items, 'blair chen')).toEqual(['note', 'pair']);
+ });
+
+ it('does not let one term name every participant whose name starts with it', () => {
+ const items = [
+ channel('namesakes', 'Avery Morgan, Avery Chen'),
+ project('project', 'Avery', NOW - 20 * DAY),
+ ];
+ expect(ids(items, 'avery')).toEqual(['project', 'namesakes']);
+ });
+
+ it('keeps a recent group of namesakes below a DM with only one of them', () => {
+ const items = [
+ channel('namesakes', 'Avery Morgan, Avery Chen'),
+ channel('dm', 'Avery Morgan', NOW - 60 * DAY, 'dm'),
+ ];
+ expect(ids(items, 'avery morgan')).toEqual(['dm', 'namesakes']);
+ });
+
+ it('matches namesakes when each has a term of their own', () => {
+ const items = [
+ channel('namesakes', 'Avery Morgan, Avery Chen', NOW - 20 * DAY),
+ channel('group', 'Casey Reed, Avery Morgan, Avery Chen'),
+ ];
+ expect(ids(items, 'avery, morgan')).toEqual(['namesakes', 'group']);
+ });
+
+ it('reassigns a term when a later participant has no other', () => {
+ const group = channel('group', 'Avery Morgan, Avery Chen');
+ expect(ids([group], 'avery, chen', false)).toEqual(['group']);
+ expect(
+ ids([note('note', 'Avery chen plan'), group], 'avery, chen')[0]
+ ).toBe('group');
+ });
+
+ it('answers a long pasted query quickly on a large group', () => {
+ const people = Array.from({ length: 12 }, (_, index) =>
+ index === 11 ? 'Zane Young' : `Avery Person${index}`
+ );
+ const group = channel('group', people.join(', '));
+ const started = performance.now();
+ ids([group], Array.from({ length: 12 }, () => 'avery').join(' '), false);
+ expect(performance.now() - started).toBeLessThan(250);
+ });
+
+ it('finds a one-to-one DM by its name reversed', () => {
+ const dm = channel('dm', 'Avery Morgan', NOW, 'dm');
+ expect(ids([dm], 'morgan avery', false)).toEqual(['dm']);
+ });
+ });
+
+ describe('people matched by first name', () => {
+ const shortDm = channel('short-dm', 'Avery', NOW - 60 * DAY, 'dm');
+ const fullNameDm = channel('full-name-dm', 'Avery Morgan', NOW, 'dm');
+
+ it.each([false, true])(
+ 'puts the recent full-name DM above an older DM and a person named only the query with GraphQL %s',
+ (cacheEnabled) => {
+ const items = [
+ shortDm,
+ person('person', 'avery'),
+ fullNameDm,
+ channel('longer-handle', 'avery+1', NOW - 40 * DAY, 'dm'),
+ ];
+ expect(ids(items, 'avery', cacheEnabled).slice(0, 3)).toEqual([
+ 'full-name-dm',
+ 'short-dm',
+ 'person',
+ ]);
+ }
+ );
+
+ it('keeps a group DM out of the first-name group', () => {
+ const items = [
+ channel('group-dm', 'Avery Morgan, Blair Chen', NOW, 'dm'),
+ channel('one-to-one', 'Avery Morgan', NOW - 60 * DAY, 'dm'),
+ ];
+ expect(ids(items, 'avery')).toEqual(['one-to-one', 'group-dm']);
+ });
+
+ it('keeps the more recently viewed DM first when the short name is the active one', () => {
+ expect(
+ ids(
+ [
+ channel('short-dm', 'Avery', NOW, 'dm'),
+ channel('full-name-dm', 'Avery Morgan', NOW - 2 * DAY, 'dm'),
+ ],
+ 'avery'
+ )
+ ).toEqual(['short-dm', 'full-name-dm']);
+ });
+
+ it('puts a first-name DM above a project named exactly the query', () => {
+ const items = [project('project', 'Avery', NOW), fullNameDm];
+ expect(ids(items, 'avery')).toEqual(['full-name-dm', 'project']);
+ });
+
+ it('keeps other rows and partial first names in the prefix group', () => {
+ const items = [
+ project('exact-project', 'Avery', NOW - 20 * DAY),
+ note('first-word-note', 'Avery Morgan'),
+ fullNameDm,
+ ];
+ expect(ids(items, 'aver')).toEqual([
+ 'full-name-dm',
+ 'first-word-note',
+ 'exact-project',
+ ]);
+ expect(ids(items.slice(0, 2), 'avery')).toEqual([
+ 'exact-project',
+ 'first-word-note',
+ ]);
+ });
+ });
});
diff --git a/apps/web/src/features/command/rank-command-search-items.ts b/apps/web/src/features/command/rank-command-search-items.ts
index 47a2719100..4ca1e9b1f2 100644
--- a/apps/web/src/features/command/rank-command-search-items.ts
+++ b/apps/web/src/features/command/rank-command-search-items.ts
@@ -69,11 +69,13 @@ export function rankCommandSearchItems<T extends CommandMenuItem>(
fuzzyWeight: 0.7,
timeWeight: 0.7,
minFuzzyThreshold: 0.1,
+ commaSeparatedChannelMatch: true,
},
getName: (item) => item.searchText,
getDisplayName: displayName,
isChannelItem: (item) => item.bucket === 'channel' || item.bucket === 'dm',
isDmItem: (item) => item.bucket === 'dm',
+ isPersonItem: (item) => item.bucket === 'dm' || item.bucket === 'person',
getTimestamp: (item) => item.timestamps,
});
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
index bb870ce389..97e47c45eb 100644
--- a/apps/web/src/lib/core/context/quickAccess/entity-search.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/entity-search.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest';
-import { filterQuickAccessItems } from './entity-search';
-import type { UserItem } from './types';
+import {
+ filterQuickAccessItems,
+ searchQuickAccessItems,
+} from './entity-search';
+import type { EntityItem, UserItem } from './types';
function items(...names: string[]): UserItem[] {
return names.map((name, index) => ({
@@ -37,6 +40,10 @@ describe('pending Quick Access matches', () => {
['a😀b🎵c', '🎵😀', false],
['Alpha', 'aa', true],
['Alpha', 'aaa', false],
+ ['Avery Morgan, Blair Chen', 'Blair, aver', true],
+ ['Avery Morgan, Blair Chen', 'Blair,Avery', true],
+ ['Avery Morgan, Blair Chen', 'Blair, casey', false],
+ ['Avery Morgan, Blair Chen', ' , ', false],
])(
'matches cache subsequence semantics for %s and %s',
(name, query, matches) => {
@@ -52,3 +59,36 @@ describe('pending Quick Access matches', () => {
expect(filterQuickAccessItems(ranked, ' \t ')).toBe(ranked);
});
});
+
+describe('local Quick Access search', () => {
+ function channel(id: string, bucket: 'channel' | 'dm', name: string) {
+ const item: EntityItem = {
+ id,
+ kind: 'entity',
+ bucket,
+ searchText: name,
+ sortTimestamp: 0,
+ timestamps: {},
+ data: {
+ id,
+ type: 'channel',
+ name,
+ ownerId: 'owner',
+ channelType: bucket === 'dm' ? 'direct_message' : 'private',
+ },
+ };
+ return item;
+ }
+
+ it('finds channels and DMs by names typed in any order', () => {
+ const items = [
+ channel('group', 'channel', 'Avery Morgan, Blair Chen'),
+ channel('dm', 'dm', 'Blair Chen'),
+ ];
+ const found = (query: string) =>
+ searchQuickAccessItems(items, query).map((item) => item.id);
+
+ expect(found('Blair, Avery')).toEqual(['group']);
+ expect(found('chen blair')).toEqual(['group', 'dm']);
+ });
+});
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 0b1bbf74b3..5e68d9b778 100644
--- a/apps/web/src/lib/core/context/quickAccess/entity-search.ts
+++ b/apps/web/src/lib/core/context/quickAccess/entity-search.ts
@@ -3,9 +3,9 @@ import { matchesTokenSubsequences } from '@core/util/string';
import type { EntityItem, QuickAccessItem } from './types';
const quickAccessSearch = createFreshSearch<QuickAccessItem>({
- config: { useViewedAt: true },
+ config: { useViewedAt: true, commaSeparatedChannelMatch: true },
getName: (item) => item.searchText,
- isChannelItem: (item) => item.bucket === 'channel',
+ isChannelItem: (item) => item.bucket === 'channel' || item.bucket === 'dm',
getTimestamp: (item) => item.timestamps,
});
diff --git a/apps/web/src/lib/core/util/freshSort.test.ts b/apps/web/src/lib/core/util/freshSort.test.ts
index a1883d1345..ab32ad23e3 100644
--- a/apps/web/src/lib/core/util/freshSort.test.ts
+++ b/apps/web/src/lib/core/util/freshSort.test.ts
@@ -254,6 +254,50 @@ describe('createFreshSearch with comma-separated channel matching', () => {
expect(results2.length).toBe(1);
expect(results2[0].item.id).toBe('1');
});
+
+ it('keeps the fuzzy score of a channel typed in order, and adds channels typed out of order', () => {
+ const now = new Date();
+ const items: MockItem[] = [
+ { id: '1', name: 'Avery Morgan, Blair Chen', type: 'channel' },
+ { id: '2', name: 'Blair Chen, Avery Morgan', type: 'channel' },
+ { id: '3', name: 'Blair notes for Avery', type: 'item', viewedAt: now },
+ ];
+
+ const results = createCommaSeparatedSearch()(items, 'avery blair');
+
+ expect(results.map((result) => result.item.id)).toEqual(['1', '2']);
+ expect(results[0].fuzzyScore).toBe(1);
+ expect(results[1].fuzzyScore).toBeLessThan(1);
+ });
+
+ it('adds no channels for a query of separators alone', () => {
+ const items: MockItem[] = [
+ { id: '1', name: 'Avery Morgan, Blair Chen', type: 'channel' },
+ ];
+
+ expect(createCommaSeparatedSearch()(items, ' , ')).toEqual([]);
+ });
+
+ it('ranks the exact participants above a newer larger group without name ranking', () => {
+ const items: MockItem[] = [
+ {
+ id: 'group',
+ name: 'Avery Morgan, Blair Chen, Casey Reed',
+ type: 'channel',
+ viewedAt: new Date(),
+ },
+ {
+ id: 'pair',
+ name: 'Avery Morgan, Blair Chen',
+ type: 'channel',
+ viewedAt: applyDurationToDate(new Date(), { value: -20, unit: 'd' }),
+ },
+ ];
+
+ const results = createCommaSeparatedSearch()(items, 'blair, avery');
+
+ expect(results.map((result) => result.item.id)).toEqual(['pair', 'group']);
+ });
});
describe('normalizeFuzzyScore', () => {
diff --git a/apps/web/src/lib/core/util/freshSort.ts b/apps/web/src/lib/core/util/freshSort.ts
index 167ae5bc6f..b9bff2aa59 100644
--- a/apps/web/src/lib/core/util/freshSort.ts
+++ b/apps/web/src/lib/core/util/freshSort.ts
@@ -50,7 +50,7 @@ export interface FreshSortConfig<T = unknown> {
channelBoost?: number;
/** Boost multiplier for DM items. Default: 1.0 (no boost) */
dmBoost?: number;
- /** Enable comma-separated matching for channel names. When enabled, query "a,b" matches channel name "a,c,b". Default: false */
+ /** Also match channel names holding every query term in any order, and rank channels whose participants the query names exactly above all but exact names. When enabled, query "b,a" matches channel name "a,c,b", which the fuzzy matcher alone misses. Default: false */
commaSeparatedChannelMatch?: boolean;
/** Function to calculate per-item boost. Returns a boost multiplier (e.g., 0.2 for +20% boost). Default: undefined */
boostFn?: BoostFn<T>;
@@ -58,7 +58,7 @@ 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 */
+ /** Rank names equal to the query first, then names starting with it, then other matches, ignoring case; the blended score orders each group. People whose first name equals the query count as equal to it. Default: false */
rankNameMatchesFirst?: boolean;
}
@@ -76,7 +76,7 @@ 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`. */
+ /** 3 for an exact name or person's first name, 2 for a participant set, 1 for a name starting with the query, else 0. Without `rankNameMatchesFirst` only participant sets rank above 0, under `commaSeparatedChannelMatch`. */
nameMatchRank: number;
}
@@ -143,10 +143,62 @@ export function normalizeFuzzyScore(
return Math.max(0, Math.min(1, fuzzyScore / maxPossibleScore));
}
-function calculateNameMatchRank(name: string, term: string): number {
+/** Whether a query names everyone in a comma-separated channel name, in any
+ * order: each term starts a word of some participant and every participant has
+ * a term of their own, so a group with more people than the query names does
+ * not qualify, even when one term starts several of their names. */
+function namesEveryParticipant(normalizedName: string, term: string): boolean {
+ const participants = normalizedName
+ .split(',')
+ .map((participant) => participant.trim().split(/\s+/));
+ if (participants.length < 2) return false;
+
+ const terms = term.split(/[\s,]+/).filter(Boolean);
+ if (terms.length < participants.length) return false;
+
+ const startsWordOf = (queryTerm: string, words: string[]) =>
+ words.some((word) => word.startsWith(queryTerm));
+ if (
+ !terms.every((queryTerm) =>
+ participants.some((words) => startsWordOf(queryTerm, words))
+ )
+ ) {
+ return false;
+ }
+
+ // Bipartite matching by augmenting paths: a term taken by an earlier
+ // participant is freed when that participant can move to another term.
+ const holderOfTerm = new Map<number, number>();
+ const assignTerm = (participant: number, triedTerms: Set<number>): boolean =>
+ terms.some((queryTerm, termIndex) => {
+ if (triedTerms.has(termIndex)) return false;
+ if (!startsWordOf(queryTerm, participants[participant])) return false;
+ triedTerms.add(termIndex);
+
+ const holder = holderOfTerm.get(termIndex);
+ if (holder !== undefined && !assignTerm(holder, triedTerms)) return false;
+
+ holderOfTerm.set(termIndex, participant);
+ return true;
+ });
+
+ return participants.every((_, participant) =>
+ assignTerm(participant, new Set())
+ );
+}
+
+function calculateNameMatchRank(
+ normalizedName: string,
+ term: string,
+ isPerson: boolean
+): number {
if (!term) return 0;
- const normalizedName = name.trim().toLocaleLowerCase();
- if (normalizedName === term) return 2;
+ if (normalizedName === term) return 3;
+
+ // A comma lists several people, so its first word is only one person's name.
+ const namesOnePerson = isPerson && !normalizedName.includes(',');
+ if (namesOnePerson && normalizedName.split(/\s+/)[0] === term) return 3;
+
if (normalizedName.startsWith(term)) return 1;
return 0;
}
@@ -231,6 +283,27 @@ function ufuzzyFilter<T>(
});
}
+/** Channels holding every query term out of order, which uFuzzy skips. Rows it
+ * matched keep their score, so this only adds to its results. */
+function outOfOrderChannelMatches<T>(
+ items: T[],
+ fuzzyResults: FuzzyFilterResult<T>[],
+ query: string,
+ getName: NameFn<T>,
+ isChannelItem: BooleanFn<T>
+): FuzzyFilterResult<T>[] {
+ const fuzzyMatched = new Set(fuzzyResults.map((result) => result.original));
+ return items.flatMap((item) => {
+ if (!isChannelItem(item) || fuzzyMatched.has(item)) return [];
+
+ const name = getName(item);
+ const score = fuzzyScoreCommaSpaceSeparated(query, name);
+ if (score < 0) return [];
+
+ return [{ original: item, string: name, score: score * 100 }];
+ });
+}
+
function freshSort<T>(
filterResults: FuzzyFilterResult<T>[],
getNameMatchRank: (item: T) => number,
@@ -319,6 +392,8 @@ interface CreateFreshSearchArgs<T> {
getDisplayName?: NameFn<T>;
isChannelItem?: BooleanFn<T>;
isDmItem?: BooleanFn<T>;
+ /** Rows named after a person, whose first name alone counts as an exact name under `rankNameMatchesFirst`. Default: none */
+ isPersonItem?: BooleanFn<T>;
getTimestamp: TimestampFn<T>;
}
@@ -328,21 +403,33 @@ export function createFreshSearch<T>({
getDisplayName = getName,
isChannelItem = () => false,
isDmItem = () => false,
+ isPersonItem = () => false,
getTimestamp,
}: CreateFreshSearchArgs<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)
+ const getNameMatchRank = (item: T) => {
+ const name = getDisplayName(item).trim().toLocaleLowerCase();
+ const nameRank = finalConfig.rankNameMatchesFirst
+ ? calculateNameMatchRank(name, term, isPersonItem(item))
: 0;
+ const namesParticipants =
+ finalConfig.commaSeparatedChannelMatch &&
+ isChannelItem(item) &&
+ namesEveryParticipant(name, term);
+
+ return namesParticipants ? Math.max(nameRank, 2) : nameRank;
+ };
const hasComma = trimmedQuery.includes(',');
const hasSpace = trimmedQuery.includes(' ');
+ const hasTerms = /[^\s,]/.test(trimmedQuery);
const useMultiTermChannelMatch =
- finalConfig.commaSeparatedChannelMatch && (hasComma || hasSpace);
+ finalConfig.commaSeparatedChannelMatch &&
+ hasTerms &&
+ (hasComma || hasSpace);
if (!trimmedQuery) {
const allResults: FuzzyFilterResult<T>[] = items.map((item) => ({
@@ -360,55 +447,28 @@ export function createFreshSearch<T>({
);
}
- if (useMultiTermChannelMatch) {
- const channelResults: FuzzyFilterResult<T>[] = [];
- const nonChannelItems: T[] = [];
-
- for (const item of items) {
- if (isChannelItem(item)) {
- const name = getName(item);
- const score = fuzzyScoreCommaSpaceSeparated(trimmedQuery, name);
- if (score >= 0) {
- channelResults.push({
- original: item,
- string: name,
- score: score * 100,
- });
- }
- } else {
- nonChannelItems.push(item);
- }
- }
-
- const nonChannelResults = ufuzzyFilter(
- nonChannelItems,
- getName,
- getDisplayName,
- trimmedQuery,
- finalConfig.gapPenaltyWeight,
- finalConfig.startBonusDecay
- );
- const allResults = [...channelResults, ...nonChannelResults];
- return freshSort(
- allResults,
- getNameMatchRank,
- config,
- isChannelItem,
- isDmItem,
- getTimestamp
- );
- }
-
const fuzzyResults = ufuzzyFilter(
items,
getName,
getDisplayName,
- query,
+ trimmedQuery,
finalConfig.gapPenaltyWeight,
finalConfig.startBonusDecay
);
+ const results = useMultiTermChannelMatch
+ ? [
+ ...fuzzyResults,
+ ...outOfOrderChannelMatches(
+ items,
+ fuzzyResults,
+ trimmedQuery,
+ getName,
+ isChannelItem
+ ),
+ ]
+ : fuzzyResults;
return freshSort(
- fuzzyResults,
+ results,
getNameMatchRank,
config,
isChannelItem,
diff --git a/apps/web/src/lib/core/util/string.ts b/apps/web/src/lib/core/util/string.ts
index 5f09bcda9f..d84087e47e 100644
--- a/apps/web/src/lib/core/util/string.ts
+++ b/apps/web/src/lib/core/util/string.ts
@@ -106,9 +106,16 @@ export function isEmojiOnly(text: string): boolean {
}
/** Whether every query token appears in `text` as an ordered character
- * subsequence, case-insensitively. Mirrors cache-core/search.rs matching. */
+ * subsequence, case-insensitively. Whitespace and commas separate tokens.
+ * Mirrors cache-core/search.rs matching. */
export function matchesTokenSubsequences(text: string, query: string) {
- const tokens = query.toLowerCase().trim().split(/\s+/).filter(Boolean);
+ const tokens = query
+ .toLowerCase()
+ .trim()
+ .split(/[\s,]+/)
+ .filter(Boolean);
+ if (tokens.length === 0) return !query.trim();
+
const haystack = text.toLowerCase();
return tokens.every((token) => {
let position = 0;
diff --git a/crates/client/cache-core/AGENTS.md b/crates/client/cache-core/AGENTS.md
index 017347e6b3..f68ac42550 100644
--- a/crates/client/cache-core/AGENTS.md
+++ b/crates/client/cache-core/AGENTS.md
@@ -24,7 +24,7 @@ GraphQL response shape for callers. A concrete `Storage` impl (e.g.
- `src/store.rs`: the `Storage` trait every backend (e.g. `cache-turso`) implements.
- `src/predicate.rs` + `src/record_selection.rs`: the predicate/projection IR
used to select which cached records satisfy a query.
-- `src/search.rs`: disposable Quick Access projection (version 4); email matches subjects and all embedded senders, never snippets or bodies; task projects (`GraphqlSoupInitiative`) index their display name with recency from `metadata`.
+- `src/search.rs`: disposable Quick Access projection (version 4); email matches subjects and all embedded senders, never snippets or bodies; task projects (`GraphqlSoupInitiative`) index their display name with recency from `metadata`; whitespace and commas separate query tokens, as in the server's channel name search, and each token matches independently, so any order works.
- `src/queue.rs`: the optimistic mutation queue.
- `tests/`: the primary spec for engine behavior — one file per concern
(optimistic updates, calendar range, search, subscriptions, fuzz).
diff --git a/crates/client/cache-core/src/search.rs b/crates/client/cache-core/src/search.rs
index da7d789526..dafa3362e4 100644
--- a/crates/client/cache-core/src/search.rs
+++ b/crates/client/cache-core/src/search.rs
@@ -408,10 +408,18 @@ fn score_normalized_query(document: &SearchDocument, normalized: &str, now_ms: i
}
let mut score = 0.0;
let mut tokens = 0usize;
- for token in normalized.split_whitespace() {
+ // Commas separate tokens as in the server's channel name search. Left on a
+ // token, a comma would only match a name with one after it.
+ for token in normalized
+ .split([' ', ','])
+ .filter(|token| !token.is_empty())
+ {
tokens += 1;
score += subsequence_score(&document.search_text, token)?;
}
+ if tokens == 0 {
+ return None;
+ }
let fuzzy = score / tokens as f64;
let age = now_ms.saturating_sub(document.timestamp_ms).max(0) as f64;
let max_age = 30.0 * 24.0 * 60.0 * 60.0 * 1000.0;
diff --git a/crates/client/cache-core/src/search/test.rs b/crates/client/cache-core/src/search/test.rs
index 92498ff7d1..9f5b6271c1 100644
--- a/crates/client/cache-core/src/search/test.rs
+++ b/crates/client/cache-core/src/search/test.rs
@@ -82,6 +82,26 @@ fn fuzzy_matching_rewards_prefix_and_freshness() {
assert!(fuzzy_freshness_score(&recent, "missing", 1_000).is_none());
}
+#[test]
+fn commas_separate_query_tokens_in_any_order() {
+ let group = SearchDocument {
+ profile: SearchProfile::QuickAccessV1,
+ record_key: EntityKey::entity("GraphqlSoupChannel", &["1"]),
+ bucket: "channel".into(),
+ search_text: "avery morgan, blair chen".into(),
+ timestamp_ms: 990,
+ source_hash: "a".into(),
+ };
+ for query in ["avery, blair", "blair, avery", "blair,avery", "blair, ave"] {
+ assert!(
+ fuzzy_freshness_score(&group, query, 1_000).is_some(),
+ "{query} must match"
+ );
+ }
+ assert!(fuzzy_freshness_score(&group, "blair, casey", 1_000).is_none());
+ assert!(fuzzy_freshness_score(&group, " , ", 1_000).is_none());
+}
+
#[test]
fn soup_entity_recency_prefers_viewed_at_over_newer_activity() {
for typename in [
diff --git a/docs/agent-guide/search.md b/docs/agent-guide/search.md
index d0ac1c5020..b4a7407d2a 100644
--- a/docs/agent-guide/search.md
+++ b/docs/agent-guide/search.md
@@ -23,6 +23,12 @@ Typed **All** and **People** name searches also find known teammates before thei
first DM, with or without CRM. Existing one-to-one DMs replace person rows while
preserving name/email matches; selecting a person opens their DM. Verify both
categories with a teammate who has no conversation or CRM record.
+Name search here, in Command K, and in the Chat sidebar finds a conversation by
+its participants in any order, separated by spaces or commas, with name prefixes
+allowed. A query naming exactly its participants ranks it right after exact
+names, above a larger group holding the same people. In Command K and mobile
+name search, a person's first name alone also counts as exact for their DM or
+person row.
On phones, name-result icons and avatars are scaled to 150% (16px artwork
becomes 24px), preserving row height and text alignment.