:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat: add feature flag testing UI with condition analysis (#55298)
Gustavo H. Strassburgerb0f41e293523
diff --git a/bin/start-rust-service b/bin/start-rust-serviceindex 505565eec098..3c259cfa4129 100755--- a/bin/start-rust-service+++ b/bin/start-rust-service@@ -163,6 +163,7 @@ case "$RS_SVC" inexport ADDRESS=0.0.0.0:3001export DEBUG=1export ALLOW_INTERNAL_IPS=${ALLOW_INTERNAL_IPS:-true}+ export INTERNAL_REQUEST_TOKEN=${INTERNAL_REQUEST_TOKEN:-dev-internal-token};;hypercache-server)diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex dd5059d6800b..34020e757c3f 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -495,6 +495,7 @@ services:FLAGS_REDIS_URL: 'redis://redis7:6379/1'FLAGS_REDIS_ENABLED: 'false' # Warming but not reading yetREDIS_COMPRESSION_ENABLED: 'true'+ INTERNAL_REQUEST_TOKEN: 'dev-internal-token'# Temporal containerselasticsearch:diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex fa1a8cf6c212..b450a9cc5be7 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1815,7 +1815,7 @@ snapshots:filters-taxonomic-filter-headless--properties--dark:hash: v1.k794b7964.4ee695e5751c6f73e9742ab0cfeecf61b5adfe829cf3a0d49ab2877cae8b212f.jPN9l5TDgLRy9NzHenXHCU903UDg8-GdeGpf4PXt7aAfilters-taxonomic-filter-headless--properties--light:- hash: v1.k794b7964.7af6b884e5d826df422db99e4a99d2172f3316561a499dbe386ea098b1fc54a9.rti2DMpqC0WEtd_AtG838vQlgQMHfwjBAR4uLN_HnUk+ hash: v1.k794b7964.bd715b36b456df8730e934366a35faed4556dffa881456db1272e2804047a036.IH74-bf3miZ6nC3E0bqbzIb0km4fBh97_2XubTpcmnsfilters-taxonomic-filter-headless--suggested-filters-with-recents--dark:hash: v1.k794b7964.c3a6cd419610bc486261efa753816547f080f00c838bde0b8720cf12067b3b22.nxBtExiDfJ3USkhV9RY1VPU_U2dGyEYCMFbhvtOcuVsfilters-taxonomic-filter-headless--suggested-filters-with-recents--light:diff --git a/frontend/src/lib/components/PropertiesTable/PropertiesTable.tsx b/frontend/src/lib/components/PropertiesTable/PropertiesTable.tsxindex 41e1b46485df..25220612334c 100644--- a/frontend/src/lib/components/PropertiesTable/PropertiesTable.tsx+++ b/frontend/src/lib/components/PropertiesTable/PropertiesTable.tsx@@ -217,6 +217,8 @@ export interface PropertiesTableProps extends BasePropertyType {useDetectedPropertyType?: booleantableProps?: Partial<LemonTableProps<Record<string, any>>>highlightedKeys?: string[]+ /** Controls the highlight style for highlighted rows. Default: 'default' uses var(--mark), 'subtle' uses a more subtle background. */+ highlightVariant?: 'default' | 'subtle'type: PropertyDefinitionType/*** The container for these properties e.g. the event name of the event the properties are on@@ -239,6 +241,7 @@ export function PropertiesTable({useDetectedPropertyType,tableProps,highlightedKeys,+ highlightVariant = 'default',type,parent,}: PropertiesTableProps): JSX.Element {@@ -587,7 +590,9 @@ export function PropertiesTable({onRow={(record) =>highlightedKeys?.includes(record[0])? {- style: { background: 'var(--mark)' },+ style: {+ background: highlightVariant === 'subtle' ? 'var(--bg-3000)' : 'var(--mark)',+ },}: {}}diff --git a/frontend/src/scenes/feature-flags/FeatureFlag.tsx b/frontend/src/scenes/feature-flags/FeatureFlag.tsxindex 9875646b2ee1..daff6fb4add1 100644--- a/frontend/src/scenes/feature-flags/FeatureFlag.tsx+++ b/frontend/src/scenes/feature-flags/FeatureFlag.tsx@@ -121,6 +121,7 @@ import { FeatureFlagReleaseConditions } from './FeatureFlagReleaseConditions'import FeatureFlagSchedule from './FeatureFlagSchedule'import { FeatureFlagsTab, featureFlagsLogic } from './featureFlagsLogic'import { FeatureFlagStatusIndicator } from './FeatureFlagStatusIndicator'+import { FeatureFlagTestingTab } from './FeatureFlagTestingTab'import { UserFeedbackSection } from './FeatureFlagUserFeedback'import { FeatureFlagVariantsForm, focusVariantKeyField } from './FeatureFlagVariantsForm'import { RecentFeatureFlagInsights } from './RecentFeatureFlagInsightsCard'@@ -276,7 +277,7 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {},] as LemonTab<FeatureFlagsTab>[]- if (featureFlag.key && id) {+ if (id) {tabs.push({label: 'Usage',key: FeatureFlagsTab.USAGE,@@ -331,6 +332,21 @@ export function FeatureFlag({ id }: FeatureFlagLogicProps): JSX.Element {content: <ExperimentsTab featureFlag={featureFlag} />,})+ if (id) {+ tabs.push({+ label: (+ <div className="flex flex-row">+ <div>Testing</div>+ <LemonTag className="ml-2 float-right uppercase" type="primary">+ New+ </LemonTag>+ </div>+ ),+ key: FeatureFlagsTab.TESTING,+ content: <FeatureFlagTestingTab featureFlag={featureFlag} />,+ })+ }+return (<><div className="feature-flag">diff --git a/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsxnew file mode 100644index 000000000000..5e2a823d71ad--- /dev/null+++ b/frontend/src/scenes/feature-flags/FeatureFlagTestingTab.tsx@@ -0,0 +1,371 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonBanner, LemonLabel, LemonCalendarSelectInput } from '@posthog/lemon-ui'++import { PropertiesTable } from 'lib/components/PropertiesTable/PropertiesTable'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'+import type { Dayjs } from 'lib/dayjs'+import { CodeEditor } from 'lib/monaco/CodeEditor'++import type { FeatureFlagType, PersonType } from '~/types'+import { PropertyDefinitionType } from '~/types'++import type { ConditionAnalysis } from './featureFlagTestingLogic'+import { featureFlagTestingLogic } from './featureFlagTestingLogic'++const CONDITION_DISPLAY_STYLES = {+ success: {+ card: 'border-success bg-success-highlight',+ badge: 'bg-success text-success-content',+ },+ info: {+ card: 'border-info bg-info-highlight',+ badge: 'bg-info text-info-content',+ },+ warning: {+ card: 'border-warning bg-warning-highlight',+ badge: 'bg-warning text-warning-content',+ },+ muted: {+ card: 'border-muted bg-bg-light',+ badge: 'bg-muted text-muted-alt',+ },+} as const++export function FeatureFlagTestingTab({ featureFlag }: { featureFlag: FeatureFlagType }): JSX.Element {+ const logic = featureFlagTestingLogic({ flagId: featureFlag.id! })++ const {+ testFormData: formData,+ includeTime,+ testResult: result,+ datePickerOpen,+ datePickerValue,+ testEvaluationLoading: isLoading,+ selectedPerson,+ usedProperties,+ enrichedConditions,+ hasValidPerson,+ errorDisplay,+ } = useValues(logic)++ const {+ setTestFormData,+ setDatePickerOpen,+ setDatePickerValue,+ setSelectedPerson,+ setIncludeTime,+ clearTestForm,+ testFlagEvaluation,+ } = useActions(logic)++ const handleSubmit = (): void => {+ testFlagEvaluation({ flagId: featureFlag.id!, formData })+ }++ return (+ <div className="space-y-6">+ <div>+ <h3 className="font-semibold">Test flag evaluation</h3>+ <p className="text-muted">+ Test how this feature flag evaluates for a specific user, optionally at a historical timestamp.+ Provides detailed explanations of why the flag matched or didn't match.+ </p>+ </div>++ <div className="flex gap-6">+ {/* Left Panel - Form */}+ <div className="flex-1 space-y-4 max-w-md bg-bg-light p-6 rounded-lg border">+ <h4 className="font-semibold">Test parameters</h4>++ {/* User Selection */}+ <div className="space-y-3">+ <LemonLabel>Select person</LemonLabel>+ <TaxonomicPopover+ groupType={TaxonomicFilterGroupType.Persons}+ value={selectedPerson ? selectedPerson.distinct_ids[0] : ''}+ onChange={(_, __, person) => {+ if (person) {+ setSelectedPerson(person as PersonType)+ setTestFormData({+ person_id: person.uuid || '',+ })+ } else {+ setSelectedPerson(null)+ setTestFormData({+ person_id: '',+ })+ }+ }}+ groupTypes={[TaxonomicFilterGroupType.Persons]}+ placeholder="Search for a person by name, email, or ID..."+ allowClear+ fullWidth+ renderValue={() => {+ if (selectedPerson) {+ return (+ <span>+ {selectedPerson.name || selectedPerson.distinct_ids[0] || 'Unknown person'}+ </span>+ )+ }+ return null+ }}+ />+ <p className="text-xs text-muted">+ Search and select a person from your PostHog instance. You can search by name, email, or+ distinct ID.+ </p>++ {selectedPerson && (+ <div className="text-xs text-muted space-y-1 p-2 bg-bg-3000 rounded">+ <div>+ <strong>Person ID:</strong> {formData.person_id || 'Not available'}+ </div>+ <div>+ <strong>Distinct IDs:</strong> {selectedPerson.distinct_ids.slice(0, 3).join(', ')}+ {selectedPerson.distinct_ids.length > 3 &&+ ` (+${selectedPerson.distinct_ids.length - 3} more)`}+ </div>+ </div>+ )}+ </div>++ {/* Optional Timestamp */}+ <div className="space-y-3">+ <LemonLabel>Historical timestamp (optional)</LemonLabel>+ <LemonCalendarSelectInput+ value={datePickerValue}+ format={includeTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD'}+ visible={datePickerOpen}+ showTimeToggle+ onClickOutside={() => setDatePickerOpen(false)}+ onChange={(selectedDate: Dayjs | null) => {+ setDatePickerValue(selectedDate)+ const timestamp = selectedDate ? selectedDate.toISOString() : ''+ setTestFormData({+ timestamp,+ })+ setDatePickerOpen(false)+ }}+ onClose={() => setDatePickerOpen(false)}+ granularity={includeTime ? 'minute' : 'day'}+ onToggleTime={(includeTimeValue) => {+ setIncludeTime(includeTimeValue)+ }}+ clearable={true}+ buttonProps={{+ fullWidth: true,+ onClick: () => setDatePickerOpen(true),+ children: datePickerValue+ ? datePickerValue.format('YYYY-MM-DD HH:mm:ss')+ : 'Select date and time',+ }}+ placeholder="Select date and time"+ />+ <p className="text-xs text-muted">+ If provided, evaluates the flag using person properties and flag conditions as they existed+ at this time.+ </p>+ </div>++ {/* Optional Groups */}+ <div className="space-y-3">+ <LemonLabel>Groups (optional)</LemonLabel>+ <CodeEditor+ className="border"+ language="json"+ value={formData.groups || '{}'}+ onChange={(value) => setTestFormData({ groups: value || '' })}+ height={100}+ options={{+ minimap: { enabled: false },+ scrollBeyondLastLine: false,+ wordWrap: 'on',+ lineNumbers: 'off',+ folding: false,+ lineDecorationsWidth: 0,+ lineNumbersMinChars: 0,+ glyphMargin: false,+ }}+ />+ <p className="text-xs text-muted">+ Groups for group-based feature flags in JSON format. Used when testing flags that target+ organizations, teams, or other groups rather than individual users.+ </p>+ </div>++ {/* Action Buttons */}+ <div className="flex gap-2">+ <LemonButton+ type="primary"+ loading={isLoading}+ onClick={handleSubmit}+ disabledReason={!hasValidPerson ? 'Please select a person' : undefined}+ >+ Test evaluation+ </LemonButton>+ <LemonButton onClick={clearTestForm} disabled={isLoading}>+ Clear+ </LemonButton>+ </div>++ {/* Error Display */}+ {errorDisplay && (+ <LemonBanner type="error">+ <div>+ <div className="font-medium">Test evaluation failed</div>+ <div className="text-sm mt-1">{errorDisplay.message}</div>+ {errorDisplay.helpText && (+ <div className="text-xs mt-2 text-muted">+ <strong>Tip:</strong> {errorDisplay.helpText}+ </div>+ )}+ </div>+ </LemonBanner>+ )}+ </div>++ {/* Right Panel - Analysis and Properties */}+ <div className={`flex-1 bg-bg-light p-6 rounded-lg border ${!result ? 'content-center' : ''}`}>+ {result ? (+ <div className="space-y-6">+ {/* Evaluation Result */}+ <div className="space-y-3">+ <h5 className="font-semibold">Evaluation result</h5>++ <div className="space-y-2">+ <LemonLabel>Flag result</LemonLabel>+ <div+ className={`px-3 py-2 rounded text-sm font-mono ${+ result.result+ ? 'bg-success-highlight text-success'+ : 'bg-danger-highlight text-danger'+ }`}+ >+ {typeof result.result === 'boolean'+ ? result.result+ ? 'true'+ : 'false'+ : String(result.result)}+ </div>+ </div>++ {/* Timestamp Warning */}+ {formData.timestamp && (+ <LemonBanner type="info" className="mb-4">+ <strong>Historical evaluation:</strong> Both flag conditions and person+ properties reflect their state at the specified timestamp, not current values.+ </LemonBanner>+ )}++ {result.payload != null && (+ <div className="space-y-2">+ <LemonLabel>Payload</LemonLabel>+ <div className="px-3 py-2 rounded text-sm font-mono bg-bg-light">+ {JSON.stringify(result.payload, null, 2)}+ </div>+ </div>+ )}+ </div>++ {/* Two Column Layout: Conditions and Properties */}+ <div className="grid grid-cols-1 xl:grid-cols-5 gap-6">+ {/* Left Column - Condition Analysis */}+ {result.conditions && result.conditions.length > 0 && (+ <div className="space-y-3 xl:col-span-2">+ <LemonLabel>Condition analysis</LemonLabel>++ <div className="space-y-3 max-h-96 overflow-auto">+ {enrichedConditions.map((condition) => {+ const styles = CONDITION_DISPLAY_STYLES[condition.display.tone]++ return (+ <div+ key={condition.index}+ className={`border rounded-lg p-3 ${styles.card}`}+ >+ <div className="flex items-center gap-2 mb-2">+ <h6 className="font-medium text-sm">+ Condition #{condition.index}+ </h6>+ {condition.display.label && (+ <span+ className={`px-2 py-1 rounded text-xs font-mono ${styles.badge}`}+ >+ {condition.display.label}+ </span>+ )}+ {condition.rollout_percentage < 100 && (+ <span className="px-2 py-1 rounded text-xs bg-bg-light text-muted font-mono">+ {condition.rollout_percentage}%+ </span>+ )}+ </div>++ <div className="mb-2 text-xs text-muted">+ {condition.explanation}+ </div>++ {condition.properties.length > 0 && (+ <div className="space-y-1">+ {condition.properties.map(+ (+ property: ConditionAnalysis['properties'][number],+ idx: number+ ) => (+ <div+ key={`${property.key}-${idx}`}+ className="text-xs text-muted pl-2"+ >+ • {property.explanation}+ </div>+ )+ )}+ </div>+ )}+ </div>+ )+ })}+ </div>+ </div>+ )}++ {/* Right Column - Person Properties */}+ <div className="space-y-3 xl:col-span-3">+ <div>+ <LemonLabel>+ Person properties {formData.timestamp ? 'at evaluation time' : '(current)'}+ </LemonLabel>+ </div>++ <div className="max-h-96 overflow-auto">+ <PropertiesTable+ properties={result.person_properties}+ type={PropertyDefinitionType.Person}+ searchable={true}+ sortProperties={true}+ highlightedKeys={Array.from(usedProperties)}+ highlightVariant="subtle"+ embedded={true}+ />+ </div>+ </div>+ </div>+ </div>+ ) : (+ <div className="flex-grow flex items-center justify-center h-64">+ <div className="text-center text-muted">+ <p className="text-lg font-medium mb-2">No evaluation analysis yet</p>+ <p className="text-sm">+ Run a test evaluation to see condition analysis and person properties here+ </p>+ </div>+ </div>+ )}+ </div>+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.tsnew file mode 100644index 000000000000..73fcca1e077d--- /dev/null+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts@@ -0,0 +1,289 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { FeatureFlagTestEvaluationResponseApi } from 'products/feature_flags/frontend/generated/api.schemas'++import { featureFlagTestingLogic } from './featureFlagTestingLogic'++describe('featureFlagTestingLogic', () => {+ let logic: ReturnType<typeof featureFlagTestingLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team/feature_flags/1/test_evaluation': () => [200, {}],+ },+ post: {+ '/api/projects/:team/feature_flags/1/test_evaluation': () => [200, {}],+ },+ })+ initKeaTests()+ logic = featureFlagTestingLogic({ flagId: 1 })+ logic.mount()+ })++ describe('condition analysis', () => {+ it('correctly identifies matchedButNotWinner conditions', async () => {+ const mockResult: Partial<FeatureFlagTestEvaluationResponseApi> = {+ flag_key: 'test-flag',+ result: true,+ reason: 'condition_match',+ condition_index: 1,+ payload: null,+ person_properties: {},+ evaluation_distinct_id: null,+ conditions: [+ {+ index: 0,+ properties_matched: true,+ matched: false,+ rollout_excluded: false,+ explanation: 'Properties matched but condition was not winner',+ rollout_percentage: 100,+ variant: null,+ properties: [],+ },+ {+ index: 1,+ properties_matched: true,+ matched: true,+ rollout_excluded: false,+ explanation: 'Condition matched and won',+ rollout_percentage: 100,+ variant: 'test-variant',+ properties: [],+ },+ {+ index: 2,+ properties_matched: false,+ matched: false,+ rollout_excluded: false,+ explanation: 'Properties did not match',+ rollout_percentage: 100,+ variant: null,+ properties: [],+ },+ ],+ }++ await expectLogic(logic, () => {+ logic.actions.testFlagEvaluationSuccess(mockResult as FeatureFlagTestEvaluationResponseApi)+ }).toMatchValues({+ enrichedConditions: [+ expect.objectContaining({+ index: 0,+ matchedButNotWinner: true, // properties_matched=true, not winner, not rollout_excluded+ isWinningCondition: false,+ display: {+ tone: 'info',+ label: 'PROPERTIES MATCHED',+ },+ }),+ expect.objectContaining({+ index: 1,+ matchedButNotWinner: false, // is the winner+ isWinningCondition: true,+ display: {+ tone: 'success',+ label: 'MATCHED',+ },+ }),+ expect.objectContaining({+ index: 2,+ matchedButNotWinner: false, // properties_matched=false+ isWinningCondition: false,+ display: {+ tone: 'muted',+ label: null,+ },+ }),+ ],+ })+ })++ it('handles rollout_excluded conditions correctly', async () => {+ const mockResult: Partial<FeatureFlagTestEvaluationResponseApi> = {+ flag_key: 'test-flag',+ result: false,+ reason: 'rollout_excluded',+ condition_index: -1,+ payload: null,+ person_properties: {},+ evaluation_distinct_id: null,+ conditions: [+ {+ index: 0,+ properties_matched: true,+ matched: false,+ rollout_excluded: true,+ explanation: 'Properties matched but excluded from rollout',+ rollout_percentage: 50,+ variant: null,+ properties: [],+ },+ ],+ }++ await expectLogic(logic, () => {+ logic.actions.testFlagEvaluationSuccess(mockResult as FeatureFlagTestEvaluationResponseApi)+ }).toMatchValues({+ enrichedConditions: [+ expect.objectContaining({+ index: 0,+ matchedButNotWinner: false, // rollout_excluded=true+ isWinningCondition: false,+ display: {+ tone: 'warning',+ label: 'EXCLUDED FROM ROLLOUT',+ },+ }),+ ],+ })+ })++ it('does not show MATCHED when no conditions actually match', async () => {+ const mockResult: Partial<FeatureFlagTestEvaluationResponseApi> = {+ flag_key: 'test-flag',+ result: false,+ reason: 'no_condition_match',+ condition_index: 1, // Points to last condition but result is false+ payload: null,+ person_properties: {},+ evaluation_distinct_id: null,+ conditions: [+ {+ index: 0,+ properties_matched: false,+ matched: false,+ rollout_excluded: false,+ explanation: 'Properties did not match',+ rollout_percentage: 100,+ variant: null,+ properties: [],+ },+ {+ index: 1,+ properties_matched: false,+ matched: false,+ rollout_excluded: false,+ explanation: 'Properties did not match',+ rollout_percentage: 100,+ variant: null,+ properties: [],+ },+ ],+ }++ await expectLogic(logic, () => {+ logic.actions.testFlagEvaluationSuccess(mockResult as FeatureFlagTestEvaluationResponseApi)+ }).toMatchValues({+ enrichedConditions: [+ expect.objectContaining({+ index: 0,+ isWinningCondition: false,+ display: {+ tone: 'muted',+ label: null,+ },+ }),+ expect.objectContaining({+ index: 1,+ isWinningCondition: false, // Should not be winning even though condition_index=1+ display: {+ tone: 'muted',+ label: null,+ },+ }),+ ],+ })+ })+ })++ describe('errorDisplay selector', () => {+ const errorTestCases = [+ {+ description: 'build person properties error',+ input: 'Failed to build person properties at specified timestamp',+ expected: {+ message: 'Failed to build person properties at specified timestamp',+ helpText:+ 'Try a more recent timestamp when this person was active, remove the timestamp to test with current person properties, or select a different person who was active at that time.',+ },+ },+ {+ description: 'timestamp error',+ input: 'Invalid timestamp format',+ expected: {+ message: 'Invalid timestamp format',+ helpText:+ 'When using historical timestamps, the person must have existed at that time and had the necessary properties for evaluation.',+ },+ },+ {+ description: 'person not found error',+ input: 'Person not found for distinct_id',+ expected: {+ message: 'Person not found for distinct_id',+ helpText: 'Try selecting a different person or removing the timestamp to test with current data.',+ },+ },+ {+ description: 'person not found error with timestamp (rewritten error message)',+ input: 'Person not found. This person may not have existed at the selected timestamp.',+ expected: {+ message: 'Person not found. This person may not have existed at the selected timestamp.',+ helpText: 'Try selecting a different person or removing the timestamp to test with current data.',+ },+ },+ {+ description: 'generic error without helpText',+ input: 'Some generic API error',+ expected: {+ message: 'Some generic API error',+ helpText: null,+ },+ },+ {+ description: 'null error returns null',+ input: null,+ expected: null,+ },+ ]++ it.each(errorTestCases)('$description', ({ input, expected }) => {+ logic.actions.setTestError(input as any)+ expect(logic.values.errorDisplay).toEqual(expected)+ })+ })++ describe('groups validation through testFlagEvaluation', () => {+ it.each([+ { description: 'valid object succeeds', groups: '{"team": "backend"}', expectedError: null },+ { description: 'empty string succeeds', groups: '', expectedError: null },+ { description: 'whitespace succeeds', groups: ' \n\t ', expectedError: null },+ { description: 'array fails', groups: '["team","backend"]', expectedError: 'groups must be a JSON object' },+ {+ description: 'invalid JSON fails',+ groups: '{invalid: json}',+ expectedError: 'Invalid JSON format for groups',+ },+ {+ description: 'json string fails',+ groups: '"just a string"',+ expectedError: 'groups must be a JSON object',+ },+ { description: 'json number fails', groups: '42', expectedError: 'groups must be a JSON object' },+ ])('$description', async ({ groups, expectedError }) => {+ await expectLogic(logic, () => {+ logic.actions.testFlagEvaluation({+ flagId: 1,+ formData: { person_id: 'p1', timestamp: '', groups },+ })+ }).toFinishAllListeners()++ expect(logic.values.testError).toBe(expectedError)+ })+ })+})diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.tsnew file mode 100644index 000000000000..7eb33fbd009d--- /dev/null+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.ts@@ -0,0 +1,264 @@+import { actions, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { ApiError } from 'lib/api'+import { dayjs, Dayjs } from 'lib/dayjs'+import { projectLogic } from 'scenes/projectLogic'++import { PersonType } from '~/types'++import { featureFlagsTestEvaluationCreate } from 'products/feature_flags/frontend/generated/api'+import type {+ FeatureFlagConditionAnalysisApi,+ FeatureFlagTestEvaluationRequestApi,+ FeatureFlagTestEvaluationResponseApi,+} from 'products/feature_flags/frontend/generated/api.schemas'++import type { featureFlagTestingLogicType } from './featureFlagTestingLogicType'++export type ConditionAnalysis = FeatureFlagConditionAnalysisApi+export type TestResult = FeatureFlagTestEvaluationResponseApi++export interface TestFormData {+ person_id: string+ timestamp: string+ groups: string+}++const EMPTY_FORM: TestFormData = { person_id: '', timestamp: '', groups: '' }++function validateAndParseGroups(groups: string): Record<string, any> {+ const trimmed = groups.trim()+ if (!trimmed) {+ return {}+ }++ try {+ const parsed = JSON.parse(trimmed)+ if (typeof parsed !== 'object' || Array.isArray(parsed)) {+ throw new Error('groups must be a JSON object')+ }+ return parsed+ } catch (e) {+ throw e instanceof SyntaxError ? new Error('Invalid JSON format for groups') : e+ }+}++export interface FeatureFlagTestingLogicProps {+ flagId: number+}++export const featureFlagTestingLogic = kea<featureFlagTestingLogicType>([+ props({} as FeatureFlagTestingLogicProps),+ key((props) => props.flagId),+ path((key) => ['scenes', 'feature-flags', 'featureFlagTestingLogic', key]),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),+ actions({+ setTestFormData: (formData: Partial<TestFormData>) => ({ formData }),+ setTestError: (error: string | null) => ({ error }),+ setDatePickerOpen: (open: boolean) => ({ open }),+ setDatePickerValue: (value: Dayjs | null) => ({ value }),+ setSelectedPerson: (person: PersonType | null) => ({ person }),+ setIncludeTime: (includeTime: boolean) => ({ includeTime }),+ clearTestForm: true,+ }),+ loaders(({ values }) => ({+ testEvaluation: [+ null as TestResult | null,+ {+ testFlagEvaluation: async ({ flagId, formData }: { flagId: number; formData: TestFormData }) => {+ const data: FeatureFlagTestEvaluationRequestApi = {}++ if (formData.person_id?.trim()) {+ data.person_id = formData.person_id.trim()+ }++ data.groups = validateAndParseGroups(formData.groups || '')++ if (formData.timestamp?.trim()) {+ data.timestamp = formData.timestamp.trim()++ // Validate ISO string format with strict parsing+ const parsedTimestamp = dayjs(data.timestamp, 'YYYY-MM-DDTHH:mm:ss.SSS[Z]', true)+ if (!parsedTimestamp.isValid()) {+ throw new Error('Invalid timestamp format')+ }+ }++ return await featureFlagsTestEvaluationCreate(String(values.currentProjectId), flagId, data)+ },+ },+ ],+ })),+ reducers({+ testFormData: [+ EMPTY_FORM,+ {+ setTestFormData: (state, { formData }) => ({ ...state, ...formData }),+ clearTestForm: () => EMPTY_FORM,+ },+ ],+ testError: [+ null as string | null,+ {+ setTestError: (_, { error }: { error: string | null }) => error,+ testFlagEvaluation: () => null,+ clearTestForm: () => null,+ testFlagEvaluationFailure: (_, { error, errorObject }: { error: string; errorObject?: unknown }) => {+ const apiError = errorObject as ApiError+ if (apiError?.detail) {+ const errorDetail = apiError.detail++ if (errorDetail.includes('Failed to build person properties at specified timestamp')) {+ return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'+ }++ if (errorDetail.includes('person') && errorDetail.includes('not found')) {+ return 'Person not found. This person may not have existed at the selected timestamp.'+ }++ if (errorDetail.includes('timestamp') || errorDetail.toLowerCase() === 'invalid timestamp') {+ return 'Invalid timestamp. Please select a valid date and time.'+ }++ return errorDetail+ }++ const errorMessage = apiError?.message || error || ''+ if (errorMessage.includes('Failed to build person properties at specified timestamp')) {+ return 'Unable to build person properties at the selected timestamp. This person may not have had any recorded activity at that time, or the timestamp may be too far in the past.'+ }++ return errorMessage || 'An unexpected error occurred while testing the feature flag'+ },+ },+ ],+ testResult: [+ null as TestResult | null,+ {+ testFlagEvaluationSuccess: (_, { testEvaluation }) => testEvaluation,+ clearTestForm: () => null,+ setTestFormData: () => null,+ },+ ],+ datePickerOpen: [+ false,+ {+ setDatePickerOpen: (_, { open }) => open,+ },+ ],+ datePickerValue: [+ null as Dayjs | null,+ {+ setDatePickerValue: (_, { value }) => value,+ clearTestForm: () => null,+ },+ ],+ selectedPerson: [+ null as PersonType | null,+ {+ setSelectedPerson: (_, { person }) => person,+ clearTestForm: () => null,+ },+ ],+ includeTime: [+ true,+ {+ setIncludeTime: (_, { includeTime }) => includeTime,+ },+ ],+ }),+ selectors({+ // Get the set of properties used in any condition+ usedProperties: [+ (s) => [s.testResult],+ (result: TestResult | null): Set<string> => {+ const used = new Set<string>()+ if (result?.conditions) {+ for (const condition of result.conditions) {+ for (const prop of condition.properties) {+ used.add(prop.key)+ }+ }+ }+ return used+ },+ ],+ // Get enriched conditions with derived flags for UI rendering+ enrichedConditions: [+ (s) => [s.testResult],+ (result: TestResult | null) => {+ if (!result?.conditions) {+ return []+ }++ return result.conditions.map((condition: ConditionAnalysis) => {+ // Check if this condition is the actual winner+ // Per the API serializer, matched is the source of truth - "at most one condition per flag is True"+ const isWinningCondition = condition.matched+ // Determine if this condition matched but wasn't the winner+ const matchedButNotWinner =+ condition.properties_matched && !isWinningCondition && !condition.rollout_excluded++ // Determine display properties+ let tone: 'success' | 'info' | 'warning' | 'muted' = 'muted'+ let label: string | null = null++ if (isWinningCondition) {+ tone = 'success'+ label = 'MATCHED'+ } else if (matchedButNotWinner) {+ tone = 'info'+ label = 'PROPERTIES MATCHED'+ } else if (condition.rollout_excluded) {+ tone = 'warning'+ label = 'EXCLUDED FROM ROLLOUT'+ }++ return {+ ...condition,+ isWinningCondition,+ matchedButNotWinner,+ display: {+ tone,+ label,+ },+ }+ })+ },+ ],+ // Check if form has valid person selected+ hasValidPerson: [+ (s) => [s.testFormData],+ (formData: TestFormData): boolean => Boolean(formData.person_id?.trim()),+ ],+ // Get formatted error display information+ errorDisplay: [+ (s) => [s.testError],+ (error: string | null) => {+ if (!error) {+ return null+ }++ let helpText: string | null = null++ if (error.toLowerCase().includes('build person properties')) {+ helpText =+ 'Try a more recent timestamp when this person was active, remove the timestamp to test with current person properties, or select a different person who was active at that time.'+ } else if (error.toLowerCase().includes('person') && error.toLowerCase().includes('not found')) {+ helpText = 'Try selecting a different person or removing the timestamp to test with current data.'+ } else if (error.toLowerCase().includes('timestamp')) {+ helpText =+ 'When using historical timestamps, the person must have existed at that time and had the necessary properties for evaluation.'+ }++ return {+ message: error,+ helpText,+ }+ },+ ],+ }),+])diff --git a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts b/frontend/src/scenes/feature-flags/featureFlagsLogic.tsindex 562c92e61194..5f7b758ebac7 100644--- a/frontend/src/scenes/feature-flags/featureFlagsLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagsLogic.ts@@ -113,6 +113,7 @@ export enum FeatureFlagsTab {SCHEDULE = 'schedule',FEEDBACK = 'feedback',EXPERIMENTS = 'experiments',+ TESTING = 'testing',}export interface FeatureFlagsResult extends CountedPaginatedResponse<FeatureFlagType> {