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(experiments): add a staff setup context inspector (#104139)

Marcel Poelker9d9e893e882d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 87537f940809..5bb0b531899c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8312,6 +8312,18 @@ snapshots:
hash: v1.k794b7964.02690ce57556848e6499d55ebdea346c56b0a7f0c291fc7e6ce0dbea43338c3e.CmF_cYWu6htlQfgz-p47OvL1KNUyS5xNcA_b2p10J8g
scenes-app-experiments--experiments--light:
hash: v1.k794b7964.019fd6a09af4fac7ae7650b2d16e5f8747d781d69d22fd967074f95b05c5b7dd.HQ8s3pnBaTgkJu2KhSINttf_RpbisOCwR_tsIelm6P4
+ scenes-app-experiments-setup-context--setup-context-drawer--dark:
+ hash: v1.k794b7964.7d9d810f6d852727af99b34c5ae00facfdbc8cd345f1201af9a85cfc9cf6b84e.vUqVIoW1qhcFrVnOMQnP47Rp6NEkz38c81z3m32TnfQ
+ scenes-app-experiments-setup-context--setup-context-drawer--light:
+ hash: v1.k794b7964.9dacbfa1b6b1bdef6c3f50c90c12382ddbb2437334ffb6a3e6b05e843b2285df.sLBnFqVO71xc-ez-1epdlA0UY9i0pz7VRoaujWCE24g
+ scenes-app-experiments-setup-context--setup-context-drawer-degraded--dark:
+ hash: v1.k794b7964.decace3f79b269f18bbc0bae0e34d13a95939fe578230212bd87eb66bed4ec03.i6y-ucqr4xkYT8j0QnDRPKPDUKIYeSZDMB0kTAtEU8E
+ scenes-app-experiments-setup-context--setup-context-drawer-degraded--light:
+ hash: v1.k794b7964.6e6acb3553de3a49833c8e7c08e01fdf8e5d69004fe0facb7603d59d203d9528.TQzoTS950RvzO65Rco_wso1iw-PiZC7sQN8GD6yqpT8
+ scenes-app-experiments-setup-context--setup-context-drawer-narrow--dark:
+ hash: v1.k794b7964.1074de0d6b43c97997e4cf0805a72c6d6421d705c19302d513843b20fcd228a6.iLBmTqiDcsehqfv8-kOyDSMaUBDhMJzv8zv-BXpxmPQ
+ scenes-app-experiments-setup-context--setup-context-drawer-narrow--light:
+ hash: v1.k794b7964.cc999db118582bdb5f64351350f6013fc380f65ff7f029699b999ec6ec88d165.fgI_0tKTAlU-s75XAXeOKhCSc5GAiqMeTvCcgYcPFrg
scenes-app-feature-flags--edit-encrypted-remote-config-feature-flag--dark:
hash: v1.k794b7964.4f3b66427a371ca87ed7ff3437e4e05fa321a2f1ad219b5d4424a8e1b7348b11.YfwgimzWA69iIlL9McssTirk4C2ey_bcZyKYTquJLew
scenes-app-feature-flags--edit-encrypted-remote-config-feature-flag--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 3b4c4f5ea03a..314d31b7f304 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -316,6 +316,7 @@ export const FEATURE_FLAGS = {
ERROR_TRACKING_WEEKLY_DIGEST: 'error-tracking-weekly-digest', // owner: #team-error-tracking
EXPERIMENT_BEHAVIOR_COMPARISON: 'experiment-behavior-comparison', // owner: @mp-hog #team-experiments
EXPERIMENT_METRIC_EVENT_BREAKDOWNS: 'experiment-metric-event-breakdowns', // owner: @rodrigoi #team-experiments
+ EXPERIMENT_SETUP_CONTEXT: 'experiment-setup-context', // owner: @mp-hog #team-experiments, gates the experiment-setup-context MCP tool, its endpoint and the staff setup context drawer on the experiments list
EXPERIMENTS_DW_AA_TEST: 'experiments-dw-aa-test', // owner: @rodrigoi #team-experiments
EXPERIMENTS_EXCLUDED_VARIANTS: 'experiments-excluded-variants', // owner: @rodrigoi #team-experiments
EXPERIMENTS_FREEZE_EXPOSURE_AA_TEST: 'experiments-freeze-exposure-aa-test', // owner: @mp-hog #team-experiments multivariate=control,test, dogfood A/A used to validate the freeze-exposure lifecycle action
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 90f7cc1078fb..f59d613c17fc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3486,6 +3486,9 @@ importers:
'@posthog/icons':
specifier: 'catalog:'
+ '@testing-library/dom':
+ specifier: '*'
+ version: 10.4.0
'@types/react':
specifier: 18.3.27
version: 18.3.27
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 0dcff6f5ece5..c995788baa4a 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1796,6 +1796,10 @@ READ_ONLY_IMPERSONATION_ALLOWLISTED_PATHS: list[tuple[str, str | re.Pattern]] =
"POST",
re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/warehouse_saved_queries/check_incremental/?$"),
),
+ # POST but read-only: reads the project facts that decide how to configure a new experiment, for
+ # support on identity and bucketing tickets. The action is named exactly, because the same prefix
+ # hosts the mutating experiment actions.
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/experiments/setup_context/?$")),
# POST but read-only: kicks off insight/dashboard/session replay export renders (e.g. MP4)
("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/exports/?$")),
# POST but read-only: the Logs product sends its queries as POST because the filter payload
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 0e463675c8e9..d1fc114876ce 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -1095,6 +1095,7 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):
("tracing_trace_by_id", "tracing/spans/trace/zzz/", {}),
("metrics_query", "metrics/query/", {}),
("metrics_explain", "metrics/explain/", {}),
+ ("experiments_setup_context", "experiments/setup_context/", {}),
]
)
def test_read_only_impersonation_allows_allowlisted_post(self, _name, path_suffix, body):
@@ -1119,6 +1120,7 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):
"warehouse_saved_query_materialize",
"warehouse_saved_queries/00000000-0000-0000-0000-000000000000/materialize/",
),
+ ("experiments_create", "experiments/"),
]
)
def test_read_only_impersonation_blocks_mutating_siblings(self, _name, path_suffix):
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index b5bd89ada43f..bdc2ee1c6d7f 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -18,6 +18,7 @@ from django.db.models import BooleanField, Case, Exists, OuterRef, Prefetch, Q,
from django.utils.text import slugify
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema, extend_schema_view
+from loginas.utils import is_impersonated_session
from opentelemetry import trace
from rest_framework import serializers, viewsets
from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
@@ -36,6 +37,7 @@ from posthog.auth import (
PersonalAPIKeyAuthentication,
ProjectSecretAPIKeyAuthentication,
)
+from posthog.helpers.impersonation import get_original_user_from_session
from posthog.models.activity_logging.activity_log import ActivityLog, get_activity_page
from posthog.models.activity_logging.activity_page import ActivityLogPaginatedResponseSerializer, activity_page_response
from posthog.models.organization import OrganizationMembership
@@ -1555,10 +1557,14 @@ class EnterpriseExperimentsViewSet(
return Response(ExperimentSetupContextResponseSerializer(context).data)
def _setup_context_enabled(self) -> bool:
+ # In a loginas impersonation session request.user is the customer. The flag is evaluated for the staff
+ # user, so support can read a customer's setup context without the flag being on for that customer.
+ # OAuth impersonation (MCP) has no session, so it keeps the customer's flag, which also gates the tool.
+ flag_user = get_original_user_from_session(self.request) if is_impersonated_session(self.request) else None
try:
return posthog_feature_flag_enabled(
EXPERIMENT_SETUP_CONTEXT_FLAG,
- str(cast(User, self.request.user).distinct_id),
+ str((flag_user or cast(User, self.request.user)).distinct_id),
organization_id=self.organization_id,
team_id=self.team.id,
)
diff --git a/products/experiments/backend/test/test_presentation_api.py b/products/experiments/backend/test/test_presentation_api.py
index 007a8f167a8b..02b276700786 100644
--- a/products/experiments/backend/test/test_presentation_api.py
+++ b/products/experiments/backend/test/test_presentation_api.py
@@ -12,6 +12,7 @@ from django.core.cache import cache
from django.db import connection
from django.db.models import F
from django.test.utils import CaptureQueriesContext
+from django.urls import reverse
from django.utils import timezone
from dateutil import parser
@@ -9032,6 +9033,36 @@ class TestExperimentSetupContextEndpoint(ClickhouseTestMixin, APILicensedTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.content
assert response.json()["attr"] == expected_attr
+ @parameterized.expand(
+ [
+ ("flag_on_for_staff_only", "staff", status.HTTP_200_OK),
+ ("flag_on_for_customer_only", "customer", status.HTTP_404_NOT_FOUND),
+ ]
+ )
+ def test_flag_is_evaluated_for_the_impersonating_staff_user(
+ self, _name: str, flag_on_for: str, expected_status: int
+ ) -> None:
+ self.user.is_staff = True
+ self.user.save()
+ customer = User.objects.create_and_join(self.organization, "[email protected]", None)
+ flag_distinct_id = str(self.user.distinct_id if flag_on_for == "staff" else customer.distinct_id)
+ self.client.post(
+ reverse("loginas-user-login", kwargs={"user_id": customer.id}),
+ data={"read_only": "true", "reason": "Setup context support ticket"},
+ format="multipart",
+ )
+ assert self.client.get("/api/users/@me/").json()["email"] == customer.email
+
+ with patch(
+ "posthoganalytics.feature_enabled",
+ side_effect=lambda key, distinct_id, *args, **_: (
+ key == EXPERIMENT_SETUP_CONTEXT_FLAG and distinct_id == flag_distinct_id
+ ),
+ ):
+ response = self.client.post(f"/api/projects/{self.team.id}/experiments/setup_context/", {}, format="json")
+
+ assert response.status_code == expected_status, response.content
+
def test_omits_experiments_the_user_cannot_access(self) -> None:
other_user = self._create_user("[email protected]")
visible_flag = FeatureFlag.objects.create(team=self.team, created_by=self.user, key="setup-visible")
diff --git a/products/experiments/frontend/scenes/ExperimentsScene.tsx b/products/experiments/frontend/scenes/ExperimentsScene.tsx
index 6ea210e7e36f..354a27815908 100644
--- a/products/experiments/frontend/scenes/ExperimentsScene.tsx
+++ b/products/experiments/frontend/scenes/ExperimentsScene.tsx
@@ -79,6 +79,7 @@ import {
} from 'products/experiments/frontend/scenes/experimentsLogic'
import { ExperimentsSettingsScene } from 'products/experiments/frontend/scenes/ExperimentsSettingsScene'
import { ExperimentsSharedMetricsScene } from 'products/experiments/frontend/scenes/ExperimentsSharedMetricsScene'
+import { SetupInspectorButton } from 'products/experiments/frontend/setupInspector/SetupInspectorButton'
// "Experiments open feedback" in project 2: https://us.posthog.com/project/2/surveys/01a08364-270e-0000-585b-147d32bf96ed
// Button-only: its URL condition never matches, so this button is the survey's sole entry point.
@@ -734,6 +735,7 @@ export function ExperimentsScene(): JSX.Element {
}}
actions={
<>
+ <SetupInspectorButton />
<FeedbackSurveyButton
surveyId={EXPERIMENTS_FEEDBACK_SURVEY_ID}
data-attr="experiments-feedback-button"
diff --git a/products/experiments/frontend/setupInspector/SetupContextSection.tsx b/products/experiments/frontend/setupInspector/SetupContextSection.tsx
new file mode 100644
index 000000000000..7a9295887a04
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/SetupContextSection.tsx
@@ -0,0 +1,53 @@
+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
+
+import type { SetupContextSectionStatusEnumApi } from 'products/experiments/frontend/generated/api.schemas'
+
+import { SECTION_STATUS_LABELS } from './setupInspectorUtils'
+
+const STATUS_TAG_TYPES: Record<Exclude<SetupContextSectionStatusEnumApi, 'ok'>, LemonTagType> = {
+ skipped: 'muted',
+ timed_out: 'warning',
+ error: 'danger',
+}
+
+const STATUS_MESSAGES: Record<Exclude<SetupContextSectionStatusEnumApi, 'ok'>, string> = {
+ skipped: 'This section needs an input that was not passed.',
+ timed_out: 'The query took too long and was stopped. Narrow the inputs, or try again later.',
+ error: 'The read failed. The server logs have the details.',
+}
+
+export interface SetupContextSectionProps {
+ title: string
+ description: string
+ status: SetupContextSectionStatusEnumApi
+ /** Replaces the generic message when the section is skipped, to name the missing input. */
+ skippedMessage?: string
+ children?: React.ReactNode
+}
+
+export function SetupContextSection({
+ title,
+ description,
+ status,
+ skippedMessage,
+ children,
+}: SetupContextSectionProps): JSX.Element {
+ return (
+ <section className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="mb-0">{title}</h3>
+ {status !== 'ok' && (
+ <LemonTag type={STATUS_TAG_TYPES[status]}>{SECTION_STATUS_LABELS[status]}</LemonTag>
+ )}
+ </div>
+ <p className="text-secondary text-sm mb-0">{description}</p>
+ {status === 'ok' ? (
+ children
+ ) : (
+ <p className="text-sm mb-0">
+ {status === 'skipped' && skippedMessage ? skippedMessage : STATUS_MESSAGES[status]}
+ </p>
+ )}
+ </section>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/SetupFactsTable.tsx b/products/experiments/frontend/setupInspector/SetupFactsTable.tsx
new file mode 100644
index 000000000000..76e62e19acd7
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/SetupFactsTable.tsx
@@ -0,0 +1,38 @@
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+export interface SetupFact {
+ label: string
+ value: React.ReactNode
+ /** The field's meaning, shown on hover over the label. */
+ help?: string
+}
+
+export function SetupFactsTable({ facts }: { facts: SetupFact[] }): JSX.Element {
+ return (
+ <LemonTable
+ size="small"
+ showHeader={false}
+ rowKey="label"
+ dataSource={facts}
+ columns={[
+ {
+ key: 'label',
+ width: '40%',
+ render: (_, fact) =>
+ fact.help ? (
+ <Tooltip title={fact.help}>
+ <span className="underline decoration-dotted">{fact.label}</span>
+ </Tooltip>
+ ) : (
+ <span>{fact.label}</span>
+ ),
+ },
+ {
+ key: 'value',
+ render: (_, fact) => <span translate="no">{fact.value}</span>,
+ },
+ ]}
+ />
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/SetupInspector.stories.tsx b/products/experiments/frontend/setupInspector/SetupInspector.stories.tsx
new file mode 100644
index 000000000000..6d89a9446bec
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/SetupInspector.stories.tsx
@@ -0,0 +1,356 @@
+import { Meta, StoryObj } from '@storybook/react'
+import { within } from '@testing-library/dom'
+import userEvent from '@testing-library/user-event'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { App } from 'scenes/App'
+import { urls } from 'scenes/urls'
+
+import { mswDecorator } from '~/mocks/browser'
+import EXPERIMENT_DRAFT from '~/mocks/fixtures/api/experiments/_experiment_draft.json'
+import { toPaginatedResponse } from '~/mocks/handlers'
+
+import type { ExperimentSetupContextResponseApi } from 'products/experiments/frontend/generated/api.schemas'
+
+const SETUP_CONTEXT_PATH = '/api/projects/:team_id/experiments/setup_context/'
+const COMPUTED_AT = '2025-01-27T09:00:00Z'
+
+// Typed as the generated response so a new required field on the serializer breaks the typecheck here.
+const FULL_CONTEXT: ExperimentSetupContextResponseApi = {
+ team_defaults: {
+ status: 'ok',
+ data: {
+ stats_method: null,
+ confidence_level: null,
+ minimum_detectable_effect: 20,
+ product_default_minimum_detectable_effect: 30,
+ product_default_stats_method: 'bayesian',
+ product_default_confidence_level: 0.95,
+ only_count_matured_users: false,
+ cuped_enabled: true,
+ sequential_testing_enabled: false,
+ flags_persistence_default: false,
+ test_account_filter_count: 2,
+ new_experiments_filter_test_accounts: true,
+ default_exposure_event: '$feature_flag_called',
+ },
+ },
+ sdk_profile: {
+ status: 'ok',
+ data: {
+ window_days: 7,
+ source_event: '$feature_flag_called',
+ computed_at: COMPUTED_AT,
+ libs: [
+ {
+ lib: 'web',
+ category: 'web',
+ calls: 184_220,
+ distinct_ids: 41_380,
+ device_id_share: 1,
+ locally_evaluated_share: null,
+ anonymous_share: 0.42,
+ },
+ {
+ lib: 'posthog-node',
+ category: 'server',
+ calls: 96_410,
+ distinct_ids: 12_905,
+ device_id_share: 0,
+ locally_evaluated_share: 0.97,
+ anonymous_share: null,
+ },
+ ],
+ libs_truncated: false,
+ flags_seen: 14,
+ flags_evaluated_on_server_and_web: 3,
+ evaluated_on_server_and_web: true,
+ libs_on_any_event: null,
+ libs_on_any_event_truncated: false,
+ },
+ },
+ target_surface: {
+ status: 'ok',
+ data: {
+ window_days: 14,
+ source_event: '$pageview',
+ target_url_contains: '/pricing',
+ target_properties: [{ key: '$host', type: 'event', operator: 'exact', value: ['app.example.com'] }],
+ computed_at: COMPUTED_AT,
+ test_accounts_filtered: true,
+ unique_persons: 8_470,
+ exposures_per_day_estimate: 605,
+ libs: [{ lib: 'web', category: 'web', unique_persons: 8_470, anonymous_share: 0.38, device_id_share: 1 }],
+ anonymous_share: 0.38,
+ device_id_share: 1,
+ },
+ },
+ candidate_metric: {
+ status: 'ok',
+ data: {
+ window_days: 14,
+ source_event: 'signed_up',
+ metric_properties: [],
+ target_event: '$pageview',
+ computed_at: COMPUTED_AT,
+ test_accounts_filtered: true,
+ persons_reached: 8_470,
+ persons_converted: 593,
+ conversion_rate: 0.07,
+ funnel_baseline_stats: { number_of_samples: 8_470, sum: 593, step_counts: [593] },
+ mean_count_baseline_stats: { number_of_samples: 8_470, sum: 640, sum_squares: 731 },
+ note: 'Metric events are counted in the whole window, not only after the first target event.',
+ event_volume: 1_204,
+ unique_persons: 1_130,
+ },
+ },
+ previous_experiments: {
+ status: 'ok',
+ data: {
+ experiments: [
+ {
+ id: 101,
+ name: 'Pricing page layout',
+ state: 'running',
+ created_at: '2025-01-10T10:00:00Z',
+ start_date: '2025-01-12T10:00:00Z',
+ end_date: null,
+ conclusion: null,
+ feature_flag_key: 'pricing-page-layout',
+ variant_count: 2,
+ split_even: true,
+ serving_single_variant: null,
+ rollout_percentage: 100,
+ multiple_variant_handling: 'exclude',
+ multiple_variant_handling_set: false,
+ ensure_experience_continuity: true,
+ bucketing_identifier: 'distinct_id',
+ evaluation_runtime: 'all',
+ group_aggregation: false,
+ custom_exposure_event: null,
+ custom_exposure_action_id: null,
+ exposure_property_filters: [{ key: '$pathname', type: 'event', value: ['/pricing'] }],
+ activation_event: null,
+ activation_action_id: null,
+ filter_test_accounts: true,
+ primary_metric_count: 1,
+ secondary_metric_count: 2,
+ shared_metric_count: 1,
+ primary_metric_types: ['funnel'],
+ primary_metric_events: ['signed_up'],
+ primary_metric_action_ids: [],
+ minimum_detectable_effect: 20,
+ stats_method: 'bayesian',
+ has_holdout: false,
+ outcome: {
+ metric_type: 'funnel',
+ metric_samples: 6_120,
+ analyzed_exposures: 6_120,
+ control_baseline_value: 0.068,
+ any_variant_significant: false,
+ result_completed_at: '2025-01-27T06:00:00Z',
+ result_data_through: '2025-01-27T00:00:00Z',
+ },
+ },
+ {
+ id: 97,
+ name: 'Onboarding checklist',
+ state: 'stopped',
+ created_at: '2024-12-02T10:00:00Z',
+ start_date: '2024-12-03T10:00:00Z',
+ end_date: '2025-01-05T10:00:00Z',
+ conclusion: 'won',
+ feature_flag_key: 'onboarding-checklist',
+ variant_count: 2,
+ split_even: null,
+ serving_single_variant: 'test',
+ rollout_percentage: 100,
+ multiple_variant_handling: 'first_seen',
+ multiple_variant_handling_set: true,
+ ensure_experience_continuity: false,
+ bucketing_identifier: 'device_id',
+ evaluation_runtime: 'client',
+ group_aggregation: false,
+ custom_exposure_event: 'onboarding_viewed',
+ custom_exposure_action_id: null,
+ exposure_property_filters: [],
+ activation_event: null,
+ activation_action_id: null,
+ filter_test_accounts: true,
+ primary_metric_count: 1,
+ secondary_metric_count: 0,
+ shared_metric_count: 0,
+ primary_metric_types: ['retention'],
+ primary_metric_events: ['onboarding_viewed', 'project_created'],
+ primary_metric_action_ids: [],
+ minimum_detectable_effect: null,
+ stats_method: 'frequentist',
+ has_holdout: true,
+ outcome: {
+ metric_type: 'retention',
+ metric_samples: 2_310,
+ analyzed_exposures: null,
+ control_baseline_value: null,
+ any_variant_significant: true,
+ result_completed_at: '2025-01-05T11:00:00Z',
+ result_data_through: '2025-01-05T10:00:00Z',
+ },
+ },
+ {
+ id: 104,
+ name: 'Shorter signup form',
+ state: 'draft',
+ created_at: '2025-01-25T10:00:00Z',
+ start_date: null,
+ end_date: null,
+ conclusion: null,
+ feature_flag_key: 'shorter-signup-form',
+ variant_count: 3,
+ split_even: false,
+ serving_single_variant: null,
+ rollout_percentage: 50,
+ multiple_variant_handling: 'exclude',
+ multiple_variant_handling_set: false,
+ ensure_experience_continuity: false,
+ bucketing_identifier: 'distinct_id',
+ evaluation_runtime: 'all',
+ group_aggregation: false,
+ custom_exposure_event: null,
+ custom_exposure_action_id: null,
+ exposure_property_filters: [],
+ activation_event: 'signup_form_focused',
+ activation_action_id: null,
+ filter_test_accounts: false,
+ primary_metric_count: 0,
+ secondary_metric_count: 0,
+ shared_metric_count: 0,
+ primary_metric_types: [],
+ primary_metric_events: [],
+ primary_metric_action_ids: [],
+ minimum_detectable_effect: null,
+ stats_method: 'bayesian',
+ has_holdout: false,
+ outcome: null,
+ },
+ ],
+ summary: {
+ total: 3,
+ launched: 2,
+ launched_without_results: 0,
+ launched_with_unknown_analyzed_exposures: 1,
+ launched_with_zero_analyzed_exposures: 0,
+ launched_with_under_100_analyzed_exposures: 0,
+ using_device_id_bucketing: 1,
+ using_persistence: 1,
+ using_custom_exposure: 1,
+ using_exposure_property_filters: 1,
+ using_activation: 1,
+ using_uneven_split: 1,
+ serving_single_variant: 1,
+ },
+ },
+ },
+ shared_metrics: {
+ status: 'ok',
+ data: {
+ metric_event: 'signed_up',
+ metric_event_match_truncated: false,
+ metrics: [
+ {
+ id: 12,
+ name: 'Signup conversion',
+ metric_type: 'funnel',
+ events: ['$pageview', 'signed_up'],
+ action_ids: [],
+ used_as_primary: 4,
+ used_as_secondary: 1,
+ last_used_at: '2025-01-12T10:00:00Z',
+ matches_metric_event: true,
+ metric_event_roles: ['funnel_final_step'],
+ },
+ {
+ id: 15,
+ name: 'Seven day retention',
+ metric_type: 'retention',
+ events: ['signed_up', 'project_created'],
+ action_ids: [],
+ used_as_primary: 1,
+ used_as_secondary: 3,
+ last_used_at: '2024-12-03T10:00:00Z',
+ matches_metric_event: true,
+ metric_event_roles: ['retention_start'],
+ },
+ {
+ id: 9,
+ name: 'Revenue per user',
+ metric_type: 'mean',
+ events: [],
+ action_ids: [31],
+ used_as_primary: 0,
+ used_as_secondary: 2,
+ last_used_at: null,
+ matches_metric_event: false,
+ metric_event_roles: [],
+ },
+ ],
+ },
+ },
+}
+
+// What a project with no flag calls and no inputs gets back, with one read that timed out and one
+// that failed, so every section status renders in one screenshot.
+const DEGRADED_CONTEXT: ExperimentSetupContextResponseApi = {
+ ...FULL_CONTEXT,
+ sdk_profile: { status: 'timed_out', data: null },
+ target_surface: { status: 'skipped', data: null },
+ candidate_metric: { status: 'skipped', data: null },
+ shared_metrics: { status: 'error', data: null },
+}
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Experiments/Setup context',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2025-01-27',
+ pageUrl: urls.experiments(),
+ featureFlags: [FEATURE_FLAGS.EXPERIMENT_SETUP_CONTEXT],
+ testOptions: { viewport: { width: 1300, height: 2400 } },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ // One experiment, because an empty list renders the product empty state without the title actions.
+ '/api/projects/:team_id/experiments/': toPaginatedResponse([EXPERIMENT_DRAFT]),
+ '/api/projects/:team_id/experiment_holdouts': [],
+ '/api/projects/:team_id/experiment_saved_metrics/': [],
+ },
+ }),
+ ],
+}
+export default meta
+
+type Story = StoryObj<{}>
+
+const openTheDrawer: Story['play'] = async ({ canvasElement }) => {
+ await userEvent.click(await within(canvasElement).findByText('Setup context'))
+ await within(document.body).findByText('Team defaults')
+}
+
+export const SetupContextDrawer: Story = {
+ decorators: [mswDecorator({ post: { [SETUP_CONTEXT_PATH]: FULL_CONTEXT } })],
+ play: openTheDrawer,
+}
+
+// Narrow, because the drawer's input grid and the previous experiments table run out of room first.
+export const SetupContextDrawerNarrow: Story = {
+ parameters: { testOptions: { viewport: { width: 900, height: 2400 } } },
+ decorators: [mswDecorator({ post: { [SETUP_CONTEXT_PATH]: FULL_CONTEXT } })],
+ play: openTheDrawer,
+}
+
+export const SetupContextDrawerDegraded: Story = {
+ decorators: [mswDecorator({ post: { [SETUP_CONTEXT_PATH]: DEGRADED_CONTEXT } })],
+ play: openTheDrawer,
+}
diff --git a/products/experiments/frontend/setupInspector/SetupInspectorButton.tsx b/products/experiments/frontend/setupInspector/SetupInspectorButton.tsx
new file mode 100644
index 000000000000..2a7ecb9aa968
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/SetupInspectorButton.tsx
@@ -0,0 +1,29 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+import { SetupInspectorDrawer } from './SetupInspectorDrawer'
+import { setupInspectorLogic } from './setupInspectorLogic'
+
+export function SetupInspectorButton(): JSX.Element | null {
+ const { canInspect } = useValues(setupInspectorLogic)
+ const { openSetupInspector } = useActions(setupInspectorLogic)
+
+ if (!canInspect) {
+ return null
+ }
+ return (
+ <>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={openSetupInspector}
+ tooltip="See what an agent reads about this project before it creates an experiment."
+ data-attr="experiment-setup-context-open"
+ >
+ Setup context
+ </LemonButton>
+ <SetupInspectorDrawer />
+ </>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/SetupInspectorDrawer.tsx b/products/experiments/frontend/setupInspector/SetupInspectorDrawer.tsx
new file mode 100644
index 000000000000..fd908d90b75b
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/SetupInspectorDrawer.tsx
@@ -0,0 +1,31 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
+import { LemonDrawer } from 'lib/lemon-ui/LemonDrawer/LemonDrawer'
+
+import { SetupInspectorForm } from './SetupInspectorForm'
+import { setupInspectorLogic } from './setupInspectorLogic'
+import { SetupInspectorResults } from './SetupInspectorResults'
+
+export function SetupInspectorDrawer(): JSX.Element {
+ const { isOpen } = useValues(setupInspectorLogic)
+ const { closeSetupInspector } = useActions(setupInspectorLogic)
+
+ return (
+ <LemonDrawer
+ isOpen={isOpen}
+ onClose={closeSetupInspector}
+ width="80vw"
+ resizable
+ title="Experiment setup context"
+ description="The facts the experiment-setup-context tool gives an agent before it creates an experiment in this project."
+ data-attr="experiment-setup-context-drawer"
+ >
+ <div className="@container/drawer flex flex-col gap-4">
+ <SetupInspectorForm />
+ <LemonDivider className="my-0" />
+ <SetupInspectorResults />
+ </div>
+ </LemonDrawer>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/SetupInspectorForm.tsx b/products/experiments/frontend/setupInspector/SetupInspectorForm.tsx
new file mode 100644
index 000000000000..d0f006a20c34
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/SetupInspectorForm.tsx
@@ -0,0 +1,208 @@
+import { useActions, useValues } from 'kea'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { copyToClipboard } from 'lib/utils/copyToClipboard'
+
+import { setupInspectorLogic } from './setupInspectorLogic'
+
+const PROPERTY_GROUP_TYPES = [TaxonomicFilterGroupType.EventProperties, TaxonomicFilterGroupType.PersonProperties]
+
+// A cleared number input reports NaN, which would reach the request as null and fail with a 400.
+function clampLimit(value: number | undefined): number {
+ const limit = value !== undefined && Number.isFinite(value) ? value : 10
+ return Math.min(25, Math.max(1, Math.round(limit)))
+}
+
+function InputStep({
+ step,
+ title,
+ description,
+ children,
+}: {
+ step: number
+ title: string
+ description: string
+ children: React.ReactNode
+}): JSX.Element {
+ return (
+ <LemonCard hoverEffect={false} className="p-4 flex flex-col gap-3">
+ <div className="flex flex-col gap-1">
+ <h4 className="mb-0">
+ {step}. {title}
+ </h4>
+ <p className="text-secondary text-sm mb-0">{description}</p>
+ </div>
+ {children}
+ </LemonCard>
+ )
+}
+
+export function SetupInspectorForm(): JSX.Element {
+ const { inputs, toolInput, setupContext, setupContextLoading, inputsChangedSinceRead } =
+ useValues(setupInspectorLogic)
+ const { setInputs, loadSetupContext } = useActions(setupInspectorLogic)
+
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="flex flex-col gap-1">
+ <h3 className="mb-0">Describe the experiment to check</h3>
+ <p className="text-secondary text-sm mb-0">
+ An agent sends these inputs to experiment-setup-context before it creates an experiment. Fill them
+ in the way an agent would for the experiment you have in mind, then read the setup context. With
+ both steps empty, you get only the project-wide facts: team defaults, SDK profile, previous
+ experiments and shared metrics.
+ </p>
+ </div>
+ <div className="grid grid-cols-1 gap-3 @min-[48rem]/drawer:grid-cols-2">
+ <InputStep
+ step={1}
+ title="Where users see the change"
+ description="The event a user sends on the page or screen you change. It fills the target surface section: traffic, anonymous share and SDKs on that surface."
+ >
+ <LemonField.Pure label="Event">
+ <TaxonomicStringPopover
+ groupType={TaxonomicFilterGroupType.Events}
+ value={inputs.targetEvent}
+ onChange={(targetEvent) => setInputs({ targetEvent: targetEvent || null })}
+ allowClear
+ placeholder="Pick an event, for example $pageview"
+ type="secondary"
+ size="small"
+ data-attr="experiment-setup-context-target-event"
+ />
+ </LemonField.Pure>
+ {inputs.targetEvent === '$pageview' && (
+ <LemonField.Pure label="Page URL contains" help="Matches any part of the URL, ignoring case.">
+ <LemonInput
+ size="small"
+ value={inputs.targetUrlContains}
+ onChange={(targetUrlContains) => setInputs({ targetUrlContains })}
+ placeholder="/pricing"
+ />
+ </LemonField.Pure>
+ )}
+ {inputs.targetEvent && (
+ <LemonField.Pure
+ label="Only count events where"
+ help="For example an exact $host and $pathname to isolate one page."
+ >
+ <PropertyFilters
+ pageKey="experiment-setup-context-target"
+ propertyFilters={inputs.targetProperties}
+ onChange={(targetProperties) => setInputs({ targetProperties })}
+ taxonomicGroupTypes={PROPERTY_GROUP_TYPES}
+ eventNames={[inputs.targetEvent]}
+ buttonSize="small"
+ />
+ </LemonField.Pure>
+ )}
+ </InputStep>
+ <InputStep
+ step={2}
+ title="What the primary metric counts"
+ description="The event the primary metric counts, such as a signup or a purchase. It fills the candidate metric section. With step 1 filled in too, it adds the conversion rate and the baseline the running time calculator takes."
+ >
+ <LemonField.Pure label="Event">
+ <TaxonomicStringPopover
+ groupType={TaxonomicFilterGroupType.Events}
+ value={inputs.metricEvent}
+ onChange={(metricEvent) => setInputs({ metricEvent: metricEvent || null })}
+ allowClear
+ placeholder="Pick an event, for example a signup"
+ type="secondary"
+ size="small"
+ data-attr="experiment-setup-context-metric-event"
+ />
+ </LemonField.Pure>
+ {inputs.metricEvent && (
+ <LemonField.Pure
+ label="Only count events where"
+ help="For a metric that counts only some of these events."
+ >
+ <PropertyFilters
+ pageKey="experiment-setup-context-metric"
+ propertyFilters={inputs.metricProperties}
+ onChange={(metricProperties) => setInputs({ metricProperties })}
+ taxonomicGroupTypes={PROPERTY_GROUP_TYPES}
+ eventNames={[inputs.metricEvent]}
+ buttonSize="small"
+ />
+ </LemonField.Pure>
+ )}
+ </InputStep>
+ </div>
+ <div className="flex flex-wrap items-center gap-2 text-sm">
+ <span>List the last</span>
+ <LemonInput
+ type="number"
+ size="xsmall"
+ min={1}
+ max={25}
+ className="w-16"
+ value={inputs.previousExperimentsLimit}
+ onChange={(value) => setInputs({ previousExperimentsLimit: clampLimit(value) })}
+ aria-label="Previous experiments to list"
+ />
+ <span>experiments and the</span>
+ <LemonInput
+ type="number"
+ size="xsmall"
+ min={1}
+ max={25}
+ className="w-16"
+ value={inputs.sharedMetricsLimit}
+ onChange={(value) => setInputs({ sharedMetricsLimit: clampLimit(value) })}
+ aria-label="Shared metrics to list"
+ />
+ <span>most reused shared metrics.</span>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={() => loadSetupContext()}
+ loading={setupContextLoading}
+ data-attr="experiment-setup-context-read"
+ >
+ Read setup context
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => void copyToClipboard(JSON.stringify(setupContext, null, 2), 'setup context JSON')}
+ disabledReason={setupContext ? undefined : 'Read the setup context first.'}
+ data-attr="experiment-setup-context-copy-json"
+ >
+ Copy result as JSON
+ </LemonButton>
+ {inputsChangedSinceRead && !setupContextLoading && (
+ <span className="text-warning text-sm">
+ The inputs changed. The results below are for the previous inputs.
+ </span>
+ )}
+ </div>
+ <LemonCollapse
+ size="small"
+ panels={[
+ {
+ key: 'tool-input',
+ header: 'Tool input an agent would send',
+ content: (
+ <CodeSnippet language={Language.JSON} compact>
+ {JSON.stringify(toolInput, null, 2)}
+ </CodeSnippet>
+ ),
+ },
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/SetupInspectorResults.tsx b/products/experiments/frontend/setupInspector/SetupInspectorResults.tsx
new file mode 100644
index 000000000000..135e81cd8570
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/SetupInspectorResults.tsx
@@ -0,0 +1,43 @@
+import { useValues } from 'kea'
+
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+
+import { CandidateMetricSection } from './sections/CandidateMetricSection'
+import { IdentitySummarySection } from './sections/IdentitySummarySection'
+import { PreviousExperimentsSection } from './sections/PreviousExperimentsSection'
+import { SdkProfileSection } from './sections/SdkProfileSection'
+import { SharedMetricsSection } from './sections/SharedMetricsSection'
+import { TargetSurfaceSection } from './sections/TargetSurfaceSection'
+import { TeamDefaultsSection } from './sections/TeamDefaultsSection'
+import { setupInspectorLogic } from './setupInspectorLogic'
+
+export function SetupInspectorResults(): JSX.Element {
+ const { setupContext, setupContextLoading, setupContextError, identitySummary } = useValues(setupInspectorLogic)
+
+ if (setupContextLoading && !setupContext) {
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSkeleton className="h-8 w-1/3" />
+ <LemonSkeleton repeat={6} className="h-6" />
+ </div>
+ )
+ }
+ if (setupContextError) {
+ return <LemonBanner type="error">{setupContextError}</LemonBanner>
+ }
+ if (!setupContext) {
+ return <p className="text-secondary mb-0">Read the setup context to see what an agent sees.</p>
+ }
+ return (
+ <div className="flex flex-col gap-6">
+ {identitySummary && <IdentitySummarySection facts={identitySummary} />}
+ <TeamDefaultsSection section={setupContext.team_defaults} />
+ <SdkProfileSection section={setupContext.sdk_profile} />
+ <TargetSurfaceSection section={setupContext.target_surface} />
+ <CandidateMetricSection section={setupContext.candidate_metric} />
+ <PreviousExperimentsSection section={setupContext.previous_experiments} />
+ <SharedMetricsSection section={setupContext.shared_metrics} />
+ </div>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/SetupStackedCell.tsx b/products/experiments/frontend/setupInspector/SetupStackedCell.tsx
new file mode 100644
index 000000000000..b84c8a9fe47a
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/SetupStackedCell.tsx
@@ -0,0 +1,13 @@
+/** A table cell with one fact per line. The first line is the main fact, falsy lines are left out. */
+export function SetupStackedCell({ lines }: { lines: (string | null | undefined | false)[] }): JSX.Element {
+ const shown = lines.filter((line): line is string => !!line)
+ return (
+ <div className="flex flex-col text-xs" translate="no">
+ {shown.map((line, index) => (
+ <span key={index} className={index === 0 ? undefined : 'text-secondary'}>
+ {line}
+ </span>
+ ))}
+ </div>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/sections/CandidateMetricSection.tsx b/products/experiments/frontend/setupInspector/sections/CandidateMetricSection.tsx
new file mode 100644
index 000000000000..2e22c5918d54
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/sections/CandidateMetricSection.tsx
@@ -0,0 +1,62 @@
+import type { ExperimentSetupCandidateMetricSectionApi } from 'products/experiments/frontend/generated/api.schemas'
+
+import { SetupContextSection } from '../SetupContextSection'
+import { SetupFactsTable } from '../SetupFactsTable'
+import { formatCount, formatPropertyFilters, formatShare, formatTimestamp, formatYesNo } from '../setupInspectorUtils'
+
+export function CandidateMetricSection({
+ section,
+}: {
+ section: ExperimentSetupCandidateMetricSectionApi
+}): JSX.Element {
+ const data = section.data
+ const funnel = data?.funnel_baseline_stats
+ const meanCount = data?.mean_count_baseline_stats
+ return (
+ <SetupContextSection
+ title="Candidate metric"
+ description="Traffic and baseline of the candidate primary metric. The baselines are the input the running time calculator takes."
+ status={section.status}
+ skippedMessage="Pick an event in step 2 above to read this section."
+ >
+ {data && (
+ <SetupFactsTable
+ facts={[
+ { label: 'Metric event', value: data.source_event },
+ { label: 'Property filters', value: formatPropertyFilters(data.metric_properties) },
+ { label: 'Target event', value: data.target_event ?? 'None' },
+ { label: 'Test accounts filtered', value: formatYesNo(data.test_accounts_filtered) },
+ {
+ label: 'Event volume',
+ value: formatCount(data.event_volume),
+ help: 'A volume of 0 means the event did not occur under these filters. Check the event name.',
+ },
+ { label: 'Unique persons', value: formatCount(data.unique_persons) },
+ { label: 'Persons reached', value: formatCount(data.persons_reached) },
+ {
+ label: 'Persons converted',
+ value: formatCount(data.persons_converted),
+ help: 'Persons who sent the metric event at or after their first target event.',
+ },
+ { label: 'Conversion rate', value: formatShare(data.conversion_rate) },
+ {
+ label: 'Funnel baseline',
+ value: funnel
+ ? `${formatCount(funnel.number_of_samples)} samples, step counts ${funnel.step_counts.join(', ')}`
+ : 'None',
+ },
+ {
+ label: 'Mean count baseline',
+ value: meanCount
+ ? `${formatCount(meanCount.number_of_samples)} samples, sum ${formatCount(meanCount.sum)}, sum of squares ${formatCount(meanCount.sum_squares)}`
+ : 'None',
+ help: data.note ?? undefined,
+ },
+ { label: 'Window', value: `Last ${data.window_days} days` },
+ { label: 'Computed at', value: formatTimestamp(data.computed_at) },
+ ]}
+ />
+ )}
+ </SetupContextSection>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/sections/IdentitySummarySection.tsx b/products/experiments/frontend/setupInspector/sections/IdentitySummarySection.tsx
new file mode 100644
index 000000000000..c94cc182c1e7
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/sections/IdentitySummarySection.tsx
@@ -0,0 +1,15 @@
+import { SetupFactsTable } from '../SetupFactsTable'
+import type { IdentityFact } from '../setupInspectorUtils'
+
+export function IdentitySummarySection({ facts }: { facts: IdentityFact[] }): JSX.Element {
+ return (
+ <section className="flex flex-col gap-2">
+ <h3 className="mb-0">Identity and bucketing</h3>
+ <p className="text-secondary text-sm mb-0">
+ The facts behind most identity and bucketing questions, taken from the SDK profile and the target
+ surface below.
+ </p>
+ <SetupFactsTable facts={facts} />
+ </section>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/sections/PreviousExperimentsSection.tsx b/products/experiments/frontend/setupInspector/sections/PreviousExperimentsSection.tsx
new file mode 100644
index 000000000000..04607ab01aab
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/sections/PreviousExperimentsSection.tsx
@@ -0,0 +1,198 @@
+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+import { urls } from 'scenes/urls'
+
+import type {
+ ExperimentSetupOutcomeApi,
+ ExperimentSetupPreviousExperimentApi,
+ ExperimentSetupPreviousExperimentsSectionApi,
+ PreviousExperimentStateEnumApi,
+} from 'products/experiments/frontend/generated/api.schemas'
+
+import { SetupContextSection } from '../SetupContextSection'
+import { SetupFactsTable } from '../SetupFactsTable'
+import { formatCount, formatTimestamp } from '../setupInspectorUtils'
+import { SetupStackedCell } from '../SetupStackedCell'
+
+const STATE_LABELS: Record<PreviousExperimentStateEnumApi, string> = {
+ draft: 'Draft',
+ running: 'Running',
+ paused: 'Paused',
+ exposure_frozen: 'Exposure frozen',
+ stopped: 'Stopped',
+}
+
+function splitLines(experiment: ExperimentSetupPreviousExperimentApi): (string | null)[] {
+ const split = experiment.serving_single_variant
+ ? `Serves ${experiment.serving_single_variant} only`
+ : experiment.split_even === null
+ ? 'Boolean flag'
+ : experiment.split_even
+ ? 'Even split'
+ : 'Uneven split'
+ return [
+ split,
+ `${experiment.variant_count} variants`,
+ experiment.rollout_percentage === null ? null : `${experiment.rollout_percentage}% rollout`,
+ ]
+}
+
+function bucketingLines(experiment: ExperimentSetupPreviousExperimentApi): (string | false)[] {
+ return [
+ experiment.bucketing_identifier === 'device_id' ? 'Device ID' : 'Distinct ID',
+ experiment.ensure_experience_continuity && 'Persists across authentication',
+ `Evaluated on ${experiment.evaluation_runtime}`,
+ experiment.group_aggregation && 'Groups, not persons',
+ ]
+}
+
+function exposureLines(experiment: ExperimentSetupPreviousExperimentApi): (string | false)[] {
+ const event = experiment.custom_exposure_event
+ ? `Custom: ${experiment.custom_exposure_event}`
+ : experiment.custom_exposure_action_id !== null
+ ? `Custom: action ${experiment.custom_exposure_action_id}`
+ : 'Default event'
+ const filterCount = experiment.exposure_property_filters.length
+ return [
+ event,
+ filterCount > 0 && `${filterCount} property ${filterCount === 1 ? 'filter' : 'filters'}`,
+ experiment.activation_event !== null && `Activation: ${experiment.activation_event}`,
+ experiment.activation_action_id !== null && `Activation: action ${experiment.activation_action_id}`,
+ `Multiple variants: ${experiment.multiple_variant_handling}${experiment.multiple_variant_handling_set ? '' : ' (default)'}`,
+ !experiment.filter_test_accounts && 'Test accounts included',
+ ]
+}
+
+function controlBaseline(outcome: ExperimentSetupOutcomeApi): string | null {
+ if (outcome.control_baseline_value === null) {
+ return null
+ }
+ return outcome.metric_type === 'funnel'
+ ? `Control ${percentage(outcome.control_baseline_value, 2)}`
+ : `Control ${humanFriendlyNumber(outcome.control_baseline_value, 3)} per unit`
+}
+
+function outcomeLines(outcome: ExperimentSetupOutcomeApi | null): (string | null)[] {
+ if (!outcome) {
+ return ['No result']
+ }
+ return [
+ outcome.analyzed_exposures === null
+ ? `${formatCount(outcome.metric_samples)} ${outcome.metric_type} samples`
+ : `${formatCount(outcome.analyzed_exposures)} analyzed exposures`,
+ controlBaseline(outcome),
+ outcome.any_variant_significant ? 'A variant is significant' : 'No significant variant',
+ `Data through ${formatTimestamp(outcome.result_data_through)}`,
+ `Computed ${formatTimestamp(outcome.result_completed_at)}`,
+ ]
+}
+
+const COLUMNS: LemonTableColumns<ExperimentSetupPreviousExperimentApi> = [
+ {
+ title: 'Experiment',
+ render: (_, experiment) => (
+ <LemonTableLink
+ to={urls.experiment(experiment.id)}
+ target="_blank"
+ title={experiment.name}
+ description={experiment.feature_flag_key}
+ />
+ ),
+ },
+ {
+ title: 'State',
+ render: (_, experiment) => (
+ <SetupStackedCell
+ lines={[
+ STATE_LABELS[experiment.state],
+ experiment.start_date ? `Launched ${formatTimestamp(experiment.start_date)}` : null,
+ experiment.end_date ? `Ended ${formatTimestamp(experiment.end_date)}` : null,
+ experiment.conclusion,
+ ]}
+ />
+ ),
+ },
+ { title: 'Flag', render: (_, experiment) => <SetupStackedCell lines={splitLines(experiment)} /> },
+ { title: 'Bucketing', render: (_, experiment) => <SetupStackedCell lines={bucketingLines(experiment)} /> },
+ { title: 'Exposure', render: (_, experiment) => <SetupStackedCell lines={exposureLines(experiment)} /> },
+ {
+ title: 'Metrics',
+ render: (_, experiment) => (
+ <SetupStackedCell
+ lines={[
+ `${experiment.primary_metric_count} primary, ${experiment.secondary_metric_count} secondary, ${experiment.shared_metric_count} shared`,
+ experiment.primary_metric_types.join(', '),
+ [
+ ...experiment.primary_metric_events,
+ ...experiment.primary_metric_action_ids.map((id) => `action ${id}`),
+ ].join(', '),
+ `${experiment.stats_method}${experiment.minimum_detectable_effect === null ? '' : `, MDE ${experiment.minimum_detectable_effect}%`}`,
+ experiment.has_holdout ? 'Holdout' : null,
+ ]}
+ />
+ ),
+ },
+ { title: 'Outcome', render: (_, experiment) => <SetupStackedCell lines={outcomeLines(experiment.outcome)} /> },
+]
+
+export function PreviousExperimentsSection({
+ section,
+}: {
+ section: ExperimentSetupPreviousExperimentsSectionApi
+}): JSX.Element {
+ const data = section.data
+ const summary = data?.summary
+ return (
+ <SetupContextSection
+ title="Previous experiments"
+ description="How the project's recent experiments were set up and how they went. Most recently launched first, then drafts. Flag settings are read from each flag as it stands now."
+ status={section.status}
+ >
+ {data && summary && (
+ <>
+ <SetupFactsTable
+ facts={[
+ { label: 'Listed', value: String(summary.total) },
+ { label: 'Launched', value: String(summary.launched) },
+ { label: 'Launched without results', value: String(summary.launched_without_results) },
+ {
+ label: 'Launched with 0 analyzed exposures',
+ value: String(summary.launched_with_zero_analyzed_exposures),
+ },
+ {
+ label: 'Launched with under 100 analyzed exposures',
+ value: String(summary.launched_with_under_100_analyzed_exposures),
+ },
+ {
+ label: 'Launched with unknown exposures',
+ value: String(summary.launched_with_unknown_analyzed_exposures),
+ help: 'The result stores no sample counts, or its metric is a retention or a ratio metric, whose samples are not exposures.',
+ },
+ { label: 'Device ID bucketing', value: String(summary.using_device_id_bucketing) },
+ {
+ label: 'Persist flags across authentication',
+ value: String(summary.using_persistence),
+ },
+ { label: 'Custom exposure', value: String(summary.using_custom_exposure) },
+ {
+ label: 'Exposure property filters',
+ value: String(summary.using_exposure_property_filters),
+ },
+ { label: 'Activation', value: String(summary.using_activation) },
+ { label: 'Uneven split', value: String(summary.using_uneven_split) },
+ { label: 'Serving a single variant', value: String(summary.serving_single_variant) },
+ ]}
+ />
+ <LemonTable
+ size="small"
+ rowKey="id"
+ dataSource={data.experiments}
+ columns={COLUMNS}
+ emptyState="This project has no experiments you can see."
+ />
+ </>
+ )}
+ </SetupContextSection>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/sections/SdkProfileSection.tsx b/products/experiments/frontend/setupInspector/sections/SdkProfileSection.tsx
new file mode 100644
index 000000000000..423a8681d8e6
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/sections/SdkProfileSection.tsx
@@ -0,0 +1,100 @@
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
+
+import type {
+ ExperimentSetupLibActivityApi,
+ ExperimentSetupSdkLibApi,
+ ExperimentSetupSdkProfileSectionApi,
+} from 'products/experiments/frontend/generated/api.schemas'
+
+import { SetupContextSection } from '../SetupContextSection'
+import { SetupFactsTable } from '../SetupFactsTable'
+import { formatCount, formatShare, formatTimestamp, formatYesNo } from '../setupInspectorUtils'
+
+export function SdkProfileSection({ section }: { section: ExperimentSetupSdkProfileSectionApi }): JSX.Element {
+ const data = section.data
+ return (
+ <SetupContextSection
+ title="SDK profile"
+ description="Which SDKs send multivariate flag calls across the whole project, and how they evaluate flags."
+ status={section.status}
+ >
+ {data && (
+ <>
+ <SetupFactsTable
+ facts={[
+ { label: 'Source event', value: data.source_event },
+ { label: 'Window', value: `Last ${data.window_days} days` },
+ { label: 'Flags seen', value: formatCount(data.flags_seen) },
+ {
+ label: 'Same flag evaluated on a server and on the web',
+ value: `${formatYesNo(data.evaluated_on_server_and_web)} (${formatCount(data.flags_evaluated_on_server_and_web)} flags)`,
+ help: 'The same flag decided on the server and read in the browser can put one user in two variants.',
+ },
+ { label: 'Computed at', value: formatTimestamp(data.computed_at) },
+ ]}
+ />
+ <LemonTable<ExperimentSetupSdkLibApi>
+ size="small"
+ rowKey={(lib, index) => lib.lib ?? `unknown-${index}`}
+ dataSource={data.libs}
+ emptyState="No multivariate flag calls in the window."
+ columns={[
+ { title: 'SDK', render: (_, lib) => lib.lib ?? 'unknown' },
+ { title: 'Category', dataIndex: 'category' },
+ { title: 'Calls', align: 'right', render: (_, lib) => formatCount(lib.calls) },
+ {
+ title: 'Distinct IDs',
+ align: 'right',
+ render: (_, lib) => formatCount(lib.distinct_ids),
+ },
+ {
+ title: 'Evaluated locally',
+ align: 'right',
+ render: (_, lib) => formatShare(lib.locally_evaluated_share),
+ },
+ {
+ title: 'Anonymous',
+ align: 'right',
+ render: (_, lib) => formatShare(lib.anonymous_share),
+ },
+ {
+ title: 'Device ID',
+ align: 'right',
+ render: (_, lib) => formatShare(lib.device_id_share),
+ },
+ ]}
+ />
+ {data.libs_truncated && (
+ <p className="text-secondary text-sm mb-0">More SDKs sent flag calls than the list shows.</p>
+ )}
+ {data.libs_on_any_event && (
+ <>
+ <p className="text-sm mb-0">
+ No flag calls yet. These SDKs sent events of any kind over the last day:
+ </p>
+ <LemonTable<ExperimentSetupLibActivityApi>
+ size="small"
+ rowKey={(lib, index) => lib.lib ?? `unknown-${index}`}
+ dataSource={data.libs_on_any_event}
+ columns={[
+ { title: 'SDK', render: (_, lib) => lib.lib ?? 'unknown' },
+ { title: 'Category', dataIndex: 'category' },
+ {
+ title: 'Events',
+ align: 'right',
+ render: (_, lib) => formatCount(lib.events),
+ },
+ {
+ title: 'Distinct IDs',
+ align: 'right',
+ render: (_, lib) => formatCount(lib.distinct_ids),
+ },
+ ]}
+ />
+ </>
+ )}
+ </>
+ )}
+ </SetupContextSection>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/sections/SharedMetricsSection.tsx b/products/experiments/frontend/setupInspector/sections/SharedMetricsSection.tsx
new file mode 100644
index 000000000000..0d2b270267b4
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/sections/SharedMetricsSection.tsx
@@ -0,0 +1,91 @@
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
+import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
+import { urls } from 'scenes/urls'
+
+import type {
+ ExperimentSetupSharedMetricApi,
+ ExperimentSetupSharedMetricsSectionApi,
+} from 'products/experiments/frontend/generated/api.schemas'
+
+import { SetupContextSection } from '../SetupContextSection'
+import { formatTimestamp, formatYesNo } from '../setupInspectorUtils'
+import { SetupStackedCell } from '../SetupStackedCell'
+
+export function SharedMetricsSection({ section }: { section: ExperimentSetupSharedMetricsSectionApi }): JSX.Element {
+ const data = section.data
+ return (
+ <SetupContextSection
+ title="Shared metrics"
+ description="The shared metrics the project reuses most. With a metric event, the ones that count it come first."
+ status={section.status}
+ >
+ {data && (
+ <>
+ {data.metric_event_match_truncated && (
+ <p className="text-sm mb-0">
+ The project has more shared metrics than the match could read, so a match further down may
+ be missing.
+ </p>
+ )}
+ <LemonTable<ExperimentSetupSharedMetricApi>
+ size="small"
+ rowKey="id"
+ dataSource={data.metrics}
+ emptyState="This project has no shared metrics you can see."
+ columns={[
+ {
+ title: 'Shared metric',
+ render: (_, metric) => (
+ <LemonTableLink
+ to={urls.experimentsSharedMetric(metric.id)}
+ target="_blank"
+ title={metric.name}
+ description={metric.metric_type ?? 'Legacy metric'}
+ />
+ ),
+ },
+ {
+ title: 'Events and actions',
+ render: (_, metric) => (
+ <SetupStackedCell
+ lines={[
+ metric.events.join(', '),
+ ...metric.action_ids.map((id) => `action ${id}`),
+ ]}
+ />
+ ),
+ },
+ {
+ title: 'Used',
+ render: (_, metric) => (
+ <SetupStackedCell
+ lines={[
+ `${metric.used_as_primary} primary, ${metric.used_as_secondary} secondary`,
+ metric.last_used_at
+ ? `Last used ${formatTimestamp(metric.last_used_at)}`
+ : 'Never used',
+ ]}
+ />
+ ),
+ },
+ {
+ title: `Counts ${data.metric_event ?? 'the metric event'}`,
+ render: (_, metric) =>
+ metric.matches_metric_event === null ? (
+ <span className="text-secondary text-xs">No metric event passed</span>
+ ) : (
+ <SetupStackedCell
+ lines={[
+ formatYesNo(metric.matches_metric_event),
+ (metric.metric_event_roles ?? []).join(', '),
+ ]}
+ />
+ ),
+ },
+ ]}
+ />
+ </>
+ )}
+ </SetupContextSection>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/sections/TargetSurfaceSection.tsx b/products/experiments/frontend/setupInspector/sections/TargetSurfaceSection.tsx
new file mode 100644
index 000000000000..956769545bf9
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/sections/TargetSurfaceSection.tsx
@@ -0,0 +1,70 @@
+import { LemonTable } from 'lib/lemon-ui/LemonTable'
+
+import type {
+ ExperimentSetupLibReachApi,
+ ExperimentSetupTargetSurfaceSectionApi,
+} from 'products/experiments/frontend/generated/api.schemas'
+
+import { SetupContextSection } from '../SetupContextSection'
+import { SetupFactsTable } from '../SetupFactsTable'
+import { formatCount, formatPropertyFilters, formatShare, formatTimestamp, formatYesNo } from '../setupInspectorUtils'
+
+export function TargetSurfaceSection({ section }: { section: ExperimentSetupTargetSurfaceSectionApi }): JSX.Element {
+ const data = section.data
+ return (
+ <SetupContextSection
+ title="Target surface"
+ description="Traffic on the surface under test."
+ status={section.status}
+ skippedMessage="Pick an event in step 1 above to read this section."
+ >
+ {data && (
+ <>
+ <SetupFactsTable
+ facts={[
+ { label: 'Target event', value: data.source_event },
+ { label: 'URL contains', value: data.target_url_contains ?? 'None' },
+ { label: 'Property filters', value: formatPropertyFilters(data.target_properties) },
+ { label: 'Test accounts filtered', value: formatYesNo(data.test_accounts_filtered) },
+ { label: 'Unique persons', value: formatCount(data.unique_persons) },
+ {
+ label: 'Exposures per day, estimated',
+ value: formatCount(data.exposures_per_day_estimate),
+ help: 'Unique persons divided by the days in the window.',
+ },
+ { label: 'Anonymous share', value: formatShare(data.anonymous_share) },
+ { label: 'Device ID share', value: formatShare(data.device_id_share) },
+ { label: 'Window', value: `Last ${data.window_days} days` },
+ { label: 'Computed at', value: formatTimestamp(data.computed_at) },
+ ]}
+ />
+ <LemonTable<ExperimentSetupLibReachApi>
+ size="small"
+ rowKey={(lib, index) => lib.lib ?? `unknown-${index}`}
+ dataSource={data.libs}
+ emptyState="No SDK sent the target event in the window."
+ columns={[
+ { title: 'SDK', render: (_, lib) => lib.lib ?? 'unknown' },
+ { title: 'Category', dataIndex: 'category' },
+ {
+ title: 'Persons',
+ align: 'right',
+ render: (_, lib) => formatCount(lib.unique_persons),
+ },
+ {
+ title: 'Anonymous',
+ align: 'right',
+ render: (_, lib) => formatShare(lib.anonymous_share),
+ },
+ {
+ title: 'Device ID',
+ align: 'right',
+ render: (_, lib) => formatShare(lib.device_id_share),
+ },
+ ]}
+ />
+ </>
+ )}
+ </SetupContextSection>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/sections/TeamDefaultsSection.tsx b/products/experiments/frontend/setupInspector/sections/TeamDefaultsSection.tsx
new file mode 100644
index 000000000000..636b1ab6035f
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/sections/TeamDefaultsSection.tsx
@@ -0,0 +1,56 @@
+import type { ExperimentSetupTeamDefaultsSectionApi } from 'products/experiments/frontend/generated/api.schemas'
+
+import { SetupContextSection } from '../SetupContextSection'
+import { SetupFactsTable } from '../SetupFactsTable'
+import { formatYesNo } from '../setupInspectorUtils'
+
+function withProductDefault(value: string | number | null, productDefault: string | number): string {
+ return value === null ? `Not set, product default ${productDefault}` : String(value)
+}
+
+export function TeamDefaultsSection({ section }: { section: ExperimentSetupTeamDefaultsSectionApi }): JSX.Element {
+ const data = section.data
+ return (
+ <SetupContextSection
+ title="Team defaults"
+ description="The defaults a new experiment in this project starts from."
+ status={section.status}
+ >
+ {data && (
+ <SetupFactsTable
+ facts={[
+ {
+ label: 'Stats method',
+ value: withProductDefault(data.stats_method, data.product_default_stats_method),
+ },
+ {
+ label: 'Confidence level',
+ value: withProductDefault(data.confidence_level, data.product_default_confidence_level),
+ },
+ {
+ label: 'Minimum detectable effect',
+ value: withProductDefault(
+ data.minimum_detectable_effect === null ? null : `${data.minimum_detectable_effect}%`,
+ `${data.product_default_minimum_detectable_effect}%`
+ ),
+ },
+ { label: 'Only count matured users', value: formatYesNo(data.only_count_matured_users) },
+ { label: 'CUPED', value: formatYesNo(data.cuped_enabled) },
+ { label: 'Sequential testing', value: formatYesNo(data.sequential_testing_enabled) },
+ {
+ label: 'Persist flags across authentication',
+ value: formatYesNo(data.flags_persistence_default),
+ help: 'Becomes ensure_experience_continuity on a flag the experiment creates.',
+ },
+ { label: 'Test account filters', value: String(data.test_account_filter_count) },
+ {
+ label: 'New experiments filter test accounts',
+ value: formatYesNo(data.new_experiments_filter_test_accounts),
+ },
+ { label: 'Default exposure event', value: data.default_exposure_event },
+ ]}
+ />
+ )}
+ </SetupContextSection>
+ )
+}
diff --git a/products/experiments/frontend/setupInspector/setupInspectorLogic.ts b/products/experiments/frontend/setupInspector/setupInspectorLogic.ts
new file mode 100644
index 000000000000..409ef6bfd98e
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/setupInspectorLogic.ts
@@ -0,0 +1,218 @@
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { superpowersLogic } from 'lib/components/Superpowers/superpowersLogic'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { objectsEqual } from 'lib/utils/objects'
+import { projectLogic } from 'scenes/projectLogic'
+import { userLogic } from 'scenes/userLogic'
+
+import type { UserType } from '~/types'
+
+import { experimentsSetupContextCreate } from 'products/experiments/frontend/generated/api'
+import type {
+ ExperimentSetupContextInputApi,
+ ExperimentSetupContextResponseApi,
+} from 'products/experiments/frontend/generated/api.schemas'
+
+import {
+ DEFAULT_SETUP_INSPECTOR_INPUTS,
+ IdentityFact,
+ SetupInspectorInputs,
+ canInspectSetupContext,
+ describeSetupContextError,
+ summarizeIdentity,
+ toSetupContextInput,
+} from './setupInspectorUtils'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface setupInspectorLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ currentProjectId: number | null // projectLogic
+ superpowersEnabled: boolean | undefined // superpowersLogic
+ user: UserType | null // userLogic
+ canInspect: boolean
+ identitySummary: IdentityFact[] | null
+ inputs: SetupInspectorInputs
+ inputsChangedSinceRead: boolean
+ isOpen: boolean
+ readInputs: SetupInspectorInputs | null
+ setupContext: ExperimentSetupContextResponseApi | null
+ setupContextError: string | null
+ setupContextLoading: boolean
+ toolInput: ExperimentSetupContextInputApi
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface setupInspectorLogicActions {
+ closeSetupInspector: () => {
+ value: true
+ }
+ loadSetupContext: () => any
+ loadSetupContextFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSetupContextSuccess: (
+ setupContext: ExperimentSetupContextResponseApi | null,
+ payload?: any
+ ) => {
+ setupContext: ExperimentSetupContextResponseApi | null
+ payload?: any
+ }
+ openSetupInspector: () => {
+ value: true
+ }
+ setInputs: (inputs: Partial<SetupInspectorInputs>) => {
+ inputs: Partial<SetupInspectorInputs>
+ }
+ setReadInputs: (inputs: SetupInspectorInputs) => {
+ inputs: SetupInspectorInputs
+ }
+ setSetupContextError: (error: string | null) => {
+ error: string | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface setupInspectorLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ canInspect: (
+ featureFlags: FeatureFlagsSet,
+ superpowersEnabled: boolean | undefined,
+ user: UserType | null
+ ) => boolean
+ toolInput: (inputs: SetupInspectorInputs) => ExperimentSetupContextInputApi
+ inputsChangedSinceRead: (
+ toolInput: ExperimentSetupContextInputApi,
+ readInputs: SetupInspectorInputs | null,
+ setupContext: ExperimentSetupContextResponseApi | null
+ ) => boolean
+ identitySummary: (setupContext: ExperimentSetupContextResponseApi | null) => IdentityFact[] | null
+ }
+}
+
+export type setupInspectorLogicType = MakeLogicType<
+ setupInspectorLogicValues,
+ setupInspectorLogicActions,
+ Record<string, any>,
+ setupInspectorLogicMeta
+>
+
+export const setupInspectorLogic = kea<setupInspectorLogicType>([
+ path(['products', 'experiments', 'frontend', 'setupInspector', 'setupInspectorLogic']),
+ connect(() => ({
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ projectLogic,
+ ['currentProjectId'],
+ superpowersLogic,
+ ['superpowersEnabled'],
+ userLogic,
+ ['user'],
+ ],
+ })),
+ actions({
+ openSetupInspector: true,
+ closeSetupInspector: true,
+ setInputs: (inputs: Partial<SetupInspectorInputs>) => ({ inputs }),
+ setSetupContextError: (error: string | null) => ({ error }),
+ setReadInputs: (inputs: SetupInspectorInputs) => ({ inputs }),
+ }),
+ loaders(({ actions, values }) => ({
+ setupContext: [
+ null as ExperimentSetupContextResponseApi | null,
+ {
+ // The error is caught here and shown in the drawer, because the loader's failure path
+ // would also raise a toast for the same message.
+ loadSetupContext: async () => {
+ actions.setSetupContextError(null)
+ actions.setReadInputs(values.inputs)
+ try {
+ return await experimentsSetupContextCreate(
+ String(values.currentProjectId),
+ toSetupContextInput(values.inputs)
+ )
+ } catch (error) {
+ actions.setSetupContextError(describeSetupContextError(error))
+ return null
+ }
+ },
+ },
+ ],
+ })),
+ reducers({
+ isOpen: [
+ false,
+ {
+ openSetupInspector: () => true,
+ closeSetupInspector: () => false,
+ },
+ ],
+ inputs: [
+ DEFAULT_SETUP_INSPECTOR_INPUTS,
+ {
+ setInputs: (state, { inputs }) => ({ ...state, ...inputs }),
+ },
+ ],
+ setupContextError: [
+ null as string | null,
+ {
+ setSetupContextError: (_, { error }) => error,
+ },
+ ],
+ readInputs: [
+ null as SetupInspectorInputs | null,
+ {
+ setReadInputs: (_, { inputs }) => inputs,
+ },
+ ],
+ }),
+ selectors({
+ canInspect: [
+ (s) => [s.featureFlags, s.superpowersEnabled, s.user],
+ (featureFlags: FeatureFlagsSet, superpowersEnabled: boolean | undefined, user: UserType | null): boolean =>
+ canInspectSetupContext({
+ isImpersonated: !!user?.is_impersonated,
+ superpowersEnabled: !!superpowersEnabled,
+ flagEnabled: !!featureFlags[FEATURE_FLAGS.EXPERIMENT_SETUP_CONTEXT],
+ }),
+ ],
+ toolInput: [
+ (s) => [s.inputs],
+ (inputs: SetupInspectorInputs): ExperimentSetupContextInputApi => toSetupContextInput(inputs),
+ ],
+ // Compared as the request they produce, so a change that sends nothing new does not count. A failed
+ // read leaves no results, so there is nothing to mark as stale.
+ inputsChangedSinceRead: [
+ (s) => [s.toolInput, s.readInputs, s.setupContext],
+ (
+ toolInput: ExperimentSetupContextInputApi,
+ readInputs: SetupInspectorInputs | null,
+ setupContext: ExperimentSetupContextResponseApi | null
+ ): boolean =>
+ setupContext !== null &&
+ readInputs !== null &&
+ !objectsEqual(toolInput, toSetupContextInput(readInputs)),
+ ],
+ identitySummary: [
+ (s) => [s.setupContext],
+ (setupContext: ExperimentSetupContextResponseApi | null): IdentityFact[] | null =>
+ setupContext ? summarizeIdentity(setupContext) : null,
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ // The sections that need no input are worth reading the moment the drawer opens.
+ openSetupInspector: () => {
+ if (!values.setupContext && !values.setupContextLoading && !values.setupContextError) {
+ actions.loadSetupContext()
+ }
+ },
+ })),
+])
diff --git a/products/experiments/frontend/setupInspector/setupInspectorUtils.test.ts b/products/experiments/frontend/setupInspector/setupInspectorUtils.test.ts
new file mode 100644
index 000000000000..a7ae4133f773
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/setupInspectorUtils.test.ts
@@ -0,0 +1,73 @@
+import { CohortPropertyFilter, EventPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
+
+import {
+ DEFAULT_SETUP_INSPECTOR_INPUTS,
+ SetupInspectorInputs,
+ canInspectSetupContext,
+ toSetupContextInput,
+} from './setupInspectorUtils'
+
+describe('setupInspectorUtils', () => {
+ test.each([
+ { name: 'staff with the flag', isImpersonated: false, superpowersEnabled: true, flagEnabled: true, can: true },
+ {
+ name: 'staff without the flag',
+ isImpersonated: false,
+ superpowersEnabled: true,
+ flagEnabled: false,
+ can: false,
+ },
+ // The flag also gates the MCP tool, so a customer can have it on. That alone must not show the drawer.
+ {
+ name: 'customer with the flag',
+ isImpersonated: false,
+ superpowersEnabled: false,
+ flagEnabled: true,
+ can: false,
+ },
+ { name: 'impersonating staff', isImpersonated: true, superpowersEnabled: false, flagEnabled: false, can: true },
+ ])('canInspectSetupContext: $name', ({ isImpersonated, superpowersEnabled, flagEnabled, can }) => {
+ expect(canInspectSetupContext({ isImpersonated, superpowersEnabled, flagEnabled })).toBe(can)
+ })
+
+ const pathnameFilter: EventPropertyFilter = {
+ key: '$pathname',
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: ['/'],
+ }
+ const cohortFilter: CohortPropertyFilter = {
+ key: 'id',
+ type: PropertyFilterType.Cohort,
+ operator: PropertyOperator.In,
+ value: 3,
+ }
+ const requestCases: { name: string; inputs: Partial<SetupInspectorInputs>; expected: Record<string, unknown> }[] = [
+ {
+ name: 'drops a URL filter left over from $pageview',
+ inputs: { targetEvent: '$screen', targetUrlContains: '/pricing' },
+ expected: { target_event: '$screen', target_url_contains: null },
+ },
+ {
+ name: 'drops target filters once the target event is cleared',
+ inputs: { targetEvent: null, targetProperties: [pathnameFilter] },
+ expected: { target_event: null, target_properties: null },
+ },
+ {
+ name: 'keeps only the filter types the endpoint accepts',
+ inputs: {
+ targetEvent: '$pageview',
+ targetUrlContains: ' /pricing ',
+ targetProperties: [pathnameFilter, cohortFilter],
+ },
+ expected: {
+ target_url_contains: '/pricing',
+ target_properties: [{ key: '$pathname', type: 'event', operator: 'exact', value: ['/'] }],
+ },
+ },
+ ]
+
+ test.each(requestCases)('toSetupContextInput $name', ({ inputs, expected }) => {
+ expect(toSetupContextInput({ ...DEFAULT_SETUP_INSPECTOR_INPUTS, ...inputs })).toMatchObject(expected)
+ })
+})
diff --git a/products/experiments/frontend/setupInspector/setupInspectorUtils.ts b/products/experiments/frontend/setupInspector/setupInspectorUtils.ts
new file mode 100644
index 000000000000..463deee232c9
--- /dev/null
+++ b/products/experiments/frontend/setupInspector/setupInspectorUtils.ts
@@ -0,0 +1,189 @@
+import { isEventPropertyFilter, isPersonPropertyFilter } from 'lib/components/PropertyFilters/utils'
+import { dayjs } from 'lib/dayjs'
+import { humanFriendlyNumber, percentage } from 'lib/utils/numbers'
+
+import { AnyPropertyFilter, PropertyFilterType } from '~/types'
+
+import type {
+ EventPropertyFilterApi,
+ ExperimentSetupContextInputApi,
+ ExperimentSetupContextResponseApi,
+ PersonPropertyFilterApi,
+ PropertyOperatorApi,
+ SetupContextSectionStatusEnumApi,
+ _ExperimentSetupPropertyFilterListApi,
+} from 'products/experiments/frontend/generated/api.schemas'
+
+export const SECTION_STATUS_LABELS: Record<SetupContextSectionStatusEnumApi, string> = {
+ ok: 'OK',
+ skipped: 'Skipped',
+ timed_out: 'Timed out',
+ error: 'Error',
+}
+
+export interface SetupInspectorInputs {
+ targetEvent: string | null
+ targetUrlContains: string
+ targetProperties: AnyPropertyFilter[]
+ metricEvent: string | null
+ metricProperties: AnyPropertyFilter[]
+ previousExperimentsLimit: number
+ sharedMetricsLimit: number
+}
+
+export const DEFAULT_SETUP_INSPECTOR_INPUTS: SetupInspectorInputs = {
+ targetEvent: null,
+ targetUrlContains: '',
+ targetProperties: [],
+ metricEvent: null,
+ metricProperties: [],
+ previousExperimentsLimit: 10,
+ sharedMetricsLimit: 10,
+}
+
+export interface IdentityFact {
+ label: string
+ value: string
+}
+
+// Staff see the inspector on the same terms as the experiment debug panel, and only with the flag on.
+// Under impersonation the flags and the user are the customer's, so the button shows and the endpoint
+// decides, because it evaluates the flag for the staff user behind the session.
+export function canInspectSetupContext({
+ isImpersonated,
+ superpowersEnabled,
+ flagEnabled,
+}: {
+ isImpersonated: boolean
+ superpowersEnabled: boolean
+ flagEnabled: boolean
+}): boolean {
+ return isImpersonated || (superpowersEnabled && flagEnabled)
+}
+
+// The endpoint accepts only event and person filters, so the other filter types the picker can
+// produce are dropped here instead of failing the whole request with a 400.
+export function toApiPropertyFilters(filters: AnyPropertyFilter[]): _ExperimentSetupPropertyFilterListApi {
+ return filters.flatMap((filter): (EventPropertyFilterApi | PersonPropertyFilterApi)[] => {
+ if (!isEventPropertyFilter(filter) && !isPersonPropertyFilter(filter)) {
+ return []
+ }
+ const base = {
+ key: filter.key,
+ operator: filter.operator as PropertyOperatorApi,
+ value: filter.value as EventPropertyFilterApi['value'],
+ }
+ return [
+ filter.type === PropertyFilterType.Event
+ ? { ...base, type: 'event' as const }
+ : { ...base, type: 'person' as const },
+ ]
+ })
+}
+
+// A field that depends on an event the inspector no longer has is left out, so a stale value in a
+// disabled input does not turn the request into a 400.
+export function toSetupContextInput(inputs: SetupInspectorInputs): ExperimentSetupContextInputApi {
+ const targetProperties = inputs.targetEvent ? toApiPropertyFilters(inputs.targetProperties) : []
+ const metricProperties = inputs.metricEvent ? toApiPropertyFilters(inputs.metricProperties) : []
+ const targetUrlContains = inputs.targetEvent === '$pageview' ? inputs.targetUrlContains.trim() : ''
+ return {
+ target_event: inputs.targetEvent || null,
+ target_url_contains: targetUrlContains || null,
+ target_properties: targetProperties.length ? targetProperties : null,
+ metric_event: inputs.metricEvent || null,
+ metric_properties: metricProperties.length ? metricProperties : null,
+ previous_experiments_limit: inputs.previousExperimentsLimit,
+ shared_metrics_limit: inputs.sharedMetricsLimit,
+ }
+}
+
+export function describeSetupContextError(error: unknown): string {
+ const { status, detail, attr } = (error ?? {}) as { status?: number; detail?: string; attr?: string }
+ if (status === 404) {
+ return 'The setup context is off for you. Turn on the experiment-setup-context feature flag for your user, then try again.'
+ }
+ if (status === 400 && detail) {
+ return attr ? `${attr}: ${detail}` : detail
+ }
+ return detail || "Couldn't read the setup context. Try again, and check the server logs if it keeps failing."
+}
+
+export function formatShare(share: number | null | undefined): string {
+ return share === null || share === undefined ? 'Not reported' : percentage(share, 1)
+}
+
+export function formatCount(count: number | null | undefined): string {
+ return count === null || count === undefined ? 'Not reported' : humanFriendlyNumber(count)
+}
+
+export function formatYesNo(value: boolean): string {
+ return value ? 'Yes' : 'No'
+}
+
+// Absolute times, because a reader compares a launch date against a result date in the same row.
+export function formatTimestamp(timestamp: string | null | undefined): string {
+ return timestamp ? dayjs(timestamp).format('D MMM YYYY HH:mm') : 'None'
+}
+
+export function formatPropertyFilters(filters: _ExperimentSetupPropertyFilterListApi): string {
+ if (!filters.length) {
+ return 'None'
+ }
+ return filters
+ .map((filter) => {
+ const value = Array.isArray(filter.value) ? filter.value.join(' or ') : String(filter.value ?? '')
+ return `${filter.type ?? 'event'} ${filter.key} ${filter.operator ?? 'exact'} ${value}`.trim()
+ })
+ .join('; ')
+}
+
+function formatLibShares(libs: { lib: string | null; share: number | null }[], emptyText: string): string {
+ const reported = libs.filter((lib) => lib.share !== null)
+ if (!reported.length) {
+ return emptyText
+ }
+ return reported.map((lib) => `${lib.lib ?? 'unknown'} ${formatShare(lib.share)}`).join(', ')
+}
+
+// Support answers identity and bucketing tickets from server-and-web evaluation, local evaluation and
+// the anonymous share, so the drawer shows them first. Each value restates fields of the response and
+// adds no threshold of its own.
+export function summarizeIdentity(context: ExperimentSetupContextResponseApi): IdentityFact[] {
+ const sdk = context.sdk_profile.status === 'ok' ? context.sdk_profile.data : null
+ const surface = context.target_surface.status === 'ok' ? context.target_surface.data : null
+ const sdkUnavailable = `SDK profile: ${SECTION_STATUS_LABELS[context.sdk_profile.status].toLowerCase()}`
+
+ return [
+ {
+ label: 'Same flag evaluated on a server and on the web',
+ value: sdk
+ ? `${formatYesNo(sdk.evaluated_on_server_and_web)} (${formatCount(sdk.flags_evaluated_on_server_and_web)} of ${formatCount(sdk.flags_seen)} flags)`
+ : sdkUnavailable,
+ },
+ {
+ label: 'Evaluated locally, by SDK',
+ value: sdk
+ ? formatLibShares(
+ sdk.libs.map((lib) => ({ lib: lib.lib, share: lib.locally_evaluated_share })),
+ 'No SDK reports local evaluation'
+ )
+ : sdkUnavailable,
+ },
+ {
+ label: 'Anonymous share of flag calls, by SDK',
+ value: sdk
+ ? formatLibShares(
+ sdk.libs.map((lib) => ({ lib: lib.lib, share: lib.anonymous_share })),
+ 'No SDK reports whether users are identified'
+ )
+ : sdkUnavailable,
+ },
+ {
+ label: 'Anonymous share on the target surface',
+ value: surface
+ ? formatShare(surface.anonymous_share)
+ : `Target surface: ${SECTION_STATUS_LABELS[context.target_surface.status].toLowerCase()}`,
+ },
+ ]
+}
diff --git a/products/experiments/package.json b/products/experiments/package.json
index 77b6e494c594..c1f772196773 100644
--- a/products/experiments/package.json
+++ b/products/experiments/package.json
@@ -19,6 +19,7 @@
"peerDependencies": {
"@posthog/brand": "catalog:",
"@posthog/icons": "catalog:",
+ "@testing-library/dom": "*",
"@testing-library/jest-dom": "*",
"@testing-library/react": "*",
"@testing-library/user-event": "*",