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(flags): show a flag overview in the existing definition popover (#124731)

Paul D'Ambra2a04e984dfb3
diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.scss b/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.scss
index b71c7df8005c..77a9f24ca37d 100644
--- a/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.scss
+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.scss
@@ -98,28 +98,6 @@
}
}
- .definition-popover-grid {
- display: grid;
- grid-gap: 0.5rem;
-
- .definition-popover-grid-card {
- display: flex;
- flex-direction: column;
-
- .definition-popover-grid-card-title {
- font-size: 0.6875rem;
- font-weight: 600;
- color: var(--color-text-secondary);
- text-transform: uppercase;
- letter-spacing: 0.05em;
- }
-
- .definition-popover-grid-card-content {
- margin-top: 0.25rem;
- }
- }
- }
-
.definition-popover-edit-form {
display: flex;
flex-direction: column;
diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.tsx b/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.tsx
index 36f017692a11..ea901a6ca9de 100644
--- a/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.tsx
+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopover.tsx
@@ -6,6 +6,8 @@ import { useActions, useValues } from 'kea'
import { IconPin, IconPinFilled } from '@posthog/icons'
import { LemonButton, LemonDivider, ProfilePicture } from '@posthog/lemon-ui'
+import { DefinitionPopoverCard } from 'lib/components/DefinitionPopover/DefinitionPopoverCard'
+import { DefinitionPopoverGrid } from 'lib/components/DefinitionPopover/DefinitionPopoverGrid'
import { DefinitionPopoverState, definitionPopoverLogic } from 'lib/components/DefinitionPopover/definitionPopoverLogic'
import { ImageCarousel } from 'lib/components/ImageCarousel/ImageCarousel'
import { taxonomicFilterLogic } from 'lib/components/TaxonomicFilter/taxonomicFilterLogic'
@@ -231,46 +233,8 @@ function HorizontalLine({ className, label }: { className?: string; label?: stri
)
}
-interface GridProps {
- children: React.ReactNode
- cols?: number
-}
-
-function Grid({ children, cols }: GridProps): JSX.Element {
- return (
- <div
- className="definition-popover-grid"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ gridTemplateColumns: `repeat(${cols}, auto)` }}
- >
- {children}
- </div>
- )
-}
-
-function Section({ children }: GridProps): JSX.Element {
- return <Grid cols={1}>{children}</Grid>
-}
-
-function Card({
- title,
- value,
- alignItems = 'baseline',
-}: {
- title: string | JSX.Element
- value: React.ReactNode | null
- alignItems?: 'baseline' | 'center' | 'end'
-}): JSX.Element {
- return (
- <div
- className="definition-popover-grid-card"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ alignItems }}
- >
- <div className="definition-popover-grid-card-title">{title}</div>
- {value && <div className="definition-popover-grid-card-content">{value}</div>}
- </div>
- )
+function Section({ children }: { children: React.ReactNode }): JSX.Element {
+ return <DefinitionPopoverGrid cols={1}>{children}</DefinitionPopoverGrid>
}
export const DefinitionPopover = {
@@ -281,7 +245,7 @@ export const DefinitionPopover = {
Example,
TimeMeta,
HorizontalLine,
- Grid,
+ Grid: DefinitionPopoverGrid,
Section,
- Card,
+ Card: DefinitionPopoverCard,
}
diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverCard.tsx b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverCard.tsx
new file mode 100644
index 000000000000..863e7b75d3f5
--- /dev/null
+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverCard.tsx
@@ -0,0 +1,20 @@
+export function DefinitionPopoverCard({
+ title,
+ value,
+ alignItems = 'baseline',
+}: {
+ title: string | JSX.Element
+ value: React.ReactNode | null
+ alignItems?: 'baseline' | 'center' | 'end'
+}): JSX.Element {
+ return (
+ <div
+ className="definition-popover-grid-card"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ alignItems }}
+ >
+ <div className="definition-popover-grid-card-title">{title}</div>
+ {value && <div className="definition-popover-grid-card-content">{value}</div>}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
index b8d3bfeed8bf..0ce45fa1ce79 100644
--- a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverContents.tsx
@@ -9,6 +9,8 @@ import { ActionPopoverInfo } from 'lib/components/DefinitionPopover/ActionPopove
import { CohortPopoverInfo } from 'lib/components/DefinitionPopover/CohortPopoverInfo'
import { DefinitionPopover } from 'lib/components/DefinitionPopover/DefinitionPopover'
import { DefinitionPopoverState, definitionPopoverLogic } from 'lib/components/DefinitionPopover/definitionPopoverLogic'
+import { LazyFeatureFlagPopoverInfo } from 'lib/components/DefinitionPopover/LazyFeatureFlagPopoverInfo'
+import { featureFlagKeyFromProperty } from 'lib/components/DefinitionPopover/utils'
import { FlagCalledMoveNotice } from 'lib/components/FlagCalledMoveNotice/FlagCalledMoveNotice'
import { ObjectTags } from 'lib/components/ObjectTags/ObjectTags'
import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
@@ -248,6 +250,8 @@ export function DefinitionView({
if (isProperty) {
const _definition = definition as PropertyDefinition
+ const flagKey =
+ type === TaxonomicFilterGroupType.EventFeatureFlags ? featureFlagKeyFromProperty(_definition.name) : null
return (
<>
@@ -261,9 +265,13 @@ export function DefinitionView({
</Tooltip>
</div>
)}
- <DefinitionPopover.Grid cols={2}>
- <DefinitionPopover.Card title="Property Type" value={_definition.property_type ?? '-'} />
- </DefinitionPopover.Grid>
+ {flagKey ? (
+ <LazyFeatureFlagPopoverInfo flagKey={flagKey} />
+ ) : (
+ <DefinitionPopover.Grid cols={2}>
+ <DefinitionPopover.Card title="Property Type" value={_definition.property_type ?? '-'} />
+ </DefinitionPopover.Grid>
+ )}
{hasSentAs ? (
<>
<DefinitionPopover.HorizontalLine />
diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverGrid.scss b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverGrid.scss
new file mode 100644
index 000000000000..84994bef3981
--- /dev/null
+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverGrid.scss
@@ -0,0 +1,21 @@
+.definition-popover-grid {
+ display: grid;
+ grid-gap: 0.5rem;
+
+ .definition-popover-grid-card {
+ display: flex;
+ flex-direction: column;
+
+ .definition-popover-grid-card-title {
+ font-size: 0.6875rem;
+ font-weight: 600;
+ color: var(--color-text-secondary);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ }
+
+ .definition-popover-grid-card-content {
+ margin-top: 0.25rem;
+ }
+ }
+}
diff --git a/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverGrid.tsx b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverGrid.tsx
new file mode 100644
index 000000000000..65782539bfff
--- /dev/null
+++ b/frontend/src/lib/components/DefinitionPopover/DefinitionPopoverGrid.tsx
@@ -0,0 +1,18 @@
+import './DefinitionPopoverGrid.scss'
+
+interface GridProps {
+ children: React.ReactNode
+ cols?: number
+}
+
+export function DefinitionPopoverGrid({ children, cols }: GridProps): JSX.Element {
+ return (
+ <div
+ className="definition-popover-grid"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ gridTemplateColumns: `repeat(${cols}, auto)` }}
+ >
+ {children}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/DefinitionPopover/FeatureFlagPopoverInfo.tsx b/frontend/src/lib/components/DefinitionPopover/FeatureFlagPopoverInfo.tsx
new file mode 100644
index 000000000000..3675d292f9b5
--- /dev/null
+++ b/frontend/src/lib/components/DefinitionPopover/FeatureFlagPopoverInfo.tsx
@@ -0,0 +1,50 @@
+import { useValues } from 'kea'
+
+import { Spinner } from '@posthog/lemon-ui'
+
+import { DefinitionPopoverCard } from 'lib/components/DefinitionPopover/DefinitionPopoverCard'
+import { DefinitionPopoverGrid } from 'lib/components/DefinitionPopover/DefinitionPopoverGrid'
+import { pluralize } from 'lib/utils/strings'
+
+import { featureFlagSummaryLogic } from 'products/feature_flags/frontend/featureFlagSummaryLogic'
+
+export function FeatureFlagPopoverInfo({ flagKey }: { flagKey: string }): JSX.Element {
+ const { summary, flagLoading, flagLoadFailed } = useValues(featureFlagSummaryLogic({ flagKey }))
+
+ if (flagLoading) {
+ return <Spinner />
+ }
+ if (flagLoadFailed) {
+ return <span className="text-secondary">Could not load this flag. Try again in a moment.</span>
+ }
+ if (!summary) {
+ return <span className="text-secondary">No flag with this key in this project</span>
+ }
+
+ return (
+ <DefinitionPopoverGrid cols={1}>
+ <DefinitionPopoverCard
+ title="Status"
+ value={summary.archived ? 'Archived' : summary.active ? 'Enabled' : 'Disabled'}
+ />
+ {summary.conditionCount !== null && (
+ <DefinitionPopoverCard
+ title="Release conditions"
+ value={pluralize(summary.conditionCount, 'condition', 'conditions')}
+ />
+ )}
+ {summary.variants && (
+ <DefinitionPopoverCard
+ title="Variants"
+ value={
+ summary.variants.length > 0
+ ? summary.variants
+ .map((variant) => `${variant.key} (${variant.rollout_percentage}%)`)
+ .join(', ')
+ : 'None (true or false)'
+ }
+ />
+ )}
+ </DefinitionPopoverGrid>
+ )
+}
diff --git a/frontend/src/lib/components/DefinitionPopover/LazyFeatureFlagPopoverInfo.tsx b/frontend/src/lib/components/DefinitionPopover/LazyFeatureFlagPopoverInfo.tsx
new file mode 100644
index 000000000000..a116286e0d88
--- /dev/null
+++ b/frontend/src/lib/components/DefinitionPopover/LazyFeatureFlagPopoverInfo.tsx
@@ -0,0 +1,18 @@
+import { Suspense, lazy } from 'react'
+
+import { Spinner } from '@posthog/lemon-ui'
+
+import { retryImport } from 'lib/utils/retryImport'
+
+// Shared property UI ships on every logged-in page, and the flag lookup only runs inside a popover.
+const FeatureFlagPopoverInfo = lazy(() =>
+ retryImport(() => import('./FeatureFlagPopoverInfo')).then((m) => ({ default: m.FeatureFlagPopoverInfo }))
+)
+
+export function LazyFeatureFlagPopoverInfo({ flagKey }: { flagKey: string }): JSX.Element {
+ return (
+ <Suspense fallback={<Spinner />}>
+ <FeatureFlagPopoverInfo flagKey={flagKey} />
+ </Suspense>
+ )
+}
diff --git a/frontend/src/lib/components/DefinitionPopover/utils.test.ts b/frontend/src/lib/components/DefinitionPopover/utils.test.ts
index 877132dd4d62..222f4b395b96 100644
--- a/frontend/src/lib/components/DefinitionPopover/utils.test.ts
+++ b/frontend/src/lib/components/DefinitionPopover/utils.test.ts
@@ -1,6 +1,6 @@
import { AnyPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
-import { allOperatorsToHumanName, genericOperatorToHumanName } from './utils'
+import { allOperatorsToHumanName, featureFlagKeyFromProperty, genericOperatorToHumanName } from './utils'
describe('DefinitionPopover operator helpers', () => {
describe('genericOperatorToHumanName', () => {
@@ -51,3 +51,15 @@ describe('DefinitionPopover operator helpers', () => {
})
})
})
+
+describe('featureFlagKeyFromProperty', () => {
+ it.each([
+ ['$feature/my-flag', 'my-flag'],
+ ['$feature/', null],
+ ['$feature_enrollment/my-flag', null],
+ ['$browser', null],
+ [undefined, null],
+ ])('maps %s to %s', (propertyKey, expected) => {
+ expect(featureFlagKeyFromProperty(propertyKey)).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/components/DefinitionPopover/utils.ts b/frontend/src/lib/components/DefinitionPopover/utils.ts
index 87f0aa84167f..52b0e70e08a9 100644
--- a/frontend/src/lib/components/DefinitionPopover/utils.ts
+++ b/frontend/src/lib/components/DefinitionPopover/utils.ts
@@ -88,3 +88,13 @@ export function getSingularType(type: TaxonomicFilterGroupType): string {
return 'definition'
}
}
+
+const FEATURE_FLAG_PROPERTY_PREFIX = '$feature/'
+
+/** The flag key behind a `$feature/<key>` property, or null for any other property. */
+export function featureFlagKeyFromProperty(propertyKey: unknown): string | null {
+ if (typeof propertyKey !== 'string' || !propertyKey.startsWith(FEATURE_FLAG_PROPERTY_PREFIX)) {
+ return null
+ }
+ return propertyKey.slice(FEATURE_FLAG_PROPERTY_PREFIX.length) || null
+}
diff --git a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.flagTooltip.test.tsx b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.flagTooltip.test.tsx
new file mode 100644
index 000000000000..6396d62e83de
--- /dev/null
+++ b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.flagTooltip.test.tsx
@@ -0,0 +1,53 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { Provider } from 'kea'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { PropertyFilterType, PropertyOperator } from '~/types'
+
+import { TaxonomicFilterGroupType } from '../../TaxonomicFilter/types'
+import { PropertyFilters } from '../PropertyFilters'
+
+describe('TaxonomicPropertyFilter flag tooltip', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('shows the flag overview in the tooltip of a flag filter', async () => {
+ initKeaTests()
+ useMocks({
+ get: {
+ '/api/projects/:team_id/feature_flags/': {
+ count: 1,
+ results: [{ key: 'my-flag', active: true, filters: { groups: [] } }],
+ },
+ },
+ })
+ render(
+ <Provider>
+ <PropertyFilters
+ pageKey="flag-tooltip-test"
+ propertyFilters={[
+ {
+ type: PropertyFilterType.Event,
+ key: '$feature/my-flag',
+ value: 'test',
+ operator: PropertyOperator.Exact,
+ },
+ ]}
+ onChange={jest.fn()}
+ disablePopover
+ taxonomicGroupTypes={[TaxonomicFilterGroupType.EventProperties]}
+ />
+ </Provider>
+ )
+
+ const button = screen.getByLabelText('Feature: my-flag').closest('button')!
+ await userEvent.hover(button)
+
+ expect(await screen.findByText('Enabled', {}, { timeout: 3000 })).toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
index c81bbcb6572c..dc6cc9bba1f5 100644
--- a/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/TaxonomicPropertyFilter.tsx
@@ -7,6 +7,8 @@ import { useId } from 'react'
import { IconPlusSmall, IconWarning } from '@posthog/icons'
import { LemonButton, LemonDropdown, Link } from '@posthog/lemon-ui'
+import { LazyFeatureFlagPopoverInfo } from 'lib/components/DefinitionPopover/LazyFeatureFlagPopoverInfo'
+import { featureFlagKeyFromProperty } from 'lib/components/DefinitionPopover/utils'
import { OperatorValueSelect } from 'lib/components/PropertyFilters/components/OperatorValueSelect'
import { PropertyFilterInternalProps } from 'lib/components/PropertyFilters/types'
import {
@@ -129,6 +131,7 @@ export function TaxonomicPropertyFilter({
// A group row has no key, operator or value, so everything below it reads the leaf filter only.
const nestedGroup = isPropertyGroupFilterLike(row) ? row : undefined
const filter = isPropertyGroupFilterLike(row) ? null : row
+ const flagKey = featureFlagKeyFromProperty(filter?.key)
const valuePresent = !!nestedGroup || filter?.type === 'cohort' || !!filter?.key
const showInitialSearchInline =
!disablePopover &&
@@ -321,6 +324,11 @@ export function TaxonomicPropertyFilter({
tooltip={
<>
{cohortLabel ?? nestedGroupLabel ?? filterContent ?? (addText || 'Add filter')}
+ {flagKey && (
+ <div className="mt-2">
+ <LazyFeatureFlagPopoverInfo flagKey={flagKey} />
+ </div>
+ )}
{addFilterDocLink && (
<>
<br />
diff --git a/frontend/src/lib/components/PropertyKeyInfo.test.tsx b/frontend/src/lib/components/PropertyKeyInfo.test.tsx
index 30c6a10ef97f..3ac17b6e56e3 100644
--- a/frontend/src/lib/components/PropertyKeyInfo.test.tsx
+++ b/frontend/src/lib/components/PropertyKeyInfo.test.tsx
@@ -2,6 +2,9 @@ import '@testing-library/jest-dom'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
import { PropertyKeyInfo } from './PropertyKeyInfo'
import { TaxonomicFilterGroupType } from './TaxonomicFilter/types'
@@ -32,6 +35,13 @@ describe('PropertyKeyInfo', () => {
})
expect(overlayText).toBeInTheDocument()
+
+ // Unmount and flush under fake timers, or React's scheduler waits for a timer that never fires,
+ // and later lazy components in this file never resolve.
+ cleanup()
+ act(() => {
+ jest.runOnlyPendingTimers()
+ })
})
it('does not run the onClick of a wrapping element when the overlay is clicked', () => {
@@ -42,4 +52,47 @@ describe('PropertyKeyInfo', () => {
expect(onWrapperClick).not.toHaveBeenCalled()
})
+
+ test.each([
+ [
+ 'shows Archived rather than Disabled for an archived flag',
+ [{ key: 'my-flag', active: false, archived: true, filters: { groups: [] } }],
+ ['Archived', 'Release conditions'],
+ ['Disabled'],
+ ],
+ [
+ 'hides conditions and variants for a flag config it cannot read',
+ [{ key: 'my-flag', active: true, archived: false, filters: { version: 2, rules: [] } }],
+ ['Enabled'],
+ ['Release conditions', 'Variants'],
+ ],
+ ['says so when no flag has the key', [], ['No flag with this key in this project'], ['Status']],
+ [
+ 'says the lookup failed when the request fails',
+ null,
+ ['Could not load this flag. Try again in a moment.'],
+ ['No flag with this key in this project'],
+ ],
+ ])('flag overview %s', async (_name, flags, shown, hidden) => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/feature_flags/': ({ request }) => {
+ if (!flags) {
+ return [500, {}]
+ }
+ const wantsArchived = new URL(request.url).searchParams.get('archived') === 'true'
+ const results = flags.filter((flag) => flag.archived === wantsArchived)
+ return [200, { count: results.length, results }]
+ },
+ },
+ })
+ initKeaTests()
+ render(<PropertyKeyInfo value="$feature/my-flag" type={TaxonomicFilterGroupType.EventProperties} />)
+ fireEvent.mouseEnter(screen.getByLabelText('Feature: my-flag'))
+
+ expect(await screen.findByText(shown[0], {}, { timeout: 3000 })).toBeInTheDocument()
+ for (const text of [...shown, ...hidden]) {
+ expect(!!screen.queryByText(text)).toBe(shown.includes(text))
+ }
+ })
})
diff --git a/frontend/src/lib/components/PropertyKeyInfo.tsx b/frontend/src/lib/components/PropertyKeyInfo.tsx
index 6a3fc43a1158..70912db6c14e 100644
--- a/frontend/src/lib/components/PropertyKeyInfo.tsx
+++ b/frontend/src/lib/components/PropertyKeyInfo.tsx
@@ -7,6 +7,8 @@ import React, { useState } from 'react'
import { LemonDivider, TooltipProps } from '@posthog/lemon-ui'
import { Logomark } from 'lib/brand'
+import { LazyFeatureFlagPopoverInfo } from 'lib/components/DefinitionPopover/LazyFeatureFlagPopoverInfo'
+import { featureFlagKeyFromProperty } from 'lib/components/DefinitionPopover/utils'
import { FlagCalledMoveNotice } from 'lib/components/FlagCalledMoveNotice/FlagCalledMoveNotice'
import { Popover } from 'lib/lemon-ui/Popover'
import { pluralize } from 'lib/utils/strings'
@@ -59,6 +61,8 @@ const PropertyKeyInfoBase = React.forwardRef<HTMLSpanElement, PropertyKeyInfoPro
const valueDisplayText = displayText || ((coreDefinition ? coreDefinition.label : value)?.trim() ?? '')
const valueDisplayElement = valueDisplayText === '' ? <i>(empty string)</i> : valueDisplayText
+ const flagKey = featureFlagKeyFromProperty(value)
+
const recognizedSource: PropertySourceId | null =
getExternalPropertySource(value)?.id ?? (coreDefinition || value.startsWith('$') ? 'posthog' : null)
@@ -106,6 +110,13 @@ const PropertyKeyInfoBase = React.forwardRef<HTMLSpanElement, PropertyKeyInfoPro
</>
) : null}
+ {flagKey && (
+ <>
+ <LemonDivider className="my-3" />
+ <LazyFeatureFlagPopoverInfo flagKey={flagKey} />
+ </>
+ )}
+
{!coreDefinition.virtual && (
<>
<LemonDivider className="my-3" />
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index 87aca80b8a2a..6710e2ad09ca 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -110,6 +110,7 @@ import {
reloadIfStaleRowVersion,
rowVersionToken,
} from 'products/feature_flags/frontend/featureFlagConfigFormat'
+import { forgetFlagLookup } from 'products/feature_flags/frontend/featureFlagSummaryLogic'
import { TEMPLATE_NAMES } from 'products/feature_flags/frontend/featureFlagTemplateConstants'
import {
featureFlagsCopyFlagsCreate,
@@ -4511,6 +4512,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
},
saveFeatureFlagSuccess: ({ featureFlag }) => {
delete cache.rollbackReasonAnswer
+ forgetFlagLookup(featureFlag.key)
lemonToast.success(
'Feature flag saved',
liveFlagToastOptions(
diff --git a/frontend/src/toolbar/shared/shims/featureFlagSummaryLogic.ts b/frontend/src/toolbar/shared/shims/featureFlagSummaryLogic.ts
new file mode 100644
index 000000000000..1ac60965b9f9
--- /dev/null
+++ b/frontend/src/toolbar/shared/shims/featureFlagSummaryLogic.ts
@@ -0,0 +1,38 @@
+import { MakeLogicType, kea, key, path, props, reducers } from 'kea'
+
+// Toolbar shim — the flag overview reads the feature flags API, which the toolbar can't reach on
+// customer pages. The toolbar shows PropertyKeyInfo only for event names, never for `$feature/`
+// keys, so the overview never renders here. The shim keeps PropertyKeyInfo out of the app zone.
+export interface FeatureFlagSummaryLogicProps {
+ flagKey: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagSummaryLogicValues {
+ flagLoadFailed: boolean
+ flagLoading: boolean
+ summary: null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagSummaryLogicMeta {
+ key: string
+}
+
+export type featureFlagSummaryLogicType = MakeLogicType<
+ featureFlagSummaryLogicValues,
+ {},
+ FeatureFlagSummaryLogicProps,
+ featureFlagSummaryLogicMeta
+>
+
+export const featureFlagSummaryLogic = kea<featureFlagSummaryLogicType>([
+ props({} as FeatureFlagSummaryLogicProps),
+ key((props) => props.flagKey),
+ path((flagKey) => ['toolbar', 'shims', 'featureFlagSummaryLogic', flagKey]),
+ reducers({
+ flagLoadFailed: [false, {}],
+ flagLoading: [false, {}],
+ summary: [null, {}],
+ }),
+])
diff --git a/frontend/src/toolbar/shared/shims/shims.test.ts b/frontend/src/toolbar/shared/shims/shims.test.ts
index 48fd9f7c94c3..ddf3c0086913 100644
--- a/frontend/src/toolbar/shared/shims/shims.test.ts
+++ b/frontend/src/toolbar/shared/shims/shims.test.ts
@@ -3,6 +3,7 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
import { featureFlagLogic, getFeatureFlagPayload } from './featureFlagLogic'
+import { featureFlagSummaryLogic } from './featureFlagSummaryLogic'
import { membersLogic } from './membersLogic'
import { sceneLogic } from './sceneLogic'
import { surveyQuestionLabelsLogic } from './surveyQuestionLabelsLogic'
@@ -22,6 +23,11 @@ describe('toolbar shims', () => {
['teamLogic', teamLogic, { currentTeam: null, timezone: 'UTC', weekStartDay: 0 }],
['featureFlagLogic', featureFlagLogic, { featureFlags: {} }],
['surveyQuestionLabelsLogic', surveyQuestionLabelsLogic, { surveyQuestionLabels: {} }],
+ [
+ 'featureFlagSummaryLogic',
+ featureFlagSummaryLogic({ flagKey: 'my-flag' }),
+ { summary: null, flagLoading: false, flagLoadFailed: false },
+ ],
])('%s provides expected defaults', (_name, logic, expected) => {
logic.mount()
expectLogic(logic).toMatchValues(expected)
@@ -56,6 +62,7 @@ describe('toolbar shims', () => {
teamLogic.mount()
featureFlagLogic.mount()
surveyQuestionLabelsLogic.mount()
+ featureFlagSummaryLogic({ flagKey: 'my-flag' }).mount()
expect(fetchSpy).not.toHaveBeenCalled()
})
diff --git a/frontend/toolbar-config.mjs b/frontend/toolbar-config.mjs
index cccb23caed9b..71dbda2ff97d 100644
--- a/frontend/toolbar-config.mjs
+++ b/frontend/toolbar-config.mjs
@@ -30,6 +30,9 @@ const shimmedModules = {
// Survey question labels load from an authenticated endpoint the toolbar can't reach, so
// the shim keeps its shared consumers (PropertyKeyInfo, taxonomy helpers) out of the app zone.
'scenes/surveys/surveyQuestionLabelsLogic': 'src/toolbar/shared/shims/surveyQuestionLabelsLogic.ts',
+ // The flag overview reads the feature flags API, which the toolbar can't reach, so the shim
+ // keeps PropertyKeyInfo out of the app zone.
+ 'products/feature_flags/frontend/featureFlagSummaryLogic': 'src/toolbar/shared/shims/featureFlagSummaryLogic.ts',
// Not a kea shim: the toolbar's parity-tested urls duplicate (see src/toolbar/shared/urls.ts).
// Toolbar code imports it directly; this entry covers lib/ components shared with the
// app (TZLabel, Link, HeatmapEventsPanel), whose scenes/urls import would otherwise pull
diff --git a/products/feature_flags/frontend/featureFlagSummaryLogic.test.ts b/products/feature_flags/frontend/featureFlagSummaryLogic.test.ts
new file mode 100644
index 000000000000..eb9d23a4b45e
--- /dev/null
+++ b/products/feature_flags/frontend/featureFlagSummaryLogic.test.ts
@@ -0,0 +1,113 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { featureFlagSummaryLogic } from './featureFlagSummaryLogic'
+
+type FlagRow = { key: string; active: boolean; archived?: boolean; filters: Record<string, unknown> }
+
+describe('featureFlagSummaryLogic', () => {
+ test.each<[string, FlagRow[], Record<string, unknown> | null]>([
+ [
+ 'summarizes a multivariate flag',
+ [
+ {
+ key: 'my-flag',
+ active: true,
+ filters: {
+ groups: [{ rollout_percentage: 100 }, { rollout_percentage: 50 }],
+ multivariate: {
+ variants: [
+ { key: 'control', rollout_percentage: 50 },
+ { key: 'test', rollout_percentage: 50 },
+ ],
+ },
+ },
+ },
+ ],
+ {
+ active: true,
+ archived: false,
+ conditionCount: 2,
+ variants: [
+ { key: 'control', rollout_percentage: 50 },
+ { key: 'test', rollout_percentage: 50 },
+ ],
+ },
+ ],
+ [
+ 'summarizes a disabled boolean flag',
+ [{ key: 'my-flag', active: false, filters: { groups: [{ rollout_percentage: 100 }] } }],
+ { active: false, archived: false, conditionCount: 1, variants: [] },
+ ],
+ [
+ 'leaves conditions out for a flag config the UI cannot read',
+ [{ key: 'my-flag', active: true, filters: { version: 2, rules: [] } }],
+ { active: true, archived: false, conditionCount: null, variants: null },
+ ],
+ [
+ 'treats a flag with empty filters as a boolean flag with no conditions',
+ [{ key: 'my-flag', active: true, filters: {} }],
+ { active: true, archived: false, conditionCount: 0, variants: [] },
+ ],
+ ['has no summary when no flag has the key', [], null],
+ [
+ 'finds an archived flag when no live flag has the key',
+ [{ key: 'my-flag', active: false, archived: true, filters: { groups: [] } }],
+ { active: false, archived: true, conditionCount: 0, variants: [] },
+ ],
+ [
+ 'picks the flag whose key matches in the same case',
+ [
+ { key: 'MY-FLAG', active: false, filters: { groups: [] } },
+ { key: 'my-flag', active: true, filters: { groups: [{ rollout_percentage: 100 }] } },
+ ],
+ { active: true, archived: false, conditionCount: 1, variants: [] },
+ ],
+ ])('%s', async (_name, results, expectedSummary) => {
+ useMocks({
+ get: {
+ '/api/projects/:team_id/feature_flags/': ({ request }) => {
+ const params = new URL(request.url).searchParams
+ const isLookupForKey = params.get('key') === 'my-flag'
+ const wantsArchived = params.get('archived') === 'true'
+ const matches = results.filter((flag) => !!flag.archived === wantsArchived)
+ return [200, { count: matches.length, results: isLookupForKey ? matches : [] }]
+ },
+ },
+ })
+ initKeaTests()
+ const logic = featureFlagSummaryLogic({ flagKey: 'my-flag' })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ summary: expectedSummary })
+
+ logic.unmount()
+ })
+
+ test.each([
+ ['a found flag', [{ key: 'my-flag', active: true, filters: { groups: [] } }], 1],
+ ['a missing key, after the live and archived lookups', [], 2],
+ ])('reuses a recent lookup for %s when the logic mounts again', async (_name, results, expectedRequests) => {
+ let requests = 0
+ useMocks({
+ get: {
+ '/api/projects/:team_id/feature_flags/': () => {
+ requests++
+ return [200, { count: results.length, results }]
+ },
+ },
+ })
+ initKeaTests()
+
+ for (let mount = 0; mount < 2; mount++) {
+ const logic = featureFlagSummaryLogic({ flagKey: 'my-flag' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.unmount()
+ }
+
+ expect(requests).toBe(expectedRequests)
+ })
+})
diff --git a/products/feature_flags/frontend/featureFlagSummaryLogic.ts b/products/feature_flags/frontend/featureFlagSummaryLogic.ts
new file mode 100644
index 000000000000..61d11d874ca3
--- /dev/null
+++ b/products/feature_flags/frontend/featureFlagSummaryLogic.ts
@@ -0,0 +1,144 @@
+import { MakeLogicType, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { RetainedValues } from 'lib/utils/retainedValues'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { FeatureFlagConfig, MultivariateFlagVariant } from '~/types'
+
+import { isV1FeatureFlagConfig } from './featureFlagConfigFormat'
+import { featureFlagsList } from './generated/api'
+import { FeatureFlagsListArchived, type FeatureFlagApi } from './generated/api.schemas'
+
+const FLAG_LOOKUP_TTL_MS = 60 * 1000
+
+const retainedFlagLookups = new RetainedValues<{ flag: FeatureFlagApi | null }>({
+ maxEntries: 200,
+ ttlMs: FLAG_LOOKUP_TTL_MS,
+})
+
+export function forgetFlagLookup(flagKey: string): void {
+ retainedFlagLookups.delete(flagKey)
+}
+
+export interface FeatureFlagSummaryLogicProps {
+ flagKey: string
+}
+
+export interface FeatureFlagSummary {
+ active: boolean
+ archived: boolean
+ variants: MultivariateFlagVariant[] | null
+ conditionCount: number | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagSummaryLogicValues {
+ currentProjectId: number | null // projectLogic
+ flag: FeatureFlagApi | null
+ flagLoadFailed: boolean
+ flagLoading: boolean
+ summary: FeatureFlagSummary | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagSummaryLogicActions {
+ loadFlag: (_: void) => void
+ loadFlagFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadFlagSuccess: (
+ flag: FeatureFlagApi | null,
+ payload?: void
+ ) => {
+ flag: FeatureFlagApi | null
+ payload?: void
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface featureFlagSummaryLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ summary: (flag: FeatureFlagApi | null) => FeatureFlagSummary | null
+ }
+}
+
+export type featureFlagSummaryLogicType = MakeLogicType<
+ featureFlagSummaryLogicValues,
+ featureFlagSummaryLogicActions,
+ FeatureFlagSummaryLogicProps,
+ featureFlagSummaryLogicMeta
+>
+
+/** A short overview of the flag behind a `$feature/<key>` property, for its definition popover. */
+export const featureFlagSummaryLogic = kea<featureFlagSummaryLogicType>([
+ props({} as FeatureFlagSummaryLogicProps),
+ key((props) => props.flagKey),
+ path((key) => ['products', 'feature_flags', 'frontend', 'featureFlagSummaryLogic', key]),
+ connect(() => ({ values: [projectLogic, ['currentProjectId']] })),
+ loaders(({ props, values }) => ({
+ flag: [
+ null as FeatureFlagApi | null,
+ {
+ loadFlag: async (_: void, breakpoint) => {
+ // A pointer that sweeps across `$feature/` rows mounts this logic for each row it crosses.
+ await breakpoint(300)
+ if (!values.currentProjectId) {
+ return null
+ }
+ const projectId = String(values.currentProjectId)
+ // The API matches the key case-insensitively, but flag keys that differ only by case can both exist.
+ const findFlag = async (archived?: FeatureFlagsListArchived): Promise<FeatureFlagApi | null> =>
+ (await featureFlagsList(projectId, { key: props.flagKey, archived })).results.find(
+ (flag) => flag.key === props.flagKey
+ ) ?? null
+ // The list leaves out archived flags unless asked, and old events can still carry their key.
+ const flag = (await findFlag()) ?? (await findFlag(FeatureFlagsListArchived.True))
+ retainedFlagLookups.set(props.flagKey, { flag })
+ return flag
+ },
+ },
+ ],
+ })),
+ reducers({
+ flagLoadFailed: [
+ false,
+ {
+ loadFlag: () => false,
+ loadFlagSuccess: () => false,
+ loadFlagFailure: () => true,
+ },
+ ],
+ }),
+ selectors({
+ summary: [
+ (s) => [s.flag],
+ (flag: FeatureFlagApi | null): FeatureFlagSummary | null => {
+ if (!flag) {
+ return null
+ }
+ const filters = flag.filters as FeatureFlagConfig | undefined
+ const isV1 = !!filters && isV1FeatureFlagConfig(filters)
+ return {
+ active: !!flag.active,
+ archived: !!flag.archived,
+ variants: isV1 ? (filters.multivariate?.variants ?? []) : null,
+ conditionCount: isV1 ? (filters.groups?.length ?? 0) : null,
+ }
+ },
+ ],
+ }),
+ afterMount(({ actions, props }) => {
+ const retained = retainedFlagLookups.get(props.flagKey)
+ if (retained) {
+ actions.loadFlagSuccess(retained.flag)
+ } else {
+ actions.loadFlag()
+ }
+ }),
+])