Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(search): rank command k persons into results for email searches (#123344)

Shy Alter2e50cec95cc4
diff --git a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
index fbc9b6908fb0..c8b7f35ae032 100644
--- a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
+++ b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md
@@ -97,7 +97,7 @@ The input is always in exactly one mode, decided from the token under the cursor
2. In-memory lists, filtered on every keystroke: **Data management**, **People**, **Health**, **Misc**, **Settings** (with a Dark mode / Light mode row for "dark", "light", "theme", "appearance"), **Create new**. For a search with words they keep only items that match every word with no typo. Products rank with the results instead.
3. Remote lists that the file system does not hold: **Events**, **Properties**, **Workflows** (one unified search request), **Accounts** (behind the customer analytics flag), **Support tickets** (3+ characters or a ticket number).
4. **Ask PostHog AI**.
- 5. **Persons**, **Groups**. Person and group searches can take seconds, so they come last and nothing above them waits for them. The person search starts with the file system search, after 50 ms. In the test group of the `command-k-persons-first-for-email` experiment, a search that contains "@" shows **Persons** right below **Results** instead, and the sections under it wait for the person search.
+ 5. **Persons**, **Groups**. Person and group searches can take seconds, so they come last and nothing above them waits for them. The person search starts with the file system search, after 50 ms. In the test group of the `command-k-persons-first-for-email` experiment, a search that contains "@" waits for the person search and ranks the persons it finds with **Results**, so a person who matches every word comes first and weaker matches drop out. Persons that do not rank stay in **Persons** below.
- With any filter (a chip, or a valid `key:value` still being typed), only **Results** and **Ask PostHog AI** show, because filters apply only to objects.
- With an `is:` chip (not negated), **Results** holds a **View all <types>** row (`View all feature flags`) that opens the list page of that type. With no search text it is the first row; once you type a search it moves below the results. It shows only for types with a list page.
diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx
index 5ccc04814d7e..4f2ca0c7108f 100644
--- a/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx
+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx
@@ -35,7 +35,9 @@ export function CommandKSearchRankedItem({ row }: { row: Extract<CommandKRow, {
? null
: item.category === 'results'
? getItemTypeDisplayName(item.itemType)
- : 'Product'
+ : item.category === 'persons'
+ ? 'Person'
+ : 'Product'
const context = rankedContext(item, !!row.showCreator)
return (
<>
diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts
index 9e0eba26714f..6e0af9c52c1e 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts
@@ -154,7 +154,26 @@ describe('buildRankedResults', () => {
products: [],
expected: ['notice: (partial: xyzzy -> report)', 'Results: Weekly report'],
},
- ])('$name', ({ query, results, products, expected }) => {
+ {
+ name: 'a group of persons gets no see-all row, because persons are not a file system type',
+ query: 'ada',
+ results: [1, 2, 3, 4].map((n) =>
+ result(`insight-${n}`, `Ada insight ${n}`, 'insight', exactWordRank(n), { typeCount: 9 })
+ ),
+ products: [],
+ persons: ['a', 'b', 'c', 'd', 'e'].map((suffix) => ({
+ id: `person-${suffix}`,
+ name: `ada@${suffix}.example.com`,
+ category: 'persons',
+ record: { type: 'person', ref: suffix },
+ })),
+ expected: [
+ 'Best matches: Ada insight 4, [email protected]',
+ 'Insights: Ada insight 3, Ada insight 2, Ada insight 1, (See all 9 insights)',
+ ],
+ },
+ ])('$name', ({ query, results, products, persons = [], expected }) => {
expect(
summary(
buildRankedResults({
@@ -162,6 +181,7 @@ describe('buildRankedResults', () => {
highlightWords: query.split(' '),
results,
products,
+ persons,
state: 'ready',
scoped: false,
})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
index bd28ea99ff86..139f3152e070 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts
@@ -9,6 +9,7 @@ import type { CommandKRow, CommandKSection } from './commandKSections'
const BEST_MATCHES_LIMIT = 3
const GROUP_LIMIT = 3
const FLAT_LIST_LIMIT = 8
+const LOCAL_GROUPS = ['products', 'persons']
interface RankedItem {
item: SearchItem
@@ -26,8 +27,8 @@ function groupLabel(groupKey: string): string {
return capitalizeFirstLetter(pluralTypeName(getItemTypeDisplayName(groupKey) ?? groupKey.replace(/_/g, ' ')))
}
-function rankProducts(products: SearchItem[], query: string): RankedItem[] {
- return products.flatMap((item) => {
+function rankLocalItems(items: SearchItem[], query: string, groupKey: string): RankedItem[] {
+ return items.flatMap((item) => {
const ranked = rankLocalItem(
query,
String(item.displayName || item.name),
@@ -39,7 +40,7 @@ function rankProducts(products: SearchItem[], query: string): RankedItem[] {
{
item: ranked.matchedAlias ? { ...item, matchedSearchKeyword: ranked.matchedAlias } : item,
rank: ranked.rank,
- groupKey: 'products',
+ groupKey,
},
]
: []
@@ -57,7 +58,7 @@ const itemRow = (
kind: 'item',
key: `${section}/${item.id}`,
item,
- section: item.category === 'results' ? 'results' : 'products',
+ section: item.category === 'results' ? 'results' : item.category === 'persons' ? 'persons' : 'products',
highlightWords,
ranked: true,
showType,
@@ -135,6 +136,7 @@ interface RankedResultsInput {
highlightWords: string[]
results: SearchItem[]
products: SearchItem[]
+ persons?: SearchItem[]
state: CommandKSection['state']
scoped: boolean
}
@@ -144,12 +146,14 @@ export function buildRankedResults({
highlightWords,
results,
products,
+ persons = [],
state,
scoped,
}: RankedResultsInput): CommandKSection[] {
const candidates: RankedItem[] = [
...results.map((item) => ({ item, rank: item.rankKey ?? [], groupKey: groupKeyFor(item) })),
- ...rankProducts(products, query),
+ ...rankLocalItems(products, query, 'products'),
+ ...rankLocalItems(persons, query, 'persons'),
].sort((a, b) => compareRanks(a.rank, b.rank))
if (!candidates.length) {
return []
@@ -256,7 +260,7 @@ export function buildRankedResults({
itemRow(`group-${groupKey}`, entry.item, highlightWords, entry.duplicates, entry.duplicates > 0)
)
const covered = inBest.length + shown.reduce((sum, entry) => sum + 1 + entry.duplicates, 0)
- if (groupKey !== 'products' && total > covered) {
+ if (!LOCAL_GROUPS.includes(groupKey) && total > covered) {
rows.push({
kind: 'scope',
key: `group-${groupKey}/see-all`,
@@ -273,7 +277,7 @@ export function buildRankedResults({
key: `group-${groupKey}`,
label: groupLabel(groupKey),
count: total,
- countIsLowerBound: capped && groupKey !== 'products',
+ countIsLowerBound: capped && !LOCAL_GROUPS.includes(groupKey),
rows,
state,
})
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
index 12a006561877..8c6d9c0a339e 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts
@@ -207,16 +207,16 @@ describe('buildSections', () => {
['results', 'events', 'ask-ai', 'persons'],
],
[
- 'only a loading row below Results while persons that go first load',
+ 'only result skeletons while persons that go first load',
{ events: [dashboard('e', '8')] },
true,
- ['results', 'loading-more'],
+ ['results'],
],
[
- 'persons right below Results when they go first',
+ 'persons above filter-only Results when they go first',
{ persons: [dashboard('p', '9')] },
true,
- ['results', 'persons', 'loading-more'],
+ ['persons', 'results', 'loading-more'],
],
])('reveals %s', (_, loaded, personsFirst, expectedKeys) => {
const remote = emptyRemoteSlots()
@@ -235,6 +235,32 @@ describe('buildSections', () => {
expect(sections.map((section) => section.key)).toEqual(expectedKeys)
})
+ it('ranks a person who matches every word of an email search above results that match fewer', () => {
+ const person: SearchItem = {
+ id: 'person-1',
+ displayName: '[email protected]',
+ category: 'persons',
+ record: { type: 'person', ref: '1' },
+ }
+ const remote = emptyRemoteSlots()
+ remote.results = {
+ cache: { 'ada.l@': [{ ...dashboard('a', '1'), name: 'Ada', rankKey: [-1, 0, 0, 0, -1, 0, 1, 0, 0] }] },
+ }
+ remote.persons = { cache: { 'ada.l@': [person] } }
+ const sections = buildSections(
+ input('search', {
+ remote,
+ remoteQueries: { results: 'ada.l@', persons: 'ada.l@' },
+ localQuery: 'ada.l@',
+ personsFirst: true,
+ })
+ )
+
+ expect(sections.map((section) => section.key)).toEqual(['best-matches'])
+ expect(sections[0].rows).toMatchObject([{ kind: 'item', section: 'persons', item: { id: 'person-1' } }])
+ })
+
it('says which words were dropped when a filter is active', () => {
const remote = emptyRemoteSlots()
remote.results = {
diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.ts
index 5396f6aa005d..8b12db5106f4 100644
--- a/frontend/src/lib/components/CommandKSearch/commandKSections.ts
+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.ts
@@ -266,10 +266,12 @@ function rankedResultsSections(
query: string,
local: LocalLists,
localQuery: string,
- state: CommandKSection['state']
+ state: CommandKSection['state'],
+ persons: SearchItem[]
): CommandKSection[] {
const words = freeWords(query)
return buildRankedResults({
+ persons,
query: words.join(' '),
highlightWords: words,
results,
@@ -279,7 +281,12 @@ function rankedResultsSections(
})
}
-function lowerSections(input: SectionsInput, ranked: boolean, state: CommandKSection['state']): CommandKSection[] {
+function lowerSections(
+ input: SectionsInput,
+ ranked: boolean,
+ state: CommandKSection['state'],
+ shown: Set<string>
+): CommandKSection[] {
const { local, remote, remoteQueries, localQuery } = input
const sections: (CommandKSection | null)[] = []
const loaded = (): CommandKSection[] => sections.filter((section): section is CommandKSection => section !== null)
@@ -293,13 +300,18 @@ function lowerSections(input: SectionsInput, ranked: boolean, state: CommandKSec
if (!isSettled(remote[source], query)) {
return false
}
- sections.push(query ? remoteSection(source, remote[source].cache[query], state) : null)
+ sections.push(
+ query
+ ? remoteSection(
+ source,
+ remote[source].cache[query].filter((item) => !shown.has(item.id)),
+ state
+ )
+ : null
+ )
}
return true
}
- if (input.personsFirst && !appendInOrder(['persons'])) {
- return loadingMore()
- }
if (localQuery) {
for (const source of LOCAL_SOURCES) {
if (ranked && source === 'products') {
@@ -325,8 +337,7 @@ function lowerSections(input: SectionsInput, ranked: boolean, state: CommandKSec
state,
})
}
- const trailing = input.personsFirst ? TRAILING_SOURCES.filter((source) => source !== 'persons') : TRAILING_SOURCES
- return appendInOrder(trailing) ? loaded() : loadingMore()
+ return appendInOrder(TRAILING_SOURCES) ? loaded() : loadingMore()
}
export function buildSections(input: SectionsInput): CommandKSection[] {
@@ -365,12 +376,17 @@ export function buildSections(input: SectionsInput): CommandKSection[] {
const resultsQuery = remoteQueries.results
const results = resultsQuery ? remote.results.cache[resultsQuery] : undefined
const ranked = isRanked(input)
- if (resultsQuery && !results) {
+ const personsQuery = input.personsFirst && mode !== 'value' ? remoteQueries.persons : undefined
+ if ((resultsQuery && !results) || (personsQuery && !isSettled(remote.persons, personsQuery))) {
sections.push(withViewAll(loadingSection('results'), input.viewAll))
return sections.filter((section): section is CommandKSection => section !== null)
}
+ const leadingPersons = personsQuery ? remote.persons.cache[personsQuery] : []
+ if (!ranked && leadingPersons.length) {
+ sections.push(remoteSection('persons', leadingPersons, state))
+ }
if (ranked && results && resultsQuery) {
- const rankedSections = rankedResultsSections(results, resultsQuery, local, localQuery, state)
+ const rankedSections = rankedResultsSections(results, resultsQuery, local, localQuery, state, leadingPersons)
sections.push(
...(rankedSections.some((section) => section.key === 'results')
? rankedSections.map((section) =>
@@ -382,7 +398,12 @@ export function buildSections(input: SectionsInput): CommandKSection[] {
sections.push(withViewAll(results ? remoteSection('results', results, state) : null, input.viewAll))
}
if (mode !== 'value') {
- sections.push(...lowerSections(input, ranked, state))
+ const shown = new Set(
+ sections.flatMap(
+ (section) => section?.rows.flatMap((row) => (row.kind === 'item' ? [row.item.id] : [])) ?? []
+ )
+ )
+ sections.push(...lowerSections(input, ranked, state, shown))
}
return sections.filter((section): section is CommandKSection => section !== null)
}