: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(settings): trim and tokenize settings search queries (#94760)
posthog[bot]7493735203f6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex c0ea954b7098..10511eb4b3f2 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1985,9 +1985,9 @@ snapshots:components-search--product-recents-and-starred--light:hash: v1.k794b7964.f2c75682469c037327f94f22550286ed866d4883e03ef7c66a3f234a31b1017b.1gKkr-42m5_F8qJMq6ahElSjOFRERpPTay3A0__UOo0components-search--searching--dark:- hash: v1.k794b7964.7b5de739918a3105f14ef1b5c831b8ddc13f3e33cbf3f2d99f45b74e1bdb5212.Vml_l6q1RdulTgTpPJtHtfW26V4T71fyXmdz1e8eakk+ hash: v1.k794b7964.3ce8ecf4192605f50f2ab332c2f6f370e79080ef1dd9628746b59ec59043e1b0.8RSulgjoFeYFhPE9GqdfAZ5eNfm4qVUy88-C8XemASAcomponents-search--searching--light:- hash: v1.k794b7964.749679cdf00b2d0892c9132e603542b4eab245e0ec4ac480e4cde730173e8fb3.nU303Ca0l5AQaU3QJBLpStoi54YwzrVTwJSrD5ggQL4+ hash: v1.k794b7964.e3c66e67f7bca4e981758e7f1a2be7684796dc64559e557530218938905849a9.2QaIxMkDumTR2GyoyM2avUDc7FJyKeYlpCBa2dzTEmkcomponents-sentencelist--full-sentence--dark:hash: v1.k794b7964.7e8e5dd2e09d246cc3668f362f2391fe67618bd1143aa393832297f5dc30e558.yptEWKc5RAUY613Fwd5cQ0VIinMvpdoI6cuKgagAGxkcomponents-sentencelist--full-sentence--light:diff --git a/frontend/src/lib/components/Search/searchLogic.tsx b/frontend/src/lib/components/Search/searchLogic.tsxindex 8328187cf4c9..c8e4bbe9227a 100644--- a/frontend/src/lib/components/Search/searchLogic.tsx+++ b/frontend/src/lib/components/Search/searchLogic.tsx@@ -30,6 +30,7 @@ import { recentItemsModel } from '~/models/recentItemsModel'import { getTreeItemsMetadata, getTreeItemsNew, getTreeItemsProducts } from '~/products'import { FileSystemEntry, GroupsQueryResponse } from '~/queries/schema/schema-general'import { matchesFlagDefinition } from '~/scenes/settings/flagGating'+import { getTitleText } from '~/scenes/settings/settingsSearch'import { Setting, SettingSection, SettingSectionId } from '~/scenes/settings/types'import { ActivityTab, FileSystemIconColor, GroupTypeIndex, PersonType, SearchResponse } from '~/types'@@ -175,6 +176,7 @@ export interface SettingsSectionSummary {hideFromNavigation?: booleanflag?: SettingSection['flag']to?: string+ keywords?: string[]settings: {id: stringhasTitle: boolean@@ -1259,14 +1261,17 @@ export const searchLogic = kea<searchLogicType>([// Create a search item for each settings sectionconst levelPrefix = toSentenceCase(effectiveLevel)- const settings = section.settings- .filter((setting) => setting.hasTitle)- .flatMap((setting) => [- toSentenceCase(setting.id.replace(/[-]/g, ' ')),- ...(setting.titleString ? [setting.titleString] : []),- ...(setting.descriptionString ? [setting.descriptionString] : []),- ...(setting.keywords ?? []),- ])+ const searchTerms = [+ ...(section.keywords ?? []),+ ...section.settings+ .filter((setting) => setting.hasTitle)+ .flatMap((setting) => [+ toSentenceCase(setting.id.replace(/[-]/g, ' ')),+ ...(setting.titleString ? [setting.titleString] : []),+ ...(setting.descriptionString ? [setting.descriptionString] : []),+ ...(setting.keywords ?? []),+ ]),+ ]// Create the display name for each settings sectionconst displayName = section.titleString ?? toSentenceCase(section.id.replace(/[-]/g, ' '))@@ -1278,7 +1283,7 @@ export const searchLogic = kea<searchLogicType>([items.push({id: `settings-${effectiveSectionId}`,- name: `${levelPrefix}: ${displayName} (${settings})`,+ name: `${levelPrefix}: ${displayName} (${searchTerms})`,displayName: `${displayName}${displayNameSuffix}`,category: 'settings',href: billingHref || section.to || urls.settings(effectiveSectionId),@@ -1736,17 +1741,21 @@ export const searchLogic = kea<searchLogicType>([SETTINGS_MAP.map((section) => ({id: section.id,level: section.level,- titleString: typeof section.title === 'string' ? section.title : null,+ titleString: getTitleText(section.title) || null,hideFromNavigation: section.hideFromNavigation,flag: section.flag,to: section.to,+ keywords: section.keywords,settings: section.settings.map((setting) => ({id: setting.id,- // A JSX-titled setting has no title string to search but must stay- // findable via its id token — hasTitle preserves that distinction.+ // A setting can render a title that getTitleText cannot read, such as a+ // whole component, and it must stay findable via its id token.+ // hasTitle preserves that distinction.hasTitle: !!setting.title,- titleString: typeof setting.title === 'string' ? setting.title : null,- descriptionString: typeof setting.description === 'string' ? setting.description : null,+ titleString: getTitleText(setting.title) || null,+ descriptionString:+ setting.searchDescription ??+ (typeof setting.description === 'string' ? setting.description : null),keywords: setting.keywords,})),}))diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 0ca89b0da5ca..aa8a35017773 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -1826,7 +1826,17 @@ export const SETTINGS_MAP: SettingSection[] = [</>),component: <OrganizationAI />,- keywords: ['llm', 'consent', 'opt-in', 'data sharing'],+ keywords: [+ 'ai',+ 'max',+ 'llm',+ 'artificial intelligence',+ 'consent',+ 'approve',+ 'enable',+ 'opt-in',+ 'data sharing',+ ],searchDescription:'PostHog AI features use external AI services for data analysis. This can involve transfer of identifying user data.',},@@ -1932,6 +1942,7 @@ export const SETTINGS_MAP: SettingSection[] = [title: 'Billing',to: urls.organizationBilling(),settings: [],+ keywords: ['usage', 'subscription', 'invoice', 'plan', 'payment', 'spend', 'quota', 'credits', 'card'],},{level: 'organization',diff --git a/frontend/src/scenes/settings/settingsLogic.ts b/frontend/src/scenes/settings/settingsLogic.tsindex 5fec194b3b2d..c68a4490f37f 100644--- a/frontend/src/scenes/settings/settingsLogic.ts+++ b/frontend/src/scenes/settings/settingsLogic.ts@@ -2,6 +2,7 @@ import FuseClass from 'fuse.js'import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'+import posthog from 'posthog-js'import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'@@ -19,27 +20,21 @@ import type { IntegrationType, PreflightStatus, TeamPublicType, TeamType } fromimport type { AvailableFeature, OrganizationType } from '../../types'import { matchesFlagDefinition } from './flagGating'import { SETTINGS_MAP } from './SettingsMap'+import {+ FUSE_THRESHOLD,+ GlobalSearchFuse,+ buildSettingsSearchIndex,+ createSettingsSearchFuse,+ searchSettingsIndex,+} from './settingsSearch'import { Setting, SettingId, SettingLevelId, SettingSection, SettingSectionId, SettingsLogicProps } from './types'-// Explicitly avoid "heat" matching "feature flags", but still allowing "heature" to match it-const FUSE_THRESHOLD = 0.2-// Helping kea-typegen navigate the exported default class for Fuseexport interface SettingsFuse extends FuseClass<Setting & { searchValue: string }> {}export interface SectionsFuse extends FuseClass<SettingSection & { searchValue: string; settingsSearchValues: string }> {}-export interface SearchIndexEntry {- settingId: SettingId- settingTitle: string- sectionId: SettingSectionId- sectionTitle: string- level: SettingLevelId- keywords: string- description: string-}-export interface SearchResult {settingId: SettingIdsettingTitle: string@@ -55,8 +50,6 @@ export interface SearchResultGroup {results: SearchResult[]}-export interface GlobalSearchFuse extends FuseClass<SearchIndexEntry> {}-const getSettingStringValue = (setting: Setting): string => {if (setting.searchTerm) {return setting.searchTerm@@ -405,6 +398,24 @@ export const settingsLogic = kea<settingsLogicType>([}}, 100)},+ setSearchTerm: async ({ searchTerm }, breakpoint) => {+ // Wait for typing to settle so one search reports once, not once per keystroke.+ await breakpoint(1000)++ const term = searchTerm.trim()+ if (!term) {+ return+ }++ const resultCount = values.searchResults.reduce((count, group) => count + group.results.length, 0)+ posthog.capture('settings search', {+ result_count: resultCount,+ word_count: term.split(/\s+/).length,+ // Only a search that found nothing is worth reading back, because that is what+ // a gap between the words people use and the words the index carries looks like.+ search_term: resultCount === 0 ? term : null,+ })+ },navigateToSetting: ({ sectionId, settingId }) => {const section = values.sections.find((s) => s.id === sectionId)if (section) {@@ -682,84 +693,27 @@ export const settingsLogic = kea<settingsLogicType>([preflight: null | import('../../types').PreflightStatus,currentTeam: null | import('../../types').TeamPublicType | import('../../types').TeamType): GlobalSearchFuse => {- const entries: SearchIndexEntry[] = []-- for (const section of sections.filter((s) => !s.hideFromNavigation)) {- const sectionTitle =- typeof section.title === 'string' ? section.title : section.id.replace(/[-]/g, ' ')-- for (const setting of section.settings) {- if (!doesMatchFlags(setting)) {- continue- }- if (preflight?.realm && setting.hideOn?.includes(preflight.realm)) {- continue- }- if (setting.allowForTeam && !setting.allowForTeam(currentTeam)) {- continue- }-- const settingTitle =- typeof setting.title === 'string' ? setting.title : setting.id.replace(/[-]/g, ' ')-- entries.push({- settingId: setting.id,- settingTitle,- sectionId: section.id,- sectionTitle,- level: section.level,- keywords: (setting.keywords ?? []).join(' '),- description:- setting.searchDescription ??- (typeof setting.description === 'string' ? setting.description : ''),- })+ const isSettingVisible = (setting: Setting): boolean => {+ if (!doesMatchFlags(setting)) {+ return false}- }-- // Index sections that are top-level links with no settings (e.g. Billing)- for (const section of sections.filter((s) => !s.hideFromNavigation)) {- if (section.settings.length === 0) {- const sectionTitle =- typeof section.title === 'string' ? section.title : section.id.replace(/[-]/g, ' ')-- entries.push({- settingId: section.id as SettingId,- settingTitle: sectionTitle,- sectionId: section.id,- sectionTitle,- level: section.level,- keywords: '',- description: '',- })+ if (preflight?.realm && setting.hideOn?.includes(preflight.realm)) {+ return false}+ return !setting.allowForTeam || setting.allowForTeam(currentTeam)}- return createFuse(entries, {- keys: [- { name: 'settingTitle', weight: 2 },- { name: 'keywords', weight: 1.5 },- { name: 'sectionTitle', weight: 1 },- { name: 'description', weight: 0.5 },- { name: 'settingId', weight: 0.5 },- ],- threshold: FUSE_THRESHOLD,- includeScore: true,- })+ return createSettingsSearchFuse(buildSettingsSearchIndex(sections, isSettingVisible))},],searchResults: [(s) => [s.searchTerm, s.globalSearchIndex],(searchTerm: string, globalSearchIndex: GlobalSearchFuse): SearchResultGroup[] => {- if (!searchTerm.trim()) {- return []- }-- const results = globalSearchIndex.search(searchTerm, { limit: 30 })+ const results = searchSettingsIndex(globalSearchIndex, searchTerm)const groupMap = new Map<SettingSectionId, SearchResultGroup>()- for (const result of results) {- const { sectionId, sectionTitle, level, settingId, settingTitle } = result.item+ for (const { sectionId, sectionTitle, level, settingId, settingTitle } of results) {let group = groupMap.get(sectionId)if (!group) {group = { sectionId, sectionTitle, level, results: [] }diff --git a/frontend/src/scenes/settings/settingsSearch.test.tsx b/frontend/src/scenes/settings/settingsSearch.test.tsxnew file mode 100644index 000000000000..5856af2c6997--- /dev/null+++ b/frontend/src/scenes/settings/settingsSearch.test.tsx@@ -0,0 +1,112 @@+import { buildSettingsSearchIndex, createSettingsSearchFuse, searchSettingsIndex } from './settingsSearch'+import { Setting, SettingSection } from './types'++const SECTIONS: SettingSection[] = [+ {+ level: 'environment',+ id: 'environment-details',+ title: 'General',+ settings: [+ {+ id: 'variables',+ title: 'Project token & ID',+ description: 'Your project token and ID used to connect SDKs and APIs to this environment.',+ component: <div />,+ keywords: ['api key', 'token', 'project id'],+ },+ {+ id: 'js-snippet-version',+ title: (+ <>+ Snippet version <span>Experimental</span>+ </>+ ),+ description: 'Pin the snippet to a specific version of posthog-js.',+ component: <div />,+ keywords: ['pin', 'posthog-js'],+ },+ ],+ },+ {+ level: 'environment',+ id: 'environment-replay',+ title: 'Session replay',+ settings: [+ {+ id: 'replay-retention',+ title: 'Data retention',+ description: 'Control how long your recordings are stored.',+ component: <div />,+ keywords: ['storage', 'retention', 'delete', 'days', 'months'],+ },+ ],+ },+ {+ level: 'organization',+ id: 'organization-details',+ title: 'General',+ settings: [+ {+ id: 'organization-ai-consent',+ title: 'AI service providers',+ component: <div />,+ keywords: ['ai', 'max', 'llm', 'consent', 'approve', 'enable', 'opt-in', 'data sharing'],+ searchDescription: 'PostHog AI features use external AI services for data analysis.',+ },+ {+ id: 'organization-ai-training-opt-out',+ title: 'Internal AI training',+ component: <div />,+ keywords: ['ai', 'training', 'opt-out', 'opt-in', 'model', 'max'],+ },+ ],+ },+ {+ level: 'organization',+ id: 'organization-billing',+ title: 'Billing',+ to: '/organization/billing',+ settings: [],+ keywords: ['usage', 'subscription', 'invoice', 'plan', 'payment', 'spend', 'quota', 'credits', 'card'],+ },+]++const search = (term: string, isSettingVisible: (setting: Setting) => boolean = () => true): string[] => {+ const fuse = createSettingsSearchFuse(buildSettingsSearchIndex(SECTIONS, isSettingVisible))+ return searchSettingsIndex(fuse, term).map((entry) => entry.settingId)+}++describe('settingsSearch', () => {+ test.each([+ ['a single word', 'retention', 'replay-retention'],+ ['a trailing space', 'project id ', 'variables'],+ ['a leading space', ' project id', 'variables'],+ ['a repeated space', 'project id', 'variables'],+ ['trailing punctuation', 'project id?', 'variables'],+ ['words split across the title and the section title', 'session replay retention', 'replay-retention'],+ ['a keyword late in the keyword list', 'max', 'organization-ai-training-opt-out'],+ ['an action phrased query', 'enable AI', 'organization-ai-consent'],+ ['a synonym on a section that has no settings', 'usage', 'organization-billing'],+ ['a word the index does not carry alongside one it does', 'usage dashboard', 'organization-billing'],+ ])('finds a setting by %s', (_description, term, expectedSettingId) => {+ expect(search(term)).toContain(expectedSettingId)+ })++ it('indexes a JSX title by the words it shows, not by its id', () => {+ const entries = buildSettingsSearchIndex(SECTIONS, () => true)+ const snippetVersion = entries.find((entry) => entry.settingId === 'js-snippet-version')++ expect(snippetVersion?.settingTitle).toBe('Snippet version Experimental')+ expect(search('snippet version')).toContain('js-snippet-version')+ })++ it('leaves out a setting that is not visible to this user', () => {+ const isVisible = (setting: Setting): boolean => setting.id !== 'organization-ai-training-opt-out'++ expect(search('internal AI training', isVisible)).not.toContain('organization-ai-training-opt-out')+ })++ it('returns nothing for a term that is only whitespace', () => {+ expect(search(' ')).toEqual([])+ })+})diff --git a/frontend/src/scenes/settings/settingsSearch.ts b/frontend/src/scenes/settings/settingsSearch.tsnew file mode 100644index 000000000000..5e71e0691538--- /dev/null+++ b/frontend/src/scenes/settings/settingsSearch.ts@@ -0,0 +1,187 @@+import FuseClass from 'fuse.js'+import { type ReactNode, isValidElement } from 'react'++import { createFuse } from 'lib/utils/fuseSearch'++import { Setting, SettingId, SettingLevelId, SettingSection, SettingSectionId } from './types'++// Explicitly avoid "heat" matching "feature flags", but still allowing "heature" to match it+export const FUSE_THRESHOLD = 0.2++const RESULT_LIMIT = 30++export interface SearchIndexEntry {+ settingId: SettingId+ settingTitle: string+ sectionId: SettingSectionId+ sectionTitle: string+ level: SettingLevelId+ keywords: string+ sectionKeywords: string+ description: string+}++// Helping kea-typegen navigate the exported default class for Fuse+export interface GlobalSearchFuse extends FuseClass<SearchIndexEntry> {}++function collectText(node: ReactNode): string {+ if (typeof node === 'string') {+ return node+ }+ if (typeof node === 'number') {+ return String(node)+ }+ if (Array.isArray(node)) {+ return node.map(collectText).join(' ')+ }+ if (isValidElement(node)) {+ return collectText((node.props as { children?: ReactNode }).children)+ }+ return ''+}++/**+ * The words a title puts on screen. A title is JSX whenever it carries a tag such as "Beta",+ * so reading only string titles drops those settings out of the index and leaves them+ * findable by their hyphen-split id alone. Returns an empty string for a title that renders+ * through a component, because its text is not reachable without rendering it.+ */+export function getTitleText(title: ReactNode): string {+ return collectText(title).replace(/\s+/g, ' ').trim()+}++/** The title a search matches on, falling back to the id for a title with no readable text. */+const indexedTitle = (title: ReactNode, id: string): string => getTitleText(title) || id.replace(/[-]/g, ' ')++const keywordText = (keywords: string[] | undefined): string => (keywords ?? []).join(' ')++const settingDescription = (setting: Setting): string =>+ setting.searchDescription ?? (typeof setting.description === 'string' ? setting.description : '')++export function buildSettingsSearchIndex(+ sections: SettingSection[],+ isSettingVisible: (setting: Setting) => boolean+): SearchIndexEntry[] {+ const entries: SearchIndexEntry[] = []++ for (const section of sections) {+ if (section.hideFromNavigation) {+ continue+ }++ const sectionTitle = indexedTitle(section.title, section.id)+ const shared = {+ sectionId: section.id,+ sectionTitle,+ level: section.level,+ sectionKeywords: keywordText(section.keywords),+ }++ // A section that is a top-level link (e.g. Billing) has no settings of its own, so the+ // section itself is the only thing a search can land on.+ if (section.settings.length === 0) {+ entries.push({+ ...shared,+ settingId: section.id as SettingId,+ settingTitle: sectionTitle,+ keywords: '',+ description: '',+ })+ continue+ }++ for (const setting of section.settings) {+ if (!isSettingVisible(setting)) {+ continue+ }++ entries.push({+ ...shared,+ settingId: setting.id,+ settingTitle: indexedTitle(setting.title, setting.id),+ keywords: keywordText(setting.keywords),+ description: settingDescription(setting),+ })+ }+ }++ return entries+}++export function createSettingsSearchFuse(entries: SearchIndexEntry[]): GlobalSearchFuse {+ return createFuse(entries, {+ keys: [+ { name: 'settingTitle', weight: 2 },+ { name: 'keywords', weight: 1.5 },+ { name: 'sectionTitle', weight: 1 },+ { name: 'sectionKeywords', weight: 0.75 },+ { name: 'description', weight: 0.5 },+ { name: 'settingId', weight: 0.5 },+ ],+ threshold: FUSE_THRESHOLD,+ // Fuse defaults to scoring a match by how close it sits to the start of the field. A+ // keyword list is one joined string, so without this an exact keyword late in the list+ // (such as "max" on "Internal AI training") scores below the threshold and never matches.+ ignoreLocation: true,+ includeScore: true,+ })+}++interface WordMatch {+ entry: SearchIndexEntry+ matchedWords: number+ score: number+}++const entryKey = (entry: SearchIndexEntry): string => `${entry.sectionId}::${entry.settingId}`++function matchWords(index: GlobalSearchFuse, words: string[]): WordMatch[] {+ const matches = new Map<string, WordMatch>()++ for (const word of words) {+ for (const { item, score } of index.search(word)) {+ const key = entryKey(item)+ const match = matches.get(key)+ if (match) {+ match.matchedWords += 1+ // Rank a multi-word query by its weakest word, so an entry that matches every+ // word closely stays ahead of one that only matches a single word well.+ match.score = Math.max(match.score, score ?? 1)+ } else {+ matches.set(key, { entry: item, matchedWords: 1, score: score ?? 1 })+ }+ }+ }++ return Array.from(matches.values())+}++/**+ * Fuse treats a query as one fuzzy pattern, so a multi-word query only matches when those+ * words sit together in one indexed field. That makes "session replay retention" and+ * "enable AI" return nothing. Searching word by word restores them: prefer the entries that+ * match every word, and fall back to the entries that match any word when none match all,+ * which is what rescues a query with a verb the index does not carry.+ */+export function searchSettingsIndex(index: GlobalSearchFuse, term: string): SearchIndexEntry[] {+ // Trim before searching: leading/trailing whitespace changes the pattern length and+ // inflates Fuse's effective edit budget (threshold × length), so an untrimmed term either+ // matches nothing or matches far too much.+ const trimmed = term.trim()+ if (!trimmed) {+ return []+ }++ const words = trimmed.split(/\s+/)+ if (words.length === 1) {+ return index.search(trimmed, { limit: RESULT_LIMIT }).map((result) => result.item)+ }++ const matches = matchWords(index, words)+ const matchingEveryWord = matches.filter((match) => match.matchedWords === words.length)+ const ranked = matchingEveryWord.length > 0 ? matchingEveryWord : matches++ ranked.sort((a, b) => b.matchedWords - a.matchedWords || a.score - b.score)++ return ranked.slice(0, RESULT_LIMIT).map((match) => match.entry)+}diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 70054e30a6ed..04fffce47f05 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -347,6 +347,13 @@ export interface SettingSection extends Pick<Setting, 'flag'> {minimumAccessLevel?: EitherMembershipLevelsearchValue?: string+ /**+ * Additional search terms that help users find this section and the settings inside it+ * (e.g. ['usage', 'invoice'] on Billing). A section that is a top-level link has no settings+ * to carry keywords of its own, so this is the only way to make it answer to a synonym.+ */+ keywords?: string[]+/*** If the setting is restricted, the resource type and minimum access level* that are required to access the setting