: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(search): rank account matches in command-k results (#124442)
Arthur Moreira de Deus01bb3fdaf162
diff --git a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.mdindex 47b7a7d5af96..10c99d4f9173 100644--- a/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md+++ b/frontend/src/lib/components/CommandKSearch/COMMAND_K_SEARCH_UX.md@@ -95,7 +95,7 @@ The input is always in exactly one mode, decided from the token under the cursor- Sections, in this fixed order, covering everything the current palette finds:1. **Results**: file system objects (insights, dashboards, feature flags, experiments, surveys, notebooks, cohorts, actions, early access features, replay playlists, data pipelines), and products. For a search with words, see [Ranked results](#ranked-results).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. In the test group of the `command-k-settings-in-results` experiment, settings that match every word with no typo also rank with the results, unless a product has the same name, and the **Settings** section lists only the ones that did not.- 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).+ 3. Remote lists that the file system does not hold: **Events**, **Properties**, **Workflows** (one unified search request), **Accounts** (behind the customer analytics flag, excluding accounts already shown in ranked results), **Support tickets** (3+ characters or a ticket number).4. **Ask PostHog AI**.5. **Persons**, **Groups**. Person and group searches can take seconds, so they usually come last. The person search starts with the file system search, after 50 ms. A search that contains "@" waits for the person search and ranks the persons it finds with **Results** / **Best matches**. A person who matches every word comes first. Persons that do not rank stay in **Persons** below, with no duplicates. Other searches do not wait for persons or groups.- 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.@@ -105,6 +105,7 @@ The input is always in exactly one mode, decided from the token under the cursorResults for a search with words follow ordered tie-breaking rules: words matched, typos, word proximity, name before folder, exact words, word position, exactness, the person's recent views, then recency. Products rank with the same rules through their name and search keywords, so "recordings" finds Session replay. When a name match and a search keyword match tie, the name match ranks first, so "metrics" puts Metrics above Data catalog.+- Accounts rank with the results when account search is enabled. The Accounts API matches the full search text, so an account can suppress the partial-match or spelling notice even when its display name does not contain the text. Distinct accounts with the same name stay separate. Accounts get no file-system **See all** filter.- When no result has every word, results use the words that matched. A callout above the results names the dropped word ("No matches for **xyzzy**. Showing results for **report**."). When every match needs a typo, it says "No exact matches for **dashbord**. Showing close spellings." The callout is not selectable.- **Best matches** comes first: the three best results of different types.- The other results follow in groups by type, each with its total count and up to three rows. A group ends with a **See all N <types>** row that adds the `is:` chip and keeps the words. A one-word search that starts a type name (`dash`, `flag`) moves that type's group up.@@ -154,7 +155,7 @@ Rule for adding a filter: it ships only when its values can be suggested (staticThese are the rules reviewers check. Breaking one is a bug.1. **Fixed section order.** Sections render in the order in this doc for a given mode. A section never moves above another because its data arrived first. Ranked groups are ordered by their best result for each query, and do not move while that query's rows stay on screen.-2. **Reserve space while loading.** On its first load, the Results section renders 3 skeleton rows, and nothing renders below it until the file system search returns. Products wait too, because they rank with the saved objects. Below Results, a section appears only once it and every section above it have loaded, so a late source never pushes rows on screen down. A section that comes back empty reserves nothing. While a section below Results is still loading, a quiet **Loading more…** row with a spinner sits at the very bottom, so people know more is coming. It fades in after 150 ms, so fast searches never flash it, and nothing above it ever moves.+2. **Reserve space while loading.** On its first load, the Results section renders 3 skeleton rows, and nothing renders below it until the file system search returns. Ranked searches also wait for Accounts when account search is enabled. Products wait too, because they rank with the saved objects. Below Results, a section appears only once it and every section above it have loaded, so a late source never pushes rows on screen down. A section that comes back empty reserves nothing. While a section below Results is still loading, a quiet **Loading more…** row with a spinner sits at the very bottom, so people know more is coming. It fades in after 150 ms, so fast searches never flash it, and nothing above it ever moves.3. **Never blank on keystroke.** Keep the previous query's whole list visible (dimmed slightly after 150 ms) until the new query's results arrive. Then swap Results and the sections below it in one commit.4. **No mid-query re-rank.** Once rows for a query string are painted, later responses for the same query append to their own section. They never reorder rows above them.5. **Highlight follows identity, not index.** The highlighted row is tracked by item key (`section/type:ref`). Once the person moves the highlight (arrow keys or pointer), it stays on that item through result swaps for the same query while the item still exists. If it is gone, or the person never moved it, the first row is highlighted. Any change to the query (typing, clearing, adding or removing a chip) starts again at the first row.diff --git a/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx b/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsxindex 2a3dc0c73da6..0676a6cfd104 100644--- a/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx+++ b/frontend/src/lib/components/CommandKSearch/CommandKSearchRankedItem.tsx@@ -39,7 +39,9 @@ export function CommandKSearchRankedItem({ row }: { row: Extract<CommandKRow, {? 'Person': item.category === 'settings'? 'Setting'- : 'Product'+ : item.category === 'accounts'+ ? 'Account'+ : '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.tsindex 6e0af9c52c1e..c29a00cadd61 100644--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.test.ts@@ -34,6 +34,8 @@ const product = (name: string, searchKeywords: string[] = []): SearchItem => ({const exactWordRank = (created: number): number[] => [-1, 0, 0, 0, -1, 0, 2, 0, -created]+const account = (id: string, name: string): SearchItem => ({ id, name, category: 'accounts', itemType: 'account' })+const summary = (sections: CommandKSection[]): string[] =>sections.map((section) => {const rows = section.rows.map((row) => {@@ -154,6 +156,54 @@ describe('buildRankedResults', () => {products: [],expected: ['notice: (partial: xyzzy -> report)', 'Results: Weekly report'],},+ {+ name: 'an account identity match hides the dropped-words notice and leads partial matches',+ query: 'billing customer',+ results: [+ result('1', 'Customer report', 'insight', [-1, 0, 0, 1, -1, 0, 5, 0, -1], {+ matchedAllWords: false,+ matchedWords: ['customer'],+ }),+ ],+ products: [product('Customer analytics')],+ accounts: [account('account-1', 'Test organization')],+ expected: ['Results: Test organization'],+ },+ {+ name: 'an account match hides the close-spellings notice',+ query: 'dashbord',+ results: [+ result('1', 'Dashboard', 'dashboard', [-1, 1, 0, 0, 0, 0, 5, 0, -1], {+ matchedWords: ['dashbord'],+ withTypos: true,+ }),+ ],+ products: [],+ accounts: [account('account-1', 'Dashbord tools')],+ expected: ['Results: Dashbord tools'],+ },+ {+ name: 'an account can rank without saved objects or a matching display name',+ query: 'atlas.example.org',+ results: [],+ products: [],+ accounts: [account('account-1', 'Test organization')],+ expected: ['Results: Test organization'],+ },+ {+ name: 'distinct accounts with the same name stay separate and get no file-system scope row',+ query: 'billing',+ results: [1, 2, 3, 4, 5, 6].map((n) =>+ result(`insight-${n}`, `Billing insight ${n}`, 'insight', exactWordRank(n), { typeCount: 6 })+ ),+ products: [],+ accounts: [1, 2, 3, 4].map((n) => account(`account-${n}`, 'Billing')),+ expected: [+ 'Best matches: Billing, Billing insight 6',+ 'Accounts: Billing, Billing, Billing',+ 'Insights: Billing insight 5, Billing insight 4, Billing insight 3, (See all 6 insights)',+ ],+ },{name: 'a group of persons gets no see-all row, because persons are not a file system type',query: 'ada',@@ -173,7 +223,7 @@ describe('buildRankedResults', () => {],},- ])('$name', ({ query, results, products, persons = [], expected }) => {+ ])('$name', ({ query, results, products, persons = [], accounts = [], expected }) => {expect(summary(buildRankedResults({@@ -182,6 +232,7 @@ describe('buildRankedResults', () => {results,products,persons,+ accounts,state: 'ready',scoped: false,})diff --git a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.tsindex 11c552946bf9..7e220e90b1a1 100644--- a/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKRankedResults.ts@@ -9,7 +9,7 @@ import type { CommandKRow, CommandKSection } from './commandKSections'const BEST_MATCHES_LIMIT = 3const GROUP_LIMIT = 3const FLAT_LIST_LIMIT = 8-const LOCAL_GROUPS = ['products', 'persons', 'settings']+const LOCAL_GROUPS = ['products', 'persons', 'settings', 'accounts']interface RankedItem {item: SearchItem@@ -72,6 +72,20 @@ function rankItems(items: SearchItem[], query: string, groupKey: string): Ranked})}+function rankAccounts(accounts: SearchItem[], query: string): RankedItem[] {+ const queryMatch = rankLocalItem(query, query)+ if (!queryMatch) {+ return []+ }+ return accounts.map((item) => {+ const nameMatch = rankLocalItem(query, String(item.displayName || item.name))+ // The Accounts API matches the full query, including identities that the display name does not contain.+ const rank =+ nameMatch?.rank[0] === queryMatch.rank[0] && nameMatch.rank[1] === 0 ? nameMatch.rank : queryMatch.rank+ return { item, rank, groupKey: 'accounts' }+ })+}+const itemRow = (section: string,item: SearchItem,@@ -84,7 +98,10 @@ const itemRow = (key: `${section}/${item.id}`,item,section:- item.category === 'results' || item.category === 'persons' || item.category === 'settings'+ item.category === 'results' ||+ item.category === 'persons' ||+ item.category === 'settings' ||+ item.category === 'accounts'? item.category: 'products',highlightWords,@@ -109,7 +126,10 @@ function collapseSameName(entries: RankedItem[]): CollapsedItem[] {const byName = new Map<string, CollapsedItem>()const collapsed: CollapsedItem[] = []for (const entry of entries) {- const key = `${entry.groupKey}|${entry.item.parentName ?? ''}|${normalizedName(entry.item)}`+ const key =+ entry.groupKey === 'accounts'+ ? `${entry.groupKey}|${entry.item.id}`+ : `${entry.groupKey}|${entry.item.parentName ?? ''}|${normalizedName(entry.item)}`const existing = byName.get(key)if (existing) {existing.duplicates++@@ -166,6 +186,7 @@ interface RankedResultsInput {products: SearchItem[]persons?: SearchItem[]settings?: SearchItem[]+ accounts?: SearchItem[]state: CommandKSection['state']scoped: boolean}@@ -177,6 +198,7 @@ export function buildRankedResults({products,persons = [],settings = [],+ accounts = [],state,scoped,}: RankedResultsInput): CommandKSection[] {@@ -185,6 +207,7 @@ export function buildRankedResults({...rankLocalItems(products, query, 'products'),...rankLocalItems(persons, query, 'persons'),...rankLocalItems(settings, query, 'settings'),+ ...rankAccounts(accounts, query),].sort((a, b) => compareRanks(a.rank, b.rank))if (!candidates.length) {return []diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.test.tsindex cdfd8f839e49..82f492bfd7b1 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.test.ts@@ -10,6 +10,7 @@ import {buildSections,emptyRemoteSlots,pickDisplayedQuery,+ resultsSettled,} from './commandKSections'import { RESULTS_LIMIT } from './commandKSources'@@ -262,6 +263,48 @@ describe('buildSections', () => {expect(sections[0].rows).toMatchObject([{ kind: 'item', section: 'persons', item: { id: 'person-1' } }])})+ test.each(['results', 'accounts'] as const)('waits for both ranked sources when %s loads first', (firstSource) => {+ const account: SearchItem = {+ id: 'account-1',+ name: 'Test organization',+ category: 'accounts',+ href: '/customer_analytics/accounts/account-1',+ }+ const remote = emptyRemoteSlots()+ const current = query({+ remoteQueries: { results: 'atlas.example.org', accounts: 'atlas.example.org' },+ localQuery: 'atlas.example.org',+ })+ const shown = query({ remoteQueries: { results: 'old' }, localQuery: 'old' })+ remote.results.cache.old = []+ remote[firstSource].cache['atlas.example.org'] = firstSource === 'accounts' ? [account] : []+ const sectionsInput = input('search', { remote, ...current })++ expect(sectionKinds(buildSections(sectionsInput))).toEqual([['results', ['skeleton', 'skeleton', 'skeleton']]])+ expect(resultsSettled(current, remote)).toBe(false)+ expect(pickDisplayedQuery(current, shown, remote)).toEqual({ query: shown, stale: true })++ remote.results.cache['atlas.example.org'] = []+ remote.accounts.cache['atlas.example.org'] = [account]+ const sections = buildSections(sectionsInput)+ expect(resultsSettled(current, remote)).toBe(true)+ expect(pickDisplayedQuery(current, shown, remote)).toEqual({ query: current, stale: false })+ expect(sections.map((section) => section.key)).toEqual(['best-matches'])+ expect(sections[0].rows).toMatchObject([{ kind: 'item', section: 'accounts', item: account }])+ })++ it('shows saved objects when the Accounts request settles empty', () => {+ const remote = emptyRemoteSlots()+ remote.results.cache.billing = [{ ...dashboard('a', '1'), rankKey: [-1, 0, 0, 0, -1, 0, 2, 0, 0] }]+ remote.accounts.cache.billing = []+ const current = query({ remoteQueries: { results: 'billing', accounts: 'billing' }, localQuery: 'billing' })++ expect(resultsSettled(current, remote)).toBe(true)+ expect(sectionKinds(buildSections(input('search', { remote, ...current })))).toEqual([+ ['best-matches', ['item']],+ ])+ })+test.each([['off', false, 'Personal API keys', ['best-matches', 'settings'], 'Ada board'],['on', true, 'Personal API keys', ['best-matches'], 'Personal API keys'],diff --git a/frontend/src/lib/components/CommandKSearch/commandKSections.ts b/frontend/src/lib/components/CommandKSearch/commandKSections.tsindex 7b4fc09b0821..bf0b13b656cb 100644--- a/frontend/src/lib/components/CommandKSearch/commandKSections.ts+++ b/frontend/src/lib/components/CommandKSearch/commandKSections.ts@@ -230,12 +230,16 @@ export interface SectionsInput extends SectionsQuery {const isRanked = (query: SectionsQuery): boolean =>!!query.remoteQueries.results && freeWords(query.remoteQueries.results).length > 0+export const resultsSettled = (query: SectionsQuery, remote: RemoteSlots): boolean =>+ isSettled(remote.results, query.remoteQueries.results) &&+ (!isRanked(query) || isSettled(remote.accounts, query.remoteQueries.accounts))+export function pickDisplayedQuery(current: SectionsQuery,shown: SectionsQuery | null,remote: RemoteSlots): { query: SectionsQuery; stale: boolean } {- if (!shown?.remoteQueries.results || isSettled(remote.results, current.remoteQueries.results)) {+ if (!shown?.remoteQueries.results || resultsSettled(current, remote)) {return { query: current, stale: false }}if (isRanked(current) && !isRanked(shown)) {@@ -247,9 +251,6 @@ export function pickDisplayedQuery(const exactSettingsMatches = (settings: SearchItem[], localQuery: string): SearchItem[] =>localQuery ? matchLocal('settings', settings, localQuery, true) : []-export const resultsSettled = (query: SectionsQuery, remote: RemoteSlots): boolean =>- isSettled(remote.results, query.remoteQueries.results)-const LOCAL_MATCH_CACHE_SIZE = 50const localMatchCache = new WeakMap<SearchItem[], Map<string, SearchItem[]>>()@@ -304,11 +305,13 @@ function rankedResultsSections(localQuery: string,state: CommandKSection['state'],persons: SearchItem[],+ accounts: SearchItem[],settingsInResults: boolean): CommandKSection[] {const words = freeWords(query)return buildRankedResults({persons,+ accounts,settings: settingsInResults ? rankableSettings(local, localQuery) : [],query: words.join(' '),highlightWords: words,@@ -412,7 +415,12 @@ export function buildSections(input: SectionsInput): CommandKSection[] {const results = resultsQuery ? remote.results.cache[resultsQuery] : undefinedconst ranked = isRanked(input)const personsQuery = input.personsFirst && mode !== 'value' ? remoteQueries.persons : undefined- if ((resultsQuery && !results) || (personsQuery && !isSettled(remote.persons, personsQuery))) {+ const accountsQuery = ranked && mode !== 'value' ? remoteQueries.accounts : undefined+ if (+ (resultsQuery && !results) ||+ (personsQuery && !isSettled(remote.persons, personsQuery)) ||+ (accountsQuery && !isSettled(remote.accounts, accountsQuery))+ ) {sections.push(withViewAll(loadingSection('results'), input.viewAll))return sections.filter((section): section is CommandKSection => section !== null)}@@ -428,6 +436,7 @@ export function buildSections(input: SectionsInput): CommandKSection[] {localQuery,state,leadingPersons,+ accountsQuery ? remote.accounts.cache[accountsQuery] : [],input.settingsInResults)sections.push(