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.

feat(error-tracking): auto-discover quick filter values (#109161)

Aleksander Błaszkiewicz540daa3e4e33
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 58e217d5e068..3dbff2496194 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -3917,6 +3917,20 @@ export interface EmojiSearchResponseApi {
suggestions: EmojiSuggestionApi[]
}
+export interface EventPropertyValueApi {
+ /** A value of the property, always as a string. Booleans come back as 'true' or 'false', and objects and lists as JSON. */
+ name: string
+ /** How many times the value occurs, when the lookup counts values. */
+ count?: number
+}
+
+export interface EventPropertyValuesResponseApi {
+ /** Values of the property that match the request. */
+ results: EventPropertyValueApi[]
+ /** True when these results come from a stale cache and a refresh runs in the background. */
+ refreshing: boolean
+}
+
/**
* * `image/png` - image/png
* * `application/pdf` - application/pdf
@@ -5749,6 +5763,33 @@ export type EmojiSearchSuggestRetrieveParams = {
query: string
}
+export type EventsValuesRetrieveParams = {
+ /**
+ * Only read values from events with these names. Repeat to pass several. Required with a personal API key. Projects that read values from the precomputed property values table ignore this filter.
+ */
+ event_name?: string[]
+ format?: EventsValuesRetrieveFormat
+ /**
+ * Read 'key' as an events table column, not a property.
+ */
+ is_column?: boolean
+ /**
+ * The property to list values for.
+ */
+ key: string
+ /**
+ * Only return values that contain this text, ignoring case.
+ */
+ value?: string
+}
+
+export type EventsValuesRetrieveFormat = (typeof EventsValuesRetrieveFormat)[keyof typeof EventsValuesRetrieveFormat]
+
+export const EventsValuesRetrieveFormat = {
+ Csv: 'csv',
+ Json: 'json',
+} as const
+
export type ExportsListParams = {
/**
* Number of results to return per page.
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index f738f1382b8b..8f442c4446fb 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -28,6 +28,8 @@ import type {
EventIngestionRestrictionApi,
EventMatchRequestApi,
EventMatchResponseApi,
+ EventPropertyValuesResponseApi,
+ EventsValuesRetrieveParams,
ExportedAssetApi,
ExportedAssetCreateApi,
ExportsListParams,
@@ -1598,6 +1600,45 @@ export const emojiSearchSuggestRetrieve = async (
})
}
+export const getEventsValuesRetrieveUrl = (projectId: string, params: EventsValuesRetrieveParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ const explodeParameters = ['event_name']
+
+ if (Array.isArray(value) && explodeParameters.includes(key)) {
+ value.forEach((v) => {
+ normalizedParams.append(key, v === null ? 'null' : String(v))
+ })
+ return
+ }
+
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/events/values/?${stringifiedParams}`
+ : `/api/projects/${projectId}/events/values/`
+}
+
+/**
+ * List values of an event property from recent events.
+ */
+export const eventsValuesRetrieve = async (
+ projectId: string,
+ params: EventsValuesRetrieveParams,
+ options?: RequestInit
+): Promise<EventPropertyValuesResponseApi> => {
+ return apiMutator<EventPropertyValuesResponseApi>(getEventsValuesRetrieveUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getExportsListUrl = (projectId: string, params?: ExportsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/lib/components/QuickFilters/QuickFilterForm.tsx b/frontend/src/lib/components/QuickFilters/QuickFilterForm.tsx
index 72a51769f876..ff37f26a0b71 100644
--- a/frontend/src/lib/components/QuickFilters/QuickFilterForm.tsx
+++ b/frontend/src/lib/components/QuickFilters/QuickFilterForm.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { Form } from 'kea-forms'
import { IconPlus, IconTrash } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonSelect } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonSegmentedButton } from '@posthog/lemon-ui'
import { OperatorValueSelect } from 'lib/components/PropertyFilters/components/OperatorValueSelect'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
@@ -14,6 +14,7 @@ import { QuickFilterContext } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator, QuickFilterOption } from '~/types'
import { allowedOperators, operatorsWithoutValues, quickFilterFormLogic } from './quickFilterFormLogic'
+import { QuickFilterSelector } from './QuickFilterSelector'
import { quickFiltersLogic } from './quickFiltersLogic'
import { quickFiltersModalLogic } from './quickFiltersModalLogic'
@@ -27,7 +28,7 @@ export function QuickFilterForm({ context }: QuickFilterFormProps): JSX.Element
const formLogic = quickFilterFormLogic({ context, filter: editedFilter })
const { handleFormBack } = useActions(modalLogic)
const { quickFiltersLoading } = useValues(quickFiltersLogic({ context }))
- const { name, propertyName, options, isQuickFilterSubmitting } = useValues(formLogic)
+ const { name, propertyName, type, options, isQuickFilterSubmitting } = useValues(formLogic)
const { addOption } = useActions(formLogic)
return (
@@ -68,7 +69,33 @@ export function QuickFilterForm({ context }: QuickFilterFormProps): JSX.Element
</div>
</div>
- {propertyName && (
+ <LemonField
+ name="type"
+ label="Dropdown values"
+ help={
+ type === 'auto-discovery'
+ ? 'The dropdown lists values of this property from events in the last 7 days.'
+ : undefined
+ }
+ >
+ <LemonSegmentedButton
+ size="small"
+ options={[
+ {
+ value: 'auto-discovery',
+ label: 'Discover automatically',
+ 'data-attr': 'quick-filter-type-auto-discovery',
+ },
+ {
+ value: 'manual-options',
+ label: 'Set manually',
+ 'data-attr': 'quick-filter-type-manual-options',
+ },
+ ]}
+ />
+ </LemonField>
+
+ {propertyName && type === 'manual-options' && (
<div>
<div className="flex items-center justify-between mb-2">
<label className="block font-medium">Filter options</label>
@@ -90,23 +117,17 @@ export function QuickFilterForm({ context }: QuickFilterFormProps): JSX.Element
</div>
)}
- <div className="border rounded p-4 bg-bg-3000">
- <div className="text-xs font-semibold uppercase text-muted mb-2">Preview</div>
- <LemonSelect
- value={null}
- options={[
- { value: null, label: `Any ${name?.toLowerCase() || 'items'}` },
- ...options.map((opt: QuickFilterOption) => ({
- value: opt.id,
- label: opt.label,
- })),
- ]}
- size="small"
- placeholder={name || 'Filter name'}
- dropdownMatchSelectWidth={false}
- allowClear
- />
- </div>
+ {propertyName && (
+ <div className="border rounded p-4 bg-bg-3000">
+ <div className="text-xs font-semibold uppercase text-muted mb-2">Preview</div>
+ <QuickFilterSelector
+ filter={{ name, property_name: propertyName, type, options }}
+ context={context}
+ selectedOptionId={null}
+ onChange={() => undefined}
+ />
+ </div>
+ )}
<div className="flex justify-between gap-2 pt-4 border-t">
<LemonButton
diff --git a/frontend/src/lib/components/QuickFilters/QuickFilterSelector.tsx b/frontend/src/lib/components/QuickFilters/QuickFilterSelector.tsx
index 0501e1ba65c8..1c26de7978c1 100644
--- a/frontend/src/lib/components/QuickFilters/QuickFilterSelector.tsx
+++ b/frontend/src/lib/components/QuickFilters/QuickFilterSelector.tsx
@@ -1,56 +1,111 @@
+import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
-import { LemonSelect } from '@posthog/lemon-ui'
+import { LemonSearchableSelect, LemonSelect, LemonSelectOptionLeaf, Spinner } from '@posthog/lemon-ui'
-import { QuickFilterOption } from '~/types'
+import { QuickFilterContext } from '~/queries/schema/schema-general'
+import { QuickFilter, QuickFilterOption } from '~/types'
+
+import { anyOptionLabel, discoveredSelectOptions } from './discoveredSelectOptions'
+import { withSelectedOption } from './quickFilterOptions'
+import { discoveredValuesMessage, quickFilterValuesLogic } from './quickFilterValuesLogic'
interface QuickFilterSelectorProps {
- label: string
- options: QuickFilterOption[]
+ filter: Pick<QuickFilter, 'name' | 'property_name' | 'type' | 'options'>
+ context: QuickFilterContext
selectedOptionId: string | null
onChange: (option: QuickFilterOption | null) => void
}
-export function QuickFilterSelector({
- label,
- options,
+type SelectValue = string | null
+
+function selectOptions(filterName: string, options: QuickFilterOption[]): LemonSelectOptionLeaf<SelectValue>[] {
+ return [
+ { value: null, label: anyOptionLabel(filterName) },
+ ...options.map((option) => ({ value: option.id, label: option.label })),
+ ]
+}
+
+function selectedValue(options: QuickFilterOption[], selectedOptionId: string | null): SelectValue {
+ return selectedOptionId && options.some((option) => option.id === selectedOptionId) ? selectedOptionId : null
+}
+
+function findOption(options: QuickFilterOption[], optionId: SelectValue): QuickFilterOption | null {
+ return optionId === null ? null : (options.find((option) => option.id === optionId) ?? null)
+}
+
+export function QuickFilterSelector(props: QuickFilterSelectorProps): JSX.Element {
+ return props.filter.type === 'auto-discovery' ? (
+ <DiscoveredValuesSelector {...props} />
+ ) : (
+ <ManualOptionsSelector {...props} />
+ )
+}
+
+function ManualOptionsSelector({ filter, selectedOptionId, onChange }: QuickFilterSelectorProps): JSX.Element {
+ const options = useMemo(() => selectOptions(filter.name, filter.options), [filter.name, filter.options])
+
+ return (
+ <LemonSelect
+ value={selectedValue(filter.options, selectedOptionId)}
+ onChange={(optionId) => onChange(findOption(filter.options, optionId))}
+ options={options}
+ size="small"
+ placeholder={filter.name || 'Filter name'}
+ dropdownMatchSelectWidth={false}
+ truncateText={{ maxWidthClass: 'max-w-60' }}
+ />
+ )
+}
+
+function DiscoveredValuesSelector({
+ filter,
+ context,
selectedOptionId,
onChange,
}: QuickFilterSelectorProps): JSX.Element {
- const allOptions = useMemo(
+ const valuesLogic = quickFilterValuesLogic({ context, propertyName: filter.property_name })
+ const { discoveredOptions, discoveredValuesStatus, search } = useValues(valuesLogic)
+ const { setSearch } = useActions(valuesLogic)
+
+ const options = useMemo(
+ () => withSelectedOption(discoveredOptions, selectedOptionId),
+ [discoveredOptions, selectedOptionId]
+ )
+ const message = discoveredValuesMessage(discoveredValuesStatus, search, discoveredOptions.length)
+ const sections = useMemo(
() => [
- { value: null, label: `Any ${label.toLowerCase()}` },
- ...options.map((opt) => ({
- value: opt.id,
- label: opt.label,
- })),
+ {
+ options: discoveredSelectOptions(filter.name, discoveredOptions, selectedOptionId, search),
+ footer:
+ discoveredValuesStatus === 'loading' ? (
+ <span className="flex items-center gap-1">
+ <Spinner textColored />
+ {message}
+ </span>
+ ) : (
+ (message ?? undefined)
+ ),
+ },
],
- [options, label]
+ [filter.name, discoveredOptions, selectedOptionId, search, discoveredValuesStatus, message]
)
- const displayValue = useMemo(() => {
- if (selectedOptionId === null) {
- return null
- }
- return options.some((opt) => opt.id === selectedOptionId) ? selectedOptionId : null
- }, [selectedOptionId, options])
-
return (
- <LemonSelect
- value={displayValue}
- onChange={(selectedId) => {
- if (selectedId === null) {
- onChange(null)
- } else {
- const selected = options.find((opt) => opt.id === selectedId)
- onChange(selected || null)
- }
- }}
- options={allOptions}
+ <LemonSearchableSelect
+ value={selectedValue(options, selectedOptionId)}
+ className={selectedValue(options, selectedOptionId) ? 'ph-no-capture' : undefined}
+ onChange={(optionId) => onChange(findOption(options, optionId))}
+ options={sections}
+ searchPlaceholder="Search values"
+ searchInputDataAttr="quick-filter-values-search"
+ onSearchChange={setSearch}
+ filterOptionsLocally={false}
size="small"
- placeholder={label}
+ placeholder={filter.name || 'Filter name'}
dropdownMatchSelectWidth={false}
truncateText={{ maxWidthClass: 'max-w-60' }}
+ menu={{ onVisibilityChange: (visible) => visible && setSearch('') }}
/>
)
}
diff --git a/frontend/src/lib/components/QuickFilters/QuickFiltersModalContent.tsx b/frontend/src/lib/components/QuickFilters/QuickFiltersModalContent.tsx
index 9712bb591df2..8fdb54594db7 100644
--- a/frontend/src/lib/components/QuickFilters/QuickFiltersModalContent.tsx
+++ b/frontend/src/lib/components/QuickFilters/QuickFiltersModalContent.tsx
@@ -79,27 +79,30 @@ export function QuickFiltersModalContent({
{
title: 'Options',
dataIndex: 'options',
- render: (options: QuickFilterOption[]) => (
- <div className="flex gap-1 flex-wrap">
- {options.slice(0, 3).map((opt, index) => (
- <span key={index} className="px-2 py-0.5 bg-border rounded text-xs">
- {opt.label}
- </span>
- ))}
- {options.length > 3 && (
- <Tooltip
- title={options
- .slice(3)
- .map((o) => o.label)
- .join(', ')}
- >
- <span className="px-2 py-0.5 bg-border rounded text-xs">
- +{options.length - 3} more
+ render: (options: QuickFilterOption[], filter: QuickFilter) =>
+ filter.type === 'auto-discovery' ? (
+ <span className="text-xs text-secondary">Discovered automatically</span>
+ ) : (
+ <div className="flex gap-1 flex-wrap">
+ {options.slice(0, 3).map((opt, index) => (
+ <span key={index} className="px-2 py-0.5 bg-border rounded text-xs">
+ {opt.label}
</span>
- </Tooltip>
- )}
- </div>
- ),
+ ))}
+ {options.length > 3 && (
+ <Tooltip
+ title={options
+ .slice(3)
+ .map((o) => o.label)
+ .join(', ')}
+ >
+ <span className="px-2 py-0.5 bg-border rounded text-xs">
+ +{options.length - 3} more
+ </span>
+ </Tooltip>
+ )}
+ </div>
+ ),
},
{
title: 'Updated',
diff --git a/frontend/src/lib/components/QuickFilters/QuickFiltersSection.tsx b/frontend/src/lib/components/QuickFilters/QuickFiltersSection.tsx
index 8ddd00b0146c..444b345bcfcb 100644
--- a/frontend/src/lib/components/QuickFilters/QuickFiltersSection.tsx
+++ b/frontend/src/lib/components/QuickFilters/QuickFiltersSection.tsx
@@ -48,8 +48,8 @@ export function QuickFiltersSection({
return (
<QuickFilterSelector
key={filter.id}
- label={filter.name}
- options={filter.options}
+ filter={filter}
+ context={context}
selectedOptionId={selectedFilter?.optionId || null}
onChange={(option) => {
if (option === null) {
diff --git a/frontend/src/lib/components/QuickFilters/consts.ts b/frontend/src/lib/components/QuickFilters/consts.ts
index 5e8d5fc99362..6cd1a0f77df7 100644
--- a/frontend/src/lib/components/QuickFilters/consts.ts
+++ b/frontend/src/lib/components/QuickFilters/consts.ts
@@ -1,6 +1,17 @@
+import { QuickFilterContext } from '~/queries/schema/schema-general'
+
export const QuickFiltersEvents = {
QuickFilterCreated: 'quick filter created',
QuickFilterUpdated: 'quick filter updated',
QuickFilterSelected: 'quick filter selected',
QuickFiltersModalOpened: 'quick filters modal opened',
}
+
+/**
+ * Event names sent with the values lookup for each context.
+ * Only a scan of the events table applies them. Values read from the precomputed
+ * property values table come from all events, because that table has no event column.
+ */
+export const QUICK_FILTER_VALUE_EVENT_NAMES: Partial<Record<QuickFilterContext, string[]>> = {
+ [QuickFilterContext.ErrorTrackingIssueFilters]: ['$exception'],
+}
diff --git a/frontend/src/lib/components/QuickFilters/discoveredSelectOptions.test.ts b/frontend/src/lib/components/QuickFilters/discoveredSelectOptions.test.ts
new file mode 100644
index 000000000000..ba51da74b846
--- /dev/null
+++ b/frontend/src/lib/components/QuickFilters/discoveredSelectOptions.test.ts
@@ -0,0 +1,28 @@
+import { discoveredSelectOptions } from './discoveredSelectOptions'
+import { autoDiscoveredOption } from './quickFilterOptions'
+
+const web = autoDiscoveredOption('web')
+const python = autoDiscoveredOption('posthog-python')
+
+describe('discoveredSelectOptions', () => {
+ it.each([
+ {
+ description: 'shows the Any option and the pinned selection without a search',
+ search: '',
+ discoveredOptions: [web],
+ expectedVisible: [null, python.id, web.id],
+ },
+ {
+ description: 'shows only matches while searching, so ArrowDown and Enter pick a match',
+ search: 'we',
+ discoveredOptions: [web],
+ expectedVisible: [web.id],
+ },
+ ])('$description', ({ search, discoveredOptions, expectedVisible }) => {
+ const options = discoveredSelectOptions('Library', discoveredOptions, python.id, search)
+
+ expect(options.filter((option) => !option.hidden).map((option) => option.value)).toEqual(expectedVisible)
+ // The selected value stays in the list, hidden or not, so the trigger keeps showing it
+ expect(options.map((option) => option.value)).toContain(python.id)
+ })
+})
diff --git a/frontend/src/lib/components/QuickFilters/discoveredSelectOptions.ts b/frontend/src/lib/components/QuickFilters/discoveredSelectOptions.ts
new file mode 100644
index 000000000000..46fc166690ed
--- /dev/null
+++ b/frontend/src/lib/components/QuickFilters/discoveredSelectOptions.ts
@@ -0,0 +1,33 @@
+import type { LemonSelectOptionLeaf } from '@posthog/lemon-ui'
+
+import { QuickFilterOption } from '~/types'
+
+import { withSelectedOption } from './quickFilterOptions'
+
+export function anyOptionLabel(filterName: string): string {
+ return `Any ${filterName.toLowerCase() || 'items'}`
+}
+
+/**
+ * Keyboard navigation in the searchable select starts at the first visible option. While a search runs,
+ * the "Any" option and a pinned selection that does not match stay hidden, so ArrowDown and Enter pick a
+ * match instead of clearing the filter. A hidden option still lets the trigger show the selected value.
+ */
+export function discoveredSelectOptions(
+ filterName: string,
+ discoveredOptions: QuickFilterOption[],
+ selectedOptionId: string | null,
+ search: string
+): LemonSelectOptionLeaf<string | null>[] {
+ const matchingIds = new Set(discoveredOptions.map((option) => option.id))
+ return [
+ { value: null, label: anyOptionLabel(filterName), hidden: !!search },
+ ...withSelectedOption(discoveredOptions, selectedOptionId).map((option) => ({
+ value: option.id,
+ label: option.label,
+ hidden: !!search && !matchingIds.has(option.id),
+ // Discovered values are raw event data, so keep them out of autocapture and replay
+ className: 'ph-no-capture',
+ })),
+ ]
+}
diff --git a/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.test.ts b/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.test.ts
new file mode 100644
index 000000000000..a83fafad63c2
--- /dev/null
+++ b/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.test.ts
@@ -0,0 +1,56 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { QuickFilterContext, QuickFilterType } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { quickFilterFormLogic } from './quickFilterFormLogic'
+import { quickFiltersLogic } from './quickFiltersLogic'
+
+const context = QuickFilterContext.ErrorTrackingIssueFilters
+
+describe('quickFilterFormLogic', () => {
+ let createdFilterBodies: Record<string, unknown>[]
+
+ beforeEach(() => {
+ createdFilterBodies = []
+ useMocks({
+ get: {
+ '/api/environments/:team_id/quick_filters/': { results: [] },
+ '/api/event/values/': { results: [], refreshing: false },
+ },
+ post: {
+ '/api/environments/:team_id/quick_filters/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, unknown>
+ createdFilterBodies.push(body)
+ return [201, { id: 'new-filter', created_at: '2024-01-01', updated_at: '2024-01-01', ...body }]
+ },
+ },
+ })
+ initKeaTests()
+ quickFiltersLogic({ context }).mount()
+ })
+
+ it.each([
+ {
+ description: 'saves an auto-discovery filter without options',
+ type: 'auto-discovery' as QuickFilterType,
+ expectedBodies: [{ type: 'auto-discovery', options: [] }],
+ },
+ {
+ description: 'requires option values for a manual filter',
+ type: 'manual-options' as QuickFilterType,
+ expectedBodies: [],
+ },
+ ])('$description', async ({ type, expectedBodies }) => {
+ const logic = quickFilterFormLogic({ context, filter: null })
+ logic.mount()
+
+ await expectLogic(logic, () => {
+ logic.actions.setQuickFilterValues({ name: 'Release', propertyName: '$release', type })
+ logic.actions.submitQuickFilter()
+ }).toFinishAllListeners()
+
+ expect(createdFilterBodies).toEqual(expectedBodies.map((body) => expect.objectContaining(body)))
+ })
+})
diff --git a/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.ts b/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.ts
index bbc57f7d4233..8dbf38a32012 100644
--- a/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.ts
+++ b/frontend/src/lib/components/QuickFilters/quickFilterFormLogic.ts
@@ -6,6 +6,7 @@ import { propertyFilterTypeToPropertyDefinitionType } from 'lib/components/Prope
import { uuid } from 'lib/utils/dom'
import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'
+import { QuickFilterType } from '~/queries/schema/schema-general'
import { PropertyFilterType, PropertyOperator, QuickFilter, QuickFilterOption } from '~/types'
import type { Option } from '../../../models/propertyDefinitionsModel'
@@ -20,6 +21,7 @@ export interface QuickFilterFormLogicProps extends QuickFiltersModalLogicProps {
export interface QuickFilterFormValues {
name: string
propertyName: string
+ type: QuickFilterType
options: QuickFilterOption[]
}
@@ -33,6 +35,8 @@ export const allowedOperators = [
PropertyOperator.IsNotSet,
]
+const emptyOption = (): QuickFilterOption => ({ id: uuid(), value: null, label: '', operator: PropertyOperator.Exact })
+
const trimValue = (value: string | string[] | null): string | string[] | null => {
if (value === null) {
return null
@@ -64,6 +68,7 @@ export interface quickFilterFormLogicValues {
quickFilterValidationErrors: DeepPartialMap<QuickFilterFormValues, ValidationErrorType>
showQuickFilterErrors: boolean
suggestions: any[]
+ type: QuickFilterType
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -156,6 +161,7 @@ export interface quickFilterFormLogicMeta {
name: (quickFilter: QuickFilterFormValues) => string
propertyName: (quickFilter: QuickFilterFormValues) => string
options: (quickFilter: QuickFilterFormValues) => QuickFilterOption[]
+ type: (quickFilter: QuickFilterFormValues) => QuickFilterType
suggestions: (propertyName: string, propertyOptions: Record<string, Option>) => any[]
}
}
@@ -193,11 +199,12 @@ export const quickFilterFormLogic: LogicWrapper<quickFilterFormLogicType> = kea<
defaults: {
name: props.filter?.name || '',
propertyName: props.filter?.property_name || '',
- options: (props.filter?.options || [
- { id: uuid(), value: null, label: '', operator: PropertyOperator.Exact },
- ]) as QuickFilterOption[],
+ type: props.filter?.type || 'auto-discovery',
+ options: (props.filter?.options?.length
+ ? props.filter.options
+ : [emptyOption()]) as QuickFilterOption[],
} as QuickFilterFormValues,
- errors: ({ name, propertyName, options }) => {
+ errors: ({ name, propertyName, type, options }) => {
const errors: Record<string, string | object | undefined> = {}
if (!name.trim()) {
@@ -208,6 +215,10 @@ export const quickFilterFormLogic: LogicWrapper<quickFilterFormLogicType> = kea<
errors.propertyName = 'Event property is required'
}
+ if (type === 'auto-discovery') {
+ return errors
+ }
+
if (options.length === 0) {
errors.options = 'At least one option is required'
} else {
@@ -240,17 +251,20 @@ export const quickFilterFormLogic: LogicWrapper<quickFilterFormLogicType> = kea<
return errors
},
- submit: async ({ name, propertyName, options }) => {
+ submit: async ({ name, propertyName, type, options }) => {
const payload = {
name: name.trim(),
property_name: propertyName.trim(),
- type: 'manual-options' as const,
- options: options.map((opt: QuickFilterOption) => ({
- id: opt.id,
- value: trimValue(opt.value),
- label: opt.label.trim(),
- operator: opt.operator || PropertyOperator.Exact,
- })),
+ type,
+ options:
+ type === 'auto-discovery'
+ ? []
+ : options.map((opt: QuickFilterOption) => ({
+ id: opt.id,
+ value: trimValue(opt.value),
+ label: opt.label.trim(),
+ operator: opt.operator || PropertyOperator.Exact,
+ })),
}
if (props.filter) {
@@ -270,6 +284,7 @@ export const quickFilterFormLogic: LogicWrapper<quickFilterFormLogicType> = kea<
name: [(s) => [s.quickFilter], (quickFilter: QuickFilterFormValues) => quickFilter.name],
propertyName: [(s) => [s.quickFilter], (quickFilter: QuickFilterFormValues) => quickFilter.propertyName],
options: [(s) => [s.quickFilter], (quickFilter: QuickFilterFormValues) => quickFilter.options],
+ type: [(s) => [s.quickFilter], (quickFilter: QuickFilterFormValues) => quickFilter.type],
suggestions: [
(s) => [s.propertyName, s.propertyOptions],
(
@@ -307,10 +322,7 @@ export const quickFilterFormLogic: LogicWrapper<quickFilterFormLogicType> = kea<
}
},
addOption: () => {
- actions.setQuickFilterValue('options', [
- ...values.options,
- { id: uuid(), value: null, label: '', operator: PropertyOperator.Exact },
- ])
+ actions.setQuickFilterValue('options', [...values.options, emptyOption()])
},
removeOption: ({ index }) => {
actions.setQuickFilterValue(
diff --git a/frontend/src/lib/components/QuickFilters/quickFilterOptions.ts b/frontend/src/lib/components/QuickFilters/quickFilterOptions.ts
new file mode 100644
index 000000000000..23241bb21a9d
--- /dev/null
+++ b/frontend/src/lib/components/QuickFilters/quickFilterOptions.ts
@@ -0,0 +1,36 @@
+import { PropertyOperator, QuickFilter, QuickFilterOption } from '~/types'
+
+// Auto-discovered option ids carry this prefix, so the URL and widget configs can store the value itself.
+// Option ids from the manual form are UUIDs and never start with it. A stale manual id from an old link
+// therefore does not resolve to a value after its filter switches to auto-discovery.
+const DISCOVERED_OPTION_ID_PREFIX = '~'
+
+export function autoDiscoveredOption(value: string): QuickFilterOption {
+ return { id: `${DISCOVERED_OPTION_ID_PREFIX}${value}`, value, label: value, operator: PropertyOperator.Exact }
+}
+
+function discoveredValueFromOptionId(optionId: string): string | null {
+ return optionId.startsWith(DISCOVERED_OPTION_ID_PREFIX) && optionId.length > DISCOVERED_OPTION_ID_PREFIX.length
+ ? optionId.slice(DISCOVERED_OPTION_ID_PREFIX.length)
+ : null
+}
+
+export function resolveQuickFilterOption(
+ filter: Pick<QuickFilter, 'type' | 'options'>,
+ optionId: string
+): QuickFilterOption | null {
+ if (filter.type === 'auto-discovery') {
+ const value = discoveredValueFromOptionId(optionId)
+ return value === null ? null : autoDiscoveredOption(value)
+ }
+ return filter.options.find((option) => option.id === optionId) ?? null
+}
+
+/** Keeps a selected value visible when it is not among the discovered values, for example a value restored from the URL. */
+export function withSelectedOption(options: QuickFilterOption[], selectedOptionId: string | null): QuickFilterOption[] {
+ if (!selectedOptionId || options.some((option) => option.id === selectedOptionId)) {
+ return options
+ }
+ const value = discoveredValueFromOptionId(selectedOptionId)
+ return value === null ? options : [autoDiscoveredOption(value), ...options]
+}
diff --git a/frontend/src/lib/components/QuickFilters/quickFilterValuesLogic.test.ts b/frontend/src/lib/components/QuickFilters/quickFilterValuesLogic.test.ts
new file mode 100644
index 000000000000..641b65a3bb4d
--- /dev/null
+++ b/frontend/src/lib/components/QuickFilters/quickFilterValuesLogic.test.ts
@@ -0,0 +1,125 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { QuickFilterContext } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { quickFilterValuesLogic } from './quickFilterValuesLogic'
+
+const context = QuickFilterContext.ErrorTrackingIssueFilters
+
+const VALUES_BY_KEY: Record<string, string[]> = {
+ $lib: ['web', 'posthog-python'],
+ $browser: ['Chrome', 'Firefox'],
+}
+
+describe('quickFilterValuesLogic', () => {
+ let requests: URLSearchParams[]
+ let failRequests: boolean
+
+ beforeEach(() => {
+ requests = []
+ failRequests = false
+ useMocks({
+ get: {
+ '/api/projects/:team_id/events/values/': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ requests.push(params)
+ if (failRequests) {
+ return [500, { detail: 'error' }]
+ }
+ const search = params.get('value') ?? ''
+ const names = (VALUES_BY_KEY[params.get('key') ?? ''] ?? []).filter((name) =>
+ name.toLowerCase().includes(search.toLowerCase())
+ )
+ return [200, { results: names.map((name) => ({ name })), refreshing: false }]
+ },
+ },
+ })
+ initKeaTests()
+ })
+
+ const valuesOf = (logic: ReturnType<typeof quickFilterValuesLogic.build>): (string | string[] | null)[] =>
+ logic.values.discoveredOptions.map((option) => option.value)
+
+ it('loads each filter on mount without waiting for another', async () => {
+ const libLogic = quickFilterValuesLogic({ context, propertyName: '$lib' })
+ const browserLogic = quickFilterValuesLogic({ context, propertyName: '$browser' })
+ libLogic.mount()
+ browserLogic.mount()
+
+ await expectLogic(libLogic).toDispatchActions(['setValues'])
+ await expectLogic(browserLogic).toDispatchActions(['setValues'])
+
+ expect(valuesOf(libLogic)).toEqual(['web', 'posthog-python'])
+ expect(valuesOf(browserLogic)).toEqual(['Chrome', 'Firefox'])
+ expect(requests.map((params) => params.getAll('event_name'))).toEqual([['$exception'], ['$exception']])
+ })
+
+ it('serves a cleared search from the cache', async () => {
+ const logic = quickFilterValuesLogic({ context, propertyName: '$lib' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['setValues'])
+
+ await expectLogic(logic, () => logic.actions.setSearch('py')).toDispatchActions(['loadValues', 'setValues'])
+ expect(valuesOf(logic)).toEqual(['posthog-python'])
+
+ logic.actions.setSearch('')
+ expect(valuesOf(logic)).toEqual(['web', 'posthog-python'])
+ expect(logic.values.discoveredValuesStatus).toEqual('loaded')
+ expect(requests.map((params) => params.get('value'))).toEqual([null, 'py'])
+ })
+
+ it('shows an error and retries when the dropdown opens again', async () => {
+ failRequests = true
+ const logic = quickFilterValuesLogic({ context, propertyName: '$lib' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['setValuesFailed'])
+ expect(logic.values.discoveredValuesStatus).toEqual('error')
+
+ failRequests = false
+ await expectLogic(logic, () => logic.actions.setSearch('')).toDispatchActions(['loadValues', 'setValues'])
+ expect(logic.values.discoveredValuesStatus).toEqual('loaded')
+ expect(valuesOf(logic)).toEqual(['web', 'posthog-python'])
+ })
+
+ it.each([
+ { description: 'keeps fresh values when the dropdown opens again', minutesLater: 1, expectedRequests: 1 },
+ {
+ description: 'refreshes values older than five minutes when the dropdown opens again',
+ minutesLater: 6,
+ expectedRequests: 2,
+ },
+ ])('$description', async ({ minutesLater, expectedRequests }) => {
+ const now = jest.spyOn(Date, 'now').mockReturnValue(1_000_000)
+ try {
+ const logic = quickFilterValuesLogic({ context, propertyName: '$lib' })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['setValues'])
+
+ now.mockReturnValue(1_000_000 + minutesLater * 60_000)
+ logic.actions.setSearch('')
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(requests).toHaveLength(expectedRequests)
+ expect(logic.values.discoveredValuesStatus).toEqual('loaded')
+ } finally {
+ now.mockRestore()
+ }
+ })
+
+ it('loads once the project loads when mounted before it is known', async () => {
+ projectLogic.mount()
+ projectLogic.actions.loadCurrentProjectSuccess(null)
+ const logic = quickFilterValuesLogic({ context, propertyName: '$lib' })
+ logic.mount()
+ expect(logic.values.discoveredValuesStatus).toEqual('error')
+
+ projectLogic.actions.loadCurrentProjectSuccess({ id: 997, name: 'Test project' } as any)
+ await expectLogic(logic).toDispatchActions(['loadValues', 'setValues'])
+
+ expect(valuesOf(logic)).toEqual(['web', 'posthog-python'])
+ })
+})
diff --git a/frontend/src/lib/components/QuickFilters/quickFilterValuesLogic.ts b/frontend/src/lib/components/QuickFilters/quickFilterValuesLogic.ts
new file mode 100644
index 000000000000..55f3fcb1dfaa
--- /dev/null
+++ b/frontend/src/lib/components/QuickFilters/quickFilterValuesLogic.ts
@@ -0,0 +1,234 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import { eventsValuesRetrieve } from '~/generated/core/api'
+import type { EventPropertyValueApi } from '~/generated/core/api.schemas'
+import { QuickFilterContext } from '~/queries/schema/schema-general'
+import { QuickFilterOption } from '~/types'
+
+import { QUICK_FILTER_VALUE_EVENT_NAMES } from './consts'
+import { autoDiscoveredOption } from './quickFilterOptions'
+
+const SEARCH_DEBOUNCE_MS = 200
+// New values keep arriving while a scene stays open, so opening the dropdown refreshes values older than this
+const STALE_AFTER_MS = 5 * 60 * 1000
+
+export type DiscoveredValuesStatus = 'loading' | 'loaded' | 'error'
+
+/** The status line for a discovered-values dropdown, or null when the values need no explanation. */
+export function discoveredValuesMessage(
+ status: DiscoveredValuesStatus,
+ search: string,
+ valueCount: number
+): string | null {
+ if (status === 'loading') {
+ return 'Loading values…'
+ }
+ if (status === 'error') {
+ return "Couldn't load values. Close and reopen the dropdown to try again."
+ }
+ if (valueCount > 0) {
+ return null
+ }
+ return search ? 'No matching values in the last 7 days.' : 'No values found in the last 7 days.'
+}
+
+export interface QuickFilterValuesLogicProps {
+ context: QuickFilterContext
+ propertyName: string
+}
+
+function toValueNames(results: EventPropertyValueApi[]): string[] {
+ const names = results.map((result) => String(result.name))
+ return Array.from(new Set(names.filter((name) => name !== '')))
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface quickFilterValuesLogicValues {
+ currentProjectId: number | null // projectLogic
+ discoveredOptions: QuickFilterOption[]
+ discoveredValuesStatus: DiscoveredValuesStatus
+ failedSearch: string | null
+ fetchedAtBySearch: Record<string, number>
+ search: string
+ valuesBySearch: Record<string, string[]>
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface quickFilterValuesLogicActions {
+ loadCurrentProjectSuccess: (
+ currentProject: null | import('~/types').ProjectType,
+ payload?: any
+ ) => {
+ currentProject: null | import('~/types').ProjectType
+ payload?: any
+ } // projectLogic
+ loadValues: (search: string) => {
+ search: string
+ }
+ setSearch: (search: string) => {
+ search: string
+ }
+ setValues: (
+ search: string,
+ values: string[],
+ fetchedAt?: number
+ ) => {
+ fetchedAt: number
+ search: string
+ values: string[]
+ }
+ setValuesFailed: (search: string) => {
+ search: string
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface quickFilterValuesLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ discoveredOptions: (search: string, valuesBySearch: Record<string, string[]>) => QuickFilterOption[]
+ discoveredValuesStatus: (
+ search: string,
+ valuesBySearch: Record<string, string[]>,
+ failedSearch: string | null
+ ) => DiscoveredValuesStatus
+ }
+}
+
+export type quickFilterValuesLogicType = MakeLogicType<
+ quickFilterValuesLogicValues,
+ quickFilterValuesLogicActions,
+ QuickFilterValuesLogicProps,
+ quickFilterValuesLogicMeta
+>
+
+export const quickFilterValuesLogic: LogicWrapper<quickFilterValuesLogicType> = kea<quickFilterValuesLogicType>([
+ props({} as QuickFilterValuesLogicProps),
+ key((props) => `${props.context}-${props.propertyName}`),
+ path((key) => ['lib', 'components', 'QuickFilters', 'quickFilterValuesLogic', key]),
+
+ connect(() => ({
+ values: [projectLogic, ['currentProjectId']],
+ actions: [projectLogic, ['loadCurrentProjectSuccess']],
+ })),
+
+ actions({
+ setSearch: (search: string) => ({ search }),
+ loadValues: (search: string) => ({ search }),
+ setValues: (search: string, values: string[], fetchedAt: number = Date.now()) => ({
+ search,
+ values,
+ fetchedAt,
+ }),
+ setValuesFailed: (search: string) => ({ search }),
+ }),
+
+ reducers({
+ search: ['', { setSearch: (_, { search }) => search }],
+ valuesBySearch: [
+ {} as Record<string, string[]>,
+ { setValues: (state, { search, values }) => ({ ...state, [search]: values }) },
+ ],
+ fetchedAtBySearch: [
+ {} as Record<string, number>,
+ { setValues: (state, { search, fetchedAt }) => ({ ...state, [search]: fetchedAt }) },
+ ],
+ // Failures are not cached, so opening the dropdown again retries the request.
+ failedSearch: [null as string | null, { loadValues: () => null, setValuesFailed: (_, { search }) => search }],
+ }),
+
+ selectors({
+ discoveredOptions: [
+ (s) => [s.search, s.valuesBySearch],
+ (search: string, valuesBySearch: Record<string, string[]>): QuickFilterOption[] => {
+ if (Object.hasOwn(valuesBySearch, search)) {
+ return valuesBySearch[search].map(autoDiscoveredOption)
+ }
+ // Until the server answers a search, narrow the unfiltered values so the list reacts to typing at once
+ const lowerSearch = search.toLowerCase()
+ return (valuesBySearch[''] ?? [])
+ .filter((value) => value.toLowerCase().includes(lowerSearch))
+ .map(autoDiscoveredOption)
+ },
+ ],
+ discoveredValuesStatus: [
+ (s) => [s.search, s.valuesBySearch, s.failedSearch],
+ (
+ search: string,
+ valuesBySearch: Record<string, string[]>,
+ failedSearch: string | null
+ ): DiscoveredValuesStatus => {
+ if (Object.hasOwn(valuesBySearch, search)) {
+ return 'loaded'
+ }
+ return search === failedSearch ? 'error' : 'loading'
+ },
+ ],
+ }),
+
+ listeners(({ actions, values, props, cache }) => ({
+ setSearch: async ({ search }, breakpoint) => {
+ const fetchedAt = values.fetchedAtBySearch[search]
+ if (fetchedAt !== undefined && Date.now() - fetchedAt < STALE_AFTER_MS) {
+ return
+ }
+ if (search) {
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ }
+ actions.loadValues(search)
+ },
+ loadValues: async ({ search }) => {
+ if (!values.currentProjectId) {
+ // Report a failure rather than stay in 'loading'. The project load or a reopened dropdown retries it.
+ actions.setValuesFailed(search)
+ return
+ }
+ cache.pendingSearches ??= new Set<string>()
+ if (cache.pendingSearches.has(search)) {
+ return
+ }
+ cache.pendingSearches.add(search)
+ try {
+ const response = await eventsValuesRetrieve(String(values.currentProjectId), {
+ key: props.propertyName,
+ event_name: QUICK_FILTER_VALUE_EVENT_NAMES[props.context],
+ ...(search ? { value: search } : {}),
+ })
+ if (!cache.disposables.isDisposed) {
+ actions.setValues(search, toValueNames(response.results))
+ }
+ } catch {
+ if (!cache.disposables.isDisposed) {
+ actions.setValuesFailed(search)
+ }
+ } finally {
+ cache.pendingSearches.delete(search)
+ }
+ },
+ loadCurrentProjectSuccess: () => {
+ if (!Object.hasOwn(values.valuesBySearch, values.search)) {
+ actions.loadValues(values.search)
+ }
+ },
+ })),
+
+ // Load before the dropdown opens, so the values are ready when the user clicks
+ afterMount(({ actions }) => {
+ actions.loadValues('')
+ }),
+])
diff --git a/frontend/src/lib/components/QuickFilters/quickFiltersSectionLogic.test.ts b/frontend/src/lib/components/QuickFilters/quickFiltersSectionLogic.test.ts
index 9a7f83194de2..0da884f671c2 100644
--- a/frontend/src/lib/components/QuickFilters/quickFiltersSectionLogic.test.ts
+++ b/frontend/src/lib/components/QuickFilters/quickFiltersSectionLogic.test.ts
@@ -1,11 +1,14 @@
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { useMocks } from '~/mocks/jest'
import { QuickFilterContext } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { PropertyOperator, QuickFilter, QuickFilterOption } from '~/types'
+import { QuickFiltersEvents } from './consts'
+import { autoDiscoveredOption } from './quickFilterOptions'
import { quickFiltersLogic } from './quickFiltersLogic'
import { quickFiltersSectionLogic } from './quickFiltersSectionLogic'
@@ -52,8 +55,26 @@ const mockQuickFilters: QuickFilter[] = [
created_at: '2024-01-01',
updated_at: '2024-01-01',
},
+ {
+ id: 'filter-4',
+ name: 'Release',
+ property_name: '$release',
+ type: 'auto-discovery',
+ options: [],
+ contexts: [QuickFilterContext.ErrorTrackingIssueFilters],
+ created_at: '2024-01-01',
+ updated_at: '2024-01-01',
+ },
]
+const autoDiscoveredSelection = (value: string): Record<string, unknown> => ({
+ filterId: 'filter-4',
+ propertyName: '$release',
+ optionId: `~${value}`,
+ value,
+ operator: PropertyOperator.Exact,
+})
+
describe('quickFiltersSectionLogic', () => {
let logic: ReturnType<typeof quickFiltersSectionLogic.build>
@@ -122,6 +143,39 @@ describe('quickFiltersSectionLogic', () => {
})
})
+ describe('selection analytics', () => {
+ it.each([
+ {
+ description: 'sends the label and value of a manual option',
+ filter: mockQuickFilters[0],
+ option: mockOption1,
+ expectedValues: { label: 'Production', value: 'production' },
+ },
+ {
+ description: 'leaves out an auto-discovered value, which is raw event data',
+ filter: mockQuickFilters[3],
+ option: autoDiscoveredOption('v1'),
+ expectedValues: {},
+ },
+ ])('$description', async ({ filter, option, expectedValues }) => {
+ await expectLogic(
+ quickFiltersLogic({ context: QuickFilterContext.ErrorTrackingIssueFilters })
+ ).toDispatchActions(['loadQuickFiltersSuccess'])
+ const capture = jest.spyOn(posthog, 'capture').mockReturnValue(undefined)
+
+ logic.actions.setQuickFilterValue(filter.id, filter.property_name, option)
+
+ expect(capture).toHaveBeenCalledWith(QuickFiltersEvents.QuickFilterSelected, {
+ name: filter.name,
+ property_name: filter.property_name,
+ filter_type: filter.type,
+ context: QuickFilterContext.ErrorTrackingIssueFilters,
+ ...expectedValues,
+ })
+ capture.mockRestore()
+ })
+ })
+
describe('URL serialization round-trip', () => {
it.each([
{
@@ -173,7 +227,12 @@ describe('quickFiltersSectionLogic', () => {
operator: PropertyOperator.Exact,
},
},
- expectedParam: 'filter-1:opt:with:colons',
+ expectedParam: 'filter-1:opt%3Awith%3Acolons',
+ },
+ {
+ description: 'auto-discovered values containing separators are encoded',
+ selections: { 'filter-4': autoDiscoveredSelection('v1,2:beta') },
+ expectedParam: 'filter-4:~v1%2C2%3Abeta',
},
])('$description', async ({ selections, expectedParam }) => {
await expectLogic(logic, () => {
@@ -265,6 +324,14 @@ describe('quickFiltersSectionLogic', () => {
})
})
+ it('restores auto-discovered values that no option lists', async () => {
+ await mountWithUrl(`filter-4:${encodeURIComponent('~v1,2:beta')}`)
+
+ expectLogic(logic).toMatchValues({
+ selectedQuickFilters: { 'filter-4': autoDiscoveredSelection('v1,2:beta') },
+ })
+ })
+
it('ignores unknown filter IDs in URL', async () => {
await mountWithUrl('nonexistent:opt-1')
@@ -273,8 +340,14 @@ describe('quickFiltersSectionLogic', () => {
})
})
- it('ignores unknown option IDs in URL', async () => {
- await mountWithUrl('filter-1:nonexistent')
+ it.each([
+ { description: 'ignores unknown option IDs in URL', param: 'filter-1:nonexistent' },
+ {
+ description: 'ignores a manual option ID from an old link on an auto-discovery filter',
+ param: 'filter-4:opt-1',
+ },
+ ])('$description', async ({ param }) => {
+ await mountWithUrl(param)
expectLogic(logic).toMatchValues({
selectedQuickFilters: {},
@@ -326,6 +399,43 @@ describe('quickFiltersSectionLogic', () => {
})
})
+ it.each([
+ {
+ description: 'keeps an auto-discovered selection when the filter is renamed',
+ selectedFilter: mockQuickFilters[3],
+ selectedOption: autoDiscoveredOption('v1'),
+ updatedFilter: { ...mockQuickFilters[3], name: 'Version' },
+ expectedAction: 'setQuickFilterValue',
+ expectedSelection: { 'filter-4': autoDiscoveredSelection('v1') },
+ },
+ {
+ description: 'clears an auto-discovered selection when the property changes',
+ selectedFilter: mockQuickFilters[3],
+ selectedOption: autoDiscoveredOption('v1'),
+ updatedFilter: { ...mockQuickFilters[3], property_name: '$app_version' },
+ expectedAction: 'clearQuickFilter',
+ expectedSelection: {},
+ },
+ {
+ description: 'clears a manual selection when the filter switches to auto-discovery',
+ selectedFilter: mockQuickFilters[0],
+ selectedOption: mockOption1,
+ updatedFilter: { ...mockQuickFilters[0], type: 'auto-discovery' as const, options: [] },
+ expectedAction: 'clearQuickFilter',
+ expectedSelection: {},
+ },
+ ])(
+ '$description',
+ async ({ selectedFilter, selectedOption, updatedFilter, expectedAction, expectedSelection }) => {
+ await expectLogic(logic, () => {
+ logic.actions.setQuickFilterValue(selectedFilter.id, selectedFilter.property_name, selectedOption)
+ logic.actions.filterUpdated(updatedFilter)
+ })
+ .toDispatchActions(['setQuickFilterValue', 'filterUpdated', expectedAction])
+ .toMatchValues({ selectedQuickFilters: expectedSelection })
+ }
+ )
+
it('clears selection when selected option is removed', async () => {
const updatedFilter: QuickFilter = {
...mockQuickFilters[0],
diff --git a/frontend/src/lib/components/QuickFilters/quickFiltersSectionLogic.ts b/frontend/src/lib/components/QuickFilters/quickFiltersSectionLogic.ts
index aa1542dab73b..ae5ffa536f09 100644
--- a/frontend/src/lib/components/QuickFilters/quickFiltersSectionLogic.ts
+++ b/frontend/src/lib/components/QuickFilters/quickFiltersSectionLogic.ts
@@ -9,18 +9,28 @@ import { PropertyOperator, QuickFilterOption } from '~/types'
import type { QuickFilter } from '../../../types'
import { QuickFiltersEvents } from './consts'
+import { resolveQuickFilterOption } from './quickFilterOptions'
const QUICK_FILTERS_URL_PARAM = 'quick_filters'
const PAIR_SEPARATOR = ':'
const ENTRY_SEPARATOR = ','
+// Auto-discovered option ids are property values, which can contain ':' and ','
function serializeQuickFilters(selectedFilters: Record<string, SelectedQuickFilter>): string {
return Object.entries(selectedFilters)
- .map(([filterId, filter]) => `${filterId}${PAIR_SEPARATOR}${filter.optionId}`)
+ .map(([filterId, filter]) => `${filterId}${PAIR_SEPARATOR}${encodeURIComponent(filter.optionId)}`)
.join(ENTRY_SEPARATOR)
}
+function decodeOptionId(encodedOptionId: string): string | null {
+ try {
+ return decodeURIComponent(encodedOptionId)
+ } catch {
+ return null
+ }
+}
+
function deserializeQuickFilters(param: string): Record<string, string> {
const result: Record<string, string> = {}
if (!param) {
@@ -33,7 +43,7 @@ function deserializeQuickFilters(param: string): Record<string, string> {
continue
}
const filterId = entry.substring(0, separatorIndex)
- const optionId = entry.substring(separatorIndex + PAIR_SEPARATOR.length)
+ const optionId = decodeOptionId(entry.substring(separatorIndex + PAIR_SEPARATOR.length))
if (filterId && optionId) {
result[filterId] = optionId
}
@@ -206,8 +216,11 @@ export const quickFiltersSectionLogic = kea<quickFiltersSectionLogicType>([
return
}
- const updatedOption = filter.options.find((o) => o.id === currentSelection.optionId)
- if (updatedOption) {
+ const updatedOption = resolveQuickFilterOption(filter, currentSelection.optionId)
+ // A discovered value belongs to one property, so it no longer applies after the property changes
+ const selectionStillMatches =
+ filter.type !== 'auto-discovery' || currentSelection.propertyName === filter.property_name
+ if (updatedOption && selectionStillMatches) {
actions.setQuickFilterValue(filter.id, filter.property_name, updatedOption)
} else {
actions.clearQuickFilter(filter.id)
@@ -218,8 +231,9 @@ export const quickFiltersSectionLogic = kea<quickFiltersSectionLogicType>([
posthog.capture(QuickFiltersEvents.QuickFilterSelected, {
name: filter?.name,
property_name: filter?.property_name,
- label: option.label,
- value: option.value,
+ filter_type: filter?.type,
+ // Auto-discovered values are raw event data, which can hold personal data, so only send author-written options
+ ...(filter?.type === 'manual-options' && { label: option.label, value: option.value }),
context: props.context,
})
actions.quickFiltersChanged()
@@ -244,7 +258,7 @@ export const quickFiltersSectionLogic = kea<quickFiltersSectionLogicType>([
return
}
- const option = filter.options.find((o) => o.id === optionId)
+ const option = resolveQuickFilterOption(filter, optionId)
if (!option) {
return
}
diff --git a/frontend/src/lib/lemon-ui/LemonSelect/LemonSearchableSelect.tsx b/frontend/src/lib/lemon-ui/LemonSelect/LemonSearchableSelect.tsx
index 10bce7180fd2..e44792e614f7 100644
--- a/frontend/src/lib/lemon-ui/LemonSelect/LemonSearchableSelect.tsx
+++ b/frontend/src/lib/lemon-ui/LemonSelect/LemonSearchableSelect.tsx
@@ -23,6 +23,10 @@ export interface LemonSearchableSelectPropsBase<T> extends LemonSelectPropsBase<
searchInputDataAttr?: string
/** Message shown when a search term matches no options. */
noResultsMessage?: string
+ /** Called with the search text whenever it changes, including the reset to '' on close. */
+ onSearchChange?: (searchTerm: string) => void
+ /** Set to false when `onSearchChange` loads matching options from a server, so local matching does not hide them. */
+ filterOptionsLocally?: boolean
}
export interface LemonSearchableSelectPropsClearable<T>
@@ -125,6 +129,8 @@ export function LemonSearchableSelect<T extends string | number | boolean | null
searchKeys = ['label'],
searchInputDataAttr = 'lemon-searchable-select-search',
noResultsMessage = 'No results',
+ onSearchChange,
+ filterOptionsLocally = true,
onChange,
onSelect,
...selectProps
@@ -134,8 +140,8 @@ export function LemonSearchableSelect<T extends string | number | boolean | null
const [activeIndex, setActiveIndex] = useState(-1)
const filteredOptions = useMemo(() => {
- return filterOptions(selectProps.options, searchTerm, searchKeys)
- }, [selectProps.options, searchTerm, searchKeys])
+ return filterOptionsLocally ? filterOptions(selectProps.options, searchTerm, searchKeys) : selectProps.options
+ }, [selectProps.options, searchTerm, searchKeys, filterOptionsLocally])
const navigableOptions = useMemo(() => getSearchableLeaves(filteredOptions), [filteredOptions])
const activeOption =
@@ -144,6 +150,7 @@ export function LemonSearchableSelect<T extends string | number | boolean | null
const handleSearchChange = (newSearchTerm: string): void => {
setSearchTerm(newSearchTerm)
setActiveIndex(-1)
+ onSearchChange?.(newSearchTerm)
}
const scrollMenuItemIntoView = (fromElement: HTMLElement, index: number): void => {
@@ -214,8 +221,7 @@ export function LemonSearchableSelect<T extends string | number | boolean | null
const handleChange = (newValue: T | null): void => {
// Cast to `any` because `onChange` is a union type (T vs T | null) and TS can't infer it here.
onChange?.(newValue as any)
- setSearchTerm('')
- setActiveIndex(-1)
+ handleSearchChange('')
}
const handleOnSelect = (newValue: T | null): void => {
@@ -236,8 +242,7 @@ export function LemonSearchableSelect<T extends string | number | boolean | null
// Clear the filter when the dropdown closes, otherwise a stale search term keeps the
// selected option filtered out and the trigger falls back to rendering the raw value.
if (!visible) {
- setSearchTerm('')
- setActiveIndex(-1)
+ handleSearchChange('')
}
},
}}
diff --git a/posthog/api/event.py b/posthog/api/event.py
index 72d724fbc303..c4fe8fe19656 100644
--- a/posthog/api/event.py
+++ b/posthog/api/event.py
@@ -132,6 +132,23 @@ class ElementSerializer(serializers.ModelSerializer):
]
+class EventPropertyValueSerializer(serializers.Serializer):
+ name = serializers.CharField(
+ help_text="A value of the property, always as a string. Booleans come back as 'true' or 'false', "
+ "and objects and lists as JSON."
+ )
+ count = serializers.IntegerField(
+ required=False, help_text="How many times the value occurs, when the lookup counts values."
+ )
+
+
+class EventPropertyValuesResponseSerializer(serializers.Serializer):
+ results = EventPropertyValueSerializer(many=True, help_text="Values of the property that match the request.")
+ refreshing = serializers.BooleanField(
+ help_text="True when these results come from a stale cache and a refresh runs in the background."
+ )
+
+
class UncountedLimitOffsetPagination(LimitOffsetPagination):
"""
the events api works with the default LimitOffsetPagination, but the
@@ -382,6 +399,31 @@ class EventViewSet(
res = ClickhouseEventSerializer(query_result[0], many=False, context=query_context).data
return response.Response(res)
+ @extend_schema(
+ description="List values of an event property from recent events.",
+ parameters=[
+ OpenApiParameter("key", OpenApiTypes.STR, required=True, description="The property to list values for."),
+ OpenApiParameter(
+ "event_name",
+ OpenApiTypes.STR,
+ many=True,
+ # The generated client emits repeated keys only for params the spec marks explode,
+ # and getlist below needs repeated keys, because a comma-joined value matches no event.
+ explode=True,
+ description="Only read values from events with these names. Repeat to pass several. "
+ "Required with a personal API key. Projects that read values from the precomputed "
+ "property values table ignore this filter.",
+ ),
+ OpenApiParameter(
+ "value", OpenApiTypes.STR, description="Only return values that contain this text, ignoring case."
+ ),
+ OpenApiParameter(
+ "is_column", OpenApiTypes.BOOL, description="Read 'key' as an events table column, not a property."
+ ),
+ ],
+ responses=EventPropertyValuesResponseSerializer,
+ extensions={"x-product": "core"},
+ )
@action(methods=["GET"], detail=False, required_scopes=["query:read"])
def values(self, request: request.Request, **kwargs) -> response.Response:
# `/events/values` is hit from every taxonomic property-value picker across the app, so
diff --git a/posthog/api/quick_filters.py b/posthog/api/quick_filters.py
index b21b59662c9a..f2fbc34f7c57 100644
--- a/posthog/api/quick_filters.py
+++ b/posthog/api/quick_filters.py
@@ -8,6 +8,7 @@ from posthog.schema import QuickFilterContext as QuickFilterContextEnum
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.models.quick_filter import QuickFilter, QuickFilterContext
+from posthog.schema_enums import QuickFilterType
class QuickFilterSerializer(serializers.ModelSerializer):
@@ -32,18 +33,38 @@ class QuickFilterSerializer(serializers.ModelSerializer):
"created_at",
"updated_at",
]
+ extra_kwargs = {
+ "type": {
+ "help_text": "'manual-options' shows the options you define. "
+ "'auto-discovery' shows property values found in recent events, and ignores 'options'.",
+ },
+ "options": {
+ "help_text": "Options to show in the dropdown. Each option is an object with 'id', 'value', "
+ "'label', and 'operator'. Required for 'manual-options', stored as an empty list for 'auto-discovery'.",
+ },
+ }
@extend_schema_field(serializers.ListField(child=serializers.CharField()))
def get_contexts(self, obj):
return list(obj.context_memberships.values_list("context", flat=True))
+ def validate(self, attrs):
+ filter_type = attrs.get("type", self.instance.type if self.instance else QuickFilterType.MANUAL_OPTIONS)
+
+ if filter_type == QuickFilterType.AUTO_DISCOVERY:
+ attrs["options"] = []
+ return attrs
+
+ options = attrs.get("options", self.instance.options if self.instance else None)
+ if not options:
+ raise ValidationError({"options": "Options must contain at least one item"})
+
+ return attrs
+
def validate_options(self, value):
if not isinstance(value, list):
raise ValidationError("Options must be a list")
- if len(value) == 0:
- raise ValidationError("Options must contain at least one item")
-
for option in value:
if not isinstance(option, dict):
raise ValidationError(
diff --git a/posthog/api/test/test_quick_filters.py b/posthog/api/test/test_quick_filters.py
index 87ed353e1e74..f5f06565ec5f 100644
--- a/posthog/api/test/test_quick_filters.py
+++ b/posthog/api/test/test_quick_filters.py
@@ -1,9 +1,13 @@
+from typing import Any
+
from posthog.test.base import APIBaseTest
-from django.test import override_settings
+from django.test import SimpleTestCase, override_settings
+from parameterized import parameterized
from rest_framework import status
+from posthog.api.quick_filters import QuickFilterSerializer
from posthog.models.quick_filter import QuickFilter
from products.dashboards.backend.models.dashboard import Dashboard
@@ -151,3 +155,55 @@ class TestQuickFilters(APIBaseTest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+
+MANUAL_OPTION = {"id": "prod", "value": "production", "label": "Production", "operator": "exact"}
+
+
+class TestQuickFilterSerializerOptions(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("auto_discovery_without_options", {"type": "auto-discovery"}, None, True, []),
+ (
+ "auto_discovery_drops_sent_options",
+ {"type": "auto-discovery", "options": [MANUAL_OPTION]},
+ None,
+ True,
+ [],
+ ),
+ ("manual_without_options", {"type": "manual-options"}, None, False, None),
+ ("manual_with_empty_options", {"type": "manual-options", "options": []}, None, False, None),
+ (
+ "manual_with_options",
+ {"type": "manual-options", "options": [MANUAL_OPTION]},
+ None,
+ True,
+ [MANUAL_OPTION],
+ ),
+ ("switch_manual_to_auto", {"type": "auto-discovery"}, "manual-options", True, []),
+ ("switch_auto_to_manual_without_options", {"type": "manual-options"}, "auto-discovery", False, None),
+ ("rename_auto_discovery", {"name": "Renamed"}, "auto-discovery", True, []),
+ ]
+ )
+ def test_options_depend_on_type(
+ self,
+ _name: str,
+ data: dict[str, Any],
+ instance_type: str | None,
+ expected_valid: bool,
+ expected_options: list[dict[str, Any]] | None,
+ ) -> None:
+ if instance_type is None:
+ serializer = QuickFilterSerializer(data={"name": "Environment", "property_name": "$environment", **data})
+ else:
+ instance_options = [] if instance_type == "auto-discovery" else [MANUAL_OPTION]
+ instance = QuickFilter(
+ name="Environment", property_name="$environment", type=instance_type, options=instance_options
+ )
+ serializer = QuickFilterSerializer(instance, data=data, partial=True)
+
+ self.assertEqual(serializer.is_valid(), expected_valid, serializer.errors)
+ if expected_valid:
+ self.assertEqual(serializer.validated_data.get("options"), expected_options)
+ else:
+ self.assertIn("options", serializer.errors)
diff --git a/products/dashboards/frontend/widgets/WidgetPropertyFiltersSection.tsx b/products/dashboards/frontend/widgets/WidgetPropertyFiltersSection.tsx
index c421befbf619..64ead5d75ed3 100644
--- a/products/dashboards/frontend/widgets/WidgetPropertyFiltersSection.tsx
+++ b/products/dashboards/frontend/widgets/WidgetPropertyFiltersSection.tsx
@@ -1,16 +1,19 @@
import { QuickFilterSelector } from 'lib/components/QuickFilters/QuickFilterSelector'
+import type { QuickFilterContext } from '~/queries/schema/schema-general'
import type { QuickFilter } from '~/types'
import type { WidgetFilterConfigEntry, WidgetFilterConfigRecord } from '../generated/widget-configs.zod'
export type WidgetPropertyFiltersSectionProps = {
+ context: QuickFilterContext
filterDefinitions: QuickFilter[]
widgetFilters: WidgetFilterConfigRecord
onWidgetFiltersChange: (widgetFilters: WidgetFilterConfigRecord) => void
}
export function WidgetPropertyFiltersSection({
+ context,
filterDefinitions,
widgetFilters,
onWidgetFiltersChange,
@@ -24,8 +27,8 @@ export function WidgetPropertyFiltersSection({
return (
<QuickFilterSelector
key={filter.id}
- label={filter.name}
- options={filter.options}
+ filter={filter}
+ context={context}
selectedOptionId={selectedOptionId}
onChange={(option) => {
const next = { ...widgetFilters }
diff --git a/products/dashboards/frontend/widgets/error_tracking/ErrorTrackingWidgetTileFilters.tsx b/products/dashboards/frontend/widgets/error_tracking/ErrorTrackingWidgetTileFilters.tsx
index 27d7402ecf7f..1ef7452f3635 100644
--- a/products/dashboards/frontend/widgets/error_tracking/ErrorTrackingWidgetTileFilters.tsx
+++ b/products/dashboards/frontend/widgets/error_tracking/ErrorTrackingWidgetTileFilters.tsx
@@ -127,6 +127,7 @@ export function ErrorTrackingWidgetTileFilters({
)}
{filterDefinitions.length > 0 ? (
<WidgetPropertyFiltersSection
+ context={filterDefinitionsContext}
filterDefinitions={filterDefinitions}
widgetFilters={widgetFilters}
onWidgetFiltersChange={applyWidgetFilters}
diff --git a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidgetTileFilters.tsx b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidgetTileFilters.tsx
index 523ea19b9054..8c4124d91127 100644
--- a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidgetTileFilters.tsx
+++ b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidgetTileFilters.tsx
@@ -196,6 +196,7 @@ export function SessionReplayWidgetTileFilters({
) : null}
{showPropertyFilters && filterDefinitions.length > 0 ? (
<WidgetPropertyFiltersSection
+ context={filterDefinitionsContext}
filterDefinitions={filterDefinitions}
widgetFilters={widgetFilters}
onWidgetFiltersChange={applyWidgetFilters}
diff --git a/products/error_tracking/frontend/components/IssueFilters/DiscoveredValuesQuickFilterSelect.tsx b/products/error_tracking/frontend/components/IssueFilters/DiscoveredValuesQuickFilterSelect.tsx
new file mode 100644
index 000000000000..4d62c752bce1
--- /dev/null
+++ b/products/error_tracking/frontend/components/IssueFilters/DiscoveredValuesQuickFilterSelect.tsx
@@ -0,0 +1,156 @@
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+import { useMemo, useRef } from 'react'
+
+import { IconSearch } from '@posthog/icons'
+
+import { resolveQuickFilterOption, withSelectedOption } from 'lib/components/QuickFilters/quickFilterOptions'
+import { discoveredValuesMessage, quickFilterValuesLogic } from 'lib/components/QuickFilters/quickFilterValuesLogic'
+import {
+ Button,
+ Combobox,
+ ComboboxContent,
+ ComboboxInput,
+ ComboboxItem,
+ ComboboxList,
+ ComboboxTrigger,
+ InputGroupAddon,
+ Text,
+} from 'lib/ui/quill'
+
+import { QuickFilterContext } from '~/queries/schema/schema-general'
+import { QuickFilter, QuickFilterOption } from '~/types'
+
+import { ANY_ITEM, STATUS_ITEM, discoveredValuesComboboxItems } from './discoveredValuesComboboxItems'
+
+export interface DiscoveredValuesQuickFilterSelectProps {
+ filter: QuickFilter
+ context: QuickFilterContext
+ selectedOptionId: string | null
+ onChange: (option: QuickFilterOption | null) => void
+}
+
+export function DiscoveredValuesQuickFilterSelect({
+ filter,
+ context,
+ selectedOptionId,
+ onChange,
+}: DiscoveredValuesQuickFilterSelectProps): JSX.Element {
+ const valuesLogic = quickFilterValuesLogic({ context, propertyName: filter.property_name })
+ const { discoveredOptions, discoveredValuesStatus, search } = useValues(valuesLogic)
+ const { setSearch } = useActions(valuesLogic)
+ const triggerRef = useRef<HTMLButtonElement>(null)
+
+ const anyLabel = `Any ${filter.name.toLowerCase()}`
+ const statusMessage = discoveredValuesMessage(discoveredValuesStatus, search, discoveredOptions.length)
+ const selectedOption = selectedOptionId ? resolveQuickFilterOption(filter, selectedOptionId) : null
+ const selectedLabel = selectedOption?.label ?? anyLabel
+
+ const labelByItem = useMemo(
+ () =>
+ new Map(withSelectedOption(discoveredOptions, selectedOptionId).map((option) => [option.id, option.label])),
+ [discoveredOptions, selectedOptionId]
+ )
+ const items = useMemo(
+ () =>
+ discoveredValuesComboboxItems({
+ search,
+ discoveredOptions,
+ selectedOptionId,
+ showStatus: !!statusMessage,
+ }),
+ [search, discoveredOptions, selectedOptionId, statusMessage]
+ )
+
+ return (
+ <Combobox
+ items={items}
+ value={selectedOption ? selectedOption.id : ANY_ITEM}
+ inputValue={search}
+ // Search runs on the server, so the list shows the returned values unfiltered
+ filter={null}
+ autoHighlight
+ highlightItemOnHover
+ itemToStringLabel={(item: string) => (item === ANY_ITEM ? anyLabel : (labelByItem.get(item) ?? ''))}
+ onInputValueChange={(value: string, { reason }) => {
+ if (reason === 'input-change' || reason === 'input-clear') {
+ setSearch(value)
+ }
+ }}
+ onOpenChange={(open: boolean) => {
+ if (open) {
+ setSearch('')
+ }
+ }}
+ onValueChange={(item: string | null) => {
+ if (item === ANY_ITEM) {
+ onChange(null)
+ return
+ }
+ const option = item === null || item === STATUS_ITEM ? null : resolveQuickFilterOption(filter, item)
+ if (option) {
+ onChange(option)
+ }
+ }}
+ >
+ <ComboboxTrigger
+ ref={triggerRef}
+ render={
+ <Button
+ variant="outline"
+ size="default"
+ left
+ // Discovered values are raw event data, so keep them out of autocapture and replay
+ className={clsx('justify-between gap-3', selectedOption && 'ph-no-capture')}
+ title={selectedLabel}
+ />
+ }
+ aria-label={`${filter.name}: ${selectedLabel}`}
+ >
+ <span className="max-w-60 truncate">{selectedLabel}</span>
+ </ComboboxTrigger>
+ <ComboboxContent
+ anchor={triggerRef}
+ align="start"
+ className="w-64 [&_[data-slot=combobox-input-group-wrapper]]:border-b-0"
+ >
+ <ComboboxInput
+ placeholder="Search values"
+ autoFocus
+ showTrigger={false}
+ className="h-7 [&_input]:text-sm"
+ >
+ <InputGroupAddon align="inline-start">
+ <IconSearch className="size-3" />
+ </InputGroupAddon>
+ </ComboboxInput>
+ <ComboboxList>
+ {(item: string) => {
+ if (item === STATUS_ITEM) {
+ return (
+ <ComboboxItem key={item} value={item} disabled className="text-sm">
+ <Text size="sm" variant="muted" className="italic">
+ {statusMessage}
+ </Text>
+ </ComboboxItem>
+ )
+ }
+ if (item === ANY_ITEM) {
+ return (
+ <ComboboxItem key={item} value={item} className="text-sm">
+ {anyLabel}
+ </ComboboxItem>
+ )
+ }
+ // A plain string child lets ComboboxItem set a title, so a truncated value shows in full on hover
+ return (
+ <ComboboxItem key={item} value={item} className="text-sm ph-no-capture">
+ {labelByItem.get(item) ?? ''}
+ </ComboboxItem>
+ )
+ }}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )
+}
diff --git a/products/error_tracking/frontend/components/IssueFilters/QuickFilters.tsx b/products/error_tracking/frontend/components/IssueFilters/QuickFilters.tsx
index a5d1d8ec6a5a..37441b7132df 100644
--- a/products/error_tracking/frontend/components/IssueFilters/QuickFilters.tsx
+++ b/products/error_tracking/frontend/components/IssueFilters/QuickFilters.tsx
@@ -25,23 +25,18 @@ import { QuickFilterContext } from '~/queries/schema/schema-general'
import { QuickFilter, QuickFilterOption } from '~/types'
import { ERROR_TRACKING_SCENE_LOGIC_KEY } from '../../scenes/ErrorTrackingScene/errorTrackingSceneLogic'
+import { DiscoveredValuesQuickFilterSelect } from './DiscoveredValuesQuickFilterSelect'
const ANY_OPTION = '__any__'
+const CONTEXT = QuickFilterContext.ErrorTrackingIssueFilters
-const QuickFilterSelect = ({ filter }: { filter: QuickFilter }): JSX.Element => {
- const { selectedQuickFilters } = useValues(
- quickFiltersSectionLogic({
- context: QuickFilterContext.ErrorTrackingIssueFilters,
- logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY,
- })
- )
- const { setQuickFilterValue, clearQuickFilter } = useActions(
- quickFiltersSectionLogic({
- context: QuickFilterContext.ErrorTrackingIssueFilters,
- logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY,
- })
- )
- const selectedOptionId = selectedQuickFilters[filter.id]?.optionId ?? ANY_OPTION
+interface QuickFilterSelectProps {
+ filter: QuickFilter
+ selectedOptionId: string | null
+ onChange: (option: QuickFilterOption | null) => void
+}
+
+const ManualQuickFilterSelect = ({ filter, selectedOptionId, onChange }: QuickFilterSelectProps): JSX.Element => {
const items = useMemo(
() => [
{ value: ANY_OPTION, label: `Any ${filter.name.toLowerCase()}` },
@@ -53,16 +48,16 @@ const QuickFilterSelect = ({ filter }: { filter: QuickFilter }): JSX.Element =>
return (
<Select
items={items}
- value={selectedOptionId}
+ value={selectedOptionId ?? ANY_OPTION}
onValueChange={(selectedId) => {
if (selectedId === ANY_OPTION) {
- clearQuickFilter(filter.id)
+ onChange(null)
return
}
const selectedOption = filter.options.find((option: QuickFilterOption) => option.id === selectedId)
if (selectedOption) {
- setQuickFilterValue(filter.id, filter.property_name, selectedOption)
+ onChange(selectedOption)
}
}}
>
@@ -80,8 +75,28 @@ const QuickFilterSelect = ({ filter }: { filter: QuickFilter }): JSX.Element =>
)
}
+const QuickFilterSelect = ({ filter }: { filter: QuickFilter }): JSX.Element => {
+ const sectionLogic = quickFiltersSectionLogic({ context: CONTEXT, logicKey: ERROR_TRACKING_SCENE_LOGIC_KEY })
+ const { selectedQuickFilters } = useValues(sectionLogic)
+ const { setQuickFilterValue, clearQuickFilter } = useActions(sectionLogic)
+ const selectedOptionId = selectedQuickFilters[filter.id]?.optionId ?? null
+ const onChange = (option: QuickFilterOption | null): void =>
+ option ? setQuickFilterValue(filter.id, filter.property_name, option) : clearQuickFilter(filter.id)
+
+ return filter.type === 'auto-discovery' ? (
+ <DiscoveredValuesQuickFilterSelect
+ filter={filter}
+ context={CONTEXT}
+ selectedOptionId={selectedOptionId}
+ onChange={onChange}
+ />
+ ) : (
+ <ManualQuickFilterSelect filter={filter} selectedOptionId={selectedOptionId} onChange={onChange} />
+ )
+}
+
export const ErrorTrackingQuickFilters = (): JSX.Element => {
- const context = QuickFilterContext.ErrorTrackingIssueFilters
+ const context = CONTEXT
const { quickFilters } = useValues(quickFiltersLogic({ context }))
const modalProps = { context }
const { openModal } = useActions(quickFiltersModalLogic(modalProps))
diff --git a/products/error_tracking/frontend/components/IssueFilters/discoveredValuesComboboxItems.test.ts b/products/error_tracking/frontend/components/IssueFilters/discoveredValuesComboboxItems.test.ts
new file mode 100644
index 000000000000..e1340116a6c3
--- /dev/null
+++ b/products/error_tracking/frontend/components/IssueFilters/discoveredValuesComboboxItems.test.ts
@@ -0,0 +1,39 @@
+import { autoDiscoveredOption } from 'lib/components/QuickFilters/quickFilterOptions'
+
+import { ANY_ITEM, STATUS_ITEM, discoveredValuesComboboxItems } from './discoveredValuesComboboxItems'
+
+const web = autoDiscoveredOption('web')
+const python = autoDiscoveredOption('posthog-python')
+
+describe('discoveredValuesComboboxItems', () => {
+ it.each([
+ {
+ description: 'offers the clear control first and pins the selection without a search',
+ search: '',
+ discoveredOptions: [web],
+ selectedOptionId: python.id,
+ showStatus: false,
+ expected: [ANY_ITEM, python.id, web.id],
+ },
+ {
+ description: 'lists only matches while searching, so Enter picks the top match',
+ search: 'we',
+ discoveredOptions: [web],
+ selectedOptionId: python.id,
+ showStatus: false,
+ expected: [web.id],
+ },
+ {
+ description: 'leaves nothing selectable when a search has no matches',
+ search: 'zzz',
+ discoveredOptions: [],
+ selectedOptionId: python.id,
+ showStatus: true,
+ expected: [STATUS_ITEM],
+ },
+ ])('$description', ({ search, discoveredOptions, selectedOptionId, showStatus, expected }) => {
+ expect(discoveredValuesComboboxItems({ search, discoveredOptions, selectedOptionId, showStatus })).toEqual(
+ expected
+ )
+ })
+})
diff --git a/products/error_tracking/frontend/components/IssueFilters/discoveredValuesComboboxItems.ts b/products/error_tracking/frontend/components/IssueFilters/discoveredValuesComboboxItems.ts
new file mode 100644
index 000000000000..e9946bdd0684
--- /dev/null
+++ b/products/error_tracking/frontend/components/IssueFilters/discoveredValuesComboboxItems.ts
@@ -0,0 +1,28 @@
+import { withSelectedOption } from 'lib/components/QuickFilters/quickFilterOptions'
+
+import { QuickFilterOption } from '~/types'
+
+// Auto-discovered option ids start with '~', so a property value never equals a control id
+export const ANY_ITEM = 'control:any'
+export const STATUS_ITEM = 'control:status'
+
+export interface DiscoveredValuesComboboxItemsInput {
+ search: string
+ discoveredOptions: QuickFilterOption[]
+ selectedOptionId: string | null
+ showStatus: boolean
+}
+
+/**
+ * The combobox highlights its first item and Enter picks it. While a search runs, the list therefore holds
+ * only matches, so Enter selects the top match instead of the "Any" control or the pinned selection.
+ */
+export function discoveredValuesComboboxItems({
+ search,
+ discoveredOptions,
+ selectedOptionId,
+ showStatus,
+}: DiscoveredValuesComboboxItemsInput): string[] {
+ const options = search ? discoveredOptions : withSelectedOption(discoveredOptions, selectedOptionId)
+ return [...(search ? [] : [ANY_ITEM]), ...options.map((option) => option.id), ...(showStatus ? [STATUS_ITEM] : [])]
+}
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 6737dc6115d9..fac809012173 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -106,6 +106,9 @@ tools:
emoji-search-suggest-retrieve:
operation: emoji_search_suggest_retrieve
enabled: false
+ events-values-retrieve:
+ operation: events_values_retrieve
+ enabled: false
exports-content-retrieve:
operation: exports_content_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0d4c7ffc7822..ca395078bf9c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -41176,6 +41176,20 @@ export namespace Schemas {
Session: 'session',
} as const;
+ export interface EventPropertyValue {
+ /** A value of the property, always as a string. Booleans come back as 'true' or 'false', and objects and lists as JSON. */
+ name: string;
+ /** How many times the value occurs, when the lookup counts values. */
+ count?: number;
+ }
+
+ export interface EventPropertyValuesResponse {
+ /** Values of the property that match the request. */
+ results: EventPropertyValue[];
+ /** True when these results come from a stale cache and a refresh runs in the background. */
+ refreshing: boolean;
+ }
+
/**
* * `DateTime` - DateTime
* * `String` - String
@@ -68019,7 +68033,12 @@ export namespace Schemas {
name: string;
/** @maxLength 500 */
property_name: string;
+ /** 'manual-options' shows the options you define. 'auto-discovery' shows property values found in recent events, and ignores 'options'.
+ *
+ * * `manual-options` - manual-options
+ * * `auto-discovery` - auto-discovery */
type?: QuickFilterTypeEnum;
+ /** Options to show in the dropdown. Each option is an object with 'id', 'value', 'label', and 'operator'. Required for 'manual-options', stored as an empty list for 'auto-discovery'. */
options?: unknown;
readonly contexts: readonly string[];
readonly created_at: string;
@@ -79617,7 +79636,12 @@ export namespace Schemas {
name?: string;
/** @maxLength 500 */
property_name?: string;
+ /** 'manual-options' shows the options you define. 'auto-discovery' shows property values found in recent events, and ignores 'options'.
+ *
+ * * `manual-options` - manual-options
+ * * `auto-discovery` - auto-discovery */
type?: QuickFilterTypeEnum;
+ /** Options to show in the dropdown. Each option is an object with 'id', 'value', 'label', and 'operator'. Required for 'manual-options', stored as an empty list for 'auto-discovery'. */
options?: unknown;
readonly contexts?: readonly string[];
readonly created_at?: string;
@@ -115530,7 +115554,23 @@ export namespace Schemas {
export type EventsRetrieve200Two = { [key: string]: unknown };
export type EventsValuesRetrieveParams = {
+ /**
+ * Only read values from events with these names. Repeat to pass several. Required with a personal API key. Projects that read values from the precomputed property values table ignore this filter.
+ */
+ event_name?: string[];
format?: EventsValuesRetrieveFormat;
+ /**
+ * Read 'key' as an events table column, not a property.
+ */
+ is_column?: boolean;
+ /**
+ * The property to list values for.
+ */
+ key: string;
+ /**
+ * Only return values that contain this text, ignoring case.
+ */
+ value?: string;
};
export type EventsValuesRetrieveFormat = typeof EventsValuesRetrieveFormat[keyof typeof EventsValuesRetrieveFormat];