: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(experiments): drop results from legacy experiment pages (#105010)
Anders964d45e6c576
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 59b947034270..95d12135bcdd 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -353,7 +353,6 @@ export const FEATURE_FLAGS = {EXPERIMENTS_DW_AA_TEST: 'experiments-dw-aa-test', // owner: @rodrigoi #team-experimentsEXPERIMENTS_EXCLUDED_VARIANTS: 'experiments-excluded-variants', // owner: @rodrigoi #team-experimentsEXPERIMENTS_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- EXPERIMENTS_LEGACY_DEPRECATION_NOTICE: 'experiments-legacy-deprecation-notice', // owner: @andehen #team-experiments, shows the legacy experiments deprecation bannerEXPERIMENTS_RECALCULATION_RATE_LIMIT: 'experiment-metric-recalculation-rate-limit', // owner: @rodrigoi #team-experiments, five-minute window between manual metric reloadsEXPERIMENTS_SHOW_SQL: 'experiments-show-sql', // owner: @jurajmajerik #team-experimentsEXPERIMENTS_SYNC_QUERIES: 'experiments-sync-queries', // owner: @andehen #team-experimentsdiff --git a/frontend/src/lib/utils/eventUsageLogic.test.ts b/frontend/src/lib/utils/eventUsageLogic.test.tsindex 451db7ed9bf1..4b8d91a0f84c 100644--- a/frontend/src/lib/utils/eventUsageLogic.test.ts+++ b/frontend/src/lib/utils/eventUsageLogic.test.ts@@ -3,6 +3,7 @@ import posthog from 'posthog-js'import { NodeKind } from '~/queries/schema/schema-general'import type {ExperimentFunnelMetric,+ ExperimentFunnelsQuery,ExperimentMeanMetric,ExperimentRatioMetric,ExperimentRetentionMetric,@@ -481,4 +482,13 @@ describe('eventUsageLogic', () => {})})})++ it('reports only the kind for a legacy metric', () => {+ const metric = {+ kind: NodeKind.ExperimentFunnelsQuery,+ funnels_query: { series: [{ kind: NodeKind.EventsNode }] },+ } as ExperimentFunnelsQuery++ expect(getEventPropertiesForMetric(metric)).toEqual({ kind: NodeKind.ExperimentFunnelsQuery })+ })})diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex 76c416453fd0..bef75bd90c0c 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -538,18 +538,8 @@ export function getEventPropertiesForMetric(}return base- } else if (metric.kind === NodeKind.ExperimentFunnelsQuery) {- return {- kind: NodeKind.ExperimentFunnelsQuery,- steps_count: metric.funnels_query?.series?.length,- filter_test_accounts: metric.funnels_query?.filterTestAccounts,- }- }- return {- kind: NodeKind.ExperimentTrendsQuery,- series_kind: metric.count_query?.series?.[0]?.kind,- filter_test_accounts: metric.count_query?.filterTestAccounts,}+ return { kind: metric.kind }}/**@@ -1128,7 +1118,7 @@ export interface eventUsageLogicActions {}reportExperimentMetricFinished: (experimentId: ExperimentIdType,- metric: ExperimentFunnelsQuery | ExperimentMetric | ExperimentTrendsQuery,+ metric: ExperimentMetric,teamId?: number | null,queryId?: string | null,context?: {@@ -1155,7 +1145,7 @@ export interface eventUsageLogicActions {}| undefinedexperimentId: ExperimentIdType- metric: ExperimentFunnelsQuery | ExperimentMetricUnion | ExperimentTrendsQuery+ metric: ExperimentMetricUnionqueryId: string | null | undefinedteamId: number | null | undefined}@@ -1981,7 +1971,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([}),reportExperimentMetricFinished: (experimentId: ExperimentIdType,- metric: ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery,+ metric: ExperimentMetric,teamId?: number | null,queryId?: string | null,context?: {@@ -2631,7 +2621,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([posthog.capture('experiment shared metric created', {name: sharedMetric.name,id: sharedMetric.id,- ...getEventPropertiesForMetric(sharedMetric.query as ExperimentTrendsQuery | ExperimentFunnelsQuery),+ ...getEventPropertiesForMetric(sharedMetric.query as ExperimentMetric),})},reportExperimentSharedMetricAssigned: ({ experimentId, sharedMetric }) => {@@ -2639,7 +2629,7 @@ export const eventUsageLogic = kea<eventUsageLogicType>([experiment_id: experimentId,name: sharedMetric.name,id: sharedMetric.id,- ...getEventPropertiesForMetric(sharedMetric.query as ExperimentTrendsQuery | ExperimentFunnelsQuery),+ ...getEventPropertiesForMetric(sharedMetric.query as ExperimentMetric),})},reportExperimentDashboardCreated: ({ experiment, dashboardId }) => {diff --git a/frontend/src/mocks/fixtures/api/experiments/_experiment_launched.json b/frontend/src/mocks/fixtures/api/experiments/_experiment_launched.jsonnew file mode 100644index 000000000000..ed9a21b18984--- /dev/null+++ b/frontend/src/mocks/fixtures/api/experiments/_experiment_launched.json@@ -0,0 +1,160 @@+{+ "id": 90,+ "name": "jan-16-running",+ "description": "Dashboard: [http://localhost:8010/project/1/dashboard/147](http://localhost:8010/project/1/dashboard/147)",+ "start_date": "2024-12-30T21:55:00Z",+ "end_date": null,+ "feature_flag_key": "jan-16-running",+ "feature_flag": {+ "id": 103,+ "team_id": 1,+ "name": "Feature Flag for Experiment jan-16-running",+ "key": "jan-16-running",+ "filters": {+ "groups": [+ {+ "properties": [],+ "rollout_percentage": 100+ }+ ],+ "multivariate": {+ "variants": [+ {+ "key": "control",+ "rollout_percentage": 50+ },+ {+ "key": "test",+ "rollout_percentage": 50+ }+ ]+ },+ "holdout_groups": null,+ "aggregation_group_type_index": null,+ "payloads": {}+ },+ "deleted": false,+ "active": true,+ "ensure_experience_continuity": false+ },+ "holdout": null,+ "holdout_id": null,+ "parameters": {+ "feature_flag_variants": [+ {+ "key": "control",+ "rollout_percentage": 50+ },+ {+ "key": "test",+ "rollout_percentage": 50+ }+ ]+ },+ "running_time_calculation": {+ "minimum_detectable_effect": 1,+ "recommended_running_time": 0,+ "recommended_sample_size": 0+ },+ "secondary_metrics": [],+ "saved_metrics": [+ {+ "id": 108,+ "experiment": 90,+ "saved_metric": 15,+ "metadata": {+ "type": "primary"+ },+ "created_at": "2025-01-22T14:56:12.766068Z",+ "query": {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {+ "kind": "EventsNode",+ "event": "[jan-16-running] event one",+ "math": "total"+ }+ },+ "name": "jan-16-running event one"+ },+ {+ "id": 109,+ "experiment": 90,+ "saved_metric": 16,+ "metadata": {+ "type": "secondary"+ },+ "created_at": "2025-01-22T14:56:12.770270Z",+ "query": {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {+ "kind": "EventsNode",+ "event": "[jan-16-running] event two",+ "math": "total"+ }+ },+ "name": "jan-16-running event two"+ }+ ],+ "saved_metrics_ids": [+ {+ "id": 108,+ "metadata": {+ "type": "primary"+ }+ },+ {+ "id": 109,+ "metadata": {+ "type": "secondary"+ }+ }+ ],+ "filters": {},+ "archived": false,+ "created_by": {+ "id": 1,+ "uuid": "0192f783-9ca1-0000-047c-397bd60d6c39",+ "distinct_id": "6PMxBkEONKiJoizOIKGkcTICvtOk1smj277H6lqowDG",+ "first_name": "Employee 427",+ "last_name": "",+ "email": "[email protected]",+ "is_email_verified": null,+ "hedgehog_config": null,+ "role_at_organization": null+ },+ "created_at": "2025-01-16T21:51:09.062768Z",+ "updated_at": "2025-01-22T14:56:12.772335Z",+ "type": "product",+ "metrics": [+ {+ "kind": "ExperimentMetric",+ "metric_type": "funnel",+ "series": [+ {+ "kind": "EventsNode",+ "event": "[jan-16-running] seen"+ },+ {+ "kind": "EventsNode",+ "event": "[jan-16-running] payment"+ }+ ],+ "uuid": "434cb6ba-7fa6-4ca1-b7a0-8970b2d9a47d"+ }+ ],+ "metrics_secondary": [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {+ "kind": "EventsNode",+ "event": "[jan-16-running] event one",+ "math": "total"+ },+ "uuid": "cbdd02f8-4a27-4017-a8d8-5f989b304ada"+ }+ ],+ "user_access_level": "editor"+}diff --git a/frontend/src/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json b/frontend/src/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.jsondeleted file mode 100644index d6e693004d08..000000000000--- a/frontend/src/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json+++ /dev/null@@ -1,221 +0,0 @@-{- "id": 90,- "name": "jan-16-running",- "description": "Dashboard: [http://localhost:8010/project/1/dashboard/147](http://localhost:8010/project/1/dashboard/147)",- "start_date": "2024-12-30T21:55:00Z",- "end_date": null,- "feature_flag_key": "jan-16-running",- "feature_flag": {- "id": 103,- "team_id": 1,- "name": "Feature Flag for Experiment jan-16-running",- "key": "jan-16-running",- "filters": {- "groups": [- {- "properties": [],- "rollout_percentage": 100- }- ],- "multivariate": {- "variants": [- {- "key": "control",- "rollout_percentage": 50- },- {- "key": "test",- "rollout_percentage": 50- }- ]- },- "holdout_groups": null,- "aggregation_group_type_index": null,- "payloads": {}- },- "deleted": false,- "active": true,- "ensure_experience_continuity": false- },- "holdout": null,- "holdout_id": null,- "parameters": {- "feature_flag_variants": [- {- "key": "control",- "rollout_percentage": 50- },- {- "key": "test",- "rollout_percentage": 50- }- ]- },- "running_time_calculation": {- "minimum_detectable_effect": 1,- "recommended_running_time": 0,- "recommended_sample_size": 0- },- "secondary_metrics": [],- "saved_metrics": [- {- "id": 108,- "experiment": 90,- "saved_metric": 15,- "metadata": {- "type": "primary"- },- "created_at": "2025-01-22T14:56:12.766068Z",- "query": {- "kind": "ExperimentTrendsQuery",- "count_query": {- "kind": "TrendsQuery",- "series": [- {- "kind": "EventsNode",- "math": "total",- "name": "[jan-16-running] event one",- "event": "[jan-16-running] event one"- }- ],- "interval": "day",- "dateRange": {- "date_to": "2025-01-20T23:59",- "date_from": "2025-01-06T13:54",- "explicitDate": true- },- "trendsFilter": {- "display": "ActionsLineGraph"- },- "filterTestAccounts": true- }- },- "name": "jan-16-running event one"- },- {- "id": 109,- "experiment": 90,- "saved_metric": 16,- "metadata": {- "type": "secondary"- },- "created_at": "2025-01-22T14:56:12.770270Z",- "query": {- "kind": "ExperimentTrendsQuery",- "count_query": {- "kind": "TrendsQuery",- "series": [- {- "kind": "EventsNode",- "math": "total",- "name": "[jan-16-running] event two",- "event": "[jan-16-running] event two"- }- ],- "interval": "day",- "dateRange": {- "date_to": "2025-01-20T23:59",- "date_from": "2025-01-06T13:54",- "explicitDate": true- },- "trendsFilter": {- "display": "ActionsLineGraph"- },- "filterTestAccounts": true- }- },- "name": "jan-16-running event two"- }- ],- "saved_metrics_ids": [- {- "id": 108,- "metadata": {- "type": "primary"- }- },- {- "id": 109,- "metadata": {- "type": "secondary"- }- }- ],- "filters": {},- "archived": false,- "created_by": {- "id": 1,- "uuid": "0192f783-9ca1-0000-047c-397bd60d6c39",- "distinct_id": "6PMxBkEONKiJoizOIKGkcTICvtOk1smj277H6lqowDG",- "first_name": "Employee 427",- "last_name": "",- "email": "[email protected]",- "is_email_verified": null,- "hedgehog_config": null,- "role_at_organization": null- },- "created_at": "2025-01-16T21:51:09.062768Z",- "updated_at": "2025-01-22T14:56:12.772335Z",- "type": "product",- "metrics": [- {- "kind": "ExperimentFunnelsQuery",- "funnels_query": {- "kind": "FunnelsQuery",- "series": [- {- "kind": "EventsNode",- "name": "[jan-16-running] seen",- "event": "[jan-16-running] seen"- },- {- "kind": "EventsNode",- "name": "[jan-16-running] payment",- "event": "[jan-16-running] payment"- }- ],- "dateRange": {- "date_to": "2025-01-16T23:59",- "date_from": "2025-01-02T13:54",- "explicitDate": true- },- "funnelsFilter": {- "layout": "horizontal",- "funnelVizType": "steps",- "funnelWindowInterval": 14,- "funnelWindowIntervalUnit": "day"- },- "filterTestAccounts": true- },- "uuid": "434cb6ba-7fa6-4ca1-b7a0-8970b2d9a47d"- }- ],- "metrics_secondary": [- {- "kind": "ExperimentTrendsQuery",- "count_query": {- "kind": "TrendsQuery",- "series": [- {- "kind": "EventsNode",- "math": "total",- "name": "[jan-16-running] event one",- "event": "[jan-16-running] event one"- }- ],- "interval": "day",- "dateRange": {- "date_to": "2025-01-16T23:59",- "date_from": "2025-01-02T13:54",- "explicitDate": true- },- "trendsFilter": {- "display": "ActionsLineGraph"- },- "filterTestAccounts": true- },- "uuid": "cbdd02f8-4a27-4017-a8d8-5f989b304ada"- }- ],- "user_access_level": "editor"-}diff --git a/frontend/src/mocks/fixtures/api/experiments/_experiment_metric_results_success.json b/frontend/src/mocks/fixtures/api/experiments/_experiment_metric_results_success.jsonindex 06e359c37d05..ffd089763ee4 100644--- a/frontend/src/mocks/fixtures/api/experiments/_experiment_metric_results_success.json+++ b/frontend/src/mocks/fixtures/api/experiments/_experiment_metric_results_success.json@@ -13,542 +13,74 @@"query_async": true,"query_progress": null,"results": {- "cache_key": "cache_c300194ee6faab6132b1ee71028d8542",- "cache_target_age": "2025-02-07T13:33:39.651191Z",- "calculation_trigger": null,- "count_query": {- "aggregation_group_type_index": null,- "breakdownFilter": {- "breakdown": "$feature/jan-16-running",- "breakdown_group_type_index": null,- "breakdown_hide_other_aggregation": null,- "breakdown_histogram_bin_count": null,- "breakdown_limit": null,- "breakdown_normalize_url": null,- "breakdown_type": "event",- "breakdowns": null- },- "compareFilter": null,- "conversionGoal": null,- "dataColorTheme": null,- "dateRange": {- "date_from": "2024-12-31T21:55:00+00:00",- "date_to": null,- "explicitDate": true- },- "filterTestAccounts": true,- "interval": "day",- "kind": "TrendsQuery",- "modifiers": null,- "properties": [- {- "key": "$feature/jan-16-running",- "label": null,- "operator": "exact",- "type": "event",- "value": ["control", "test"]- }- ],- "response": null,- "samplingFactor": null,- "series": [- {- "custom_name": null,- "event": "[jan-16-running] event two",- "fixedProperties": null,- "kind": "EventsNode",- "limit": null,- "math": "total",- "math_group_type_index": null,- "math_hogql": null,- "math_property": null,- "math_property_type": null,- "name": "[jan-16-running] event two",- "orderBy": null,- "properties": null,- "response": null- }- ],- "trendsFilter": {- "aggregationAxisFormat": "numeric",- "aggregationAxisPostfix": null,- "aggregationAxisPrefix": null,- "breakdown_histogram_bin_count": null,- "decimalPlaces": null,- "display": "ActionsLineGraphCumulative",- "formula": null,- "goalLines": null,- "hiddenLegendIndexes": null,- "resultCustomizationBy": "value",- "resultCustomizations": null,- "showAlertThresholdLines": false,- "showLabelsOnSeries": null,- "showLegend": false,- "showMultipleYAxes": false,- "showPercentStackView": false,- "showValuesOnSeries": false,- "smoothingIntervals": 1,- "yAxisScaleType": "linear"- }- },- "credible_intervals": {- "control": [0.30513415741158273, 0.4586578577303907],- "test": [0.45645934257644455, 0.6368739523582623]+ "baseline": {+ "denominator_sum": null,+ "denominator_sum_squares": null,+ "key": "control",+ "number_of_samples": 989,+ "numerator_denominator_sum_product": null,+ "sum": 1636.0,+ "sum_squares": 3760.0,+ "validation_failures": []},- "exposure_query": {- "aggregation_group_type_index": null,- "breakdownFilter": {- "breakdown": "$feature_flag_response",- "breakdown_group_type_index": null,- "breakdown_hide_other_aggregation": null,- "breakdown_histogram_bin_count": null,- "breakdown_limit": null,- "breakdown_normalize_url": null,- "breakdown_type": "event",- "breakdowns": null- },- "compareFilter": null,- "conversionGoal": null,- "dataColorTheme": null,- "dateRange": {- "date_from": "2024-12-31T21:55:00+00:00",- "date_to": null,- "explicitDate": true- },- "filterTestAccounts": true,- "interval": "day",- "kind": "TrendsQuery",- "modifiers": null,- "properties": [- {- "key": "$feature_flag_response",- "label": null,- "operator": "exact",- "type": "event",- "value": ["control", "test"]- },- {- "key": "$feature_flag",- "label": null,- "operator": "exact",- "type": "event",- "value": ["jan-16-running"]- }- ],- "response": null,- "samplingFactor": null,- "series": [- {- "custom_name": null,- "event": "$feature_flag_called",- "fixedProperties": null,- "kind": "EventsNode",- "limit": null,- "math": "dau",- "math_group_type_index": null,- "math_hogql": null,- "math_property": null,- "math_property_type": null,- "name": null,- "orderBy": null,- "properties": null,- "response": null- }- ],- "trendsFilter": {- "aggregationAxisFormat": "numeric",- "aggregationAxisPostfix": null,- "aggregationAxisPrefix": null,- "breakdown_histogram_bin_count": null,- "decimalPlaces": null,- "display": "ActionsLineGraphCumulative",- "formula": null,- "goalLines": null,- "hiddenLegendIndexes": null,- "resultCustomizationBy": "value",- "resultCustomizations": null,- "showAlertThresholdLines": false,- "showLabelsOnSeries": null,- "showLegend": false,- "showMultipleYAxes": false,- "showPercentStackView": false,- "showValuesOnSeries": false,- "smoothingIntervals": 1,- "yAxisScaleType": "linear"- }+ "cache_key": "cache_17925ec0dddf2fa25f9dd34a591743c2",+ "cache_target_age": "2025-09-05T16:14:05.259133Z",+ "calculation_trigger": null,+ "credible_intervals": null,+ "insight": null,+ "is_cached": true,+ "kind": "ExperimentQuery",+ "last_refresh": "2025-09-04T16:14:05.259133Z",+ "metric": null,+ "next_allowed_client_refresh": "2025-09-04T16:15:05.259133Z",+ "p_value": null,+ "probability": null,+ "query_metadata": {+ "events": [],+ "updated_at": "2025-09-04T16:14:11.010108Z"},- "insight": [+ "query_status": null,+ "significance_code": null,+ "significant": null,+ "stats_version": null,+ "timezone": "UTC",+ "variant_results": [{- "data": [- 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 8.0, 14.0, 23.0, 30.0, 46.0, 74.0, 97.0, 138.0,- 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0,- 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0, 138.0+ "chance_to_win": 2.7262704800611193e-08,+ "credible_interval": [+ -0.19740467628759228,+ -0.09277676754203046],- "labels": [- "31-Dec-2024",- "1-Jan-2025",- "2-Jan-2025",- "3-Jan-2025",- "4-Jan-2025",- "5-Jan-2025",- "6-Jan-2025",- "7-Jan-2025",- "8-Jan-2025",- "9-Jan-2025",- "10-Jan-2025",- "11-Jan-2025",- "12-Jan-2025",- "13-Jan-2025",- "14-Jan-2025",- "15-Jan-2025",- "16-Jan-2025",- "17-Jan-2025",- "18-Jan-2025",- "19-Jan-2025",- "20-Jan-2025",- "21-Jan-2025",- "22-Jan-2025",- "23-Jan-2025",- "24-Jan-2025",- "25-Jan-2025",- "26-Jan-2025",- "27-Jan-2025",- "28-Jan-2025",- "29-Jan-2025",- "30-Jan-2025",- "31-Jan-2025",- "1-Feb-2025",- "2-Feb-2025",- "3-Feb-2025",- "4-Feb-2025",- "5-Feb-2025",- "6-Feb-2025"- ],- "days": [- "2024-12-31",- "2025-01-01",- "2025-01-02",- "2025-01-03",- "2025-01-04",- "2025-01-05",- "2025-01-06",- "2025-01-07",- "2025-01-08",- "2025-01-09",- "2025-01-10",- "2025-01-11",- "2025-01-12",- "2025-01-13",- "2025-01-14",- "2025-01-15",- "2025-01-16",- "2025-01-17",- "2025-01-18",- "2025-01-19",- "2025-01-20",- "2025-01-21",- "2025-01-22",- "2025-01-23",- "2025-01-24",- "2025-01-25",- "2025-01-26",- "2025-01-27",- "2025-01-28",- "2025-01-29",- "2025-01-30",- "2025-01-31",- "2025-02-01",- "2025-02-02",- "2025-02-03",- "2025-02-04",- "2025-02-05",- "2025-02-06"- ],- "count": 138.0,- "label": "test",- "filter": {- "insight": "TRENDS",- "properties": [- {- "key": "$feature/jan-16-running",- "label": null,- "operator": "exact",- "type": "event",- "value": ["control", "test"]- }- ],- "filter_test_accounts": true,- "date_to": "2025-02-06T13:33:40.106611Z",- "date_from": "2024-12-31T21:55:00Z",- "entity_type": "events",- "interval": "day",- "aggregationAxisFormat": "numeric",- "display": "ActionsLineGraphCumulative",- "resultCustomizationBy": "value",- "showAlertThresholdLines": false,- "showLegend": false,- "showMultipleYAxes": false,- "showPercentStackView": false,- "showValuesOnSeries": false,- "smoothingIntervals": 1,- "yAxisScaleType": "linear",- "breakdown": "$feature/jan-16-running",- "breakdown_type": "event"- },- "action": {- "days": [- "2024-12-31T00:00:00Z",- "2025-01-01T00:00:00Z",- "2025-01-02T00:00:00Z",- "2025-01-03T00:00:00Z",- "2025-01-04T00:00:00Z",- "2025-01-05T00:00:00Z",- "2025-01-06T00:00:00Z",- "2025-01-07T00:00:00Z",- "2025-01-08T00:00:00Z",- "2025-01-09T00:00:00Z",- "2025-01-10T00:00:00Z",- "2025-01-11T00:00:00Z",- "2025-01-12T00:00:00Z",- "2025-01-13T00:00:00Z",- "2025-01-14T00:00:00Z",- "2025-01-15T00:00:00Z",- "2025-01-16T00:00:00Z",- "2025-01-17T00:00:00Z",- "2025-01-18T00:00:00Z",- "2025-01-19T00:00:00Z",- "2025-01-20T00:00:00Z",- "2025-01-21T00:00:00Z",- "2025-01-22T00:00:00Z",- "2025-01-23T00:00:00Z",- "2025-01-24T00:00:00Z",- "2025-01-25T00:00:00Z",- "2025-01-26T00:00:00Z",- "2025-01-27T00:00:00Z",- "2025-01-28T00:00:00Z",- "2025-01-29T00:00:00Z",- "2025-01-30T00:00:00Z",- "2025-01-31T00:00:00Z",- "2025-02-01T00:00:00Z",- "2025-02-02T00:00:00Z",- "2025-02-03T00:00:00Z",- "2025-02-04T00:00:00Z",- "2025-02-05T00:00:00Z",- "2025-02-06T00:00:00Z"- ],- "id": "[jan-16-running] event two",- "type": "events",- "order": 0,- "name": "[jan-16-running] event two",- "custom_name": null,- "math": "total",- "math_property": null,- "math_hogql": null,- "math_group_type_index": null,- "properties": {}- },- "breakdown_value": "test"+ "denominator_sum": null,+ "denominator_sum_squares": null,+ "key": "test-1",+ "method": "bayesian",+ "number_of_samples": 874,+ "numerator_denominator_sum_product": null,+ "significant": true,+ "sum": 1236.0,+ "sum_squares": 2634.0,+ "validation_failures": []},{- "data": [- 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 4.0, 8.0, 15.0, 19.0, 29.0, 40.0, 61.0, 92.0, 92.0,- 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0, 92.0,- 92.0, 92.0, 92.0, 92.0- ],- "labels": [- "31-Dec-2024",- "1-Jan-2025",- "2-Jan-2025",- "3-Jan-2025",- "4-Jan-2025",- "5-Jan-2025",- "6-Jan-2025",- "7-Jan-2025",- "8-Jan-2025",- "9-Jan-2025",- "10-Jan-2025",- "11-Jan-2025",- "12-Jan-2025",- "13-Jan-2025",- "14-Jan-2025",- "15-Jan-2025",- "16-Jan-2025",- "17-Jan-2025",- "18-Jan-2025",- "19-Jan-2025",- "20-Jan-2025",- "21-Jan-2025",- "22-Jan-2025",- "23-Jan-2025",- "24-Jan-2025",- "25-Jan-2025",- "26-Jan-2025",- "27-Jan-2025",- "28-Jan-2025",- "29-Jan-2025",- "30-Jan-2025",- "31-Jan-2025",- "1-Feb-2025",- "2-Feb-2025",- "3-Feb-2025",- "4-Feb-2025",- "5-Feb-2025",- "6-Feb-2025"+ "chance_to_win": 0.9999998975983043,+ "credible_interval": [+ 0.09706777250053614,+ 0.21468859747750865],- "days": [- "2024-12-31",- "2025-01-01",- "2025-01-02",- "2025-01-03",- "2025-01-04",- "2025-01-05",- "2025-01-06",- "2025-01-07",- "2025-01-08",- "2025-01-09",- "2025-01-10",- "2025-01-11",- "2025-01-12",- "2025-01-13",- "2025-01-14",- "2025-01-15",- "2025-01-16",- "2025-01-17",- "2025-01-18",- "2025-01-19",- "2025-01-20",- "2025-01-21",- "2025-01-22",- "2025-01-23",- "2025-01-24",- "2025-01-25",- "2025-01-26",- "2025-01-27",- "2025-01-28",- "2025-01-29",- "2025-01-30",- "2025-01-31",- "2025-02-01",- "2025-02-02",- "2025-02-03",- "2025-02-04",- "2025-02-05",- "2025-02-06"- ],- "count": 92.0,- "label": "control",- "filter": {- "insight": "TRENDS",- "properties": [- {- "key": "$feature/jan-16-running",- "label": null,- "operator": "exact",- "type": "event",- "value": ["control", "test"]- }- ],- "filter_test_accounts": true,- "date_to": "2025-02-06T13:33:40.106611Z",- "date_from": "2024-12-31T21:55:00Z",- "entity_type": "events",- "interval": "day",- "aggregationAxisFormat": "numeric",- "display": "ActionsLineGraphCumulative",- "resultCustomizationBy": "value",- "showAlertThresholdLines": false,- "showLegend": false,- "showMultipleYAxes": false,- "showPercentStackView": false,- "showValuesOnSeries": false,- "smoothingIntervals": 1,- "yAxisScaleType": "linear",- "breakdown": "$feature/jan-16-running",- "breakdown_type": "event"- },- "action": {- "days": [- "2024-12-31T00:00:00Z",- "2025-01-01T00:00:00Z",- "2025-01-02T00:00:00Z",- "2025-01-03T00:00:00Z",- "2025-01-04T00:00:00Z",- "2025-01-05T00:00:00Z",- "2025-01-06T00:00:00Z",- "2025-01-07T00:00:00Z",- "2025-01-08T00:00:00Z",- "2025-01-09T00:00:00Z",- "2025-01-10T00:00:00Z",- "2025-01-11T00:00:00Z",- "2025-01-12T00:00:00Z",- "2025-01-13T00:00:00Z",- "2025-01-14T00:00:00Z",- "2025-01-15T00:00:00Z",- "2025-01-16T00:00:00Z",- "2025-01-17T00:00:00Z",- "2025-01-18T00:00:00Z",- "2025-01-19T00:00:00Z",- "2025-01-20T00:00:00Z",- "2025-01-21T00:00:00Z",- "2025-01-22T00:00:00Z",- "2025-01-23T00:00:00Z",- "2025-01-24T00:00:00Z",- "2025-01-25T00:00:00Z",- "2025-01-26T00:00:00Z",- "2025-01-27T00:00:00Z",- "2025-01-28T00:00:00Z",- "2025-01-29T00:00:00Z",- "2025-01-30T00:00:00Z",- "2025-01-31T00:00:00Z",- "2025-02-01T00:00:00Z",- "2025-02-02T00:00:00Z",- "2025-02-03T00:00:00Z",- "2025-02-04T00:00:00Z",- "2025-02-05T00:00:00Z",- "2025-02-06T00:00:00Z"- ],- "id": "[jan-16-running] event two",- "type": "events",- "order": 0,- "name": "[jan-16-running] event two",- "custom_name": null,- "math": "total",- "math_property": null,- "math_hogql": null,- "math_group_type_index": null,- "properties": {}- },- "breakdown_value": "control"+ "denominator_sum": null,+ "denominator_sum_squares": null,+ "key": "test-2",+ "method": "bayesian",+ "number_of_samples": 1137,+ "numerator_denominator_sum_product": null,+ "significant": true,+ "sum": 2174.0,+ "sum_squares": 5478.0,+ "validation_failures": []}],- "is_cached": false,- "kind": "ExperimentTrendsQuery",- "last_refresh": "2025-02-06T13:33:39.651191Z",- "next_allowed_client_refresh": "2025-02-06T13:34:39.651191Z",- "p_value": 5.491810766882499e-5,- "probability": {- "control": 0.0038,- "test": 0.9962- },- "query_status": null,- "significance_code": "significant",- "significant": true,- "stats_version": 2,- "timezone": "UTC",- "variants": [- {- "absolute_exposure": 245.0,- "count": 92.0,- "exposure": 1.0,- "key": "control"- },- {- "absolute_exposure": 255.0,- "count": 138.0,- "exposure": 1.0408163265306123,- "key": "test"- }- ]+ "variants": null},"start_time": "2025-02-06T13:33:35.542Z","task_id": "367e8246-6028-4a27-a402-5dc5690a5b35",diff --git a/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx b/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsxindex 20c562f23e1c..8e3d849dad9d 100644--- a/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx+++ b/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx@@ -70,7 +70,7 @@ export const RelatedExperimentsTable = ({)}{isLegacyExperiment(experiment) && (<Tooltip- title="This experiment uses the legacy engine, so some features and improvements may be missing."+ title="This experiment uses the legacy engine, so its results are no longer available."docLink="https://posthog.com/docs/experiments/new-experimentation-engine"><LemonTag type="warning" className="ml-1">diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsxindex c28045491b70..167b6086cb99 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx@@ -13,7 +13,7 @@ import { ExperimentMetaBar } from 'products/experiments/frontend/components/Expeimport { ExperimentHealthDebug } from 'products/experiments/frontend/health/ExperimentHealthDebug'import { ExperimentHealthPanel } from 'products/experiments/frontend/health/ExperimentHealthPanel'import { useHealthFindingReporting } from 'products/experiments/frontend/health/useHealthFindingReporting'-import { LegacyExperimentView } from 'products/experiments/frontend/legacy'+import { LegacyExperimentView } from 'products/experiments/frontend/legacy/LegacyExperimentView'import { ExperimentMetricModal } from 'products/experiments/frontend/modals/ExperimentMetricModal/ExperimentMetricModal'import { experimentMetricModalLogic } from 'products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic'import { MetricSourceModal } from 'products/experiments/frontend/modals/MetricSourceModal/MetricSourceModal'diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsxindex 2db2defb4066..e7dfc1a7ad17 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx@@ -7,12 +7,7 @@ import { useActions, useValues } from 'kea'import { verticalSortableListCollisionDetection } from 'lib/sortable'import { experimentsConfigLogic } from 'scenes/settings/environment/experimentsConfigLogic'-import {- ExperimentFunnelsQuery,- ExperimentMetric,- ExperimentTrendsQuery,- NewExperimentQueryResponse,-} from '~/queries/schema/schema-general'+import { ExperimentMetric, NewExperimentQueryResponse } from '~/queries/schema/schema-general'import { ExperimentStatsMethod, InsightType } from '~/types'import { isLaunched } from 'products/experiments/frontend/experimentStatus'@@ -42,7 +37,7 @@ interface MetricsTableProps {results: (NewExperimentQueryResponse | undefined)[]errors: any[]isSecondary: boolean- getInsightType: (metric: ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery) => InsightType+ getInsightType: (metric: ExperimentMetric) => InsightTypeshowDetailsModal?: boolean/** Drops the table's own border so it can sit inside a parent panel. */embedded?: booleandiff --git a/frontend/src/scenes/experiments/MetricsView/shared/ChartEmptyState.tsx b/frontend/src/scenes/experiments/MetricsView/shared/ChartEmptyState.tsxindex 86bad93eac17..b5fc68fe84c8 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/ChartEmptyState.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/ChartEmptyState.tsx@@ -1,10 +1,6 @@import { IconClock } from '@posthog/icons'import { LemonTag } from '@posthog/lemon-ui'-import { isLegacyExperimentQuery } from 'scenes/experiments/utils'--import { LegacyErrorChecklist } from 'products/experiments/frontend/legacy'-import { MetricErrorState } from '../new/MetricErrorState'import { ErrorChecklist } from './ErrorChecklist'@@ -49,19 +45,6 @@ export function ChartEmptyState({return null}- const isLegacyMetric = isLegacyExperimentQuery(metric)- /**- * if it's a legacy metric, use the legacy error checklist- */- if (isLegacyMetric) {- return (- // eslint-disable-next-line react/forbid-dom-props- <div className="flex items-center justify-center w-full" style={{ height: `${height}px` }}>- <LegacyErrorChecklist error={error} metric={metric} />- </div>- )- }-return (<divclassName="flex items-center justify-center w-full"diff --git a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsxindex 0c37bc7e5fc6..e18153fc7cd8 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx@@ -17,7 +17,6 @@ import {getExposureEventAndProperty,resolvedExposureEvent,} from 'scenes/experiments/exposureContract'-import { modalsLogic } from 'scenes/experiments/modalsLogic'import { urls } from 'scenes/urls'import type { Breakdown, EventsNode, ExperimentMetric } from '~/queries/schema/schema-general'@@ -118,16 +117,6 @@ export const MetricHeader = ({onDeleteMetricClick?: (metric: ExperimentMetric) => voidreadOnly?: boolean}): JSX.Element => {- /**- * This is necessary for legacy experiments support- */- const {- openPrimaryMetricModal,- openSecondaryMetricModal,- openPrimarySharedMetricModal,- openSecondarySharedMetricModal,- } = useActions(modalsLogic)-const { moveMetricsBetweenSections } = useActions(experimentLogic)const { openExperimentMetricModal } = useActions(experimentMetricModalLogic)const { openSharedMetricDetailModal } = useActions(sharedMetricDetailsModalLogic)@@ -139,23 +128,10 @@ export const MetricHeader = ({const openEditModal = (): void => {if (isSharedMetric) {- /**- * this is for legacy experiments support- */- const openSharedModal = isPrimaryMetric ? openPrimarySharedMetricModal : openSecondarySharedMetricModal- openSharedModal(metric.sharedMetricId!)-openSharedMetricDetailModal(metric, METRIC_CONTEXTS[isPrimaryMetric ? 'primary' : 'secondary'])return}- /**- * this is for legacy experiments support- */- const openMetricModal = isPrimaryMetric ? openPrimaryMetricModal : openSecondaryMetricModal- if (metric.uuid) {- openMetricModal(metric.uuid)- }openExperimentMetricModal(METRIC_CONTEXTS[isPrimaryMetric ? 'primary' : 'secondary'], metric)}diff --git a/frontend/src/scenes/experiments/SharedMetrics/SharedMetric.tsx b/frontend/src/scenes/experiments/SharedMetrics/SharedMetric.tsxindex a510e72ca530..5c74c3c7dfdb 100644--- a/frontend/src/scenes/experiments/SharedMetrics/SharedMetric.tsx+++ b/frontend/src/scenes/experiments/SharedMetrics/SharedMetric.tsx@@ -1,8 +1,8 @@import { useActions, useValues } from 'kea'import { useState } from 'react'-import { IconBalance, IconCheckCircle, IconTrash } from '@posthog/icons'-import { LemonButton, LemonDialog, Link, Spinner } from '@posthog/lemon-ui'+import { IconBalance, IconTrash } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonDialog, Link, Spinner } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'@@ -29,15 +29,13 @@ import {ScenePanelInfoSection,} from '~/layout/scenes/SceneLayout'import { tagsModel } from '~/models/tagsModel'-import { ExperimentMetric, NodeKind } from '~/queries/schema/schema-general'+import { ExperimentMetric } from '~/queries/schema/schema-general'import { AccessControlLevel, AccessControlResourceType, ExperimentsTabs } from '~/types'import type { ExperimentSavedMetricLinkedExperimentApi } from 'products/experiments/frontend/generated/api.schemas'-import { LegacySharedFunnelsMetricForm } from 'products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm'-import { LegacySharedTrendsMetricForm } from 'products/experiments/frontend/legacy/sharedMetrics/LegacySharedTrendsMetricForm'import { ExperimentMetricForm } from '../ExperimentMetricForm'-import { getDefaultFunnelsMetric, getDefaultTrendsMetric } from '../utils'+import { isLegacyExperimentQuery } from '../utils'import { openDeleteSharedMetricDialog } from './deleteSharedMetricDialog'import { SharedMetricLinkedExperiments } from './SharedMetricLinkedExperiments'import { SharedMetricLogicProps, sharedMetricLogic } from './sharedMetricLogic'@@ -101,6 +99,12 @@ export function SharedMetric(): JSX.Element {const [deleteCheckLoading, setDeleteCheckLoading] = useState(false)const runningExperiments = (sharedMetric?.linked_experiments || []).filter((experiment) => experiment.is_running)+ const isLegacy = isLegacyExperimentQuery(sharedMetric?.query)+ const saveDisabledReason = isLegacy+ ? 'Legacy shared metrics can no longer be edited'+ : sharedMetric?.name+ ? undefined+ : 'You must give your metric a name'const handleDelete = async (): Promise<void> => {if (!sharedMetric.id || deleteCheckLoading) {@@ -143,55 +147,6 @@ export function SharedMetric(): JSX.Element {return (<SceneContent>- {sharedMetric.query.kind !== NodeKind.ExperimentMetric && (- <div className="flex gap-4 mb-4">- <div- className={`flex-1 cursor-pointer p-4 rounded border ${- sharedMetric.query.kind === NodeKind.ExperimentTrendsQuery- ? 'border-accent bg-accent-highlight-secondary'- : 'border-primary'- }`}- onClick={() => {- setSharedMetric({- query: getDefaultTrendsMetric(),- })- }}- >- <div className="font-semibold flex justify-between items-center">- <span>Trend</span>- {sharedMetric.query.kind === NodeKind.ExperimentTrendsQuery && (- <IconCheckCircle fontSize={18} color="var(--color-accent)" />- )}- </div>- <div className="text-secondary text-sm leading-relaxed">- Track a single event, action or a property value.- </div>- </div>- <div- className={`flex-1 cursor-pointer p-4 rounded border ${- sharedMetric.query.kind === NodeKind.ExperimentFunnelsQuery- ? 'border-accent bg-accent-highlight-secondary'- : 'border-primary'- }`}- onClick={() => {- setSharedMetric({- query: getDefaultFunnelsMetric(),- })- }}- >- <div className="font-semibold flex justify-between items-center">- <span>Funnel</span>- {sharedMetric.query.kind === NodeKind.ExperimentFunnelsQuery && (- <IconCheckCircle fontSize={18} color="var(--color-accent)" />- )}- </div>- <div className="text-secondary text-sm leading-relaxed">- Analyze conversion rates between sequential steps.- </div>- </div>- </div>- )}-{sceneMenuBarEnabled && action === 'update' && (<SceneMenuBar><SceneMenuBarMenu label="File" dataAttr="shared-metric-menubar-file">@@ -229,7 +184,7 @@ export function SharedMetric(): JSX.Element {updateSharedMetric(false)}}}- canEdit+ canEdit={!isLegacy}tags={sharedMetric.tags}tagsAvailable={allExistingTags}dataAttrKey="shared-metric"@@ -270,7 +225,7 @@ export function SharedMetric(): JSX.Element {description: newDescription,})}}- canEdit+ canEdit={!isLegacy}forceEdit={!sharedMetric.id}forceBackTo={{name: 'Experiments / shared metrics',@@ -308,7 +263,7 @@ export function SharedMetric(): JSX.Element {userAccessLevel={sharedMetric.user_access_level}><LemonButton- disabledReason={sharedMetric.name ? undefined : 'You must give your metric a name'}+ disabledReason={saveDisabledReason}loading={metricSaving}size="small"type="primary"@@ -323,7 +278,12 @@ export function SharedMetric(): JSX.Element {<div className="flex flex-col gap-4 @min-[64rem]/main-content:flex-row @min-[64rem]/main-content:items-start"><div className="min-w-0 flex-1 order-2 @min-[64rem]/main-content:order-1">- {sharedMetric.query.kind === NodeKind.ExperimentMetric ? (+ {isLegacy ? (+ <LemonBanner type="warning">+ Legacy shared metrics can no longer be edited. When you migrate an experiment that uses this+ metric with PostHog AI, the metric is migrated too.+ </LemonBanner>+ ) : (<ExperimentMetricFormmetric={sharedMetric.query as ExperimentMetric}isSharedMetric={true}@@ -335,10 +295,6 @@ export function SharedMetric(): JSX.Element {}}filterTestAccounts={currentTeam?.test_account_filters?.length ? true : false}/>- ) : sharedMetric.query.kind === NodeKind.ExperimentTrendsQuery ? (- <LegacySharedTrendsMetricForm />- ) : (- <LegacySharedFunnelsMetricForm />)}</div>{action === 'update' && (sharedMetric.linked_experiments || []).length > 0 && (@@ -354,7 +310,7 @@ export function SharedMetric(): JSX.Element {userAccessLevel={sharedMetric.user_access_level}><LemonButton- disabledReason={sharedMetric.name ? undefined : 'You must give your metric a name'}+ disabledReason={saveDisabledReason}loading={metricSaving}size="medium"type="primary"diff --git a/frontend/src/scenes/experiments/experimentLogic.test.ts b/frontend/src/scenes/experiments/experimentLogic.test.tsindex a8aacc1988bd..145d590e9a18 100644--- a/frontend/src/scenes/experiments/experimentLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentLogic.test.ts@@ -1,5 +1,6 @@import { api } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'@@ -7,9 +8,10 @@ import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'-import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'+import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched.json'import experimentMetricResultsSuccessJson from '~/mocks/fixtures/api/experiments/_experiment_metric_results_success.json'import { useMocks } from '~/mocks/jest'import { tagsModel } from '~/models/tagsModel'@@ -131,6 +133,34 @@ describe('experimentLogic', () => {})describe('refreshExperimentResults', () => {+ it.each([+ [+ 'sends no queries for a legacy experiment',+ [+ {+ kind: NodeKind.ExperimentTrendsQuery,+ uuid: 'legacy-metric',+ count_query: { kind: NodeKind.TrendsQuery, series: [] },+ },+ ],+ false,+ ],+ ['sends queries for a new-engine experiment', experiment.metrics, true],+ ])('%s', async (_, metrics, expectQueries) => {+ const queryHandler = jest.fn(() => [200, {}])+ useMocks({+ post: {+ '/api/environments/:team/query': queryHandler,+ '/api/environments/:team/query/:kind': queryHandler,+ },+ })+ logic.actions.setExperiment({ ...experiment, metrics } as Experiment)++ await logic.asyncActions.refreshExperimentResults(true, 'manual')++ expect(queryHandler.mock.calls.length > 0).toBe(expectQueries)+ })+const unevenExposures = {timeseries: [{ variant: 'control' }, { variant: 'test' }, { variant: '$multiple' }],total_exposures: { control: 600, test: 350, $multiple: 50 },@@ -212,7 +242,6 @@ describe('experimentLogic', () => {'reports the exposure state with the completed refresh: $desc',async ({ exposures, handling, expected }) => {const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)- // The fixture holds legacy metrics, so the refresh keeps the exposures that are set here.logic.actions.setExperiment({...experiment,exposure_criteria: { ...experiment.exposure_criteria, multiple_variant_handling: handling },@@ -222,10 +251,17 @@ describe('experimentLogic', () => {}useMocks({post: {- '/api/environments/:team/query': () => [- 200,- { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },- ],+ // The exposure query fails, so the refresh keeps the exposures that are set here.+ '/api/environments/:team/query/:kind': ({ params }) =>+ params.kind === NodeKind.ExperimentExposureQuery+ ? [500, { detail: 'Exposures are unavailable' }]+ : [+ 200,+ {+ cache_key: 'cache_key',+ query_status: experimentMetricResultsSuccessJson.query_status,+ },+ ],},get: {'/api/environments/:team/query/:id': () => [200, experimentMetricResultsSuccessJson],@@ -1074,6 +1110,46 @@ describe('experimentLogic', () => {expect(logic.values.experiment.metrics).toEqual([otherPrimaryMetric, primaryMetric])})})+ describe('migrateLegacyExperiment', () => {+ const MIGRATED_EXP_ID = 777++ it.each([+ {+ name: 'opens the migrated experiment when the migration succeeds',+ response: [200, { ...experiment, id: MIGRATED_EXP_ID }],+ expectedPath: urls.experiment(MIGRATED_EXP_ID),+ },+ {+ name: 'stays on the legacy experiment when the migration fails',+ response: [400, { type: 'validation_error', detail: "Couldn't migrate this experiment" }],+ expectedPath: urls.experiment(experiment.id),+ },+ ])('$name', async ({ response, expectedPath }) => {+ useMocks({+ get: { '/api/projects/:team/experiments/:id': experiment },+ post: {+ '/api/projects/:team/experiments/:id/migrate': () => response,+ '/api/environments/:team/query': () => [+ 200,+ { cache_key: 'cache_key', query_status: experimentMetricResultsSuccessJson.query_status },+ ],+ },+ })+ router.actions.push(urls.experiment(experiment.id))+ const keyed = experimentLogic({ experimentId: experiment.id })+ keyed.mount()+ await expectLogic(keyed).toFinishAllListeners()++ await expectLogic(keyed, () => {+ keyed.actions.migrateLegacyExperiment()+ })+ .toFinishAllListeners()+ .toMatchValues({ migrateLegacyExperimentLoading: false })++ expect(router.values.location.pathname).toContain(expectedPath)+ keyed.unmount()+ })+ })describe('tags refresh', () => {it('reloads tagsModel after an update that changed tags', async () => {logic.actions.setExperiment(experiment)@@ -2297,8 +2373,17 @@ describe('experimentLogic', () => {})const running = { start_date: '2020-01-01', end_date: undefined }- // The fixture holds legacy metrics, and a legacy experiment never shows the health panel.const newEngineMetrics = { metrics: [], metrics_secondary: [], saved_metrics: [] }+ // A legacy experiment never shows the health panel.+ const legacyMetrics = {+ metrics: [+ {+ kind: NodeKind.ExperimentTrendsQuery,+ uuid: 'legacy-metric',+ count_query: { kind: NodeKind.TrendsQuery, series: [] },+ },+ ],+ } as Partial<Experiment>it.each<{desc: string@@ -2542,7 +2627,7 @@ describe('experimentLogic', () => {},{desc: 'a reader with the flag on a legacy experiment, which shows the separate warnings',- overrides: { ...running, feature_flag: flag(true, multivariantFilters) },+ overrides: { ...running, ...legacyMetrics, feature_flag: flag(true, multivariantFilters) },health: { findings: [] },expected: { health_ui: 'warnings', health_finding_count: 0 },},@@ -2682,6 +2767,7 @@ describe('experimentLogic', () => {.map(([event, properties]) => [event, properties])it('reports a shown finding once per experiment load, without customer text', () => {+ setHealthFindingsFlag(false)const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)const draft = { ...experiment, id: 7, status: ExperimentStatus.Draft, start_date: undefined } as Experimentconst finding: ExperimentHealthFinding = {@@ -2756,6 +2842,7 @@ describe('experimentLogic', () => {})it('reports a finding as shown before it reports the finding as opened', () => {+ setHealthFindingsFlag(false)const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)const running = {...experiment,diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsxindex 3a92d88941a9..9046612e683e 100644--- a/frontend/src/scenes/experiments/experimentLogic.tsx+++ b/frontend/src/scenes/experiments/experimentLogic.tsx@@ -37,7 +37,6 @@ import {featureFlagLogic as sceneFeatureFlagLogic,} from 'scenes/feature-flags/featureFlagLogic'import { featureFlagsLogic } from 'scenes/feature-flags/featureFlagsLogic'-import { insightDataLogic } from 'scenes/insights/insightDataLogic'import { projectLogic } from 'scenes/projectLogic'import { experimentsConfigLogic } from 'scenes/settings/environment/experimentsConfigLogic'import { teamLogic } from 'scenes/teamLogic'@@ -49,7 +48,6 @@ import { groupsModel } from '~/models/groupsModel'import { tagsModel } from '~/models/tagsModel'import { performQuery } from '~/queries/query'import {- AnyEntityNode,Breakdown,ExperimentExposureCriteria,ExperimentExposureQueryResponse,@@ -76,13 +74,9 @@ import {MultivariateFlagVariant,} from '~/types'-import {- EXPERIMENT_MIN_EXPOSURES_FOR_RESULTS,- NEW_EXPERIMENT,- MetricInsightId,-} from 'products/experiments/frontend/constants'+import { EXPERIMENT_MIN_EXPOSURES_FOR_RESULTS, NEW_EXPERIMENT } from 'products/experiments/frontend/constants'import { hasEnded, isLaunched } from 'products/experiments/frontend/experimentStatus'-import { experimentsHealthRetrieve } from 'products/experiments/frontend/generated/api'+import { experimentsHealthRetrieve, experimentsMigrateCreate } from 'products/experiments/frontend/generated/api'import type { ExperimentHealthApi } from 'products/experiments/frontend/generated/api.schemas'import {type ExperimentHealthFinding,@@ -98,32 +92,16 @@ import {exposureHealthEventProperties,} from 'products/experiments/frontend/health/experimentHealthFindingEvents'import { type HealthPanelFinding, healthPanelFindings } from 'products/experiments/frontend/health/healthPanelFindings'-import {- legacyExpectedRunningTime,- legacyMinimumSampleSizePerVariant,- legacyRecommendedExposureForCountData,-} from 'products/experiments/frontend/legacy/calculations/legacyExperimentCalculations'import {experimentsLogic,getShippedVariantKey,isSingleVariantShipped,} from 'products/experiments/frontend/scenes/experimentsLogic'-import { funnelDataLogic } from 'products/product_analytics/frontend/insights/funnels/funnelDataLogic'-import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'import type { ProductIntentProperties } from '../../lib/utils/product-intents'import type { Noun } from '../../models/groupsModel'import type { ExperimentMetricUnion } from '../../queries/schema/schema-general'-import type {- BillingType,- ExperimentHoldoutType,- ExperimentIdType,- FunnelResultType,- FunnelTimeConversionMetrics,- GroupType,- GroupTypeIndex,-} from '../../types'-import type { TrendResult } from '../../types'+import type { BillingType, ExperimentHoldoutType, ExperimentIdType, GroupType, GroupTypeIndex } from '../../types'import type { ExperimentsConfig } from '../settings/environment/experimentsConfigLogic'import { experimentMetricsLogic } from './experimentMetricsLogic'import { featureFlagVariantProperty, resolvedExposureEvent } from './exposureContract'@@ -370,26 +348,16 @@ export interface experimentLogicValues {defaultMinimumDetectableEffect: number // experimentsConfigLogicexperimentsConfig: ExperimentsConfig | null // experimentsConfigLogicfeatureFlags: FeatureFlagsSet // featureFlagLogic- conversionMetrics: FunnelTimeConversionMetrics // funnelDataLogic- funnelResults: FunnelResultType // funnelDataLogicaggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModelgroupTypes: Map<GroupTypeIndex, GroupType> // groupsModelshowGroupsOptions: boolean // groupsModelholdouts: ExperimentHoldoutType[] // holdoutsLogic- funnelMetricInsightLoading: boolean // insightDataLogic- trendMetricInsightLoading: boolean // insightDataLogiccurrentProjectId: number | null // projectLogicsharedMetrics: SharedMetric[] // sharedMetricsLogiccurrentTeamId: number | null // teamLogic- trendResults: TrendResult[] // trendsDataLogic- actualRunningTime: numberbrowserExperimentWarning: ExperimentWarning | nullbrowserNoMetricsWarning: boolean- compatibleSharedMetrics: SharedMetric[]currentRefresh: CurrentRefreshSnapshot | null- editingPrimaryMetricUuid: string | null- editingSecondaryMetricUuid: string | null- editingSharedMetricId: SharedMetric['id'] | nullendExperimentLoading: booleanexcludedVariants: string[]experiment: Experiment@@ -407,7 +375,6 @@ export interface experimentLogicValues {exposureCriteria: ExperimentExposureCriteria | undefinedexposures: anyexposuresLoading: boolean- firstPrimaryMetric: ExperimentFunnelsQuery | ExperimentMetric | ExperimentTrendsQuery | undefinedformMode: FormModesfreezeExposureLoading: booleangetInsightType: (@@ -427,12 +394,10 @@ export interface experimentLogicValues {isFlagActive: booleanisSingleVariantShipped: booleanlaunchExperimentLoading: boolean- minimumDetectableEffect: number+ migrateLegacyExperimentLoading: booleanopenDatePicker: 'end' | 'start' | nullprimaryMetricsLengthWithSharedMetrics: numberprops: any- recommendedRunningTime: number- recommendedSampleSize: numberresolvedExposureEvent: stringshippedVariantKey: string | nullshowDebugPanel: boolean@@ -547,33 +512,15 @@ export interface experimentLogicActions {closePauseExperimentModal: () => {value: true} // modalsLogic- closePrimaryMetricModal: () => {- value: true- } // modalsLogiccloseResumeExperimentModal: () => {value: true} // modalsLogic- closeSecondaryMetricModal: () => {- value: true- } // modalsLogiccloseStatsEngineModal: () => {value: true} // modalsLogic- openPrimaryMetricModal: (uuid: string) => {- uuid: string- } // modalsLogic- openPrimarySharedMetricModal: (sharedMetricId: number | null) => {- sharedMetricId: number | null- } // modalsLogicopenReleaseConditionsModal: () => {value: true} // modalsLogic- openSecondaryMetricModal: (uuid: string) => {- uuid: string- } // modalsLogic- openSecondarySharedMetricModal: (sharedMetricId: number | null) => {- sharedMetricId: number | null- } // modalsLogicloadTags: () => {value: true} // tagsModel@@ -742,6 +689,9 @@ export interface experimentLogicActions {refreshId: stringtriggeredBy: ExperimentTriggeredBy}+ migrateLegacyExperiment: () => {+ value: true+ }moveMetricsBetweenSections: (isSecondary: boolean,orderedUuids: string[],@@ -865,43 +815,6 @@ export interface experimentLogicActions {setFreezeExposureLoading: (loading: boolean) => {loading: boolean}- setFunnelsMetric: ({- uuid,- name,- series,- filterTestAccounts,- breakdownAttributionType,- breakdownAttributionValue,- funnelWindowInterval,- funnelWindowIntervalUnit,- aggregation_group_type_index,- funnelAggregateByHogQL,- isSecondary,- }: {- aggregation_group_type_index?: number- breakdownAttributionType?: BreakdownAttributionType- breakdownAttributionValue?: number- filterTestAccounts?: boolean- funnelAggregateByHogQL?: string- funnelWindowInterval?: number- funnelWindowIntervalUnit?: string- isSecondary?: boolean- name?: string- series?: AnyEntityNode[]- uuid: string- }) => {- aggregation_group_type_index: number | undefined- breakdownAttributionType: BreakdownAttributionType | undefined- breakdownAttributionValue: number | undefined- filterTestAccounts: boolean | undefined- funnelAggregateByHogQL: string | undefined- funnelWindowInterval: number | undefined- funnelWindowIntervalUnit: string | undefined- isSecondary: boolean | undefined- name: string | undefined- series: AnyEntityNode[] | undefined- uuid: string- }setHogfettiTrigger: (trigger: (() => void) | null) => {trigger: (() => void) | null}@@ -927,47 +840,12 @@ export interface experimentLogicActions {name: string | undefineduuid: string}+ setMigrateLegacyExperimentLoading: (loading: boolean) => {+ loading: boolean+ }setOpenDatePicker: (boundary: 'end' | 'start' | null) => {boundary: 'end' | 'start' | null}- setTrendsExposureMetric: ({- uuid,- name,- series,- filterTestAccounts,- isSecondary,- }: {- filterTestAccounts?: boolean- isSecondary?: boolean- name?: string- series?: AnyEntityNode[]- uuid: string- }) => {- filterTestAccounts: boolean | undefined- isSecondary: boolean- name: string | undefined- series: AnyEntityNode[] | undefined- uuid: string- }- setTrendsMetric: ({- uuid,- name,- series,- filterTestAccounts,- isSecondary,- }: {- filterTestAccounts?: boolean- isSecondary?: boolean- name?: string- series?: AnyEntityNode[]- uuid: string- }) => {- filterTestAccounts: boolean | undefined- isSecondary: boolean- name: string | undefined- series: AnyEntityNode[] | undefined- uuid: string- }setUnfreezeExposureLoading: (loading: boolean) => {loading: boolean}@@ -1086,25 +964,6 @@ export interface experimentLogicMeta {isExperimentStopped: (experiment: Experiment) => booleanvariants: (experiment: Experiment) => MultivariateFlagVariant[]excludedVariants: (experiment: Experiment) => string[]- minimumDetectableEffect: (experiment: Experiment, defaultMinimumDetectableEffect: number) => number- recommendedSampleSize: (- conversionMetrics: FunnelTimeConversionMetrics,- variants: MultivariateFlagVariant[],- minimumDetectableEffect: number- ) => number- recommendedRunningTime: (- experiment: Experiment,- variants: MultivariateFlagVariant[],- getInsightType: (- metric: ExperimentFunnelsQuery | ExperimentMetricUnion | ExperimentTrendsQuery | undefined- ) => InsightType,- firstPrimaryMetric: ExperimentFunnelsQuery | ExperimentMetricUnion | ExperimentTrendsQuery | undefined,- funnelResults: FunnelResultType,- conversionMetrics: FunnelTimeConversionMetrics,- trendResults: TrendResult[],- minimumDetectableEffect: number- ) => number- actualRunningTime: (experiment: Experiment) => numberisSingleVariantShipped: (experiment: Experiment) => booleanshippedVariantKey: (experiment: Experiment) => string | nullbrowserExperimentWarning: (@@ -1140,11 +999,7 @@ export interface experimentLogicMeta {exposures: any,isExperimentDraft: boolean) => HealthPanelFinding[] | null- firstPrimaryMetric: (- experiment: Experiment- ) => ExperimentFunnelsQuery | ExperimentMetric | ExperimentTrendsQuery | undefinedprimaryMetricsLengthWithSharedMetrics: (experiment: Experiment) => number- compatibleSharedMetrics: (sharedMetrics: SharedMetric[], usesNewQueryRunner: boolean) => SharedMetric[]usesNewQueryRunner: (experiment: Experiment) => booleanhasMinimumExposureForResults: (exposures: any, usesNewQueryRunner: boolean) => booleanexposureCriteria: (experiment: Experiment) => ExperimentExposureCriteria | undefined@@ -1179,16 +1034,6 @@ export const experimentLogic = kea<experimentLogicType>([['holdouts'],billingLogic,['billing'],- // Hook the insight state to get the results for the sample size estimation- funnelDataLogic({ dashboardItemId: MetricInsightId.Funnels }),- ['results as funnelResults', 'conversionMetrics'],- trendsDataLogic({ dashboardItemId: MetricInsightId.Trends }),- ['results as trendResults'],- // Hook into the loading state of the metric insight- insightDataLogic({ dashboardItemId: MetricInsightId.Trends }),- ['insightDataLoading as trendMetricInsightLoading'],- insightDataLogic({ dashboardItemId: MetricInsightId.Funnels }),- ['insightDataLoading as funnelMetricInsightLoading'],sharedMetricsLogic,['sharedMetrics'],experimentsConfigLogic,@@ -1221,12 +1066,6 @@ export const experimentLogic = kea<experimentLogicType>([['updateFlagFromPartial'],modalsLogic,[- 'openPrimaryMetricModal',- 'closePrimaryMetricModal',- 'openSecondaryMetricModal',- 'closeSecondaryMetricModal',- 'openPrimarySharedMetricModal',- 'openSecondarySharedMetricModal','closePauseExperimentModal','closeResumeExperimentModal','closeFinishExperimentModal',@@ -1335,6 +1174,8 @@ export const experimentLogic = kea<experimentLogicType>([setFreezeExposureLoading: (loading: boolean) => ({ loading }),unfreezeExposure: true,setUnfreezeExposureLoading: (loading: boolean) => ({ loading }),+ migrateLegacyExperiment: true,+ setMigrateLegacyExperimentLoading: (loading: boolean) => ({ loading }),archiveExperiment: (disableFeatureFlag: boolean = false) => ({ disableFeatureFlag }),unarchiveExperiment: true,resetRunningExperiment: true,@@ -1360,69 +1201,6 @@ export const experimentLogic = kea<experimentLogicType>([metric: ExperimentMetricisSecondary?: boolean}) => ({ uuid, name, metric, isSecondary: isSecondary ?? false }),- setTrendsMetric: ({- uuid,- name,- series,- filterTestAccounts,- isSecondary,- }: {- uuid: string- name?: string- series?: AnyEntityNode[]- filterTestAccounts?: boolean- isSecondary?: boolean- }) => ({ uuid, name, series, filterTestAccounts, isSecondary: isSecondary ?? false }),- setTrendsExposureMetric: ({- uuid,- name,- series,- filterTestAccounts,- isSecondary,- }: {- uuid: string- name?: string- series?: AnyEntityNode[]- filterTestAccounts?: boolean- isSecondary?: boolean- }) => ({ uuid, name, series, filterTestAccounts, isSecondary: isSecondary ?? false }),- setFunnelsMetric: ({- uuid,- name,- series,- filterTestAccounts,- breakdownAttributionType,- breakdownAttributionValue,- funnelWindowInterval,- funnelWindowIntervalUnit,- aggregation_group_type_index,- funnelAggregateByHogQL,- isSecondary,- }: {- uuid: string- name?: string- series?: AnyEntityNode[]- filterTestAccounts?: boolean- breakdownAttributionType?: BreakdownAttributionType- breakdownAttributionValue?: number- funnelWindowInterval?: number- funnelWindowIntervalUnit?: string- aggregation_group_type_index?: number- funnelAggregateByHogQL?: string- isSecondary?: boolean- }) => ({- uuid,- name,- series,- filterTestAccounts,- breakdownAttributionType,- breakdownAttributionValue,- funnelWindowInterval,- funnelWindowIntervalUnit,- aggregation_group_type_index,- funnelAggregateByHogQL,- isSecondary,- }),addSharedMetricsToExperiment: (sharedMetricIds: SharedMetric['id'][],metadata: { type: 'primary' | 'secondary' }@@ -1538,108 +1316,6 @@ export const experimentLogic = kea<experimentLogicType>([[metricsKey]: metrics,}},- setTrendsMetric: (state, { uuid, name, series, filterTestAccounts, isSecondary }) => {- const metricsKey = isSecondary ? 'metrics_secondary' : 'metrics'- const metrics = [...(state?.[metricsKey] || [])]- const targetIndex = metrics.findIndex((m) => m.uuid === uuid)-- if (targetIndex === -1) {- return state- }-- const metric = metrics[targetIndex]-- metrics[targetIndex] = {- ...metric,- ...(name !== undefined && { name }),- count_query: {- ...(metric as ExperimentTrendsQuery).count_query,- ...(series && { series }),- ...(filterTestAccounts !== undefined && { filterTestAccounts }),- },- } as ExperimentTrendsQuery-- return {- ...state,- [metricsKey]: metrics,- }- },- setTrendsExposureMetric: (state, { uuid, name, series, filterTestAccounts, isSecondary }) => {- const metricsKey = isSecondary ? 'metrics_secondary' : 'metrics'- const metrics = [...(state?.[metricsKey] || [])]- const targetIndex = metrics.findIndex((m) => m.uuid === uuid)-- if (targetIndex === -1) {- return state- }-- const metric = metrics[targetIndex]-- metrics[targetIndex] = {- ...metric,- ...(name !== undefined && { name }),- exposure_query: {- ...(metric as ExperimentTrendsQuery).exposure_query,- ...(series && { series }),- ...(filterTestAccounts !== undefined && { filterTestAccounts }),- },- } as ExperimentTrendsQuery-- return {- ...state,- [metricsKey]: metrics,- }- },- setFunnelsMetric: (- state,- {- uuid,- name,- series,- filterTestAccounts,- breakdownAttributionType,- breakdownAttributionValue,- funnelWindowInterval,- funnelWindowIntervalUnit,- aggregation_group_type_index,- funnelAggregateByHogQL,- isSecondary,- }- ) => {- const metricsKey = isSecondary ? 'metrics_secondary' : 'metrics'- const metrics = [...(state?.[metricsKey] || [])]- const targetIndex = metrics.findIndex((m) => m.uuid === uuid)-- if (targetIndex === -1) {- return state- }-- const metric = metrics[targetIndex]-- metrics[targetIndex] = {- ...metric,- ...(name !== undefined && { name }),- funnels_query: {- ...(metric as ExperimentFunnelsQuery).funnels_query,- ...(series && { series }),- ...(filterTestAccounts !== undefined && { filterTestAccounts }),- ...(aggregation_group_type_index != null && { aggregation_group_type_index }),- funnelsFilter: {- ...(metric as ExperimentFunnelsQuery).funnels_query.funnelsFilter,- ...(breakdownAttributionType && { breakdownAttributionType }),- ...(breakdownAttributionValue !== undefined && { breakdownAttributionValue }),- ...(funnelWindowInterval !== undefined && { funnelWindowInterval }),- ...(funnelWindowIntervalUnit && { funnelWindowIntervalUnit }),- ...(funnelAggregateByHogQL !== undefined && { funnelAggregateByHogQL }),- },- },- } as ExperimentFunnelsQuery-- return {- ...state,- [metricsKey]: metrics,- }- },duplicateMetric: (state, { uuid, isSecondary, newUuid }) => {const metricsKey = isSecondary ? 'metrics_secondary' : 'metrics'const metrics = [...(state?.[metricsKey] || [])]@@ -1783,31 +1459,6 @@ export const experimentLogic = kea<experimentLogicType>([: experiment,},],- editingPrimaryMetricUuid: [- null as string | null,- {- openPrimaryMetricModal: (_, { uuid }) => uuid,- closePrimaryMetricModal: () => null,- updateExperimentMetrics: () => null,- setEditingPrimaryMetricUuid: (_, { uuid }) => uuid,- },- ],- editingSecondaryMetricUuid: [- null as string | null,- {- openSecondaryMetricModal: (_, { uuid }) => uuid,- closeSecondaryMetricModal: () => null,- updateExperimentMetrics: () => null,- },- ],- editingSharedMetricId: [- null as SharedMetric['id'] | null,- {- openPrimarySharedMetricModal: (_, { sharedMetricId }) => sharedMetricId,- openSecondarySharedMetricModal: (_, { sharedMetricId }) => sharedMetricId,- updateExperimentMetrics: () => null,- },- ],isCreatingExperimentDashboard: [false,{@@ -1845,6 +1496,12 @@ export const experimentLogic = kea<experimentLogicType>([setUnfreezeExposureLoading: (_, { loading }) => loading,},],+ migrateLegacyExperimentLoading: [+ false,+ {+ setMigrateLegacyExperimentLoading: (_, { loading }) => loading,+ },+ ],hogfettiTrigger: [null as (() => void) | null,{@@ -2119,6 +1776,34 @@ export const experimentLogic = kea<experimentLogicType>([actions.setUnfreezeExposureLoading(false)}},+ migrateLegacyExperiment: async () => {+ const { currentProjectId, experimentId } = values+ if (values.migrateLegacyExperimentLoading || !currentProjectId || typeof experimentId !== 'number') {+ return+ }+ actions.setMigrateLegacyExperimentLoading(true)+ try {+ const migrated = await experimentsMigrateCreate(String(currentProjectId), experimentId)+ posthog.capture('legacy experiment migrated', {+ experiment_id: experimentId,+ migrated_experiment_id: migrated.id,+ })+ // Reset before navigating, because the logic is keyed by experiment id and this instance unmounts when the router opens the migrated one+ actions.setMigrateLegacyExperimentLoading(false)+ lemonToast.success('Experiment migrated to the new engine')+ router.actions.push(urls.experiment(migrated.id))+ } catch (error: any) {+ posthog.capture('legacy experiment migration failed', {+ experiment_id: experimentId,+ status: error?.status,+ })+ actions.setMigrateLegacyExperimentLoading(false)+ lemonToast.error(+ error?.detail ||+ "Couldn't migrate this experiment. Try again, and contact support if it keeps happening."+ )+ }+ },archiveExperiment: async ({ disableFeatureFlag }) => {try {// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. experimentsArchiveCreate() from 'products/experiments/frontend/generated/api' serves this route, but its generated types do not describe this call yet, so fix the endpoint's OpenAPI schema first.@@ -2147,6 +1832,11 @@ export const experimentLogic = kea<experimentLogicType>([}},refreshExperimentResults: async ({ forceRefresh, triggeredBy, refreshIfStale }) => {+ // Legacy metrics have no query runner, so every query for them fails.+ if (isLegacyExperiment(values.experiment)) {+ return+ }+const refreshId = generateRefreshId()const refreshStart = performance.now()@@ -3077,96 +2767,6 @@ export const experimentLogic = kea<experimentLogicType>([(s) => [s.experiment],(experiment: Experiment): string[] => experiment?.excluded_variants ?? [],],- minimumDetectableEffect: [- (s) => [s.experiment, s.defaultMinimumDetectableEffect],- (newExperiment: Experiment, defaultMinimumDetectableEffect: number): number => {- return (- newExperiment?.running_time_calculation?.minimum_detectable_effect ?? defaultMinimumDetectableEffect- )- },- ],- recommendedSampleSize: [- (s) => [s.conversionMetrics, s.variants, s.minimumDetectableEffect],- (- conversionMetrics: import('~/types').FunnelTimeConversionMetrics,- variants: MultivariateFlagVariant[],- minimumDetectableEffect: number- ): number => {- const conversionRate = conversionMetrics.totalRate * 100- const sampleSizePerVariant = legacyMinimumSampleSizePerVariant(minimumDetectableEffect, conversionRate)- const sampleSize = sampleSizePerVariant * variants.length- return sampleSize- },- ],- recommendedRunningTime: [- (s) => [- s.experiment,- s.variants,- s.getInsightType,- s.firstPrimaryMetric,- s.funnelResults,- s.conversionMetrics,- s.trendResults,- s.minimumDetectableEffect,- ],- (- experiment: Experiment,- variants: MultivariateFlagVariant[],- getInsightType: (- metric:- | ExperimentFunnelsQuery- | ExperimentTrendsQuery- | import('~/queries/schema/schema-general').ExperimentMetricUnion- | undefined- ) => InsightType,- firstPrimaryMetric: ExperimentFunnelsQuery | ExperimentMetric | ExperimentTrendsQuery | undefined,- funnelResults: import('~/types').FunnelResultType,- conversionMetrics: import('~/types').FunnelTimeConversionMetrics,- trendResults: import('~/types').TrendResult[],- minimumDetectableEffect: number- ): number => {- if (getInsightType(firstPrimaryMetric) === InsightType.FUNNELS) {- const currentDuration = dayjs().diff(dayjs(experiment?.start_date), 'hour')- let funnelEntrants: number | undefined- if (Array.isArray(funnelResults) && funnelResults[0]) {- const firstFunnelEntry = funnelResults[0]-- funnelEntrants = Array.isArray(firstFunnelEntry)- ? firstFunnelEntry[0].count- : firstFunnelEntry.count- }-- const conversionRate = conversionMetrics.totalRate * 100- const sampleSizePerVariant = legacyMinimumSampleSizePerVariant(- minimumDetectableEffect,- conversionRate- )- const funnelSampleSize = sampleSizePerVariant * variants.length- if (experiment?.start_date) {- return legacyExpectedRunningTime(funnelEntrants || 1, funnelSampleSize || 0, currentDuration)- }- return legacyExpectedRunningTime(funnelEntrants || 1, funnelSampleSize || 0)- }-- const trendCount = trendResults[0]?.count- const runningTime = legacyRecommendedExposureForCountData(minimumDetectableEffect, trendCount)- return runningTime- },- ],- actualRunningTime: [- (s) => [s.experiment],- (experiment: Experiment): number => {- if (!experiment.start_date) {- return 0- }-- if (experiment.end_date) {- return dayjs(experiment.end_date).diff(experiment.start_date, 'day')- }-- return dayjs().diff(experiment.start_date, 'day')- },- ],isSingleVariantShipped: [(s) => [s.experiment],(experiment: Experiment): boolean => isSingleVariantShipped(experiment),@@ -3281,18 +2881,6 @@ export const experimentLogic = kea<experimentLogicType>([): HealthPanelFinding[] | null =>healthPending ? [] : healthPanelFindings(shownHealth, exposures, isExperimentDraft),],- firstPrimaryMetric: [- (s) => [s.experiment],- (experiment: Experiment): ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery | undefined => {- if (experiment.metrics.length) {- return experiment.metrics[0]- }- const primaryMetric = experiment.saved_metrics.find((metric) => metric.metadata.type === 'primary')- if (primaryMetric) {- return primaryMetric.query- }- },- ],primaryMetricsLengthWithSharedMetrics: [(s) => [s.experiment],(experiment: Experiment): number => {@@ -3302,18 +2890,6 @@ export const experimentLogic = kea<experimentLogicType>([)},],- compatibleSharedMetrics: [- (s) => [s.sharedMetrics, s.usesNewQueryRunner],- (sharedMetrics: SharedMetric[], usesNewQueryRunner: boolean): SharedMetric[] => {- if (!sharedMetrics) {- return []- }- if (usesNewQueryRunner) {- return sharedMetrics.filter((metric) => metric.query.kind === NodeKind.ExperimentMetric)- }- return sharedMetrics.filter((metric) => metric.query.kind !== NodeKind.ExperimentMetric)- },- ],usesNewQueryRunner: [(s) => [s.experiment],(experiment: Experiment): boolean => {diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex e74306c94311..d0bcae8bc188 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -7,7 +7,7 @@ import { preflightLogic } from 'lib/logic/preflightLogic'import { projectLogic } from 'scenes/projectLogic'import preflightJson from '~/mocks/fixtures/_preflight.json'-import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'+import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched.json'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { Experiment } from '~/types'diff --git a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.tsindex 44dcf37c1d9f..a0e44dee0804 100644--- a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts@@ -2,7 +2,7 @@ import { expectLogic } from 'kea-test-utils'import { projectLogic } from 'scenes/projectLogic'-import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'+import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched.json'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { Experiment } from '~/types'diff --git a/frontend/src/scenes/experiments/modalsLogic.ts b/frontend/src/scenes/experiments/modalsLogic.tsindex efc649a4f88e..b4efb2647ad8 100644--- a/frontend/src/scenes/experiments/modalsLogic.ts+++ b/frontend/src/scenes/experiments/modalsLogic.ts@@ -5,7 +5,6 @@ import { projectLogic } from 'scenes/projectLogic'import { teamLogic } from 'scenes/teamLogic'import type { FeatureFlagType } from '../../types'-import { SharedMetric } from './SharedMetrics/sharedMetricLogic'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface modalsLogicValues {@@ -20,16 +19,12 @@ export interface modalsLogicValues {isExposureCriteriaModalOpen: booleanisFinishExperimentModalOpen: booleanisPauseExperimentModalOpen: boolean- isPrimaryMetricModalOpen: booleanisPrimaryMetricSourceModalOpen: boolean- isPrimarySharedMetricModalOpen: booleanisQuickSurveyModalOpen: booleanisReleaseConditionsModalOpen: booleanisResumeExperimentModalOpen: booleanisRunningTimeConfigModalOpen: boolean- isSecondaryMetricModalOpen: booleanisSecondaryMetricSourceModalOpen: boolean- isSecondarySharedMetricModalOpen: booleanisStatsEngineModalOpen: boolean}@@ -68,15 +63,9 @@ export interface modalsLogicActions {closePauseExperimentModal: () => {value: true}- closePrimaryMetricModal: () => {- value: true- }closePrimaryMetricSourceModal: () => {value: true}- closePrimarySharedMetricModal: () => {- value: true- }closeQuickSurveyModal: () => {value: true}@@ -89,15 +78,9 @@ export interface modalsLogicActions {closeRunningTimeConfigModal: () => {value: true}- closeSecondaryMetricModal: () => {- value: true- }closeSecondaryMetricSourceModal: () => {value: true}- closeSecondarySharedMetricModal: () => {- value: true- }closeStatsEngineModal: () => {value: true}@@ -128,15 +111,9 @@ export interface modalsLogicActions {openPauseExperimentModal: () => {value: true}- openPrimaryMetricModal: (uuid: string) => {- uuid: string- }openPrimaryMetricSourceModal: () => {value: true}- openPrimarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => {- sharedMetricId: number | null- }openQuickSurveyModal: () => {value: true}@@ -149,15 +126,9 @@ export interface modalsLogicActions {openRunningTimeConfigModal: () => {value: true}- openSecondaryMetricModal: (uuid: string) => {- uuid: string- }openSecondaryMetricSourceModal: () => {value: true}- openSecondarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => {- sharedMetricId: number | null- }openStatsEngineModal: () => {value: true}@@ -193,18 +164,10 @@ export const modalsLogic = kea<modalsLogicType>([closeStatsEngineModal: true,openCupedModal: true,closeCupedModal: true,- openPrimaryMetricModal: (uuid: string) => ({ uuid }),- closePrimaryMetricModal: true,- openSecondaryMetricModal: (uuid: string) => ({ uuid }),- closeSecondaryMetricModal: true,openPrimaryMetricSourceModal: true,closePrimaryMetricSourceModal: true,openSecondaryMetricSourceModal: true,closeSecondaryMetricSourceModal: true,- openPrimarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => ({ sharedMetricId }),- closePrimarySharedMetricModal: true,- openSecondarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => ({ sharedMetricId }),- closeSecondarySharedMetricModal: true,openRunningTimeConfigModal: true,closeRunningTimeConfigModal: true,openDuplicateExperimentModal: true,@@ -271,22 +234,6 @@ export const modalsLogic = kea<modalsLogicType>([closeAllModals: () => false,},],- isPrimaryMetricModalOpen: [- false,- {- openPrimaryMetricModal: () => true,- closePrimaryMetricModal: () => false,- closeAllModals: () => false,- },- ],- isSecondaryMetricModalOpen: [- false,- {- openSecondaryMetricModal: () => true,- closeSecondaryMetricModal: () => false,- closeAllModals: () => false,- },- ],isPrimaryMetricSourceModalOpen: [false,{@@ -303,22 +250,6 @@ export const modalsLogic = kea<modalsLogicType>([closeAllModals: () => false,},],- isPrimarySharedMetricModalOpen: [- false,- {- openPrimarySharedMetricModal: () => true,- closePrimarySharedMetricModal: () => false,- closeAllModals: () => false,- },- ],- isSecondarySharedMetricModalOpen: [- false,- {- openSecondarySharedMetricModal: () => true,- closeSecondarySharedMetricModal: () => false,- closeAllModals: () => false,- },- ],isDescriptionModalOpen: [false,{diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.tsindex 4e66c0c9cd0c..7dedd9d1ba8e 100644--- a/frontend/src/scenes/experiments/utils.test.ts+++ b/frontend/src/scenes/experiments/utils.test.ts@@ -1,6 +1,6 @@import { entityFilterLogic } from 'scenes/insights/filters/ActionFilter/entityFilterLogic'-import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched_with_funnel_and_trends.json'+import experimentJson from '~/mocks/fixtures/api/experiments/_experiment_launched.json'import {CachedNewExperimentQueryResponse,ExperimentEventExposureConfig,diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex c1c5b909f57a..1f2b50169eda 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -1,14 +1,12 @@import { match } from 'ts-pattern'import { getSeriesColor } from 'lib/colors'-import { EXPERIMENT_DEFAULT_DURATION, FunnelLayout, MAX_EXPERIMENT_VARIANTS } from 'lib/constants'-import { dayjs } from 'lib/dayjs'+import { MAX_EXPERIMENT_VARIANTS } from 'lib/constants'import { uuid } from 'lib/utils/dom'import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'import { SeriesNode, isActionsSeriesNode, isEventsSeriesNode } from 'scenes/insights/filters/ActionFilter/seriesNode'import {- AnyDataWarehouseNode,AnyEntityNode,Breakdown,CachedNewExperimentQueryResponse,@@ -20,7 +18,6 @@ import {ExperimentMetricSource,ExperimentMetricType,ExperimentTrendsQuery,- GroupNode,NodeKind,ProductKey,TrendsQuery,@@ -40,10 +37,7 @@ import {FeatureFlagBasicType,FeatureFlagType,FunnelConversionWindowTimeUnit,- FunnelVizType,MultivariateFlagVariant,- PropertyFilterType,- PropertyOperator,type InsightModel,UniversalFiltersGroupValue,} from '~/types'@@ -55,13 +49,7 @@ import type {ExperimentToSavedMetricApi,} from 'products/experiments/frontend/generated/api.schemas'-import {- EXPOSURE_DEFAULT_EVENT,- EXPOSURE_FEATURE_FLAG_PROPERTY,- EXPOSURE_FEATURE_FLAG_RESPONSE_PROPERTY,- featureFlagVariantProperty,- resolvedExposureEvent,-} from './exposureContract'+import { EXPOSURE_DEFAULT_EVENT, resolvedExposureEvent } from './exposureContract'import { SharedMetric } from './SharedMetrics/sharedMetricLogic'const MULTIPLE_VARIANT_WARNING_THRESHOLD = 0.5 // on the 0-100 scale (0.5 = 0.5%)@@ -160,35 +148,6 @@ export function isEvenlyDistributed(variants: MultivariateFlagVariant[]): booleareturn variants.every((variant, index) => variant.rollout_percentage === evenPercentages[index])}-function seriesToFilterLegacy(- series: AnyEntityNode<AnyDataWarehouseNode> | GroupNode,- featureFlagKey: string,- variantKey: string-): UniversalFiltersGroupValue | null {- if (series.kind === NodeKind.EventsNode) {- return {- id: series.event as string,- name: series.event as string,- type: 'events',- properties: [- {- key: featureFlagVariantProperty(featureFlagKey),- type: PropertyFilterType.Event,- value: [variantKey],- operator: PropertyOperator.Exact,- },- ],- }- } else if (series.kind === NodeKind.ActionsNode) {- return {- id: series.id,- name: series.name,- type: 'actions',- }- }- return null-}-function seriesToFilter(series: AnyEntityNode | ExperimentMetricSource): UniversalFiltersGroupValue | null {if (series.kind === NodeKind.EventsNode) {return {@@ -395,83 +354,6 @@ export function getSessionLinkabilityEventNames(experiment: Experiment): string[return Array.from(eventNames)}-export function getViewRecordingFiltersLegacy(- metric: ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery,- featureFlagKey: string,- variantKey: string-): UniversalFiltersGroupValue[] {- const filters: UniversalFiltersGroupValue[] = []- if (metric.kind === NodeKind.ExperimentMetric) {- if (isExperimentMeanMetric(metric)) {- if (metric.source.kind === NodeKind.EventsNode) {- return [- {- id: metric.source.event ?? null,- name: metric.source.event,- type: 'events',- properties: [- {- key: featureFlagVariantProperty(featureFlagKey),- type: PropertyFilterType.Event,- value: [variantKey],- operator: PropertyOperator.Exact,- },- ],- },- ]- }- }- return []- } else if (metric.kind === NodeKind.ExperimentTrendsQuery) {- if (metric.exposure_query) {- const exposureSeries = metric.exposure_query.series[0]- // Experiments don't support GroupNode yet - skip if it's a group- if (exposureSeries.kind !== NodeKind.GroupNode) {- const exposure_filter = seriesToFilterLegacy(exposureSeries, featureFlagKey, variantKey)- if (exposure_filter) {- filters.push(exposure_filter)- }- }- } else {- filters.push({- id: EXPOSURE_DEFAULT_EVENT,- name: EXPOSURE_DEFAULT_EVENT,- type: 'events',- properties: [- {- key: EXPOSURE_FEATURE_FLAG_RESPONSE_PROPERTY,- type: PropertyFilterType.Event,- value: [variantKey],- operator: PropertyOperator.Exact,- },- {- key: EXPOSURE_FEATURE_FLAG_PROPERTY,- type: PropertyFilterType.Event,- value: featureFlagKey,- operator: PropertyOperator.Exact,- },- ],- })- }- const countSeries = metric.count_query.series[0]- // Experiments don't support GroupNode yet - skip if it's a group- if (countSeries.kind !== NodeKind.GroupNode) {- const count_filter = seriesToFilterLegacy(countSeries, featureFlagKey, variantKey)- if (count_filter) {- filters.push(count_filter)- }- }- return filters- }- metric.funnels_query.series.forEach((series) => {- const filter = seriesToFilterLegacy(series, featureFlagKey, variantKey)- if (filter) {- filters.push(filter)- }- })- return filters-}-// Mirrors the backend eligibility rule (experiment_eligibility_error): multivariate with 2-20 variantsexport function featureFlagEligibleForExperiment(featureFlag: FeatureFlagType): true {const variants = getFlagVariants(featureFlag)@@ -484,70 +366,6 @@ export function featureFlagEligibleForExperiment(featureFlag: FeatureFlagType):return true}-/**- * TODO: review. Probably deprecated- */-export function getDefaultTrendsMetric(): ExperimentTrendsQuery {- return {- kind: NodeKind.ExperimentTrendsQuery,- uuid: uuid(),- count_query: {- kind: NodeKind.TrendsQuery,- series: [- {- kind: NodeKind.EventsNode,- name: '$pageview',- event: '$pageview',- },- ],- interval: 'day',- dateRange: {- date_from: dayjs().subtract(EXPERIMENT_DEFAULT_DURATION, 'day').format('YYYY-MM-DDTHH:mm'),- date_to: dayjs().endOf('d').format('YYYY-MM-DDTHH:mm'),- explicitDate: true,- },- trendsFilter: {- display: ChartDisplayType.ActionsLineGraph,- },- filterTestAccounts: true,- },- }-}--export function getDefaultFunnelsMetric(): ExperimentFunnelsQuery {- return {- kind: NodeKind.ExperimentFunnelsQuery,- uuid: uuid(),- funnels_query: {- kind: NodeKind.FunnelsQuery,- filterTestAccounts: true,- dateRange: {- date_from: dayjs().subtract(EXPERIMENT_DEFAULT_DURATION, 'day').format('YYYY-MM-DDTHH:mm'),- date_to: dayjs().endOf('d').format('YYYY-MM-DDTHH:mm'),- explicitDate: true,- },- series: [- {- kind: NodeKind.EventsNode,- event: '$pageview',- name: '$pageview',- },- {- kind: NodeKind.EventsNode,- event: '$pageview',- name: '$pageview',- },- ],- funnelsFilter: {- funnelVizType: FunnelVizType.Steps,- funnelWindowIntervalUnit: FunnelConversionWindowTimeUnit.Day,- funnelWindowInterval: 14,- layout: FunnelLayout.horizontal,- },- },- }-}-/*** TODO: review. Probably deprecated*/diff --git a/products/experiments/frontend/components/notebook/NotebookExperimentComponent.tsx b/products/experiments/frontend/components/notebook/NotebookExperimentComponent.tsxindex cc3de2f861b4..add2be3f4615 100644--- a/products/experiments/frontend/components/notebook/NotebookExperimentComponent.tsx+++ b/products/experiments/frontend/components/notebook/NotebookExperimentComponent.tsx@@ -117,8 +117,7 @@ export function NotebookExperimentComponent({ id, expanded }: NotebookExperiment<strong>Legacy experiment</strong></div><div>- This experiment uses legacy metrics. Results are only available in the full- experiment view.+ This experiment uses legacy metrics, so its results are no longer available.</div></LemonBanner></div>diff --git a/products/experiments/frontend/constants.ts b/products/experiments/frontend/constants.tsindex beb01190e351..7042c7216222 100644--- a/products/experiments/frontend/constants.ts+++ b/products/experiments/frontend/constants.ts@@ -1,33 +1,6 @@-import {- AccessControlLevel,- BaseMathType,- ExperimentConclusion,- GroupMathType,- HogQLMathType,- PropertyMathType,-} from '~/types'+import { AccessControlLevel, ExperimentConclusion } from '~/types'import type { Experiment } from '~/types'-export enum MetricInsightId {- Trends = 'new-experiment-trends-metric',- TrendsExposure = 'new-experiment-trends-exposure',- Funnels = 'new-experiment-funnels-metric',- SecondaryTrends = 'new-experiment-secondary-trends',- SecondaryFunnels = 'new-experiment-secondary-funnels',-}--export const LEGACY_EXPERIMENT_ALLOWED_MATH_TYPES = [- BaseMathType.TotalCount,- BaseMathType.UniqueUsers,- BaseMathType.UniqueSessions,- BaseMathType.WeeklyActiveUsers,- BaseMathType.MonthlyActiveUsers,- BaseMathType.FirstTimeForUser,- GroupMathType.UniqueGroup,- PropertyMathType.Sum,- HogQLMathType.HogQL,-] as const-export const EXPERIMENT_VARIANT_MULTIPLE = '$multiple'export const EXPERIMENT_HEALTH_PANEL_ELEMENT_ID = 'experiment-health-panel'diff --git a/products/experiments/frontend/legacy/LegacyExperimentDate.tsx b/products/experiments/frontend/legacy/LegacyExperimentDate.tsxindex b7a0bf7f08a9..188fe49c2228 100644--- a/products/experiments/frontend/legacy/LegacyExperimentDate.tsx+++ b/products/experiments/frontend/legacy/LegacyExperimentDate.tsx@@ -1,9 +1,6 @@import { TZLabel } from 'lib/components/TZLabel'import { Label } from 'lib/ui/Label/Label'-/**- * @deprecated Use the new ExperimentDate component instead- */export const LegacyExperimentDate = ({label,date,diff --git a/products/experiments/frontend/legacy/LegacyExperimentDates.tsx b/products/experiments/frontend/legacy/LegacyExperimentDates.tsxindex d556862c50d3..fd283227726c 100644--- a/products/experiments/frontend/legacy/LegacyExperimentDates.tsx+++ b/products/experiments/frontend/legacy/LegacyExperimentDates.tsx@@ -2,14 +2,12 @@ import { useValues } from 'kea'import { TZLabel } from 'lib/components/TZLabel'import { Label } from 'lib/ui/Label/Label'+import { experimentLogic } from 'scenes/experiments/experimentLogic'-import { LegacyExperimentDate, legacyExperimentLogic } from 'products/experiments/frontend/legacy'+import { LegacyExperimentDate } from './LegacyExperimentDate'-/**- * @deprecated use the ExperimentDuration component instead- */export function LegacyExperimentDates(): JSX.Element | null {- const { experiment } = useValues(legacyExperimentLogic)+ const { experiment } = useValues(experimentLogic)const { created_at, start_date, end_date } = experiment// If the experiment has no start date and no creation date, don't show anythingdiff --git a/products/experiments/frontend/legacy/LegacyExperimentInfo.tsx b/products/experiments/frontend/legacy/LegacyExperimentInfo.tsxindex 704e0f5cc57e..5b86a98b2e29 100644--- a/products/experiments/frontend/legacy/LegacyExperimentInfo.tsx+++ b/products/experiments/frontend/legacy/LegacyExperimentInfo.tsx@@ -1,83 +1,28 @@import clsx from 'clsx'-import { useActions, useValues } from 'kea'+import { useValues } from 'kea'-import { IconRefresh, IconWarning } from '@posthog/icons'-import { LemonButton, LemonTag, Link, ProfilePicture, Tooltip } from '@posthog/lemon-ui'+import { IconWarning } from '@posthog/icons'+import { LemonTag, Link, ProfilePicture, Tooltip } from '@posthog/lemon-ui'import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'-import { dayjs } from 'lib/dayjs'-import { usePeriodicRerender } from 'lib/hooks/usePeriodicRerender'import { IconOpenInNew } from 'lib/lemon-ui/icons'import { Label } from 'lib/ui/Label/Label'import { cn } from 'lib/utils/css-classes'+import { experimentLogic } from 'scenes/experiments/experimentLogic'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'-import { ExperimentStatsMethod, ExperimentStatus } from '~/types'+import { ExperimentStatsMethod } from '~/types'import { StatusTag } from 'products/experiments/frontend/components/StatusTag'import { CONCLUSION_DISPLAY_CONFIG } from 'products/experiments/frontend/constants'import { getExperimentStatus, isExperimentPaused } from 'products/experiments/frontend/experimentStatus'-import { LegacyExperimentDates, legacyExperimentLogic } from 'products/experiments/frontend/legacy'import { isSingleVariantShipped, getShippedVariantKey } from 'products/experiments/frontend/scenes/experimentsLogic'-/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * Frozen copy for legacy experiments - do not modify.- */-export const LegacyExperimentLastRefresh = ({- isRefreshing,- lastRefresh,- onClick,-}: {- isRefreshing: boolean- lastRefresh: string | undefined- onClick: () => void-}): JSX.Element => {- usePeriodicRerender(15000) // Re-render every 15 seconds for up-to-date last refresh time- return (- <div className="flex flex-col">- <Label intent="menu">Last refreshed</Label>- <div className="inline-flex deprecated-space-x-2">- <span- className={`${- lastRefresh- ? dayjs().diff(dayjs(lastRefresh), 'hours') > 12- ? 'text-danger'- : dayjs().diff(dayjs(lastRefresh), 'hours') > 6- ? 'text-warning'- : ''- : ''- }`}- >- {isRefreshing ? 'Loading…' : lastRefresh ? dayjs(lastRefresh).fromNow() : 'a while ago'}- </span>- <LemonButton- type="secondary"- size="xsmall"- onClick={onClick}- data-attr="refresh-experiment"- icon={<IconRefresh />}- tooltip="Refresh experiment results"- />- </div>- </div>- )-}+import { LegacyExperimentDates } from './LegacyExperimentDates'-/**- * @deprecated use the new Info component instead- */export function LegacyExperimentInfo(): JSX.Element | null {- const {- experiment,- legacyPrimaryMetricsResults,- legacySecondaryMetricsResults,- primaryMetricsResultsLoading,- secondaryMetricsResultsLoading,- } = useValues(legacyExperimentLogic)- const { refreshExperimentResults } = useActions(legacyExperimentLogic)+ const { experiment } = useValues(experimentLogic)const { created_by } = experiment@@ -87,11 +32,6 @@ export function LegacyExperimentInfo(): JSX.Element | null {return null}- // Get the last refresh timestamp from either legacy or new results format- // Check both primary and secondary metrics for the most recent timestamp- const lastRefresh =- legacyPrimaryMetricsResults?.[0]?.last_refresh || legacySecondaryMetricsResults?.[0]?.last_refresh-const status = getExperimentStatus(experiment)const isPaused = isExperimentPaused(experiment)@@ -161,13 +101,6 @@ export function LegacyExperimentInfo(): JSX.Element | null {<div className="flex flex-col"><div className="inline-flex deprecated-space-x-8">- {status !== ExperimentStatus.Draft && (- <LegacyExperimentLastRefresh- isRefreshing={primaryMetricsResultsLoading || secondaryMetricsResultsLoading}- lastRefresh={lastRefresh}- onClick={() => refreshExperimentResults(true, 'manual')}- />- )}<LegacyExperimentDates /><div className="flex flex-col"><Label intent="menu">Created by</Label>diff --git a/products/experiments/frontend/legacy/LegacyExperimentView.tsx b/products/experiments/frontend/legacy/LegacyExperimentView.tsxindex aac7897106a1..eae2eb9514cd 100644--- a/products/experiments/frontend/legacy/LegacyExperimentView.tsx+++ b/products/experiments/frontend/legacy/LegacyExperimentView.tsx@@ -1,10 +1,8 @@-import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'-import { useEffect } from 'react'+import { useActions, useValues } from 'kea'-import { IconSparkles } from '@posthog/icons'import { LemonBanner, LemonTab, LemonTabs } from '@posthog/lemon-ui'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'import { PendingChangeRequestBanner } from 'scenes/approvals/PendingChangeRequestBanner'import { experimentLogic } from 'scenes/experiments/experimentLogic'import {@@ -21,108 +19,12 @@ import {ReleaseConditionsTable,} from 'scenes/experiments/ExperimentView/ReleaseConditionsTable'-import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'-import {- ExperimentFunnelsQuery,- ExperimentTrendsQuery,- ExperimentTrendsQueryResponse,- ExperimentFunnelsQueryResponse,-} from '~/queries/schema/schema-general'-import { Experiment, SidePanelTab } from '~/types'--import {- LegacyExperimentHeader,- LegacyExperimentInfo,- LegacyMetricsView,- legacyExperimentLogic,- LegacyOverview,- LegacySummaryTable,- LegacyResultsQuery,- LegacyExploreButton,-} from 'products/experiments/frontend/legacy'--const getFirstPrimaryMetric = (experiment: Experiment): ExperimentTrendsQuery | ExperimentFunnelsQuery | null => {- if (experiment.metrics.length) {- return experiment.metrics[0] as ExperimentTrendsQuery | ExperimentFunnelsQuery- }- const primaryMetric = experiment.saved_metrics.find((metric) => metric.metadata.type === 'primary')- if (primaryMetric) {- return primaryMetric.query as ExperimentTrendsQuery | ExperimentFunnelsQuery- }- return null-}-/**- * Metrics tab for legacy experiments- * Shows primary and secondary metrics in read-only mode- */-const LegacyMetricsTab = (): JSX.Element => {- const { experiment, legacyPrimaryMetricsResults } = useValues(legacyExperimentLogic)-- const firstPrimaryMetric = getFirstPrimaryMetric(experiment)-- const hasSomeResults = legacyPrimaryMetricsResults?.some((result) => result?.insight)- const primaryMetricsLengthWithSharedMetrics =- experiment.metrics.length +- experiment.saved_metrics.filter((metric) => metric.metadata.type === 'primary').length- const hasSinglePrimaryMetric = primaryMetricsLengthWithSharedMetrics === 1- const firstPrimaryMetricResult = legacyPrimaryMetricsResults?.[0]+import { AccessControlLevel, AccessControlResourceType } from '~/types'- /**- * Show a detailed results if:- * - there's a single primary metric- * - if the metric has insight results- * - if we have the minimum number of exposures- * - if it's the first primary metric (?)- *- * this is only for legacy experiments.- */- const showResultDetails = hasSomeResults && hasSinglePrimaryMetric && firstPrimaryMetric && firstPrimaryMetricResult+import { LegacyExperimentInfo } from './LegacyExperimentInfo'+import { LegacyMetricsList } from './LegacyMetricsList'- return (- <>- {hasSinglePrimaryMetric && (- <div className="mb-4 mt-2">- <LegacyOverview metricUuid={firstPrimaryMetric?.uuid || ''} />- </div>- )}- <LegacyMetricsView isSecondary={false} />- {showResultDetails && (- <>- <div className="pb-4">- <LegacySummaryTable metric={firstPrimaryMetric} displayOrder={0} isSecondary={false} />- </div>- <div className="flex justify-end">- <LegacyExploreButton- result={- firstPrimaryMetricResult as- | ExperimentTrendsQueryResponse- | ExperimentFunnelsQueryResponse- }- size="xsmall"- />- </div>- <div className="pb-4">- <LegacyResultsQuery- result={- firstPrimaryMetricResult as- | ExperimentTrendsQueryResponse- | ExperimentFunnelsQueryResponse- | null- }- showTable={true}- />- </div>- </>- )}- <LegacyMetricsView isSecondary={true} />- </>- )-}--/**- * Variants tab showing release conditions and distribution- */const VariantsTab = (): JSX.Element => {return (<div className="deprecated-space-y-8 mt-2">@@ -133,141 +35,72 @@ const VariantsTab = (): JSX.Element => {}/**- * Legacy experiment view component- *- * This component handles experiments that use the legacy query format- * (ExperimentTrendsQuery/ExperimentFunnelsQuery). These experiments are- * frozen and cannot be edited - they can only be viewed.- *- * Key differences from modern experiments:- * - No Settings tab- * - No AI Analysis tab- * - No Code tab- * - No History tab- * - No User Feedback tab- * - No metric editing (read-only metrics)- * - No exposure criteria editing- * - Uses legacy metrics view and calculations- *- * Only includes the minimal set of tabs needed to view legacy experiment results:- * - Metrics (primary and secondary, read-only)- * - Variants (distribution and release conditions)- *- * @deprecated This component exists only to support existing legacy experiments.- * New experiments use the modern ExperimentView component.+ * Read-only page for experiments whose metrics use the retired ExperimentTrendsQuery/ExperimentFunnelsQuery+ * format. Results are no longer calculated for them, so it lists the metrics and points to the migration.*/export function LegacyExperimentView(): JSX.Element {- const { experimentLoading, experiment } = useValues(experimentLogic)+ const { experimentLoading, experiment, migrateLegacyExperimentLoading } = useValues(experimentLogic)+ const { migrateLegacyExperiment } = useActions(experimentLogic)const { activeTabKey } = useValues(experimentSceneLogic)const { setActiveTabKey } = useActions(experimentSceneLogic)- const showDeprecationNotice = useFeatureFlag('EXPERIMENTS_LEGACY_DEPRECATION_NOTICE')- const { openSidePanel } = useActions(sidePanelStateLogic)-- // Props for legacy logic - uses experiment data from parent experimentLogic- const legacyLogicProps = {- experiment,- }-- // Mount the logic and load metrics when experiment is available- const logic = legacyExperimentLogic(legacyLogicProps)- useMountedLogic(logic)- const { refreshExperimentResults } = useActions(logic)-- // Load metrics on mount - afterMount doesn't fire reliably on reconnections- useEffect(() => {- if (!experimentLoading && experiment) {- refreshExperimentResults(false, 'page_load')- }- }, [experimentLoading, experiment?.id, experiment, refreshExperimentResults])const tabs: LemonTab<ExperimentTab>[] = [- {- key: 'metrics',- label: 'Metrics',- content: <LegacyMetricsTab />,- },- {- key: 'variants',- label: 'Variants',- content: <VariantsTab />,- },+ { key: 'metrics', label: 'Metrics', content: <LegacyMetricsList /> },+ { key: 'variants', label: 'Variants', content: <VariantsTab /> },]return (- <BindLogic logic={legacyExperimentLogic} props={legacyLogicProps}>- <SceneContent>- <PageHeaderCustom />- {experimentLoading ? (- <LoadingState />- ) : (- <>- <ExperimentWarningBanner />-- {showDeprecationNotice && (- <LemonBanner- type="error"- className="mb-4"- action={{- children: 'Migrate with PostHog AI',- icon: <IconSparkles />,- // The "!" prefix submits the prompt without review, so keep user-editable text like the name out of it- onClick: () =>- openSidePanel(- SidePanelTab.Max,- `!Migrate experiment ${experiment.id} to the new experiment engine`- ),- 'data-attr': 'legacy-experiment-migrate-with-ai',- }}- >- Results for legacy experiments will no longer be available after October 15, 2026.- Migrate this experiment to the new engine to keep them.- </LemonBanner>- )}-- {/* Warning banner indicating this is a legacy experiment */}- <LemonBanner type="warning" className="mb-4">- This is a legacy experiment. Metrics can no longer be edited.- </LemonBanner>-- {/* Show pending change request banner if there's one for the feature flag */}- {experiment.feature_flag?.id && (- <PendingChangeRequestBanner- resourceType="feature_flag"- resourceId={experiment.feature_flag.id}- context="experiment"- />- )}-- {/* Legacy experiment info and header */}- <LegacyExperimentInfo />- <LegacyExperimentHeader />-- {/* Tab navigation - only includes minimal tabs for legacy experiments */}- <LemonTabs- // Fall back to the default tab if the active one isn't rendered here- activeKey={- tabs.some((tab) => tab.key === activeTabKey) ? activeTabKey : DEFAULT_EXPERIMENT_TAB- }- onChange={(key) => setActiveTabKey(key)}- sceneInset- tabs={tabs}+ <SceneContent>+ <PageHeaderCustom />+ {experimentLoading ? (+ <LoadingState />+ ) : (+ <>+ <ExperimentWarningBanner />++ <LemonBanner+ type="warning"+ className="mb-4"+ action={{+ children: 'Migrate experiment',+ onClick: () => migrateLegacyExperiment(),+ loading: migrateLegacyExperimentLoading,+ disabledReason: getAccessControlDisabledReason(+ AccessControlResourceType.Experiment,+ AccessControlLevel.Editor,+ experiment.user_access_level+ ),+ // pinned: click analytics for this button key on this data-attr, so renaming it breaks them+ 'data-attr': 'legacy-experiment-migrate-with-ai',+ }}+ >+ Results for legacy experiments are no longer available. To see results, migrate this experiment+ to the new experiment engine. This creates a copy that uses the same feature flag, so users keep+ their variant.+ </LemonBanner>++ {experiment.feature_flag?.id && (+ <PendingChangeRequestBanner+ resourceType="feature_flag"+ resourceId={experiment.feature_flag.id}+ context="experiment"/>+ )}++ <LegacyExperimentInfo />- {/* Modals that legacy experiments support */}- <DistributionModal />- <ReleaseConditionsModal />+ <LemonTabs+ // Fall back to the default tab if the active one isn't rendered here+ activeKey={tabs.some((tab) => tab.key === activeTabKey) ? activeTabKey : DEFAULT_EXPERIMENT_TAB}+ onChange={(key) => setActiveTabKey(key)}+ sceneInset+ tabs={tabs}+ />- {/* Legacy experiments do NOT support these modals:- - MetricSourceModal (can't add metrics)- - ExperimentMetricModal (can't edit metrics)- - SharedMetricModal (can't add shared metrics)- - SharedMetricDetailsModal (can't manage shared metrics)- - ExposureCriteriaModal (can't edit exposure)- - EditConclusionModal (uses legacy version instead)- */}- </>- )}- </SceneContent>- </BindLogic>+ <DistributionModal />+ <ReleaseConditionsModal />+ </>+ )}+ </SceneContent>)}diff --git a/products/experiments/frontend/legacy/LegacyMetricsList.tsx b/products/experiments/frontend/legacy/LegacyMetricsList.tsxnew file mode 100644index 000000000000..7e8431541946--- /dev/null+++ b/products/experiments/frontend/legacy/LegacyMetricsList.tsx@@ -0,0 +1,101 @@+import { useValues } from 'kea'++import { LemonTable, LemonTag } from '@posthog/lemon-ui'++import { experimentLogic } from 'scenes/experiments/experimentLogic'+import { MetricTypeTag } from 'scenes/experiments/MetricsView/shared/MetricTypeTag'+import { getDefaultMetricTitle } from 'scenes/experiments/MetricsView/shared/utils'++import {+ ExperimentFunnelsQuery,+ ExperimentMetric,+ ExperimentTrendsQuery,+ NodeKind,+} from '~/queries/schema/schema-general'+import { Experiment } from '~/types'++type ListedMetric = ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery++interface MetricRow {+ key: string+ metric: ListedMetric+ isShared: boolean+}++const getSeriesLabel = (node?: { custom_name?: string; name?: string; event?: string | null }): string | undefined =>+ node?.custom_name || node?.name || node?.event || undefined++const getMetricName = (metric: ListedMetric): string => {+ if (metric.name) {+ return metric.name+ }+ if (metric.kind === NodeKind.ExperimentFunnelsQuery) {+ const series = metric.funnels_query?.series ?? []+ const firstStep = getSeriesLabel(series[0])+ const lastStep = getSeriesLabel(series[series.length - 1])+ if (series.length > 1 && firstStep && lastStep) {+ return `${firstStep} → ${lastStep}`+ }+ return firstStep || 'Untitled metric'+ }+ if (metric.kind === NodeKind.ExperimentTrendsQuery) {+ return getSeriesLabel(metric.count_query?.series?.[0]) || 'Untitled metric'+ }+ return getDefaultMetricTitle(metric)+}++const getMetricRows = (experiment: Experiment, type: 'primary' | 'secondary'): MetricRow[] => {+ const inlineMetrics = type === 'primary' ? experiment.metrics : experiment.metrics_secondary+ return [+ ...inlineMetrics.map((metric, index) => ({ key: metric.uuid || `inline-${index}`, metric, isShared: false })),+ ...experiment.saved_metrics+ .filter((savedMetric) => savedMetric.metadata.type === type)+ .map((savedMetric) => ({+ key: `shared-${savedMetric.saved_metric}`,+ metric: { ...savedMetric.query, name: savedMetric.name } as ListedMetric,+ isShared: true,+ })),+ ]+}++const MetricsSection = ({ title, rows }: { title: string; rows: MetricRow[] }): JSX.Element => (+ <div className="flex flex-col gap-2">+ <h2 className="font-semibold text-lg mb-0">{title}</h2>+ <LemonTable+ dataSource={rows}+ rowKey="key"+ emptyState={`No ${title.toLowerCase()}`}+ columns={[+ {+ title: 'Metric',+ render: (_, { metric, isShared }) => (+ <div className="flex flex-wrap items-center gap-2">+ <span className="break-words">{getMetricName(metric)}</span>+ {isShared && (+ <LemonTag type="option" size="small">+ Shared+ </LemonTag>+ )}+ </div>+ ),+ },+ {+ title: 'Type',+ width: 0,+ render: (_, { metric }) => <MetricTypeTag metric={metric} />,+ },+ ]}+ />+ </div>+)++export function LegacyMetricsList(): JSX.Element {+ const { experiment } = useValues(experimentLogic)++ return (+ <div className="flex flex-col gap-6 mt-2">+ <MetricsSection title="Primary metrics" rows={getMetricRows(experiment, 'primary')} />+ <MetricsSection title="Secondary metrics" rows={getMetricRows(experiment, 'secondary')} />+ </div>+ )+}diff --git a/products/experiments/frontend/legacy/calculations/legacyExperimentCalculations.tsx b/products/experiments/frontend/legacy/calculations/legacyExperimentCalculations.tsxdeleted file mode 100644index cf0946b42620..000000000000--- a/products/experiments/frontend/legacy/calculations/legacyExperimentCalculations.tsx+++ /dev/null@@ -1,449 +0,0 @@-import { EXPERIMENT_DEFAULT_DURATION } from 'lib/constants'--import {- CachedExperimentFunnelsQueryResponse,- CachedExperimentTrendsQueryResponse,- CachedLegacyExperimentQueryResponse,- ExperimentSignificanceCode,- NodeKind,- isExperimentFunnelMetric,-} from '~/queries/schema/schema-general'-import {- CountPerActorMathType,- FunnelExperimentVariant,- FunnelStep,- InsightType,- PropertyMathType,- TrendExperimentVariant,- TrendResult,-} from '~/types'--/**- * @deprecated- * Legacy experiment calculations for ExperimentTrendsQuery/ExperimentFunnelsQuery.- * Frozen copy for legacy experiments - do not modify.- */--// Type definitions-export type LegacyExperimentMetricResult =- | CachedLegacyExperimentQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedExperimentFunnelsQueryResponse- | null--export type ExperimentVariant = FunnelExperimentVariant | TrendExperimentVariant--export interface DeltaResult {- delta: number- deltaPercent: number- isPositive: boolean-}--export interface VariantCalculationResult {- conversionRate: number | null- count: number | null- exposure: number | null- mean: number | null- credibleInterval: [number, number] | null- delta: DeltaResult | null-}--/**- * @deprecated- * Calculate conversion rate for a specific variant in experiment results- */-export function legacyConversionRateForVariant(- metricResult: LegacyExperimentMetricResult,- variantKey: string-): number | null {- if (!metricResult) {- return null- }-- if (metricResult.kind === NodeKind.ExperimentQuery && isExperimentFunnelMetric(metricResult.metric)) {- const variants = metricResult.variants as FunnelExperimentVariant[]- const variantResults = variants.find((variant) => variant.key === variantKey)-- if (!variantResults) {- return null- }- return (variantResults.success_count / (variantResults.success_count + variantResults.failure_count)) * 100- } else if (metricResult.kind === NodeKind.ExperimentFunnelsQuery && metricResult.insight) {- const variantResults = (metricResult.insight as FunnelStep[][]).find((variantFunnel: FunnelStep[]) => {- const breakdownValue = variantFunnel[0]?.breakdown_value- return Array.isArray(breakdownValue) && breakdownValue[0] === variantKey- })-- if (!variantResults) {- return null- }-- return (variantResults[variantResults.length - 1].count / variantResults[0].count) * 100- }-- return null-}--/**- * @deprecated- * Get exposure count data for a specific variant- */-export function legacyExposureCountDataForVariant(- metricResult: LegacyExperimentMetricResult,- variant: string-): number | null {- if (!metricResult || !metricResult.variants) {- return null- }-- if ('kind' in metricResult && metricResult.kind === NodeKind.ExperimentQuery) {- const variantResults = (metricResult.variants as Array<{ key: string; exposure?: number }>).find(- (variantData) => variantData.key === variant- )- return variantResults?.exposure ?? null- }-- const variantResults = (metricResult.variants as TrendExperimentVariant[]).find(- (variantTrend: TrendExperimentVariant) => variantTrend.key === variant- )- if (!variantResults || !variantResults.absolute_exposure) {- return null- }-- return variantResults.absolute_exposure-}--/**- * @deprecated- * Get count data for a specific variant with optional math aggregation- */-export function legacyCountDataForVariant(- metricResult: LegacyExperimentMetricResult,- variant: string,- type: 'primary' | 'secondary' = 'primary',- experimentMathAggregation?: PropertyMathType | CountPerActorMathType-): number | null {- if (!metricResult) {- return null- }-- if ('kind' in metricResult && metricResult.kind === NodeKind.ExperimentQuery) {- const variantResults = (metricResult.variants as Array<{ key: string } & Record<string, any>>).find(- (variantData) => variantData.key === variant- )- // NOTE: Unfortunately, there does not seem to be a better way at the moment to figure out which type it is.- // Something we can improve later when we replace the ExperimentVariantTrendsBaseStats with a new type / interface.- if (variantResults && 'success_count' in variantResults) {- return variantResults.success_count + variantResults.failure_count- } else if (variantResults && 'count' in variantResults) {- return variantResults.count- }- return null- }-- const usingMathAggregationType = type === 'primary' ? experimentMathAggregation : false- if (!metricResult.insight) {- return null- }- const variantResults = (metricResult.insight as TrendResult[]).find(- (variantTrend: TrendResult) => variantTrend.breakdown_value === variant- )- if (!variantResults) {- return null- }-- let result = variantResults.count-- if (usingMathAggregationType) {- // TODO: Aggregate end result appropriately for nth percentile- if (- [- CountPerActorMathType.Average,- CountPerActorMathType.Median,- PropertyMathType.Average,- PropertyMathType.Median,- ].includes(usingMathAggregationType)- ) {- result = variantResults.count / variantResults.data.length- } else if ([CountPerActorMathType.Maximum, PropertyMathType.Maximum].includes(usingMathAggregationType)) {- result = Math.max(...variantResults.data)- } else if ([CountPerActorMathType.Minimum, PropertyMathType.Minimum].includes(usingMathAggregationType)) {- result = Math.min(...variantResults.data)- }- }-- return result-}--/**- * @deprecated- * Calculate credible interval for a variant as percentage difference from control- */-export function legacyCredibleIntervalForVariant(- metricResult: LegacyExperimentMetricResult,- variantKey: string,- metricType: InsightType-): [number, number] | null {- const credibleInterval = metricResult?.credible_intervals?.[variantKey]- if (!credibleInterval) {- return null- }-- if (metricType === InsightType.FUNNELS) {- const controlVariant = (metricResult.variants as FunnelExperimentVariant[]).find(- ({ key }) => key === 'control'- ) as FunnelExperimentVariant- const controlConversionRate =- controlVariant.success_count / (controlVariant.success_count + controlVariant.failure_count)-- if (!controlConversionRate) {- return null- }-- // Calculate the percentage difference between the credible interval bounds of the variant and the control's conversion rate.- // This represents the range in which the true percentage change relative to the control is likely to fall.- const lowerBound = ((credibleInterval[0] - controlConversionRate) / controlConversionRate) * 100- const upperBound = ((credibleInterval[1] - controlConversionRate) / controlConversionRate) * 100- return [lowerBound, upperBound]- }-- const controlVariant = (metricResult.variants as TrendExperimentVariant[]).find(- ({ key }) => key === 'control'- ) as TrendExperimentVariant-- const controlMean = controlVariant.count / controlVariant.absolute_exposure- if (!controlMean) {- return null- }-- // Calculate the percentage difference between the credible interval bounds of the variant and the control's mean.- // This represents the range in which the true percentage change relative to the control is likely to fall.- const relativeLowerBound = ((credibleInterval[0] - controlMean) / controlMean) * 100- const relativeUpperBound = ((credibleInterval[1] - controlMean) / controlMean) * 100- return [relativeLowerBound, relativeUpperBound]-}--/**- * @deprecated- * Get the index for a variant in experiment results (for UI display order)- */-export function legacyGetIndexForVariant(- metricResult: LegacyExperimentMetricResult,- variant: string,- metricType: InsightType-): number | null {- // Ensures we get the right index from results, so the UI can- // display the right colour for the variant- if (!metricResult || !metricResult.insight) {- return null- }-- let index = -1- if (metricType === InsightType.FUNNELS) {- // Funnel Insight is displayed in order of decreasing count- index = (Array.isArray(metricResult.insight) ? [...metricResult.insight] : [])- .sort((a, b) => {- const aCount = (a && Array.isArray(a) && a[0]?.count) || 0- const bCount = (b && Array.isArray(b) && b[0]?.count) || 0- return bCount - aCount- })- .findIndex((variantFunnel) => {- if (!Array.isArray(variantFunnel) || !variantFunnel[0]?.breakdown_value) {- return false- }- const breakdownValue = variantFunnel[0].breakdown_value- return Array.isArray(breakdownValue) && breakdownValue[0] === variant- })- } else {- index = (metricResult.insight as TrendResult[]).findIndex(- (variantTrend: TrendResult) => variantTrend.breakdown_value === variant- )- }- const result = index === -1 ? null : index-- if (result !== null && metricType === InsightType.FUNNELS) {- return result + 1- }- return result-}--/**- * @deprecated- * Get the variant with the highest win probability- */-export function legacyGetHighestProbabilityVariant(results: LegacyExperimentMetricResult): string | undefined {- if (results && results.probability) {- const maxValue = Math.max(...Object.values(results.probability))- return Object.keys(results.probability).find(- (key) => Math.abs(results.probability[key] - maxValue) < Number.EPSILON- )- }-}--/**- * @deprecated- * Calculate minimum sample size per variant for a given conversion rate and MDE- */-export function legacyMinimumSampleSizePerVariant(mde: number, conversionRate: number): number {- // Using the rule of thumb: sampleSize = 16 * sigma^2 / (mde^2)- // refer https://en.wikipedia.org/wiki/Sample_size_determination with default beta and alpha- // The results are same as: https://www.evanmiller.org/ab-testing/sample-size.html- // and also: https://marketing.dynamicyield.com/ab-test-duration-calculator/- if (!mde) {- return 0- }-- return Math.ceil((1600 * conversionRate * (1 - conversionRate / 100)) / (mde * mde))-}--/**- * @deprecated- * Calculate recommended exposure for count data based on MDE- */-export function legacyRecommendedExposureForCountData(mde: number, baseCountData: number): number {- // http://www.columbia.edu/~cjd11/charles_dimaggio/DIRE/styled-4/code-12/- if (!mde) {- return 0- }-- const minCountData = (baseCountData * mde) / 100- const lambda1 = baseCountData- const lambda2 = minCountData + baseCountData-- // This is exposure in units of days- return parseFloat(- (- 4 /- Math.pow(- Math.sqrt(lambda1 / EXPERIMENT_DEFAULT_DURATION) - Math.sqrt(lambda2 / EXPERIMENT_DEFAULT_DURATION),- 2- )- ).toFixed(1)- )-}--/**- * @deprecated- * Calculate expected running time for an experiment- */-export function legacyExpectedRunningTime(- entrants: number,- sampleSize: number,- duration: number = EXPERIMENT_DEFAULT_DURATION-): number {- // recommended people / (actual people / day) = expected days- return parseFloat((sampleSize / (entrants / duration)).toFixed(1))-}--/**- * @deprecated- * Calculate delta (percentage change) between a variant and control- */-export function legacyCalculateDelta(- metricResult: LegacyExperimentMetricResult,- variantKey: string,- metricType: InsightType-): DeltaResult | null {- if (!metricResult || variantKey === 'control') {- return null- }-- let delta = 0-- if (metricType === InsightType.TRENDS) {- const controlVariant = (metricResult.variants as any[]).find((v: any) => v.key === 'control')- const variantData = (metricResult.variants as any[]).find((v: any) => v.key === variantKey)-- if (- !variantData?.count ||- !variantData?.absolute_exposure ||- !controlVariant?.count ||- !controlVariant?.absolute_exposure- ) {- return null- }-- const controlMean = controlVariant.count / controlVariant.absolute_exposure- const variantMean = variantData.count / variantData.absolute_exposure- delta = (variantMean - controlMean) / controlMean- } else {- const variantRate = legacyConversionRateForVariant(metricResult, variantKey)- const controlRate = legacyConversionRateForVariant(metricResult, 'control')-- if (!variantRate || !controlRate) {- return null- }-- delta = (variantRate - controlRate) / controlRate- }-- return {- delta,- deltaPercent: delta * 100,- isPositive: delta > 0,- }-}--/**- * @deprecated- * Get comprehensive calculation result for a variant- */-export function legacyGetVariantCalculationResult(- metricResult: LegacyExperimentMetricResult,- variantKey: string,- metricType: InsightType,- experimentMathAggregation?: PropertyMathType | CountPerActorMathType-): VariantCalculationResult {- const conversionRate = legacyConversionRateForVariant(metricResult, variantKey)- const count = legacyCountDataForVariant(metricResult, variantKey, 'primary', experimentMathAggregation)- const exposure = legacyExposureCountDataForVariant(metricResult, variantKey)- const credibleInterval = legacyCredibleIntervalForVariant(metricResult, variantKey, metricType)- const delta = legacyCalculateDelta(metricResult, variantKey, metricType)-- // Calculate mean for trends- let mean: number | null = null- if (metricType === InsightType.TRENDS && count !== null && exposure !== null && exposure > 0) {- mean = count / exposure- }-- return {- conversionRate,- count,- exposure,- mean,- credibleInterval,- delta,- }-}--/**- * @deprecated- * Generate significance details text based on experiment results- */-export function legacyGetSignificanceDetails(metricResult: LegacyExperimentMetricResult): string {- if (!metricResult) {- return ''- }-- if (metricResult.significance_code === ExperimentSignificanceCode.HighLoss) {- return `This is because the expected loss in conversion is greater than 1% (current value is ${(- (metricResult as CachedExperimentFunnelsQueryResponse)?.expected_loss || 0- )?.toFixed(2)}%).`- }-- if (metricResult.significance_code === ExperimentSignificanceCode.HighPValue) {- return `This is because the p value is greater than 0.05 (current value is ${- (metricResult as CachedExperimentTrendsQueryResponse)?.p_value?.toFixed(3) || 1- }).`- }-- if (metricResult.significance_code === ExperimentSignificanceCode.LowWinProbability) {- return 'This is because no variant (control or test) has a win probability higher than 90%.'- }-- if (metricResult.significance_code === ExperimentSignificanceCode.NotEnoughExposure) {- return 'This is because we need at least 100 people per variant to declare significance.'- }-- return ''-}diff --git a/products/experiments/frontend/legacy/components/LegacyDataCollection.tsx b/products/experiments/frontend/legacy/components/LegacyDataCollection.tsxdeleted file mode 100644index c55151f2b430..000000000000--- a/products/experiments/frontend/legacy/components/LegacyDataCollection.tsx+++ /dev/null@@ -1,246 +0,0 @@-import { useValues } from 'kea'--import { IconInfo } from '@posthog/icons'-import { LemonDivider, Tooltip } from '@posthog/lemon-ui'--import { dayjs } from 'lib/dayjs'-import { LemonProgress } from 'lib/lemon-ui/LemonProgress'-import { humanFriendlyNumber } from 'lib/utils/numbers'--import {- ExperimentTrendsQuery,- ExperimentFunnelsQuery,- CachedExperimentTrendsQueryResponse,- CachedExperimentFunnelsQueryResponse,- CachedLegacyExperimentQueryResponse,-} from '~/queries/schema/schema-general'-import { formatUnitByQuantity } from '~/scenes/experiments/utils'-import { Experiment, InsightType } from '~/types'--import { DEFAULT_MDE } from 'products/experiments/frontend/constants'-import { legacyExperimentLogic, getInsightType } from 'products/experiments/frontend/legacy'--const getFirstPrimaryMetric = (experiment: Experiment): ExperimentTrendsQuery | ExperimentFunnelsQuery | null => {- if (experiment.metrics.length) {- return experiment.metrics[0] as ExperimentTrendsQuery | ExperimentFunnelsQuery- }- const primaryMetric = experiment.saved_metrics.find((metric) => metric.metadata.type === 'primary')- if (primaryMetric) {- return primaryMetric.query as ExperimentTrendsQuery | ExperimentFunnelsQuery- }- return null-}--const getActualRunningTime = (experiment: Experiment): number => {- if (!experiment.start_date) {- return 0- }-- if (experiment.end_date) {- return dayjs(experiment.end_date).diff(experiment.start_date, 'day')- }-- return dayjs().diff(experiment.start_date, 'day')-}--const getFunnelResultsPersonsTotal =- (- experiment: Experiment,- legacyPrimaryMetricsResults: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | null- )[],- getInsightType: (metric: ExperimentTrendsQuery | ExperimentFunnelsQuery) => InsightType- ) =>- (metricIdentifier: number | string = 0): number => {- let index: number- if (typeof metricIdentifier === 'string') {- // Find index by UUID- index = experiment.metrics.findIndex((m) => m.uuid === metricIdentifier)- if (index === -1) {- return 0- }- } else {- index = metricIdentifier- }-- const result = legacyPrimaryMetricsResults?.[index]-- if (- getInsightType(experiment.metrics[index] as ExperimentTrendsQuery | ExperimentFunnelsQuery) !==- InsightType.FUNNELS ||- !result- ) {- return 0- }-- let sum = 0- result.insight.forEach((variantResult) => {- if (variantResult[0]?.count) {- sum += variantResult[0].count- }- })- return sum- }--/**- * @deprecated- * Legacy goal tooltip for ExperimentView.- * Frozen copy for legacy experiments - do not modify.- */-function LegacyGoalTooltip({- experiment,- hasHighRunningTime,-}: {- experiment: Experiment | null- hasHighRunningTime: boolean-}): JSX.Element {- if (!experiment?.running_time_calculation?.minimum_detectable_effect) {- return <></>- }-- return (- <Tooltip- title={- <div>- <div>{`Based on the Minimum detectable effect of ${experiment.running_time_calculation.minimum_detectable_effect}%.`}</div>- {hasHighRunningTime && (- <div className="mt-2">- Given the current data, this experiment might take a while to reach statistical- significance. Please make sure events are being tracked correctly and consider if this- timeline works for you.- </div>- )}- </div>- }- >- <IconInfo className="text-secondary text-base" />- </Tooltip>- )-}--/**- * @deprecated- * Legacy data collection component for ExperimentView.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyDataCollection(): JSX.Element {- const { experiment, legacyPrimaryMetricsResults } = useValues(legacyExperimentLogic)-- /**- * these variables were computed in the experimentLogic.- * the legacy experiment logic does not have these computed values.- */- const firstPrimaryMetric = getFirstPrimaryMetric(experiment)- const insightType = firstPrimaryMetric ? getInsightType(firstPrimaryMetric) : InsightType.FUNNELS- const actualRunningTime = getActualRunningTime(experiment)- const minimumDetectableEffect = experiment?.running_time_calculation?.minimum_detectable_effect || DEFAULT_MDE- const funnelResultsPersonsTotal = getFunnelResultsPersonsTotal(- experiment,- legacyPrimaryMetricsResults,- getInsightType- )-- const recommendedRunningTime = experiment?.running_time_calculation?.recommended_running_time || 1- const recommendedSampleSize = experiment?.running_time_calculation?.recommended_sample_size || 100-- const experimentProgressPercent =- insightType === InsightType.FUNNELS- ? (funnelResultsPersonsTotal(0) / recommendedSampleSize) * 100- : (actualRunningTime / recommendedRunningTime) * 100-- const hasHighRunningTime = recommendedRunningTime > 62-- return (- <div>- <div className="inline-flex items-center deprecated-space-x-2">- <h2 className="font-semibold text-lg mb-0">Data collection</h2>- <Tooltip- title="Estimated target for the number of participants. Actual data may reveal significance earlier or later- than predicted."- >- <IconInfo className="text-secondary text-base" />- </Tooltip>- </div>- <div className="flex">- <div className="w-3/5 pr-4">- <div className="mt-2 mb-1 font-semibold">{`${- experimentProgressPercent > 100 ? 100 : experimentProgressPercent.toFixed(2)- }% complete`}</div>- <LemonProgress- className="w-full border"- bgColor="var(--color-bg-table)"- size="medium"- percent={experimentProgressPercent}- />- {insightType === InsightType.TRENDS && (- <div className="flex justify-between mt-0">- <span className="flex items-center text-xs">- Completed - <b>{actualRunningTime} of</b>- {hasHighRunningTime ? (- <b> > 60 days</b>- ) : (- <span>- - <b>{recommendedRunningTime}</b>{' '}- {formatUnitByQuantity(recommendedRunningTime, 'day')}- </span>- )}- <span className="ml-1 text-xs">- <LegacyGoalTooltip- experiment={experiment}- hasHighRunningTime={hasHighRunningTime}- />- </span>- </span>- </div>- )}- {insightType === InsightType.FUNNELS && (- <div className="flex justify-between mt-0">- <div className="deprecated-space-x-1 flex items-center text-xs">- <span>- Saw - <b>- {humanFriendlyNumber(funnelResultsPersonsTotal(0))} of{' '}- {humanFriendlyNumber(recommendedSampleSize)}{' '}- </b>{' '}- {formatUnitByQuantity(recommendedSampleSize, 'participant')}- </span>- <LegacyGoalTooltip experiment={experiment} hasHighRunningTime={hasHighRunningTime} />- </div>- </div>- )}- </div>- <LemonDivider className="my-0" vertical />- <div className="w-2/5 pl-4">- <div className={`text-lg font-semibold ${experiment.end_date ? 'mt-4' : ''}`}>- {minimumDetectableEffect}%- </div>- <div className="deprecated-space-x-1 text-sm flex">- <span>Minimum detectable effect</span>- <Tooltip- docLink="https://posthog.com/docs/experiments/sample-size-running-time#minimum-detectable-effect-mde"- title={- <div className="deprecated-space-y-2">- <div>- The Minimum detectable effect represents the smallest change that you want to be- able to detect in your experiment.- </div>- <div>- To make things easier, we initially set this value to a reasonable default.- However, we encourage you to review and adjust it based on your specific goals.- </div>- </div>- }- >- <IconInfo className="text-secondary text-base" />- </Tooltip>- </div>- </div>- </div>- </div>- )-}diff --git a/products/experiments/frontend/legacy/components/LegacyExperimentHeader.tsx b/products/experiments/frontend/legacy/components/LegacyExperimentHeader.tsxdeleted file mode 100644index ee0e2a5a030e..000000000000--- a/products/experiments/frontend/legacy/components/LegacyExperimentHeader.tsx+++ /dev/null@@ -1,16 +0,0 @@-import { LegacyDataCollection } from './LegacyDataCollection'--/**- * @deprecated- * Legacy experiment header for ExperimentView.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyExperimentHeader(): JSX.Element {- return (- <>- <div className="w-1/2 mt-8 xl:mt-0">- <LegacyDataCollection />- </div>- </>- )-}diff --git a/products/experiments/frontend/legacy/components/LegacyExploreButton.tsx b/products/experiments/frontend/legacy/components/LegacyExploreButton.tsxdeleted file mode 100644index 727f670d500a..000000000000--- a/products/experiments/frontend/legacy/components/LegacyExploreButton.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { LemonButton } from '@posthog/lemon-ui'--import { IconAreaChart } from 'lib/lemon-ui/icons'-import { urls } from 'scenes/urls'--import type {- ExperimentFunnelsQueryResponse,- ExperimentTrendsQueryResponse,- InsightVizNode,-} from '~/queries/schema/schema-general'-import { NodeKind } from '~/queries/schema/schema-general'-import type { InsightQueryNode } from '~/queries/schema/schema-general'--/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyExploreButton({- result,- size = 'small',-}: {- result: ExperimentTrendsQueryResponse | ExperimentFunnelsQueryResponse | null- size?: 'xsmall' | 'small' | 'large'-}): JSX.Element {- if (!result) {- return <></>- }-- const query: InsightVizNode = {- kind: NodeKind.InsightVizNode,- source: (result.kind === NodeKind.ExperimentTrendsQuery- ? result.count_query- : result.funnels_query) as InsightQueryNode,- }-- return (- <LemonButton- className="ml-auto -translate-y-2"- size={size}- type="primary"- icon={<IconAreaChart />}- to={urls.insightNew({ query })}- targetBlank- >- Explore as Insight- </LemonButton>- )-}diff --git a/products/experiments/frontend/legacy/components/LegacyFunnelAggregationSelect.tsx b/products/experiments/frontend/legacy/components/LegacyFunnelAggregationSelect.tsxdeleted file mode 100644index 4c6e11787309..000000000000--- a/products/experiments/frontend/legacy/components/LegacyFunnelAggregationSelect.tsx+++ /dev/null@@ -1,97 +0,0 @@-import { useValues } from 'kea'--import { LemonSelect, LemonSelectSection } from '@posthog/lemon-ui'--import { HogQLEditor } from 'lib/components/HogQLEditor/HogQLEditor'-import { groupsAccessLogic } from 'lib/introductions/groupsAccessLogic'--import { groupsModel } from '~/models/groupsModel'--import { GroupIntroductionFooter } from 'products/groups/frontend/components/GroupsIntroduction'--/**- * @deprecated- * Legacy funnel aggregation select for ExperimentView.- * Frozen copy for legacy experiments - do not modify.- * Forked from https://github.com/PostHog/posthog/blob/master/products/product_analytics/frontend/insights/shared/AggregationSelect.tsx- */-export function LegacyFunnelAggregationSelect({- value,- onChange,-}: {- value: string- onChange: (value: string) => void-}): JSX.Element {- const { groupTypes, aggregationLabel } = useValues(groupsModel)- const { needsUpgradeForGroups, canStartUsingGroups } = useValues(groupsAccessLogic)-- const UNIQUE_USERS = 'person_id'- const baseValues = [UNIQUE_USERS]- const optionSections: LemonSelectSection<string>[] = [- {- title: 'Event Aggregation',- options: [- {- value: UNIQUE_USERS,- label: 'Unique users',- },- ],- },- ]- if (needsUpgradeForGroups || canStartUsingGroups) {- // if (false) {- optionSections[0].footer = <GroupIntroductionFooter needsUpgrade={needsUpgradeForGroups} />- } else {- Array.from(groupTypes.values()).forEach((groupType) => {- baseValues.push(`$group_${groupType.group_type_index}`)- optionSections[0].options.push({- value: `$group_${groupType.group_type_index}`,- label: `Unique ${aggregationLabel(groupType.group_type_index).plural}`,- })- })- }-- baseValues.push(`properties.$session_id`)- optionSections[0].options.push({- value: 'properties.$session_id',- label: `Unique sessions`,- })- optionSections[0].options.push({- label: 'Custom SQL expression',- options: [- {- // This is a bit of a hack so that the HogQL option is only highlighted as active when the user has- // set a custom value (because actually _all_ the options are HogQL)- value: !value || baseValues.includes(value) ? '' : value,- label: <span className="font-mono">{value}</span>,- labelInMenu: function CustomHogQLOptionWrapped({ onSelect }) {- return (- // eslint-disable-next-line react/forbid-dom-props- <div className="w-120" style={{ maxWidth: 'max(60vw, 20rem)' }}>- <HogQLEditor- onChange={onSelect}- value={value}- placeholder={- "Enter SQL expression, such as:\n- distinct_id\n- properties.$session_id\n- concat(distinct_id, ' ', properties.$session_id)\n- if(1 < 2, 'one', 'two')"- }- />- </div>- )- },- },- ],- })-- return (- <div className="flex items-center w-full gap-2">- <span>Aggregating by</span>- <LemonSelect- className="flex-1"- value={value}- onChange={onChange}- options={optionSections}- dropdownMatchSelectWidth={false}- />- </div>- )-}diff --git a/products/experiments/frontend/legacy/components/LegacyFunnelAttributionSelect.tsx b/products/experiments/frontend/legacy/components/LegacyFunnelAttributionSelect.tsxdeleted file mode 100644index 3d352a261497..000000000000--- a/products/experiments/frontend/legacy/components/LegacyFunnelAttributionSelect.tsx+++ /dev/null@@ -1,88 +0,0 @@-import { IconInfo } from '@posthog/icons'-import { Tooltip } from '@posthog/lemon-ui'-import { LemonSelect } from '@posthog/lemon-ui'--import { BreakdownAttributionType, StepOrderValue } from '~/types'--import { FUNNEL_STEP_COUNT_LIMIT } from 'products/product_analytics/frontend/insights/funnels/editor/FunnelsQuerySteps'--/**- * @deprecated- * Legacy funnel attribution select for ExperimentView.- * Frozen copy for legacy experiments - do not modify.- * Forked from https://github.com/PostHog/posthog/blob/master/products/product_analytics/frontend/insights/funnels/editor/FunnelAttributionFilter.tsx- */-export function LegacyFunnelAttributionSelect({- value,- onChange,- stepsLength,-}: {- value: BreakdownAttributionType | `${BreakdownAttributionType.Step}/${number}`- onChange: (value: BreakdownAttributionType | `${BreakdownAttributionType.Step}/${number}`) => void- stepsLength: number-}): JSX.Element {- const funnelOrderType = undefined-- return (- <div className="flex items-center w-full gap-2">- <div className="flex">- <span>Attribution type</span>- <Tooltip- docLink="https://posthog.com/docs/product-analytics/funnels#attribution-types"- title={- <div className="deprecated-space-y-2">- <div>- When breaking down funnels, it's possible that the same properties don't exist on every- event. For example, if you want to break down by browser on a funnel that contains both- frontend and backend events.- </div>- <div>- In this case, you can choose from which step the properties should be selected from by- modifying the attribution type. There are four modes to choose from:- </div>- <ul className="list-disc pl-4">- <li>First touchpoint: the first property value seen in any of the steps is chosen.</li>- <li>Last touchpoint: the last property value seen from all steps is chosen.</li>- <li>- All steps: the property value must be seen in all steps to be considered in the- funnel.- </li>- <li>Specific step: only the property value seen at the selected step is chosen.</li>- </ul>- </div>- }- >- <IconInfo className="text-xl text-secondary shrink-0 ml-1" />- </Tooltip>- </div>- <LemonSelect- value={value}- placeholder="Attribution"- options={[- { value: BreakdownAttributionType.FirstTouch, label: 'First touchpoint' },- { value: BreakdownAttributionType.LastTouch, label: 'Last touchpoint' },- { value: BreakdownAttributionType.AllSteps, label: 'All steps' },- {- value: BreakdownAttributionType.Step,- label: 'Any step',- hidden: funnelOrderType !== StepOrderValue.UNORDERED,- },- {- label: 'Specific step',- options: Array(FUNNEL_STEP_COUNT_LIMIT)- .fill(null)- .map((_, stepIndex) => ({- value: `${BreakdownAttributionType.Step}/${stepIndex}` as const,- label: `Step ${stepIndex + 1}`,- hidden: stepIndex >= stepsLength,- })),- hidden: funnelOrderType === StepOrderValue.UNORDERED,- },- ]}- onChange={onChange}- dropdownMaxContentWidth={true}- data-attr="breakdown-attributions"- />- </div>- )-}diff --git a/products/experiments/frontend/legacy/components/LegacyFunnelConversionWindowFilter.tsx b/products/experiments/frontend/legacy/components/LegacyFunnelConversionWindowFilter.tsxdeleted file mode 100644index 4f7d9641975b..000000000000--- a/products/experiments/frontend/legacy/components/LegacyFunnelConversionWindowFilter.tsx+++ /dev/null@@ -1,71 +0,0 @@-import { IconInfo } from '@posthog/icons'-import type { LemonSelectOption } from '@posthog/lemon-ui'-import { LemonInput, LemonSelect } from '@posthog/lemon-ui'--import { Tooltip } from 'lib/lemon-ui/Tooltip'-import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'--import { FunnelConversionWindowTimeUnit } from '~/types'--import { TIME_INTERVAL_BOUNDS } from 'products/product_analytics/frontend/insights/funnels/funnelUtils'--/**- * @deprecated- * Legacy funnel conversion window filter for ExperimentView.- * Frozen copy for legacy experiments - do not modify.- * Forked from https://github.com/PostHog/posthog/blob/master/products/product_analytics/frontend/insights/funnels/filters/FunnelConversionWindowFilter.tsx- */-export function LegacyFunnelConversionWindowFilter({- funnelWindowInterval,- funnelWindowIntervalUnit,- onFunnelWindowIntervalChange,- onFunnelWindowIntervalUnitChange,-}: {- funnelWindowInterval: number | undefined- funnelWindowIntervalUnit: FunnelConversionWindowTimeUnit | undefined- onFunnelWindowIntervalChange: (funnelWindowInterval: number | undefined) => void- onFunnelWindowIntervalUnitChange: (funnelWindowIntervalUnit: FunnelConversionWindowTimeUnit) => void-}): JSX.Element {- const options: LemonSelectOption<FunnelConversionWindowTimeUnit>[] = Object.keys(TIME_INTERVAL_BOUNDS).map(- (unit) => ({- label: capitalizeFirstLetter(pluralize(funnelWindowInterval ?? 7, unit, `${unit}s`, false)),- value: unit as FunnelConversionWindowTimeUnit,- })- )- const intervalBounds = TIME_INTERVAL_BOUNDS[funnelWindowIntervalUnit ?? FunnelConversionWindowTimeUnit.Day]-- return (- <div className="flex items-center gap-2">- <span className="flex whitespace-nowrap">- Conversion window limit- <Tooltip- title={- <>- <b>Recommended!</b> Limit to participants that converted within a specific time frame.- Participants that do not convert in this time frame will be considered as drop-offs.- </>- }- >- <IconInfo className="w-4 info-indicator" />- </Tooltip>- </span>- <div className="flex items-center gap-2">- <LemonInput- type="number"- className="max-w-20"- fullWidth={false}- min={intervalBounds[0]}- max={intervalBounds[1]}- value={funnelWindowInterval}- onChange={onFunnelWindowIntervalChange}- />- <LemonSelect- dropdownMatchSelectWidth={false}- value={funnelWindowIntervalUnit}- onChange={onFunnelWindowIntervalUnitChange}- options={options}- />- </div>- </div>- )-}diff --git a/products/experiments/frontend/legacy/components/LegacyPageHeader.tsx b/products/experiments/frontend/legacy/components/LegacyPageHeader.tsxdeleted file mode 100644index 1dc0dcb56e65..000000000000--- a/products/experiments/frontend/legacy/components/LegacyPageHeader.tsx+++ /dev/null@@ -1,160 +0,0 @@-import { useActions, useValues } from 'kea'-import { router } from 'kea-router'--import { IconArchive, IconFlask, IconTrash } from '@posthog/icons'-import { LemonButton, LemonDivider, Tooltip } from '@posthog/lemon-ui'--import { SceneMenuBarFileItems } from 'lib/components/Scenes/SceneMenuBarFileItems'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'-import { ButtonPrimitive } from 'lib/ui/Button/ButtonPrimitives'-import { userHasAccess } from 'lib/utils/accessControlUtils'-import { projectLogic } from 'scenes/projectLogic'-import { urls } from 'scenes/urls'--import {- SceneMenuBar,- SceneMenuBarItem,- SceneMenuBarMenu,- SceneMenuBarSeparator,-} from '~/layout/scenes/components/SceneMenuBar'-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { ScenePanel, ScenePanelActionsSection } from '~/layout/scenes/SceneLayout'-import { FinishExperimentModal } from '~/scenes/experiments/ExperimentView/ExperimentModals'-import { modalsLogic } from '~/scenes/experiments/modalsLogic'-import { AccessControlLevel, AccessControlResourceType, ExperimentStatus } from '~/types'--import {- canArchiveExperiment,- confirmArchiveExperiment,- confirmDeleteExperiment,-} from 'products/experiments/frontend/experimentActions'--import { legacyExperimentLogic } from '../legacyExperimentLogic'--/**- * @deprecated- * This component is used to display the header of a legacy experiment.- * For modern experiments, use the PageHeader component.- */-export function LegacyPageHeader(): JSX.Element {- const { experiment } = useValues(legacyExperimentLogic)- const { archiveExperiment } = useActions(legacyExperimentLogic)- const { currentProjectId } = useValues(projectLogic)-- const { openFinishExperimentModal } = useActions(modalsLogic)-- const canEdit = userHasAccess(- AccessControlResourceType.Experiment,- AccessControlLevel.Editor,- experiment.user_access_level- )- const canArchive = canEdit && canArchiveExperiment(experiment)- const canDelete = canEdit-- const handleArchive = (): void =>- confirmArchiveExperiment(experiment, (disableFlag) => archiveExperiment(disableFlag))- const handleDelete = (): void =>- confirmDeleteExperiment({- projectId: currentProjectId,- experiment,- onDelete: () => router.actions.push(urls.experiments()),- })-- const isExperimentRunning =- experiment.status === ExperimentStatus.Running || experiment.status === ExperimentStatus.Paused- const isExperimentStopped = experiment.status === ExperimentStatus.Stopped- const sceneMenuBarEnabled = useFeatureFlag('SCENE_MENU_BAR')-- return (- <>- {sceneMenuBarEnabled && experiment && (- <SceneMenuBar>- <SceneMenuBarMenu label="File" dataAttr="experiment-menubar-file">- <SceneMenuBarFileItems dataAttrKey="experiment" />- {(canArchive || canDelete) && <SceneMenuBarSeparator />}- {canArchive && (- <SceneMenuBarItem- variant="destructive"- onClick={handleArchive}- data-attr="experiment-menubar-archive"- >- <IconArchive />- Archive experiment- </SceneMenuBarItem>- )}- {canDelete && (- <SceneMenuBarItem- variant="destructive"- onClick={handleDelete}- data-attr="experiment-menubar-delete"- >- <IconTrash />- Delete experiment- </SceneMenuBarItem>- )}- </SceneMenuBarMenu>- </SceneMenuBar>- )}- <SceneTitleSection- name={experiment?.name}- description={null}- resourceType={{- type: 'experiment',- }}- isLoading={false}- canEdit={false}- renameDebounceMs={0}- saveOnBlur- actions={- <>- {canArchive && (- <LemonButton type="secondary" status="danger" onClick={handleArchive} size="small">- <b>Archive</b>- </LemonButton>- )}- {experiment && isExperimentRunning && !isExperimentStopped && (- <>- <Tooltip title="Conclude this experiment and decide which variant to keep">- <LemonButton- type="primary"- icon={<IconFlask />}- onClick={() => openFinishExperimentModal()}- size="small"- >- <b>End experiment</b>- </LemonButton>- </Tooltip>- <FinishExperimentModal />- </>- )}- </>- }- />-- {experiment && (- <ScenePanel>- <ScenePanelActionsSection>- <LemonDivider />-- {canArchive && (- <ButtonPrimitive menuItem data-attr="archive-experiment" onClick={handleArchive}>- <IconArchive /> Archive experiment- </ButtonPrimitive>- )}-- {canDelete && (- <ButtonPrimitive- variant="danger"- menuItem- data-attr="delete-experiment"- onClick={handleDelete}- >- <IconTrash /> Delete experiment- </ButtonPrimitive>- )}- </ScenePanelActionsSection>- </ScenePanel>- )}- </>- )-}diff --git a/products/experiments/frontend/legacy/components/LegacyResultsQuery.tsx b/products/experiments/frontend/legacy/components/LegacyResultsQuery.tsxdeleted file mode 100644index 41941365a5cb..000000000000--- a/products/experiments/frontend/legacy/components/LegacyResultsQuery.tsx+++ /dev/null@@ -1,57 +0,0 @@-import { Query } from '~/queries/Query/Query'-import type {- ExperimentFunnelsQueryResponse,- ExperimentTrendsQueryResponse,- InsightVizNode,-} from '~/queries/schema/schema-general'-import { NodeKind } from '~/queries/schema/schema-general'-import type { InsightShortId } from '~/types'--/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyResultsQuery({- result,- showTable,-}: {- result: ExperimentTrendsQueryResponse | ExperimentFunnelsQueryResponse | null- showTable: boolean-}): JSX.Element {- if (!result) {- return <></>- }-- const query = result.kind === NodeKind.ExperimentTrendsQuery ? result.count_query : result.funnels_query-- const fakeInsightId = Math.random().toString(36).substring(2, 15)-- return (- <Query- query={{- kind: NodeKind.InsightVizNode,- source: query,- showTable,- showLastComputation: true,- showLastComputationRefresh: false,- }}- context={{- insightProps: {- dashboardItemId: fakeInsightId as InsightShortId,- cachedInsight: {- short_id: fakeInsightId as InsightShortId,- query: {- kind: NodeKind.InsightVizNode,- source: query,- } as InsightVizNode,- result: result?.insight,- disable_baseline: true,- },- doNotLoad: true,- },- }}- readOnly- />- )-}diff --git a/products/experiments/frontend/legacy/components/LegacySummaryTable.tsx b/products/experiments/frontend/legacy/components/LegacySummaryTable.tsxdeleted file mode 100644index f60f6016202f..000000000000--- a/products/experiments/frontend/legacy/components/LegacySummaryTable.tsx+++ /dev/null@@ -1,360 +0,0 @@-import { useValues } from 'kea'--import { IconInfo } from '@posthog/icons'-import { LemonTable, LemonTableColumns, LemonTag, Tooltip } from '@posthog/lemon-ui'--import { EntityFilterInfo } from 'lib/components/EntityFilterInfo'-import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'-import { LemonProgress } from 'lib/lemon-ui/LemonProgress'-import { humanFriendlyNumber } from 'lib/utils/numbers'--import { ExperimentFunnelsQuery, ExperimentTrendsQuery, isExperimentTrendsQuery } from '~/queries/schema/schema-general'-import { getViewRecordingFiltersLegacy } from '~/scenes/experiments/utils'-import { FilterLogicalOperator, InsightType, RecordingUniversalFilters, TrendExperimentVariant } from '~/types'--import {- legacyCalculateDelta,- legacyConversionRateForVariant,- legacyCountDataForVariant,- legacyCredibleIntervalForVariant,- legacyExposureCountDataForVariant,- legacyGetHighestProbabilityVariant,- LegacyVariantTag,- getInsightType,- getTabularExperimentResults,- getExperimentMathAggregationForTrends,- legacyExperimentLogic,-} from 'products/experiments/frontend/legacy'--/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- */-export function LegacySummaryTable({- metric,- displayOrder = 0,- isSecondary = false,-}: {- metric: ExperimentTrendsQuery | ExperimentFunnelsQuery- displayOrder?: number- isSecondary?: boolean-}): JSX.Element {- const { experiment, legacyPrimaryMetricsResults, legacySecondaryMetricsResults } = useValues(legacyExperimentLogic)-- const insightType = getInsightType(metric as ExperimentTrendsQuery | ExperimentFunnelsQuery)- const result = isSecondary- ? legacySecondaryMetricsResults?.[displayOrder]- : legacyPrimaryMetricsResults?.[displayOrder]-- if (!result) {- return <></>- }-- const tabularExperimentResults = getTabularExperimentResults(- experiment,- legacyPrimaryMetricsResults,- legacySecondaryMetricsResults,- getInsightType- )-- const winningVariant = legacyGetHighestProbabilityVariant(result)-- const columns: LemonTableColumns<any> = [- {- key: 'variants',- title: 'Variant',- render: function Key(_, item): JSX.Element {- return (- <div className="flex items-center">- <LegacyVariantTag variantKey={item.key} />- </div>- )- },- },- ]-- if (insightType === InsightType.TRENDS) {- columns.push({- key: 'counts',- title: (- <div className="flex">- {result.insight?.[0] && 'action' in result.insight[0] && (- <EntityFilterInfo filter={result.insight[0].action} />- )}- <span className="pl-1">- {getExperimentMathAggregationForTrends(experiment) ? 'metric' : 'count'}- </span>- </div>- ),- render: function Key(_, variant): JSX.Element {- const count = legacyCountDataForVariant(result, variant.key)- if (!count) {- return <>—</>- }-- return <div className="flex">{humanFriendlyNumber(count)}</div>- },- })- columns.push({- key: 'exposure',- title: (- <div className="inline-flex items-center deprecated-space-x-1">- <div className="">Exposure</div>- <Tooltip- title={- <div>- The number of users who were exposed to this variant. By default, this is measured by- the count of <LemonTag type="option">$feature_flag_called</LemonTag> events per unique- user. Check your metric settings to confirm how this is measured.- </div>- }- >- <IconInfo className="text-secondary text-base" />- </Tooltip>- </div>- ),- render: function Key(_, variant): JSX.Element {- const exposure = legacyExposureCountDataForVariant(result, variant.key)- if (!exposure) {- return <>—</>- }-- return <div>{humanFriendlyNumber(exposure)}</div>- },- })- columns.push({- key: 'mean',- title: 'Mean',- render: function Key(_, v): JSX.Element {- const variant = v as TrendExperimentVariant- if (!variant.count || !variant.absolute_exposure) {- return <div className="font-semibold">—</div>- }-- return <div className="font-semibold">{(variant.count / variant.absolute_exposure).toFixed(2)}</div>- },- })- columns.push({- key: 'delta',- title: (- <div className="inline-flex items-center deprecated-space-x-1">- <div className="">Delta %</div>- <Tooltip title="Delta % indicates the percentage change in the mean between the control and the test variant.">- <IconInfo className="text-secondary text-base" />- </Tooltip>- </div>- ),- render: function Key(_, v): JSX.Element {- const variant = v as TrendExperimentVariant-- if (variant.key === 'control') {- return <em>Baseline</em>- }-- const deltaResult = legacyCalculateDelta(result, variant.key, insightType)- if (!deltaResult) {- return <div className="font-semibold">—</div>- }-- return (- <div- className={`font-semibold ${- deltaResult.isPositive ? 'text-success' : deltaResult.deltaPercent < 0 ? 'text-danger' : ''- }`}- >- {`${deltaResult.isPositive ? '+' : ''}${deltaResult.deltaPercent.toFixed(2)}%`}- </div>- )- },- })- columns.push({- key: 'credibleInterval',- title: (- <div className="inline-flex items-center deprecated-space-x-1">- <div className="">Credible interval (95%)</div>- <Tooltip title="A credible interval estimates the percentage change in the mean, indicating with 95% probability how much higher or lower the test variant's mean is compared to the control.">- <IconInfo className="text-secondary text-base" />- </Tooltip>- </div>- ),- render: function Key(_, v): JSX.Element {- const variant = v as TrendExperimentVariant- if (variant.key === 'control') {- return <em>Baseline</em>- }-- const credibleInterval = legacyCredibleIntervalForVariant(result || null, variant.key, insightType)- if (!credibleInterval) {- return <>—</>- }- const [lowerBound, upperBound] = credibleInterval-- return (- <div className="font-semibold">{`[${lowerBound > 0 ? '+' : ''}${lowerBound.toFixed(2)}%, ${- upperBound > 0 ? '+' : ''- }${upperBound.toFixed(2)}%]`}</div>- )- },- })- }-- if (insightType === InsightType.FUNNELS) {- columns.push({- key: 'conversionRate',- title: 'Conversion rate',- render: function Key(_, item): JSX.Element {- const conversionRate = legacyConversionRateForVariant(result, item.key)- if (!conversionRate) {- return <>—</>- }-- return <div className="font-semibold">{`${conversionRate.toFixed(2)}%`}</div>- },- })-- columns.push({- key: 'delta',- title: (- <div className="inline-flex items-center deprecated-space-x-1">- <div className="">Delta %</div>- <Tooltip title="Delta % indicates the percentage change in the conversion rate between the control and the test variant.">- <IconInfo className="text-secondary text-base" />- </Tooltip>- </div>- ),- render: function Key(_, item): JSX.Element {- if (item.key === 'control') {- return <em>Baseline</em>- }-- const controlConversionRate = legacyConversionRateForVariant(result, 'control')- const variantConversionRate = legacyConversionRateForVariant(result, item.key)-- if (!controlConversionRate || !variantConversionRate) {- return <>—</>- }-- const delta = ((variantConversionRate - controlConversionRate) / controlConversionRate) * 100-- return (- <div className={`font-semibold ${delta > 0 ? 'text-success' : delta < 0 ? 'text-danger' : ''}`}>{`${- delta > 0 ? '+' : ''- }${delta.toFixed(2)}%`}</div>- )- },- })-- columns.push({- key: 'credibleInterval',- title: (- <div className="inline-flex items-center deprecated-space-x-1">- <div className="">Credible interval (95%)</div>- <Tooltip title="A credible interval estimates the percentage change in the conversion rate, indicating with 95% probability how much higher or lower the test variant's conversion rate is compared to the control.">- <IconInfo className="text-secondary text-base" />- </Tooltip>- </div>- ),- render: function Key(_, item): JSX.Element {- if (item.key === 'control') {- return <em>Baseline</em>- }-- const credibleInterval = legacyCredibleIntervalForVariant(result || null, item.key, insightType)- if (!credibleInterval) {- return <>—</>- }- const [lowerBound, upperBound] = credibleInterval-- return (- <div className="font-semibold">{`[${lowerBound > 0 ? '+' : ''}${lowerBound.toFixed(2)}%, ${- upperBound > 0 ? '+' : ''- }${upperBound.toFixed(2)}%]`}</div>- )- },- })- }-- columns.push({- key: 'winProbability',- title: 'Win probability',- sorter: (a, b) => {- const aPercentage = (result?.probability?.[a.key] || 0) * 100- const bPercentage = (result?.probability?.[b.key] || 0) * 100- return aPercentage - bPercentage- },- render: function Key(_, item): JSX.Element {- const variantKey = item.key- const percentage = result?.probability?.[variantKey] !== undefined && result.probability?.[variantKey] * 100- const isWinning = variantKey === winningVariant-- // Only show the win probability if the conversion rate exists- // TODO: move this to the backend- const conversionRate = legacyConversionRateForVariant(result, variantKey)- const hasValidConversionRate = conversionRate !== null && conversionRate !== undefined-- return (- <>- {percentage && (insightType === InsightType.FUNNELS ? hasValidConversionRate : true) ? (- <span className="inline-flex items-center w-52 deprecated-space-x-4">- <LemonProgress className="inline-flex w-3/4" percent={percentage} />- <span className={`w-1/4 font-semibold ${isWinning && 'text-success'}`}>- {percentage.toFixed(2)}%- </span>- </span>- ) : (- '—'- )}- </>- )- },- })-- columns.push({- key: 'recordings',- title: '',- render: function Key(_, item): JSX.Element {- const variantKey = item.key-- const filters = getViewRecordingFiltersLegacy(metric, experiment.feature_flag_key, variantKey)-- const filterGroup: Partial<RecordingUniversalFilters> = {- filter_group: {- type: FilterLogicalOperator.And,- values: [- {- type: FilterLogicalOperator.And,- values: filters,- },- ],- },- date_from: experiment?.start_date,- date_to: experiment?.end_date,- filter_test_accounts: isExperimentTrendsQuery(metric)- ? metric.count_query.filterTestAccounts- : metric.funnels_query.filterTestAccounts,- }-- return (- <ViewRecordingsPlaylistButton- filters={filterGroup}- size="xsmall"- type="secondary"- tooltip="Watch recordings of people who were exposed to this variant."- disabled={filters.length === 0}- disabledReason={filters.length === 0 ? 'Unable to identify recordings for this metric' : undefined}- data-attr="experiment-summary-view-recordings"- />- )- },- })-- return (- <div className="mb-4" data-attr="experiment-results">- <LemonTable- loading={false}- columns={columns}- dataSource={tabularExperimentResults(displayOrder, isSecondary)}- />- </div>- )-}diff --git a/products/experiments/frontend/legacy/components/LegacyVariantTag.tsx b/products/experiments/frontend/legacy/components/LegacyVariantTag.tsxdeleted file mode 100644index 7a5841c727e0..000000000000--- a/products/experiments/frontend/legacy/components/LegacyVariantTag.tsx+++ /dev/null@@ -1,71 +0,0 @@-import clsx from 'clsx'-import { useValues } from 'kea'--import { LemonTag, Tooltip } from '@posthog/lemon-ui'--import { getVariantColor } from 'scenes/experiments/utils'--import { EXPERIMENT_VARIANT_MULTIPLE } from 'products/experiments/frontend/constants'-import { legacyExperimentLogic } from 'products/experiments/frontend/legacy'--/**- * @deprecated- * Legacy variant tag component.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyVariantTag({- variantKey,- fontSize,- className,-}: {- variantKey: string- fontSize?: number- className?: string-}): JSX.Element {- const { experiment, legacyPrimaryMetricsResults } = useValues(legacyExperimentLogic)-- if (variantKey === EXPERIMENT_VARIANT_MULTIPLE) {- return (- <Tooltip title="Some users were exposed to more than one variant. If this percentage is high, there may be an implementation issue causing inconsistent variant assignment.">- <LemonTag type="danger">{variantKey}</LemonTag>- </Tooltip>- )- }-- if (!legacyPrimaryMetricsResults) {- return <></>- }-- const variantColor = experiment.feature_flag?.filters.multivariate?.variants- ? getVariantColor(variantKey, experiment.feature_flag?.filters.multivariate?.variants)- : 'var(--muted)'-- if (experiment.holdout && variantKey === `holdout-${experiment.holdout_id}`) {- return (- <span className={clsx('flex items-center min-w-0', className)}>- <div- className="w-2 h-2 rounded-full shrink-0"- // eslint-disable-next-line react/forbid-dom-props- style={{- backgroundColor: variantColor,- }}- />- <LemonTag type="option" className="ml-2">- {experiment.holdout.name}- </LemonTag>- </span>- )- }-- return (- <span className={clsx('flex items-center min-w-0', className)}>- <span- className="ml-2 text-xs font-semibold truncate text-secondary"- // eslint-disable-next-line react/forbid-dom-props- style={fontSize ? { fontSize: `${fontSize}px` } : undefined}- >- {variantKey}- </span>- </span>- )-}diff --git a/products/experiments/frontend/legacy/hooks/useLegacySvgResizeObserver.ts b/products/experiments/frontend/legacy/hooks/useLegacySvgResizeObserver.tsdeleted file mode 100644index 452093444c26..000000000000--- a/products/experiments/frontend/legacy/hooks/useLegacySvgResizeObserver.ts+++ /dev/null@@ -1,64 +0,0 @@-import { useEffect, useRef, useState } from 'react'--export interface SvgResizeObserverState {- // Refs to attach to SVG elements for observation- ticksSvgRef: React.RefObject<SVGSVGElement>- chartSvgRef: React.RefObject<SVGSVGElement>-- // Height values for adjusting neighboring elements- ticksSvgHeight: number- chartSvgHeight: number-}--/**- * @deprecated- * Custom hook to observe SVG element resizing and manage heights for metrics charts- *- * This hook handles the dynamic height adjustments needed for experiment metric visualizations,- * particularly managing the alignment between SVG charts and regular divs.- *- * @param deps - Optional array of dependencies to trigger re-observation- * @returns Object containing refs and height values- */-export function useLegacySvgResizeObserver(deps: any[] = []): SvgResizeObserverState {- const ticksSvgRef = useRef<SVGSVGElement>(null)- const chartSvgRef = useRef<SVGSVGElement>(null)-- // Track SVG heights dynamically because we're fitting regular divs to match SVG viewports- const [ticksSvgHeight, setTicksSvgHeight] = useState<number>(0)- const [chartSvgHeight, setChartSvgHeight] = useState<number>(0)-- useEffect(() => {- const ticksSvg = ticksSvgRef.current- const chartSvg = chartSvgRef.current-- // oxlint-disable-next-line compat/compat- const resizeObserver = new ResizeObserver((entries) => {- for (const entry of entries) {- if (entry.target === ticksSvg) {- setTicksSvgHeight(entry.contentRect.height)- } else if (entry.target === chartSvg) {- setChartSvgHeight(entry.contentRect.height)- }- }- })-- if (ticksSvg) {- resizeObserver.observe(ticksSvg)- }- if (chartSvg) {- resizeObserver.observe(chartSvg)- }-- return () => {- resizeObserver.disconnect()- }- }, deps)-- return {- ticksSvgRef,- chartSvgRef,- ticksSvgHeight,- chartSvgHeight,- }-}diff --git a/products/experiments/frontend/legacy/index.ts b/products/experiments/frontend/legacy/index.tsdeleted file mode 100644index c2d6653db894..000000000000--- a/products/experiments/frontend/legacy/index.ts+++ /dev/null@@ -1,56 +0,0 @@-// Legacy experiment components re-exports-// These components support legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery)--// View-export { LegacyExperimentView } from './LegacyExperimentView'--// Logic-export { legacyExperimentLogic } from './legacyExperimentLogic'-export { legacyExperimentModalsLogic } from './legacyExperimentModalsLogic'--// Shared Metrics-export { LegacySharedTrendsMetricForm } from './sharedMetrics/LegacySharedTrendsMetricForm'-export { LegacySharedFunnelsMetricForm } from './sharedMetrics/LegacySharedFunnelsMetricForm'--// Components-export { LegacyDataCollection } from './components/LegacyDataCollection'-export { LegacyExperimentDate } from './LegacyExperimentDate'-export { LegacyExperimentDates } from './LegacyExperimentDates'-export { LegacyExperimentHeader } from './components/LegacyExperimentHeader'-export { LegacyExperimentInfo } from './LegacyExperimentInfo'-export { LegacyExploreButton } from './components/LegacyExploreButton'-export { LegacyResultsQuery } from './components/LegacyResultsQuery'-export { LegacySummaryTable } from './components/LegacySummaryTable'-export { LegacyFunnelAttributionSelect } from './components/LegacyFunnelAttributionSelect'-export { LegacyFunnelConversionWindowFilter } from './components/LegacyFunnelConversionWindowFilter'-export { LegacyFunnelAggregationSelect } from './components/LegacyFunnelAggregationSelect'--// Calculations-export * from './calculations/legacyExperimentCalculations'--// Functions-export * from './legacyUtils'--// Modals-export { LegacyChartModal } from './metricsView/LegacyChartModal'--// Metrics View-export { LegacyMetricsView } from './metricsView/LegacyMetricsView'-export { LegacyDeltaChart } from './metricsView/LegacyDeltaChart'-export { LegacyChartEmptyState } from './metricsView/LegacyChartEmptyState'-export { LegacyErrorChecklist } from './metricsView/LegacyErrorChecklist'-export { LegacyMetricsChartLayout } from './metricsView/LegacyMetricsChartLayout'-export { LegacySignificanceHighlight } from './metricsView/LegacySignificanceHighlight'-export { LegacyTickPanel } from './metricsView/LegacyTickPanel'-export { LegacyVariantTooltip } from './metricsView/LegacyVariantTooltip'-export { LegacyWinningVariantText, LegacySignificanceText, LegacyOverview } from './metricsView/LegacyOverview'-export { LegacyVariantTag } from './components/LegacyVariantTag'-export * from './metricsView/legacyViolinUtils'--// Metrics View - Shared (Legacy)-export { LegacyChartLoadingState } from './metricsView/LegacyChartLoadingState'-export { LegacyGridLines } from './metricsView/LegacyGridLines'-export { LegacyMetricHeader } from './metricsView/LegacyMetricHeader'-export { LegacyMetricTitle } from './metricsView/LegacyMetricTitle'-export { useLegacyChartColors, LEGACY_COLORS } from './metricsView/legacyColors'-export * from './metricsView/legacyUtils'diff --git a/products/experiments/frontend/legacy/legacyExperimentLogic.tsx b/products/experiments/frontend/legacy/legacyExperimentLogic.tsxdeleted file mode 100644index 3d4524797b01..000000000000--- a/products/experiments/frontend/legacy/legacyExperimentLogic.tsx+++ /dev/null@@ -1,657 +0,0 @@-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'--import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'-import { eventUsageLogic } from 'lib/utils/eventUsageLogic'-import { runWithLimit } from 'scenes/dashboard/dashboardUtils'-import { modalsLogic } from 'scenes/experiments/modalsLogic'-import { getDisplayOrderedIndices, isLegacyExperimentQuery, isLegacySharedMetric } from 'scenes/experiments/utils'-import { teamLogic } from 'scenes/teamLogic'--import { refreshTreeItem } from '~/layout/panel-layout/ProjectTree/projectTreeLogic'-import { performQuery } from '~/queries/query'-import {- CachedExperimentFunnelsQueryResponse,- CachedExperimentTrendsQueryResponse,- CachedLegacyExperimentQueryResponse,- NodeKind,-} from '~/queries/schema/schema-general'-import { setLatestVersionsOnQuery } from '~/queries/utils'-import { Experiment } from '~/types'-import type { ExperimentIdType } from '~/types'--import { experimentsArchiveCreate, experimentsEndCreate, experimentsShipVariantCreate } from '../generated/api'--export interface LegacyExperimentLogicProps {- experiment: Experiment-}--export type LegacyExperimentTriggeredBy = 'page_load' | 'manual' | 'auto_refresh' | 'config_change'--/**- * Validates that an experiment only contains legacy metrics.- * This is a defensive check to ensure the legacy logic doesn't attempt- * to load modern ExperimentMetric queries.- *- * @returns Object with isValid boolean and error message if invalid- */-function validateLegacyExperiment(experiment: Experiment): { isValid: boolean; error?: string } {- // Check all direct metrics- const nonLegacyMetrics = [...experiment.metrics, ...experiment.metrics_secondary].filter(- (metric) => !isLegacyExperimentQuery(metric)- )-- if (nonLegacyMetrics.length > 0) {- return {- isValid: false,- error: `Found ${nonLegacyMetrics.length} non-legacy metric(s) in experiment. Legacy logic only supports ExperimentTrendsQuery and ExperimentFunnelsQuery.`,- }- }-- // Check saved metrics- const nonLegacySavedMetrics = experiment.saved_metrics.filter((sm) => !isLegacySharedMetric(sm))-- if (nonLegacySavedMetrics.length > 0) {- return {- isValid: false,- error: `Found ${nonLegacySavedMetrics.length} non-legacy saved metric(s) in experiment. Legacy logic only supports ExperimentTrendsQuery and ExperimentFunnelsQuery.`,- }- }-- return { isValid: true }-}--function generateRefreshId(): string {- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {- return crypto.randomUUID()- }- // Fallback for environments without crypto.randomUUID (e.g., jsdom tests)- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {- const r = (Math.random() * 16) | 0- const v = c === 'x' ? r : (r & 0x3) | 0x8- return v.toString(16)- })-}--interface LegacyMetricLoadingConfig {- metrics: any[]- experimentId: Experiment['id']- refresh?: boolean- teamId?: number | null- refreshId: string- isPrimary: boolean- isRetry: boolean- metricIndexOffset: number- orderedUuids?: string[] | null- onSetLegacyResults: (- results: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedExperimentFunnelsQueryResponse- | null- )[]- ) => void- onSetErrors: (errors: any[]) => void-}--interface LegacyMetricLoadingSummary {- successfulCount: number- erroredCount: number- cachedCount: number-}--function parseMetricErrorDetail(error: any): { detail: any; hasDiagnostics: boolean } {- const errorDetailText = typeof error.detail === 'string' ? error.detail : null- const errorDetailMatch = errorDetailText?.match(/\{.*\}/)-- if (!errorDetailMatch) {- return { detail: error.detail || error.message, hasDiagnostics: false }- }-- try {- return { detail: JSON.parse(errorDetailMatch[0]), hasDiagnostics: true }- } catch {- return { detail: error.detail || error.message, hasDiagnostics: false }- }-}--// Max concurrent metric queries to avoid overwhelming the celery queue's-// per-team concurrency limit (10). Using runWithLimit instead of Promise.all-// prevents mass rejections and retry churn when experiments have many metrics.-const METRIC_QUERY_CONCURRENCY_LIMIT = 10--const loadLegacyMetrics = async ({- metrics,- experimentId,- refresh,- teamId,- refreshId,- isPrimary,- isRetry,- metricIndexOffset,- orderedUuids,- onSetLegacyResults,- onSetErrors,-}: LegacyMetricLoadingConfig): Promise<LegacyMetricLoadingSummary> => {- const legacyResults: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedExperimentFunnelsQueryResponse- | null- )[] = []-- // eslint-disable-next-line no-new-array- const currentErrors = new Array(metrics.length).fill(null)-- let successfulCount = 0- let erroredCount = 0- let cachedCount = 0-- // Build tasks in display order so higher-priority metrics get dispatched first,- // but each task writes to its original index so the UI stays consistent.- const displayOrder = getDisplayOrderedIndices(metrics, orderedUuids)-- const tasks = displayOrder.map((originalIndex) => {- const metric = metrics[originalIndex]- return async (): Promise<void> => {- let response: any = null- const startTime = performance.now()- const metricIndex = metricIndexOffset + originalIndex- const metricKind = metric.kind || 'unknown'-- try {- let queryWithExperimentId- if (metric.kind === NodeKind.ExperimentMetric) {- queryWithExperimentId = {- kind: NodeKind.ExperimentQuery,- metric: metric,- experiment_id: experimentId,- }- } else {- queryWithExperimentId = {- ...metric,- experiment_id: experimentId,- }- }- response = await performQuery(- setLatestVersionsOnQuery(queryWithExperimentId),- undefined,- refresh ? 'force_async' : 'async'- )-- const durationMs = Math.round(performance.now() - startTime)- const isCached = !!response?.is_cached-- // All responses in legacy experiments are legacy format- // Add fakeInsightId for tracking- legacyResults[originalIndex] = {- ...response,- fakeInsightId: Math.random().toString(36).substring(2, 15),- } as (- | CachedLegacyExperimentQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedExperimentFunnelsQueryResponse- ) & {- fakeInsightId: string- }- onSetLegacyResults([...legacyResults])-- successfulCount++- if (isCached) {- cachedCount++- }-- eventUsageLogic.actions.reportExperimentMetricFinished(- experimentId,- metric,- teamId,- response?.query_status?.id || null,- {- duration_ms: durationMs,- execution_mode: 'async',- is_cached: isCached,- metric_index: metricIndex,- is_primary: isPrimary,- is_retry: isRetry,- refresh_id: refreshId,- metric_kind: metricKind,- }- )- } catch (error: any) {- const errorCode = typeof error.code === 'string' ? error.code : null- const statusCode = typeof error.status === 'number' ? error.status : null- const { detail: errorDetail, hasDiagnostics } = parseMetricErrorDetail(error)- const queryId = response?.query_status?.id || error.queryId || null-- currentErrors[originalIndex] = {- detail: errorDetail,- statusCode,- hasDiagnostics,- code: errorCode,- queryId,- timestamp: Date.now(),- }- onSetErrors(currentErrors)-- erroredCount++-- // No telemetry here: the terminal `experiment metric error` event is emitted by the backend.-- legacyResults[originalIndex] = null- onSetLegacyResults([...legacyResults])- }- }- })-- await runWithLimit(tasks, METRIC_QUERY_CONCURRENCY_LIMIT)-- return { successfulCount, erroredCount, cachedCount }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface legacyExperimentLogicValues {- currentProjectId: number | string // teamLogic- currentTeamId: number | null // teamLogic- experiment: Experiment- experimentId: ExperimentIdType- legacyPrimaryMetricsResults: (- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedLegacyExperimentQueryResponse- | null- )[]- legacySecondaryMetricsResults: (- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedLegacyExperimentQueryResponse- | null- )[]- primaryMetricsResultsErrors: any[]- primaryMetricsResultsLoading: boolean- secondaryMetricsResultsErrors: any[]- secondaryMetricsResultsLoading: boolean- unmodifiedExperiment: Experiment | null-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface legacyExperimentLogicActions {- closeFinishExperimentModal: () => {- value: true- } // modalsLogic- archiveExperiment: (disableFeatureFlag?: boolean) => {- disableFeatureFlag: boolean- }- endExperiment: () => {- value: true- }- endExperimentWithoutShipping: () => {- value: true- }- finishExperiment: ({ selectedVariantKey }: { selectedVariantKey: string }) => {- selectedVariantKey: string- }- loadPrimaryMetricsResults: (- refresh?: boolean,- refreshId?: string- ) => {- refresh: boolean | undefined- refreshId: string | undefined- }- loadSecondaryMetricsResults: (- refresh?: boolean,- refreshId?: string- ) => {- refresh: boolean | undefined- refreshId: string | undefined- }- refreshExperimentResults: (- forceRefresh?: boolean,- triggeredBy?: LegacyExperimentTriggeredBy- ) => {- forceRefresh: boolean | undefined- triggeredBy: LegacyExperimentTriggeredBy- }- restoreUnmodifiedExperiment: () => {- value: true- }- setExperiment: (update: Partial<Experiment>) => {- update: Partial<Experiment>- }- setLegacyPrimaryMetricsResults: (- results: (- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedLegacyExperimentQueryResponse- | null- )[]- ) => {- results: (- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedLegacyExperimentQueryResponse- | null- )[]- }- setLegacySecondaryMetricsResults: (- results: (- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedLegacyExperimentQueryResponse- | null- )[]- ) => {- results: (- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedLegacyExperimentQueryResponse- | null- )[]- }- setPrimaryMetricsResultsErrors: (errors: any[]) => {- errors: any[]- }- setPrimaryMetricsResultsLoading: (loading: boolean) => {- loading: boolean- }- setSecondaryMetricsResultsErrors: (errors: any[]) => {- errors: any[]- }- setSecondaryMetricsResultsLoading: (loading: boolean) => {- loading: boolean- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface legacyExperimentLogicMeta {- key: string- __keaTypeGenInternalSelectorTypes: {- experimentId: (experiment: Experiment) => ExperimentIdType- }-}--export type legacyExperimentLogicType = MakeLogicType<- legacyExperimentLogicValues,- legacyExperimentLogicActions,- LegacyExperimentLogicProps,- legacyExperimentLogicMeta->--/**- * @deprecated Legacy experiment logic for read-only legacy experiments.- *- * This logic handles ONLY metrics results loading for experiments that use- * ExperimentTrendsQuery and ExperimentFunnelsQuery (legacy format).- *- * Key principles:- * - Receives experiment as prop (no duplicate loading)- * - Mostly read-only: legacy experiments can be archived, ended or finished, but not edited- * - Loads and metrics results- * - Legacy experiments are frozen/read-only, so no auto-refresh or notifications- *- * New experiments should use the modern experimentLogic.tsx instead.- */-export const legacyExperimentLogic = kea<legacyExperimentLogicType>([- props({} as LegacyExperimentLogicProps),- key((props) => {- const baseKey = props.experiment.id ?? 'new'- return `${baseKey}-legacy`- }),- path((key) => ['scenes', 'experiments', 'legacy', 'legacyExperimentLogic', key]),- connect(() => ({- values: [teamLogic, ['currentTeamId', 'currentProjectId']],- actions: [modalsLogic, ['closeFinishExperimentModal']],- })),- actions({- // Experiment mutations- archiveExperiment: (disableFeatureFlag: boolean = false) => ({ disableFeatureFlag }),- endExperiment: true,- endExperimentWithoutShipping: true,- finishExperiment: ({ selectedVariantKey }: { selectedVariantKey: string }) => ({ selectedVariantKey }),- setExperiment: (update: Partial<Experiment>) => ({ update }),- restoreUnmodifiedExperiment: true,-- // Metrics results loading- refreshExperimentResults: (forceRefresh?: boolean, triggeredBy?: LegacyExperimentTriggeredBy) => ({- forceRefresh,- triggeredBy: triggeredBy ?? 'manual',- }),- setLegacyPrimaryMetricsResults: (- results: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedExperimentFunnelsQueryResponse- | null- )[]- ) => ({ results }),- setPrimaryMetricsResultsLoading: (loading: boolean) => ({ loading }),- loadPrimaryMetricsResults: (refresh?: boolean, refreshId?: string) => ({ refresh, refreshId }),- setPrimaryMetricsResultsErrors: (errors: any[]) => ({ errors }),- setLegacySecondaryMetricsResults: (- results: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedExperimentFunnelsQueryResponse- | null- )[]- ) => ({ results }),- loadSecondaryMetricsResults: (refresh?: boolean, refreshId?: string) => ({ refresh, refreshId }),- setSecondaryMetricsResultsErrors: (errors: any[]) => ({ errors }),- setSecondaryMetricsResultsLoading: (loading: boolean) => ({ loading }),- }),- reducers(({ props }) => ({- experiment: [- props.experiment,- {- setExperiment: (state, { update }) => ({ ...state, ...update }),- },- ],- unmodifiedExperiment: [- props.experiment as Experiment | null,- {- setExperiment: (state) => state, // Preserve unmodified version- },- ],- legacyPrimaryMetricsResults: [- [] as (- | CachedLegacyExperimentQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedExperimentFunnelsQueryResponse- | null- )[],- {- setLegacyPrimaryMetricsResults: (_, { results }) => results,- },- ],- primaryMetricsResultsLoading: [- false,- {- loadPrimaryMetricsResults: () => true,- setPrimaryMetricsResultsLoading: (_, { loading }) => loading,- },- ],- primaryMetricsResultsErrors: [- [] as any[],- {- setPrimaryMetricsResultsErrors: (_, { errors }) => errors,- loadPrimaryMetricsResults: () => [],- },- ],- legacySecondaryMetricsResults: [- [] as (- | CachedLegacyExperimentQueryResponse- | CachedExperimentTrendsQueryResponse- | CachedExperimentFunnelsQueryResponse- | null- )[],- {- setLegacySecondaryMetricsResults: (_, { results }) => results,- },- ],- secondaryMetricsResultsLoading: [- false,- {- loadSecondaryMetricsResults: () => true,- setSecondaryMetricsResultsLoading: (_, { loading }) => loading,- },- ],- secondaryMetricsResultsErrors: [- [] as any[],- {- setSecondaryMetricsResultsErrors: (_, { errors }) => errors,- loadSecondaryMetricsResults: () => [],- },- ],- })),- selectors({- experimentId: [(s) => [s.experiment], (experiment: Experiment) => experiment.id],- }),- listeners(({ values, actions }) => ({- afterMount: () => {- const experiment = values.experiment-- // Defensive check: Verify all metrics are legacy on mount- const validation = validateLegacyExperiment(experiment)- if (!validation.isValid) {- lemonToast.error(- `Cannot load metrics: ${validation.error} This experiment should use the modern experiment view.`- )- return- }- },- archiveExperiment: async ({ disableFeatureFlag }) => {- try {- const response = await experimentsArchiveCreate(- String(values.currentProjectId),- Number(values.experimentId),- { disable_feature_flag: disableFeatureFlag }- )- // @ts-expect-error legacy Experiment type is narrower than the generated ExperimentApi (type is non-null)- actions.setExperiment(response)- refreshTreeItem('experiment', String(values.experimentId))- } catch (error: any) {- lemonToast.error(error.detail || 'Failed to archive experiment')- }- },- endExperiment: async () => {- try {- const response = await experimentsEndCreate(- String(values.currentProjectId),- Number(values.experimentId),- {- conclusion: values.experiment.conclusion,- conclusion_comment: values.experiment.conclusion_comment,- }- )- // @ts-expect-error legacy Experiment type is narrower than the generated ExperimentApi (type is non-null)- actions.setExperiment(response)- refreshTreeItem('experiment', String(values.experimentId))- } catch (error: any) {- lemonToast.error(error.detail || 'Failed to end experiment')- }- },- endExperimentWithoutShipping: async () => {- actions.endExperiment()- actions.closeFinishExperimentModal()- lemonToast.success('Experiment ended successfully')- },- finishExperiment: async ({ selectedVariantKey }) => {- try {- const response = await experimentsShipVariantCreate(- String(values.currentProjectId),- Number(values.experimentId),- {- variant_key: selectedVariantKey,- conclusion: values.experiment.conclusion,- conclusion_comment: values.experiment.conclusion_comment,- }- )- // @ts-expect-error legacy Experiment type is narrower than the generated ExperimentApi (type is non-null)- actions.setExperiment(response)- refreshTreeItem('experiment', String(values.experimentId))- actions.closeFinishExperimentModal()- lemonToast.success('Experiment ended. The selected variant has been rolled out to all users.')- } catch (error: any) {- actions.closeFinishExperimentModal()- lemonToast.error(error.detail || 'Failed to ship variant')- }- },- restoreUnmodifiedExperiment: () => {- if (values.unmodifiedExperiment) {- actions.setExperiment(values.unmodifiedExperiment)- }- },- refreshExperimentResults: async ({ forceRefresh }) => {- // Generate a unique refresh ID for tracking- const refreshId = generateRefreshId()-- // Always refresh both primary and secondary metrics- actions.loadPrimaryMetricsResults(forceRefresh, refreshId)- actions.loadSecondaryMetricsResults(forceRefresh, refreshId)- },- loadPrimaryMetricsResults: async ({ refresh, refreshId }) => {- const experiment = values.experiment- const metrics = [...experiment.metrics]- const savedMetricsPrimary = experiment.saved_metrics- .filter((sm) => sm.metadata.type === 'primary')- .map((sm) => sm.query)-- const allMetrics = [...metrics, ...savedMetricsPrimary]-- if (allMetrics.length === 0) {- actions.setPrimaryMetricsResultsLoading(false)- return- }-- try {- await loadLegacyMetrics({- metrics: allMetrics,- experimentId: experiment.id,- refresh,- teamId: values.currentTeamId,- refreshId: refreshId || generateRefreshId(),- isPrimary: true,- isRetry: false,- metricIndexOffset: 0,- orderedUuids: experiment.primary_metrics_ordered_uuids,- onSetLegacyResults: (results) => actions.setLegacyPrimaryMetricsResults(results),- onSetErrors: (errors) => actions.setPrimaryMetricsResultsErrors(errors),- })- } finally {- actions.setPrimaryMetricsResultsLoading(false)- }- },- loadSecondaryMetricsResults: async ({ refresh, refreshId }) => {- const experiment = values.experiment- const metrics = [...experiment.metrics_secondary]- const savedMetricsSecondary = experiment.saved_metrics- .filter((sm) => sm.metadata.type === 'secondary')- .map((sm) => sm.query)-- const allMetrics = [...metrics, ...savedMetricsSecondary]-- if (allMetrics.length === 0) {- actions.setSecondaryMetricsResultsLoading(false)- return- }-- const savedMetricsPrimary = experiment.saved_metrics.filter((sm) => sm.metadata.type === 'primary')-- try {- await loadLegacyMetrics({- metrics: allMetrics,- experimentId: experiment.id,- refresh,- teamId: values.currentTeamId,- refreshId: refreshId || generateRefreshId(),- isPrimary: false,- isRetry: false,- metricIndexOffset: experiment.metrics.length + savedMetricsPrimary.length,- orderedUuids: experiment.secondary_metrics_ordered_uuids,- onSetLegacyResults: (results) => actions.setLegacySecondaryMetricsResults(results),- onSetErrors: (errors) => actions.setSecondaryMetricsResultsErrors(errors),- })- } finally {- actions.setSecondaryMetricsResultsLoading(false)- }- },- })),-])diff --git a/products/experiments/frontend/legacy/legacyExperimentModalsLogic.ts b/products/experiments/frontend/legacy/legacyExperimentModalsLogic.tsdeleted file mode 100644index f7fc70d4b320..000000000000--- a/products/experiments/frontend/legacy/legacyExperimentModalsLogic.ts+++ /dev/null@@ -1,166 +0,0 @@-import { MakeLogicType, actions, kea, path, reducers } from 'kea'--import { SharedMetric } from 'scenes/experiments/SharedMetrics/sharedMetricLogic'--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface legacyExperimentModalsLogicValues {- isPrimaryMetricModalOpen: boolean- isPrimaryMetricSourceModalOpen: boolean- isPrimarySharedMetricModalOpen: boolean- isSecondaryMetricModalOpen: boolean- isSecondaryMetricSourceModalOpen: boolean- isSecondarySharedMetricModalOpen: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface legacyExperimentModalsLogicActions {- closePrimaryMetricModal: () => {- value: true- }- closePrimaryMetricSourceModal: () => {- value: true- }- closePrimarySharedMetricModal: () => {- value: true- }- closeSecondaryMetricModal: () => {- value: true- }- closeSecondaryMetricSourceModal: () => {- value: true- }- closeSecondarySharedMetricModal: () => {- value: true- }- openPrimaryMetricModal: (uuid: string) => {- uuid: string- }- openPrimaryMetricSourceModal: () => {- value: true- }- openPrimarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => {- sharedMetricId: number | null- }- openSecondaryMetricModal: (uuid: string) => {- uuid: string- }- openSecondaryMetricSourceModal: () => {- value: true- }- openSecondarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => {- sharedMetricId: number | null- }-}--export type legacyExperimentModalsLogicType = MakeLogicType<- legacyExperimentModalsLogicValues,- legacyExperimentModalsLogicActions->--/**- * @deprecated- * This logic manages modal state for legacy experiments (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * For modern experiments, use modalsLogic.- *- * Only includes modals that legacy experiments actually use:- * - Description editing- * - Conclusion editing- * - Stats engine viewing- * - Shared metric management- * - Custom metric viewing (read-only)- * - Metric source selection- *- * Does NOT include (modern experiment only):- * - Collection goal modal- * - Conclusion editing modal- * - Exposure criteria modal- * - Distribution modal- * - Release conditions modal- * - Running time calculator modal- * - Metrics reorder modals- * - Finish/Pause/Resume experiment modals (these are shared from main logic)- * - Variant delta timeseries modal- */-export const legacyExperimentModalsLogic = kea<legacyExperimentModalsLogicType>([- path(['scenes', 'experiments', 'legacy', 'legacyExperimentModalsLogic']),- actions({- // Shared metrics - Primary- openPrimarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => ({ sharedMetricId }),- closePrimarySharedMetricModal: true,-- // Shared metrics - Secondary- openSecondarySharedMetricModal: (sharedMetricId: SharedMetric['id'] | null) => ({ sharedMetricId }),- closeSecondarySharedMetricModal: true,-- // Custom metrics - Primary (read-only viewing)- openPrimaryMetricModal: (uuid: string) => ({ uuid }),- closePrimaryMetricModal: true,-- // Custom metrics - Secondary (read-only viewing)- openSecondaryMetricModal: (uuid: string) => ({ uuid }),- closeSecondaryMetricModal: true,-- // Metric source selection - Primary- openPrimaryMetricSourceModal: true,- closePrimaryMetricSourceModal: true,-- // Metric source selection - Secondary- openSecondaryMetricSourceModal: true,- closeSecondaryMetricSourceModal: true,- }),- reducers({- // Primary shared metric modal state- isPrimarySharedMetricModalOpen: [- false,- {- openPrimarySharedMetricModal: () => true,- closePrimarySharedMetricModal: () => false,- },- ],-- // Secondary shared metric modal state- isSecondarySharedMetricModalOpen: [- false,- {- openSecondarySharedMetricModal: () => true,- closeSecondarySharedMetricModal: () => false,- },- ],-- // Primary metric modal state (read-only)- isPrimaryMetricModalOpen: [- false,- {- openPrimaryMetricModal: () => true,- closePrimaryMetricModal: () => false,- },- ],-- // Secondary metric modal state (read-only)- isSecondaryMetricModalOpen: [- false,- {- openSecondaryMetricModal: () => true,- closeSecondaryMetricModal: () => false,- },- ],-- // Primary metric source modal state- isPrimaryMetricSourceModalOpen: [- false,- {- openPrimaryMetricSourceModal: () => true,- closePrimaryMetricSourceModal: () => false,- },- ],-- // Secondary metric source modal state- isSecondaryMetricSourceModalOpen: [- false,- {- openSecondaryMetricSourceModal: () => true,- closeSecondaryMetricSourceModal: () => false,- },- ],- }),-])diff --git a/products/experiments/frontend/legacy/legacyUtils.ts b/products/experiments/frontend/legacy/legacyUtils.tsdeleted file mode 100644index b6f92d5454b0..000000000000--- a/products/experiments/frontend/legacy/legacyUtils.ts+++ /dev/null@@ -1,208 +0,0 @@-import {- ExperimentTrendsQuery,- ExperimentFunnelsQuery,- NodeKind,- CachedLegacyExperimentQueryResponse,- CachedExperimentFunnelsQueryResponse,- CachedExperimentTrendsQueryResponse,-} from '~/queries/schema/schema-general'-import {- CountPerActorMathType,- Experiment,- FunnelExperimentVariant,- InsightType,- PropertyMathType,- TrendExperimentVariant,-} from '~/types'--import { legacyGetSignificanceDetails } from './calculations/legacyExperimentCalculations'--/**- * @deprecated- * Use the getInsightType function from the experimentLogic instead.- */-export const getInsightType = (- metric: ExperimentTrendsQuery | ExperimentFunnelsQuery | undefined | null-): InsightType => {- return metric?.kind === NodeKind.ExperimentTrendsQuery ? InsightType.TRENDS : InsightType.FUNNELS-}--/**- * @deprecated- * Use the tabularExperimentResults function from the experimentLogic instead.- */-export const getTabularExperimentResults =- (- experiment: Experiment,- legacyPrimaryMetricsResults: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | null- )[],- legacySecondaryMetricsResults: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | null- )[],- getInsightType: (metric: ExperimentTrendsQuery | ExperimentFunnelsQuery | undefined | null) => InsightType- ) =>- (metricIdentifier: number | string = 0, isSecondary: boolean = false): any[] => {- let index: number- if (typeof metricIdentifier === 'string') {- // Find index by UUID- const metrics = isSecondary ? experiment.metrics_secondary : experiment.metrics- index = metrics.findIndex((m) => m.uuid === metricIdentifier)- if (index === -1) {- return []- }- } else {- index = metricIdentifier- }-- const tabularResults = []- const metricType = isSecondary- ? getInsightType(- experiment.metrics_secondary?.[index] as ExperimentTrendsQuery | ExperimentFunnelsQuery | undefined- )- : getInsightType(experiment.metrics?.[index] as ExperimentTrendsQuery | ExperimentFunnelsQuery | undefined)- const result = isSecondary ? legacySecondaryMetricsResults?.[index] : legacyPrimaryMetricsResults?.[index]-- if (result) {- for (const variantObj of result.variants) {- if (metricType === InsightType.FUNNELS) {- const { key, success_count, failure_count } = variantObj as FunnelExperimentVariant- tabularResults.push({ key, success_count, failure_count })- } else if (metricType === InsightType.TRENDS) {- const { key, count, exposure, absolute_exposure } = variantObj as TrendExperimentVariant- tabularResults.push({ key, count, exposure, absolute_exposure })- }- }- }-- if (experiment.feature_flag?.filters.multivariate?.variants) {- for (const { key } of experiment.feature_flag.filters.multivariate.variants) {- if (tabularResults.find((variantObj) => variantObj.key === key)) {- continue- }-- if (metricType === InsightType.FUNNELS) {- tabularResults.push({ key, success_count: null, failure_count: null })- } else if (metricType === InsightType.TRENDS) {- tabularResults.push({ key, count: null, exposure: null, absolute_exposure: null })- }- }- }-- return tabularResults- }--export const getExperimentMathAggregationForTrends = (- experiment: Experiment-): PropertyMathType | CountPerActorMathType | undefined => {- const query = experiment?.metrics?.[0] as ExperimentTrendsQuery- if (!query) {- return undefined- }- const entities = query.count_query?.series || []-- // Find out if we're using count per actor math aggregates averages per user- const userMathValue = entities.filter((entity) =>- Object.values(CountPerActorMathType).includes(entity?.math as CountPerActorMathType)- )[0]?.math-- // alternatively, if we're using property math- // remove 'sum' property math from the list of math types- // since we can handle that as a regular case- const targetValues = Object.values(PropertyMathType).filter((value) => value !== PropertyMathType.Sum)-- const propertyMathValue = entities.filter((entity) =>- (targetValues as readonly PropertyMathType[]).includes(entity?.math as PropertyMathType)- )[0]?.math-- return (userMathValue ?? propertyMathValue) as PropertyMathType | CountPerActorMathType | undefined-}--/**- * @deprecated- * Use the getIsPrimaryMetricSignificant function from the experimentLogic instead.- */-export const getIsPrimaryMetricSignificant =- (- legacyPrimaryMetricsResults: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | null- )[],- experiment: Experiment- ) =>- (metricUuid: string): boolean => {- // Find metric index by UUID- const index = experiment.metrics.findIndex((m) => m.uuid === metricUuid)- if (index === -1) {- return false- }-- const result = legacyPrimaryMetricsResults?.[index]- if (!result) {- return false- }-- return result.significant || false- }--/**- * @deprecated- * Use the getIsSecondaryMetricSignificant function from the experimentLogic instead.- */-export const getIsSecondaryMetricSignificant =- (- legacySecondaryMetricsResults: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | null- )[],- experiment: Experiment- ) =>- (metricUuid: string): boolean => {- // Find metric index by UUID- const index = experiment.metrics_secondary.findIndex((m) => m.uuid === metricUuid)- if (index === -1) {- return false- }-- const result = legacySecondaryMetricsResults?.[index]- if (!result) {- return false- }-- return result.significant || false- }--/**- * @deprecated- * Use the getSignificanceDetails function from the experimentLogic instead.- */-export const getSignificanceDetails =- (- legacyPrimaryMetricsResults: (- | CachedLegacyExperimentQueryResponse- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse- | null- )[],- experiment: Experiment- ) =>- (metricUuid: string): string => {- // Find metric index by UUID- const index = experiment.metrics.findIndex((m) => m.uuid === metricUuid)- if (index === -1) {- return ''- }-- const results = legacyPrimaryMetricsResults?.[index]- return legacyGetSignificanceDetails(results)- }diff --git a/products/experiments/frontend/legacy/metricsView/LegacyChartEmptyState.tsx b/products/experiments/frontend/legacy/metricsView/LegacyChartEmptyState.tsxdeleted file mode 100644index cf7a8ba9332b..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyChartEmptyState.tsx+++ /dev/null@@ -1,56 +0,0 @@-import { IconClock } from '@posthog/icons'-import { LemonTag } from '@posthog/lemon-ui'--import { ExperimentFunnelsQuery, ExperimentTrendsQuery } from '~/queries/schema/schema-general'--import { LegacyErrorChecklist } from './LegacyErrorChecklist'--interface LegacyChartEmptyStateProps {- height: number- experimentStarted: boolean- metric: ExperimentTrendsQuery | ExperimentFunnelsQuery- error?: any-}--/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * For new experiments, use the modern ChartEmptyState component.- */-export function LegacyChartEmptyState({- height,- experimentStarted,- error,- metric,-}: LegacyChartEmptyStateProps): JSX.Element | null {- /**- * early return if experiment has not started- */- if (!experimentStarted) {- return (- <div className="flex items-center justify-center text-secondary cursor-default text-[12px] font-normal">- <LemonTag size="small" className="mr-2">- <IconClock fontSize="1em" />- </LemonTag>- <span>Waiting for experiment to start…</span>- </div>- )- }-- /**- * bail if no error- */- if (!error) {- return null- }-- /**- * Legacy metrics always use the legacy error checklist- */- return (- // eslint-disable-next-line react/forbid-dom-props- <div className="flex items-center justify-center w-full" style={{ height: `${height}px` }}>- <LegacyErrorChecklist error={error} metric={metric} />- </div>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyChartLoadingState.tsx b/products/experiments/frontend/legacy/metricsView/LegacyChartLoadingState.tsxdeleted file mode 100644index c2dda56a53a0..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyChartLoadingState.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { Spinner } from 'lib/lemon-ui/Spinner'--interface LegacyChartLoadingStateProps {- height: number-}--/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyChartLoadingState({ height }: LegacyChartLoadingStateProps): JSX.Element {- return (- <div- className="flex items-center justify-center gap-2 text-[14px] font-normal"- // eslint-disable-next-line react/forbid-dom-props- style={{ height: `${height}px` }}- >- <Spinner className="text-lg" />- <span>Loading results…</span>- </div>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyChartModal.tsx b/products/experiments/frontend/legacy/metricsView/LegacyChartModal.tsxdeleted file mode 100644index 4d564d6c1eb6..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyChartModal.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'--import { ExperimentFunnelsQuery, ExperimentTrendsQuery } from '~/queries/schema/schema-general'-import type { Experiment } from '~/types'--import {- LegacyExploreButton,- LegacyResultsQuery,- LegacySummaryTable,- LegacyWinningVariantText,- LegacySignificanceText,-} from 'products/experiments/frontend/legacy'--interface LegacyChartModalProps {- isOpen: boolean- onClose: () => void- metric: ExperimentTrendsQuery | ExperimentFunnelsQuery- displayOrder: number- isSecondary: boolean- result: any- experiment: Experiment-}--/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyChartModal({- isOpen,- onClose,- metric,- displayOrder,- isSecondary,- result,- experiment,-}: LegacyChartModalProps): JSX.Element {- // Get metric uuid from experiment metrics array using displayOrder- const metricsList = isSecondary ? experiment.metrics_secondary : experiment.metrics- const metricUuid = metricsList[displayOrder]?.uuid || ''-- return (- <LemonModal- isOpen={isOpen}- onClose={onClose}- width={1200}- title="Metric results"- footer={- <LemonButton type="secondary" onClick={onClose}>- Close- </LemonButton>- }- >- <div className="flex justify-end">- <LegacyExploreButton result={result} />- </div>- <LemonBanner type={result?.significant ? 'success' : 'info'} className="mb-4">- <div className="items-center inline-flex flex-wrap">- <LegacyWinningVariantText result={result} />- <LegacySignificanceText metricUuid={metricUuid} isSecondary={isSecondary} />- </div>- </LemonBanner>- <LegacySummaryTable metric={metric} displayOrder={displayOrder} isSecondary={isSecondary} />- <LegacyResultsQuery result={result} showTable={true} />- </LemonModal>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyDeltaChart.tsx b/products/experiments/frontend/legacy/metricsView/LegacyDeltaChart.tsxdeleted file mode 100644index 72d2de68bcd8..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyDeltaChart.tsx+++ /dev/null@@ -1,610 +0,0 @@-import { useValues } from 'kea'-import { createContext, useContext, useState } from 'react'--import { IconGraph } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'--import { Experiment, FunnelExperimentVariant, InsightType, TrendExperimentVariant } from '~/types'--import {- EXPERIMENT_MIN_EXPOSURES_FOR_RESULTS,- EXPERIMENT_MIN_METRIC_VALUE_FOR_RESULTS,-} from 'products/experiments/frontend/constants'-import { isLaunched } from 'products/experiments/frontend/experimentStatus'-import {- legacyCalculateDelta,- legacyConversionRateForVariant,- legacyCountDataForVariant,- legacyCredibleIntervalForVariant,- legacyExposureCountDataForVariant,- legacyExperimentLogic,- LegacyVariantTag,- LegacyChartEmptyState,- LegacyChartLoadingState,- LegacyChartModal,- useLegacyChartColors,- LegacyGridLines,- LegacyMetricHeader,- LegacyMetricsChartLayout,- LegacySignificanceHighlight,- LegacyVariantTooltip,- legacyGenerateViolinPath,-} from 'products/experiments/frontend/legacy'--// Chart configuration types-type ChartDimensions = {- barHeight: number- barPadding: number- viewBoxWidth: number- horizontalPadding: number- chartHeight: number-}--type TooltipState = {- tooltipData: { x: number; y: number; variant: string } | null- setTooltipData: (data: { x: number; y: number; variant: string } | null) => void- emptyStateTooltipVisible: boolean- setEmptyStateTooltipVisible: (visible: boolean) => void- tooltipPosition: { x: number; y: number }- setTooltipPosition: (position: { x: number; y: number }) => void-}--// Context containing all necessary data for child components-type DeltaChartContextType = {- // Chart properties- result: any- error: any- displayOrder: number- isSecondary: boolean- metricType: InsightType- metric: any- tickValues: number[]- chartBound: number-- // Experiment data- experiment: Experiment- variants: FunnelExperimentVariant[] | TrendExperimentVariant[]- primaryMetricsLengthWithSharedMetrics: number-- // Data transformation functions- valueToX: (value: number) => number- credibleIntervalForVariant: (result: any, variantKey: string, metricType: InsightType) => [number, number] | null- conversionRateForVariant: (result: any, variantKey: string) => number | null- countDataForVariant: (result: any, variantKey: string) => any- exposureCountDataForVariant: (result: any, variantKey: string) => any-- // Chart dimensions- dimensions: ChartDimensions-- // UI state & actions- isModalOpen: boolean- setIsModalOpen: (isOpen: boolean) => void- resultsLoading: boolean-- // Colors- colors: ReturnType<typeof useLegacyChartColors>-- // Tooltip state- tooltip: TooltipState-}--// Create context with default values-const DeltaChartContext = createContext<DeltaChartContextType | null>(null)--// Custom hook to use the chart context-function useDeltaChartContext(): DeltaChartContextType {- const context = useContext(DeltaChartContext)- if (!context) {- throw new Error('useDeltaChartContext must be used within a DeltaChartContextProvider')- }- return context-}--// Custom hook for calculating dimensions based on variant count-function useChartDimensions(variants: any[]): ChartDimensions {- const getScaleAddition = (variantCount: number): number => {- if (variantCount < 3) {- return 6- }- if (variantCount < 4) {- return 3- }- if (variantCount < 5) {- return 1- }- return 0- }-- const scaleAddition = getScaleAddition(variants.length)- const barHeight = 10 + scaleAddition- const barPadding = 10 + scaleAddition- const viewBoxWidth = 800- const horizontalPadding = 20-- // Calculate the chart height- const chartHeight = barPadding + (barHeight + barPadding) * variants.length-- return {- barHeight,- barPadding,- viewBoxWidth,- horizontalPadding,- chartHeight,- }-}--function hasEnoughDataForResults(variantExposureCount: number, variantMetricValue: number): boolean {- return (- variantExposureCount >= EXPERIMENT_MIN_EXPOSURES_FOR_RESULTS &&- variantMetricValue > EXPERIMENT_MIN_METRIC_VALUE_FOR_RESULTS- )-}--/**- * @deprecated- * Legacy variant bar component for DeltaChart.- * Frozen copy for legacy experiments - do not modify.- */-function VariantBar({ variant, index }: { variant: any; index: number }): JSX.Element {- const {- result,- metricType,- metric,- dimensions,- valueToX,- colors,- tooltip: { setTooltipData },- credibleIntervalForVariant,- isSecondary,- } = useDeltaChartContext()-- // Generate a unique ID for gradients using metric UUID or fallback to index- const metricId = metric?.uuid ? metric.uuid.slice(-8) : index-- const { barHeight, barPadding } = dimensions-- // Calculate interval and delta- const interval = credibleIntervalForVariant(result, variant.key, metricType)- const [lower, upper] = interval ? [interval[0] / 100, interval[1] / 100] : [0, 0]-- const deltaResult = legacyCalculateDelta(result, variant.key, metricType)- const delta = deltaResult?.delta || 0- let hasEnoughData: boolean-- if (metricType === InsightType.TRENDS) {- const controlVariant = result.variants.find((v: any) => v.key === 'control')- const variantData = result.variants.find((v: any) => v.key === variant.key)-- if (- !variantData?.count ||- !variantData?.absolute_exposure ||- !controlVariant?.count ||- !controlVariant?.absolute_exposure- ) {- hasEnoughData = false- } else {- hasEnoughData = hasEnoughDataForResults(variantData.absolute_exposure, variantData.count)- }- } else {- const variantData = result.variants.find((v: any) => v.key === variant.key)- if (!variantData) {- hasEnoughData = false- } else {- const total_exposures = variantData.failure_count + variantData.success_count- hasEnoughData = hasEnoughDataForResults(total_exposures, variantData.success_count)- }- }-- // Calculate positioning- const y = barPadding + (barHeight + barPadding) * index- const x1 = valueToX(lower)- const x2 = valueToX(upper)- const deltaX = valueToX(delta)-- return (- <g- key={variant.key}- onMouseEnter={(e) => {- const rect = e.currentTarget.getBoundingClientRect()- setTooltipData({- x: rect.left + rect.width / 2,- y: rect.top - 10,- variant: variant.key,- })- }}- onMouseLeave={() => setTooltipData(null)}- >- {/* Conditional rendering based on hasEnoughData */}- {hasEnoughData ? (- <>- {/* Add variant name using LegacyVariantTag */}- <foreignObject- x={x1 - 8} // Keep same positioning as the text element- y={y + barHeight / 2 - 10}- width="90"- height="16"- transform="translate(-90, 0)" // Move left to accommodate tag width- >- <LegacyVariantTag className="justify-end mt-0.5" variantKey={variant.key} fontSize={10} />- </foreignObject>- {variant.key === 'control' ? (- <path- d={legacyGenerateViolinPath(x1, x2, y, barHeight, deltaX)}- fill={colors.BAR_CONTROL}- stroke={colors.BOUNDARY_LINES}- strokeWidth={1}- strokeDasharray="2,2"- />- ) : (- <>- <defs>- <linearGradient- id={`gradient-${metricId}-${variant.key}-${isSecondary ? 'secondary' : 'primary'}`}- x1="0"- x2="1"- y1="0"- y2="0"- >- {lower < 0 && upper > 0 ? (- <>- <stop offset="0%" stopColor={colors.BAR_NEGATIVE} />- <stop- offset={`${(-lower / (upper - lower)) * 100}%`}- stopColor={colors.BAR_NEGATIVE}- />- <stop- offset={`${(-lower / (upper - lower)) * 100}%`}- stopColor={colors.BAR_POSITIVE}- />- <stop offset="100%" stopColor={colors.BAR_POSITIVE} />- </>- ) : (- <stop- offset="100%"- stopColor={upper <= 0 ? colors.BAR_NEGATIVE : colors.BAR_POSITIVE}- />- )}- </linearGradient>- </defs>- <path- d={legacyGenerateViolinPath(x1, x2, y, barHeight, deltaX)}- fill={`url(#gradient-${metricId}-${variant.key}-${- isSecondary ? 'secondary' : 'primary'- })`}- />- </>- )}-- {/* Delta marker */}- <g transform={`translate(${deltaX}, 0)`}>- <line- x1={0}- y1={y}- x2={0}- y2={y + barHeight}- stroke={- variant.key === 'control' ? colors.BAR_MIDDLE_POINT_CONTROL : colors.BAR_MIDDLE_POINT- }- strokeWidth={2}- vectorEffect="non-scaling-stroke"- shapeRendering="crispEdges"- />- </g>- </>- ) : (- /* Show "Not enough data" text when hasEnoughData is false */- <>- {/* Move foreignObject for variant tag to left of 0 point */}- <foreignObject x={valueToX(0) - 150} y={y + barHeight / 2 - 10} width="90" height="16">- <LegacyVariantTag className="justify-end mt-0.5" variantKey={variant.key} fontSize={10} />- </foreignObject>-- {/* First draw a solid background to cover grid lines */}- <rect- x={valueToX(0) - 50}- y={y + barHeight / 2 - 8}- width="100"- height="16"- rx="3"- ry="3"- fill="var(--color-bg-light)"- />- {/* Add grey background rectangle for the text */}- <rect- x={valueToX(0) - 50}- y={y + barHeight / 2 - 8}- width="100"- height="16"- rx="3"- ry="3"- fill="var(--border-light)"- strokeWidth="0"- />- {/* Center "Not enough data yet" text on the 0 point */}- <text- x={valueToX(0)}- y={y + barHeight / 2}- fontSize="10"- textAnchor="middle"- dominantBaseline="middle"- fill="var(--muted)"- >- Not enough data yet- </text>- </>- )}- </g>- )-}--// Chart SVG component-function ChartSVG({ chartSvgRef }: { chartSvgRef: React.RefObject<SVGSVGElement> }): JSX.Element {- const { dimensions, tickValues, valueToX, variants } = useDeltaChartContext()- const { viewBoxWidth, chartHeight } = dimensions-- return (- <div className="flex justify-center">- <svg- ref={chartSvgRef}- viewBox={`0 0 ${viewBoxWidth} ${chartHeight}`}- preserveAspectRatio="xMidYMid meet"- className="ml-12 max-w-[1000px]"- // eslint-disable-next-line react/forbid-dom-props- style={{ minHeight: `${chartHeight}px` }} // Dynamic height based on variant count- >- {/* Create a group for the background elements */}- <g className="grid-lines-layer">- {/* Vertical grid lines */}- <LegacyGridLines tickValues={tickValues} valueToX={valueToX} height={chartHeight} />- </g>-- {/* Create a group for the variant bars with higher priority */}- <g className="variant-bars-layer">- {/* Render variant bars */}- {variants.map((variant, index) => (- <VariantBar key={variant.key} variant={variant} index={index} />- ))}- </g>- </svg>- </div>- )-}--// Chart controls component-function ChartControls(): JSX.Element {- const { displayOrder, isSecondary, primaryMetricsLengthWithSharedMetrics, setIsModalOpen, metric } =- useDeltaChartContext()-- return (- <>- {/* Chart is z-index 100, so we need to be above it */}- <div className="absolute top-2 left-2 z-[102]">- <LegacySignificanceHighlight- displayOrder={displayOrder}- isSecondary={isSecondary}- metricUuid={metric?.uuid}- />- </div>- {(isSecondary || (!isSecondary && primaryMetricsLengthWithSharedMetrics > 1)) && (- <div- className="absolute bottom-2 left-2 flex justify-center bg-[var(--color-bg-table)] z-[101]"- // Chart is z-index 100, so we need to be above it- >- <LemonButton- type="secondary"- size="xsmall"- icon={<IconGraph />}- onClick={() => setIsModalOpen(true)}- >- Details- </LemonButton>- </div>- )}- </>- )-}--// Tooltips component-function ChartTooltips(): JSX.Element {- const {- tooltip: { tooltipData },- result,- metricType,- conversionRateForVariant,- countDataForVariant,- exposureCountDataForVariant,- credibleIntervalForVariant,- } = useDeltaChartContext()-- return (- <>- {/* Variant result tooltip */}- {tooltipData && (- <LegacyVariantTooltip- tooltipData={tooltipData}- result={result}- metricType={metricType}- conversionRateForVariant={conversionRateForVariant}- countDataForVariant={countDataForVariant}- exposureCountDataForVariant={exposureCountDataForVariant}- credibleIntervalForVariant={credibleIntervalForVariant}- />- )}- </>- )-}--/**- * @deprecated- * Legacy main chart content component for DeltaChart.- * Frozen copy for legacy experiments - do not modify.- */-function DeltaChartContent({ chartSvgRef }: { chartSvgRef: React.RefObject<SVGSVGElement> }): JSX.Element {- const { result, metric, resultsLoading, experiment, error, dimensions } = useDeltaChartContext()-- const { chartHeight } = dimensions-- if (result) {- return (- <div className="relative w-full max-w-screen">- <ChartControls />- <ChartSVG chartSvgRef={chartSvgRef} />- <ChartTooltips />- </div>- )- } else if (resultsLoading) {- return <LegacyChartLoadingState height={chartHeight} />- }-- return (- <div className="relative w-full max-w-screen">- <LegacyChartEmptyState- height={chartHeight}- experimentStarted={isLaunched(experiment)}- metric={metric}- error={error}- />- </div>- )-}--/**- * @deprecated- * Legacy main DeltaChart component.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyDeltaChart({- isSecondary,- result,- error,- variants,- metricType,- displayOrder,- isFirstMetric,- metric,- tickValues,- chartBound,-}: {- isSecondary: boolean- result: any- error: any- variants: any[]- metricType: InsightType- displayOrder: number- isFirstMetric: boolean- metric: any- tickValues: number[]- chartBound: number-}): JSX.Element {- // Get values from logic- const { experiment, primaryMetricsResultsLoading, secondaryMetricsResultsLoading } =- useValues(legacyExperimentLogic)-- const primaryMetricsLengthWithSharedMetrics =- experiment.metrics.length +- experiment.saved_metrics.filter((metric) => metric.metadata.type === 'primary').length-- // Loading state- const resultsLoading = isSecondary ? secondaryMetricsResultsLoading : primaryMetricsResultsLoading-- // Chart dimensions- const dimensions = useChartDimensions(variants)- const { viewBoxWidth: VIEW_BOX_WIDTH, horizontalPadding: HORIZONTAL_PADDING } = dimensions-- // Colors- const colors = useLegacyChartColors()-- // Modal state- const [isModalOpen, setIsModalOpen] = useState(false)-- // Tooltip state- const [tooltipData, setTooltipData] = useState<{ x: number; y: number; variant: string } | null>(null)- const [emptyStateTooltipVisible, setEmptyStateTooltipVisible] = useState(false)- const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 })-- // Value to X coordinate function- const valueToX = (value: number): number => {- // Scale the value to fit within the padded area- const percentage = (value / chartBound + 1) / 2- return HORIZONTAL_PADDING + percentage * (VIEW_BOX_WIDTH - 2 * HORIZONTAL_PADDING)- }-- // Metric title panel- const metricTitlePanel = <LegacyMetricHeader displayOrder={displayOrder} metric={metric} metricType={metricType} />-- // Chart content function that receives the ref from layout- const chartContent = (chartSvgRef: React.RefObject<SVGSVGElement>): JSX.Element => (- <DeltaChartContent chartSvgRef={chartSvgRef} />- )-- // Create context value- const contextValue: DeltaChartContextType = {- // Chart properties- result,- error,- displayOrder,- isSecondary,- metricType,- metric,- tickValues,- chartBound,-- // Experiment data- experiment,- variants,- primaryMetricsLengthWithSharedMetrics,-- // Data transformation functions- valueToX,- credibleIntervalForVariant: legacyCredibleIntervalForVariant,- conversionRateForVariant: legacyConversionRateForVariant,- countDataForVariant: legacyCountDataForVariant,- exposureCountDataForVariant: legacyExposureCountDataForVariant,-- // Chart dimensions- dimensions,-- // UI state & actions- isModalOpen,- setIsModalOpen,- resultsLoading,-- // Colors- colors,-- // Tooltip state- tooltip: {- tooltipData,- setTooltipData,- emptyStateTooltipVisible,- setEmptyStateTooltipVisible,- tooltipPosition,- setTooltipPosition,- },- }-- return (- <DeltaChartContext.Provider value={contextValue}>- <LegacyMetricsChartLayout- isFirstMetric={isFirstMetric}- tickValues={tickValues}- chartBound={chartBound}- metricTitlePanel={metricTitlePanel}- chartContent={chartContent}- viewBoxWidth={VIEW_BOX_WIDTH}- horizontalPadding={HORIZONTAL_PADDING}- />-- {/* Modal for metric details */}- <LegacyChartModal- isOpen={isModalOpen}- onClose={() => setIsModalOpen(false)}- metric={metric}- displayOrder={displayOrder}- isSecondary={isSecondary}- result={result}- experiment={experiment}- />- </DeltaChartContext.Provider>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyErrorChecklist.tsx b/products/experiments/frontend/legacy/metricsView/LegacyErrorChecklist.tsxdeleted file mode 100644index 9939ab1df92c..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyErrorChecklist.tsx+++ /dev/null@@ -1,174 +0,0 @@-import { useValues } from 'kea'-import { combineUrl } from 'kea-router/lib/utils'--import { IconCheck, IconX } from '@posthog/icons'-import { Link, Tooltip } from '@posthog/lemon-ui'--import { IconOpenInNew } from 'lib/lemon-ui/icons'-import { urls } from 'scenes/urls'--import { NodeKind } from '~/queries/schema/schema-general'-import { getExperimentVariants } from '~/scenes/experiments/utils'-import { ActivityTab, InsightType } from '~/types'--import { getInsightType, legacyExperimentLogic } from 'products/experiments/frontend/legacy'--export enum ResultErrorCode {- NO_CONTROL_VARIANT = 'no-control-variant',- NO_TEST_VARIANT = 'no-test-variant',- NO_EXPOSURES = 'no-exposures',-}--/**- * @deprecated Only on Legacy Experiments. Use the ErrorChecklist component instead.- */-function ChecklistItem({- errorCode,- value,- experiment,- variants,- getInsightType,- metric,-}: {- errorCode: ResultErrorCode- value: boolean- experiment: any- variants: any[]- getInsightType: (metric: any) => InsightType- metric: any-}): JSX.Element {- const failureText: Record<ResultErrorCode, string> = {- [ResultErrorCode.NO_CONTROL_VARIANT]: 'Events with the control variant not received',- [ResultErrorCode.NO_TEST_VARIANT]: 'Events with at least one test variant not received',- [ResultErrorCode.NO_EXPOSURES]: 'Exposure events not received',- }-- const successText: Record<ResultErrorCode, string> = {- [ResultErrorCode.NO_CONTROL_VARIANT]: 'Events with the control variant received',- [ResultErrorCode.NO_TEST_VARIANT]: 'Events with at least one test variant received',- [ResultErrorCode.NO_EXPOSURES]: 'Exposure events have been received',- }-- const insightType = getInsightType(metric)- const hasMissingExposure = errorCode === ResultErrorCode.NO_EXPOSURES-- const requiredEvent =- insightType === InsightType.TRENDS- ? hasMissingExposure- ? metric.exposure_query?.series[0]?.event || '$feature_flag_called'- : metric.count_query?.series[0]?.event- : metric.funnels_query?.series[0]?.event-- const query = {- kind: NodeKind.DataTableNode,- full: true,- source: {- kind: NodeKind.EventsQuery,- select: ['*', 'event', `properties."$feature/${experiment.feature_flag?.key}"`, 'timestamp'],- orderBy: ['timestamp DESC'],- after: experiment.start_date,- event: requiredEvent,- properties: [- {- key: `$feature/${experiment.feature_flag?.key}`,- value: hasMissingExposure- ? variants.map((variant: any) => variant.key)- : errorCode === ResultErrorCode.NO_CONTROL_VARIANT- ? ['control']- : variants.slice(1).map((variant: any) => variant.key),- operator: 'exact',- type: 'event',- },- ...(hasMissingExposure- ? [- {- key: '$feature_flag',- value: [experiment.feature_flag?.key],- operator: 'exact',- type: 'event',- },- ]- : []),- ],- filterTestAccounts: metric.count_query?.filter_test_accounts,- },- propertiesViaUrl: true,- showPersistentColumnConfigurator: true,- }-- return (- <div className="flex items-center deprecated-space-x-2">- {value === false ? (- <span className="flex items-center deprecated-space-x-2">- <IconCheck className="text-success" fontSize={16} />- <span className="text-secondary">{successText[errorCode]}</span>- </span>- ) : (- <span className="flex items-center deprecated-space-x-2">- <IconX className="text-danger" fontSize={16} />- <span>{failureText[errorCode]}</span>- <Tooltip title="Verify missing events in the Activity tab">- <Link- target="_blank"- className="font-semibold"- to={combineUrl(urls.activity(ActivityTab.ExploreEvents), {}, { q: query }).url}- >- <IconOpenInNew fontSize="16" className="-ml-1" />- </Link>- </Tooltip>- </span>- )}- </div>- )-}--export function LegacyErrorChecklist({ error, metric }: { error: any; metric: any }): JSX.Element {- const { experiment } = useValues(legacyExperimentLogic)-- if (!error) {- return <></>- }-- const variants = getExperimentVariants(experiment)-- const { statusCode, hasDiagnostics } = error-- if (hasDiagnostics) {- const checklistItems = []- for (const [errorCode, value] of Object.entries(error.detail as Record<ResultErrorCode, boolean>)) {- // Check if the error code is valid (cached response might still have old error codes)- if (!Object.values(ResultErrorCode).includes(errorCode as ResultErrorCode)) {- continue- }- checklistItems.push(- <ChecklistItem- key={errorCode}- errorCode={errorCode as ResultErrorCode}- value={value}- experiment={experiment}- variants={variants}- getInsightType={getInsightType}- metric={metric}- />- )- }-- return <div>{checklistItems}</div>- }-- if (statusCode === 504) {- return (- <>- <h2 className="text-xl font-semibold leading-tight">Experiment results timed out</h2>- <div className="text-sm text-center text-balance">- This may occur when the experiment has a large amount of data or is particularly complex. We are- actively working on fixing this. In the meantime, please try refreshing the experiment to retrieve- the results.- </div>- </>- )- }-- // Other unexpected errors- return <div>{error.detail}</div>-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyGridLines.tsx b/products/experiments/frontend/legacy/metricsView/LegacyGridLines.tsxdeleted file mode 100644index c882f125bdf3..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyGridLines.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { LEGACY_COLORS } from './legacyColors'--interface LegacyGridLinesProps {- tickValues: number[]- valueToX: (value: number) => number- height: number-}--/**- * @deprecated- * This component supports legacy experiment metrics.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyGridLines({ tickValues, valueToX, height }: LegacyGridLinesProps): JSX.Element {- return (- <>- {tickValues.map((value) => {- const x = valueToX(value)- return (- <line- key={value}- x1={x}- y1={0}- x2={x}- y2={height}- stroke={value === 0 ? LEGACY_COLORS.ZERO_LINE : LEGACY_COLORS.BOUNDARY_LINES}- strokeWidth={value === 0 ? 1 : 0.5}- />- )- })}- </>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyMetricHeader.tsx b/products/experiments/frontend/legacy/metricsView/LegacyMetricHeader.tsxdeleted file mode 100644index d54a2a3b6d35..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyMetricHeader.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { LemonTag } from '@posthog/lemon-ui'--import type { ExperimentFunnelsQuery, ExperimentTrendsQuery } from '~/queries/schema/schema-general'-import { NodeKind } from '~/queries/schema/schema-general'-import { InsightType } from '~/types'--import { LegacyMetricTitle } from './LegacyMetricTitle'--// Type for legacy metrics that may have optional shared metric properties-type LegacyMetricWithOptionalShared = (ExperimentTrendsQuery | ExperimentFunnelsQuery) & {- isSharedMetric?: boolean- sharedMetricId?: number-}--function getMetricTag(metric: LegacyMetricWithOptionalShared): string {- if (metric.kind === NodeKind.ExperimentFunnelsQuery) {- return 'Funnel'- }- return 'Trend'-}--/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * Frozen copy for legacy experiments - do not modify.- *- * Note: Legacy experiments do not support editing, duplication, or shared metrics.- * These features were added after legacy experiment format.- */-export const LegacyMetricHeader = ({- displayOrder,- metric,- metricType,-}: {- displayOrder?: number- metric: LegacyMetricWithOptionalShared- metricType: InsightType-}): JSX.Element => {- return (- <div className="text-xs font-semibold flex flex-col justify-between h-full">- <div className="deprecated-space-y-1">- <div className="flex items-start justify-between gap-2 min-w-0">- <div className="text-xs font-semibold flex items-start min-w-0 flex-1">- {displayOrder !== undefined && <span className="mr-1 flex-shrink-0">{displayOrder + 1}.</span>}- <div className="min-w-0 flex-1">- <LegacyMetricTitle metric={metric} metricType={metricType} />- </div>- </div>- </div>- <div className="deprecated-space-x-1">- <LemonTag type="muted" size="small">- {getMetricTag(metric)}- </LemonTag>- {metric.isSharedMetric && (- <LemonTag type="option" size="small">- Shared- </LemonTag>- )}- </div>- </div>- </div>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyMetricTitle.tsx b/products/experiments/frontend/legacy/metricsView/LegacyMetricTitle.tsxdeleted file mode 100644index 75a998969a8a..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyMetricTitle.tsx+++ /dev/null@@ -1,69 +0,0 @@-import { IconArrowRight, IconFunnels } from '@posthog/icons'-import { Tooltip } from '@posthog/lemon-ui'--import { InsightType } from '~/types'--/**- * @deprecated- * This component supports legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * Frozen copy for legacy experiments - do not modify.- */-export const LegacyMetricTitle = ({- metric,- metricType,- singleLine,-}: {- metric: any- metricType?: InsightType- singleLine?: boolean-}): JSX.Element => {- const shouldShowTooltip = (text: string): boolean => {- // Show tooltip for longer text that might be clamped- return text.length > 50- }-- const getTextClassName = (text: string): string => {- if (singleLine) {- return 'truncate block'- }- // Use break-words for text with spaces, break-all for underscore-separated text- const breakClass = text.includes(' ') ? 'break-words' : 'break-all'- return `line-clamp-3 ${breakClass}`- }-- const wrapWithTooltip = (text: string, element: JSX.Element): JSX.Element => {- if (shouldShowTooltip(text)) {- return <Tooltip title={text}>{element}</Tooltip>- }- return element- }-- if (metricType === InsightType.TRENDS && metric.count_query?.series?.[0]?.name) {- const name = metric.count_query.series[0].name- const element = <span className={getTextClassName(name)}>{name}</span>- return wrapWithTooltip(name, element)- }-- if (metricType === InsightType.FUNNELS && metric.funnels_query?.series) {- const series = metric.funnels_query.series- if (series.length > 0) {- const firstStep = series[0]?.name- const lastStep = series[series.length - 1]?.name-- return (- <div className="inline-flex flex-wrap items-center gap-1 min-w-0">- <div className="inline-flex items-center gap-1 min-w-0">- <IconFunnels className="text-secondary flex-shrink-0" fontSize="14" />- {wrapWithTooltip(firstStep, <span className={getTextClassName(firstStep)}>{firstStep}</span>)}- </div>- <div className="inline-flex items-center gap-1 min-w-0 @max-[200px]:ml-5">- <IconArrowRight className="text-secondary flex-shrink-0" fontSize="14" />- {wrapWithTooltip(lastStep, <span className={getTextClassName(lastStep)}>{lastStep}</span>)}- </div>- </div>- )- }- }-- return <span className={`text-secondary ${getTextClassName('Untitled metric')}`}>Untitled metric</span>-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyMetricsChartLayout.tsx b/products/experiments/frontend/legacy/metricsView/LegacyMetricsChartLayout.tsxdeleted file mode 100644index 1537ff349189..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyMetricsChartLayout.tsx+++ /dev/null@@ -1,99 +0,0 @@-import { ReactNode } from 'react'--import { useLegacySvgResizeObserver } from '../hooks/useLegacySvgResizeObserver'-import { LegacyTickPanel } from './LegacyTickPanel'-import { legacyValueToXCoordinate } from './legacyUtils'--interface LegacyMetricsChartLayoutProps {- isFirstMetric: boolean- tickValues: number[]- chartBound: number- metricTitlePanel: ReactNode- chartContent: ReactNode | ((chartSvgRef: React.RefObject<SVGSVGElement>) => JSX.Element)- viewBoxWidth?: number- horizontalPadding?: number- tickPanelHeight?: number-}--/**- * @deprecated- * Reusable component to handle the layout and animation concerns for metric charts- * This component extracts the `isFirstMetric` logic from DeltaChart- */-export function LegacyMetricsChartLayout({- isFirstMetric,- tickValues,- chartBound,- metricTitlePanel,- chartContent,- viewBoxWidth = 800,- horizontalPadding = 20,- tickPanelHeight = 20,-}: LegacyMetricsChartLayoutProps): JSX.Element {- // Use the shared resize observer hook to maintain synchronized heights- // This hook is responsible for the animation effects when metrics are added/removed- const { ticksSvgRef, chartSvgRef, ticksSvgHeight, chartSvgHeight } = useLegacySvgResizeObserver([- tickValues,- chartBound,- ])-- const valueToX = (value: number): number =>- legacyValueToXCoordinate(value, chartBound, viewBoxWidth, horizontalPadding)-- // Ensure a minimum height for the title panel even when chart is empty/error state- const metricTitlePanelHeight = Math.max(chartSvgHeight, 80)-- return (- <div className="rounded bg-[var(--color-bg-table)]">- <div className="flex">- {/* Metric title panel - 20% width with right border */}- <div className="w-1/5 border-r border-primary">- {isFirstMetric && (- <>- {/* Spacer div to match tick panel height */}- <div- // eslint-disable-next-line react/forbid-dom-props- style={{ height: `${ticksSvgHeight}px` }}- />- <div className="w-full border-t border-primary" />- </>- )}-- {/* Container for metric title that will match the chart height */}- <div- className="p-2"- // eslint-disable-next-line react/forbid-dom-props- style={{ height: `${metricTitlePanelHeight}px` }}- >- {metricTitlePanel}- </div>- </div>-- {/* SVGs container - 80% width */}- <div className="w-4/5 min-w-[780px]">- {/* Ticks */}- {isFirstMetric && (- <>- <div className="flex justify-center">- <LegacyTickPanel- svgRef={ticksSvgRef}- tickValues={tickValues}- valueToX={valueToX}- viewBoxWidth={viewBoxWidth}- tickPanelHeight={tickPanelHeight}- />- </div>- <div className="w-full border-t border-primary" />- </>- )}-- {/* Chart content panel with proper reference for animation */}- <div className="flex justify-center">- {/* Pass the SVG reference to the chart content */}- {typeof chartContent === 'function' ? chartContent(chartSvgRef) : chartContent}- </div>- </div>- </div>- </div>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyMetricsView.tsx b/products/experiments/frontend/legacy/metricsView/LegacyMetricsView.tsxdeleted file mode 100644index e812a776b71e..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyMetricsView.tsx+++ /dev/null@@ -1,201 +0,0 @@-import { useValues } from 'kea'--import { IconInfo } from '@posthog/icons'-import { LemonDivider, Tooltip } from '@posthog/lemon-ui'--import { IconAreaChart } from 'lib/lemon-ui/icons'--import { ExperimentFunnelsQuery, ExperimentTrendsQuery } from '~/queries/schema/schema-general'--import {- legacyCredibleIntervalForVariant,- LegacyDeltaChart,- legacyGetNiceTickValues,- getInsightType,- legacyExperimentLogic,-} from 'products/experiments/frontend/legacy'--/**- * @deprecated- * Legacy metrics view component.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyMetricsView({ isSecondary }: { isSecondary?: boolean }): JSX.Element {- const {- experiment,- legacyPrimaryMetricsResults,- legacySecondaryMetricsResults,- primaryMetricsResultsErrors,- secondaryMetricsResultsErrors,- } = useValues(legacyExperimentLogic)-- const variants = experiment?.feature_flag?.filters?.multivariate?.variants- if (!variants) {- return <></>- }-- const results = isSecondary ? legacySecondaryMetricsResults : legacyPrimaryMetricsResults-- const errors = isSecondary ? secondaryMetricsResultsErrors : primaryMetricsResultsErrors- const hasSomeResults = results?.some((result) => result?.insight)-- let metrics = isSecondary ? experiment.metrics_secondary : experiment.metrics- const sharedMetrics = experiment.saved_metrics- .filter((sharedMetric) => sharedMetric.metadata.type === (isSecondary ? 'secondary' : 'primary'))- .map((sharedMetric) => ({- ...sharedMetric.query,- name: sharedMetric.name,- sharedMetricId: sharedMetric.saved_metric,- isSharedMetric: true,- }))-- if (sharedMetrics) {- metrics = [...metrics, ...sharedMetrics]- }-- // Calculate the maximum absolute value across ALL metrics- const maxAbsValue = Math.max(- ...metrics.flatMap((metric, index) => {- const result = results?.[index]- if (!result) {- return []- }- return variants.flatMap((variant) => {- const insightType = getInsightType(metric as ExperimentTrendsQuery | ExperimentFunnelsQuery)- const interval = legacyCredibleIntervalForVariant(result, variant.key, insightType)- return interval ? [Math.abs(interval[0] / 100), Math.abs(interval[1] / 100)] : []- })- })- )-- const padding = Math.max(maxAbsValue * 0.05, 0.1)- const chartBound = maxAbsValue + padding-- const commonTickValues = legacyGetNiceTickValues(chartBound)-- return (- <div className="mb-4 -mt-2">- <div className="flex">- <div className="w-1/2 pt-5">- <div className="inline-flex items-center deprecated-space-x-2 mb-0">- <h2 className="mb-0 font-semibold text-lg leading-6">- {isSecondary ? 'Secondary metrics' : 'Primary metrics'}- </h2>- {metrics.length > 0 && (- <Tooltip- title={- isSecondary- ? 'Secondary metrics capture additional outcomes or behaviors affected by your experiment. They help you understand broader impacts and potential side effects beyond the primary goal.'- : 'Primary metrics represent the main goal of your experiment. They directly measure whether your hypothesis was successful and are the key factor in deciding if the test achieved its primary objective.'- }- >- <IconInfo className="text-secondary text-lg" />- </Tooltip>- )}- {hasSomeResults && !isSecondary && (- <>- <LemonDivider vertical className="mx-2" />- <Tooltip- title={- <div className="p-2">- <p className="mb-4">- Each bar shows how a variant is performing compared to the control (the- gray bar) for this metric, using a{' '}- <strong>95% credible interval.</strong> That means there's a 95% chance- the true difference for that variant falls within this range. The- vertical "0%" line is your baseline:- </p>- <ul className="mb-4 list-disc pl-4">- <li>- <strong>To the right (green):</strong> The metric is higher (an- improvement).- </li>- <li>- <strong>To the left (red):</strong> The metric is lower (a- decrease).- </li>- </ul>- <p className="mb-4">- The shape of each bar represents the probability distribution. The true- value is more likely to be near the center (where the bar is wider) than- at the edges (where it tapers off).- </p>- <p className="mb-4">- The control (baseline) is always shown in gray. Other bars will be green- or red—or even a mix—depending on whether the change is positive or- negative.- </p>- <img- src="https://res.cloudinary.com/dmukukwp6/image/upload/violin_plot_screenshot_acca775d36.png"- width={700}- className="rounded border object-contain"- alt="How to read metrics"- />- </div>- }- >- <span className="text-xs text-secondary cursor-help">How to read</span>- </Tooltip>- </>- )}- </div>- </div>-- <div className="w-1/2 flex flex-col justify-end" />- </div>- {metrics.length > 0 ? (- <div className="w-full overflow-x-auto">- <div className="min-w-[1000px]">- {metrics.map((metric, index) => {- const result = results?.[index]- const isFirstMetric = index === 0-- return (- <div- key={metric.uuid || index}- className={`w-full border border-primary bg-light ${- metrics.length === 1- ? 'rounded'- : isFirstMetric- ? 'rounded-t'- : index === metrics.length - 1- ? 'rounded-b'- : ''- }`}- >- <LegacyDeltaChart- isSecondary={!!isSecondary}- result={result}- error={errors?.[index]}- variants={variants}- metricType={getInsightType(- metric as ExperimentTrendsQuery | ExperimentFunnelsQuery- )}- displayOrder={index}- metric={metric}- isFirstMetric={isFirstMetric}- tickValues={commonTickValues}- chartBound={chartBound}- />- </div>- )- })}- </div>- </div>- ) : (- <div className="border rounded bg-surface-primary pt-6 pb-8 text-secondary mt-2">- <div className="flex flex-col items-center mx-auto deprecated-space-y-3">- <IconAreaChart fontSize="30" />- <div className="text-sm text-center text-balance max-w-sm">- <p>- {isSecondary- ? 'Secondary metrics provide additional context and help detect unintended side effects.'- : 'Primary metrics represent the main goal of the experiment and directly measure if your hypothesis was successful.'}- </p>- </div>- </div>- </div>- )}- </div>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyOverview.tsx b/products/experiments/frontend/legacy/metricsView/LegacyOverview.tsxdeleted file mode 100644index eb8d3c96ffc4..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyOverview.tsx+++ /dev/null@@ -1,116 +0,0 @@-import { useValues } from 'kea'--import {- CachedExperimentFunnelsQueryResponse,- CachedExperimentTrendsQueryResponse,- CachedLegacyExperimentQueryResponse,- ExperimentFunnelsQuery,- ExperimentTrendsQuery,- ExperimentMetric,-} from '~/queries/schema/schema-general'--import {- legacyGetHighestProbabilityVariant,- legacyGetIndexForVariant,- getInsightType,- LegacyVariantTag,- legacyExperimentLogic,- getIsPrimaryMetricSignificant,- getIsSecondaryMetricSignificant,-} from 'products/experiments/frontend/legacy'--/**- * @deprecated- * These components support legacy experiment metrics (ExperimentTrendsQuery/ExperimentFunnelsQuery).- * For new experiments, use the modern Overview components.- */-export function LegacyWinningVariantText({- result,-}: {- result:- | CachedLegacyExperimentQueryResponse- | CachedExperimentFunnelsQueryResponse- | CachedExperimentTrendsQueryResponse-}): JSX.Element {- const { experiment } = useValues(legacyExperimentLogic)-- const highestProbabilityVariant = legacyGetHighestProbabilityVariant(result)- const index = legacyGetIndexForVariant(- result,- highestProbabilityVariant || '',- getInsightType(experiment.metrics[0] as ExperimentTrendsQuery | ExperimentFunnelsQuery)- )- if (highestProbabilityVariant && index !== null && result) {- const { probability } = result-- return (- <div className="items-center inline-flex flex-wrap">- <LegacyVariantTag variantKey={highestProbabilityVariant} />- <span> is winning with a </span>- <span className="font-semibold items-center">- {`${(probability[highestProbabilityVariant] * 100).toFixed(2)}% probability`} - </span>- <span>of being best. </span>- </div>- )- }-- return <></>-}--/**- * @deprecated- * This component supports legacy experiment metrics.- * For new experiments, use the modern SignificanceText component.- */-export function LegacySignificanceText({- metricUuid,- isSecondary = false,-}: {- metricUuid: string- isSecondary?: boolean-}): JSX.Element {- const { experiment, legacyPrimaryMetricsResults, legacySecondaryMetricsResults } = useValues(legacyExperimentLogic)-- const isSecondaryMetricSignificant = getIsSecondaryMetricSignificant(legacySecondaryMetricsResults, experiment)- const isPrimaryMetricSignificant = getIsPrimaryMetricSignificant(legacyPrimaryMetricsResults, experiment)-- return (- <div className="flex-wrap">- <span>Your results are </span>- <span className="font-semibold">- {`${- (isSecondary ? isSecondaryMetricSignificant(metricUuid) : isPrimaryMetricSignificant(metricUuid))- ? 'significant'- : 'not significant'- }`}- .- </span>- </div>- )-}--/**- * @deprecated- */-export function LegacyOverview({ metricUuid }: { metricUuid: string }): JSX.Element {- const { legacyPrimaryMetricsResults, experiment } = useValues(legacyExperimentLogic)-- // Find metric index by UUID- const index = experiment.metrics.findIndex(- (m: ExperimentTrendsQuery | ExperimentFunnelsQuery | ExperimentMetric) => m.uuid === metricUuid- )- const result = index >= 0 ? legacyPrimaryMetricsResults?.[index] : null- if (!result) {- return <></>- }-- return (- <div>- <div className="items-center inline-flex flex-wrap">- <LegacyWinningVariantText result={result} />- <LegacySignificanceText metricUuid={metricUuid} />- </div>- </div>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacySignificanceHighlight.tsx b/products/experiments/frontend/legacy/metricsView/LegacySignificanceHighlight.tsxdeleted file mode 100644index 9c581b578f77..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacySignificanceHighlight.tsx+++ /dev/null@@ -1,85 +0,0 @@-import clsx from 'clsx'-import { useValues } from 'kea'--import { IconMinus, IconTrending } from '@posthog/icons'-import { LemonTagType, Tooltip } from '@posthog/lemon-ui'--import {- getIsPrimaryMetricSignificant,- getIsSecondaryMetricSignificant,- getSignificanceDetails,- legacyExperimentLogic,-} from 'products/experiments/frontend/legacy'--interface LegacySignificanceHighlightProps {- displayOrder?: number- metricUuid?: string- isSecondary?: boolean- className?: string-}--/**- * @deprecated- * Legacy significance highlight component.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacySignificanceHighlight({- displayOrder = 0,- metricUuid,- isSecondary = false,- className = '',-}: LegacySignificanceHighlightProps): JSX.Element {- const { experiment, legacyPrimaryMetricsResults, legacySecondaryMetricsResults } = useValues(legacyExperimentLogic)-- // Convert displayOrder to UUID if UUID not provided- let identifier = metricUuid- if (!identifier) {- const metrics = isSecondary ? experiment.metrics_secondary : experiment.metrics- identifier = metrics[displayOrder]?.uuid || ''- }-- if (!identifier) {- return <div className={className} />- }-- const significanceDetails = getSignificanceDetails(legacyPrimaryMetricsResults, experiment)- const isPrimaryMetricSignificant = getIsPrimaryMetricSignificant(legacyPrimaryMetricsResults, experiment)- const isSecondaryMetricSignificant = getIsSecondaryMetricSignificant(legacySecondaryMetricsResults, experiment)-- const isSignificant = isSecondary- ? isSecondaryMetricSignificant(identifier)- : isPrimaryMetricSignificant(identifier)- const result: { color: LemonTagType; label: string } = isSignificant- ? { color: 'success', label: 'Significant' }- : { color: 'primary', label: 'Not significant' }-- const inner = isSignificant ? (- <div className="bg-success-highlight text-success-light px-1.5 py-0.5 flex items-center gap-1 rounded border border-success-light">- <IconTrending fontSize={20} fontWeight={600} />- <span className="text-xs font-semibold">{result.label}</span>- </div>- ) : (- <div className="bg-warning-highlight text-warning-dark px-1.5 py-0.5 flex items-center gap-1 rounded border border-warning">- <IconMinus fontSize={20} fontWeight={600} />- <span className="text-xs font-semibold">{result.label}</span>- </div>- )-- const details = significanceDetails(identifier)-- return details ? (- <Tooltip title={details}>- <div- className={clsx({- 'cursor-default': true,- 'bg-[var(--color-bg-table)]': true,- [className]: true,- })}- >- {inner}- </div>- </Tooltip>- ) : (- <div className={clsx({ 'bg-[var(--color-bg-table)]': true, [className]: true })}>{inner}</div>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyTickPanel.tsx b/products/experiments/frontend/legacy/metricsView/LegacyTickPanel.tsxdeleted file mode 100644index dbff9f195b88..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyTickPanel.tsx+++ /dev/null@@ -1,56 +0,0 @@-import { LEGACY_COLORS } from './legacyColors'-import { legacyFormatTickValue } from './legacyUtils'--interface LegacyTickPanelProps {- tickValues: number[]- valueToX: (value: number) => number- viewBoxWidth: number- tickPanelHeight: number- svgRef?: React.RefObject<SVGSVGElement> // Optional ref for resize observation-}--/**- * @deprecated- * Legacy tick panel component for MetricsView.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyTickPanel({- tickValues,- valueToX,- viewBoxWidth,- tickPanelHeight,- svgRef,-}: LegacyTickPanelProps): JSX.Element {- const TICK_FONT_SIZE = 9- const colors = LEGACY_COLORS-- return (- <svg- ref={svgRef}- viewBox={`0 0 ${viewBoxWidth} ${tickPanelHeight}`}- preserveAspectRatio="xMidYMid meet"- className="ml-12 max-w-[1000px]"- // eslint-disable-next-line react/forbid-dom-props- style={{ minHeight: `${tickPanelHeight}px` }} // Dynamic height based on panel configuration- >- {tickValues.map((value) => {- const x = valueToX(value)- return (- <g key={value}>- <text- x={x}- y={tickPanelHeight / 2}- textAnchor="middle"- dominantBaseline="middle"- fontSize={TICK_FONT_SIZE}- fill={colors.TICK_TEXT_COLOR}- fontWeight="600"- >- {legacyFormatTickValue(value)}- </text>- </g>- )- })}- </svg>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/LegacyVariantTooltip.tsx b/products/experiments/frontend/legacy/metricsView/LegacyVariantTooltip.tsxdeleted file mode 100644index 4f811ddae9ca..000000000000--- a/products/experiments/frontend/legacy/metricsView/LegacyVariantTooltip.tsx+++ /dev/null@@ -1,149 +0,0 @@-import { LemonProgress } from 'lib/lemon-ui/LemonProgress'-import { humanFriendlyNumber } from 'lib/utils/numbers'--import { InsightType, TrendExperimentVariant } from '~/types'--import { legacyCalculateDelta } from '../calculations/legacyExperimentCalculations'-import { LegacyVariantTag } from '../components/LegacyVariantTag'--interface LegacyVariantTooltipProps {- tooltipData: {- x: number- y: number- variant: string- }- result: any- metricType: InsightType- conversionRateForVariant: (result: any, variant: string) => any- countDataForVariant: (result: any, variant: string) => any- exposureCountDataForVariant: (result: any, variant: string) => any- credibleIntervalForVariant: (result: any, variant: string, metricType: InsightType) => any-}--/**- * @deprecated- * Legacy variant tooltip component.- * Frozen copy for legacy experiments - do not modify.- */-export function LegacyVariantTooltip({- tooltipData,- result,- metricType,- conversionRateForVariant,- countDataForVariant,- exposureCountDataForVariant,- credibleIntervalForVariant,-}: LegacyVariantTooltipProps): JSX.Element {- return (- <div- className="fixed -translate-x-1/2 -translate-y-full bg-[var(--color-bg-surface-primary)] border border-[var(--color-border-primary)] px-3 py-2 rounded-md text-[13px] shadow-md pointer-events-none z-[103] min-w-[300px]"- // eslint-disable-next-line react/forbid-dom-props- style={{- left: tooltipData.x,- top: tooltipData.y,- }} // Dynamic positioning based on mouse hover position- >- <div className="flex flex-col gap-1">- <LegacyVariantTag variantKey={tooltipData.variant} />- <div className="inline-flex">- <span className="text-secondary font-semibold mb-1">Win probability:</span>- {result?.probability?.[tooltipData.variant] !== undefined ? (- <span className="flex items-center justify-between flex-1 pl-6">- <LemonProgress- className="w-3/4 mr-4"- percent={result.probability[tooltipData.variant] * 100}- />- <span className="font-semibold">- {(result.probability[tooltipData.variant] * 100).toFixed(2)}%- </span>- </span>- ) : (- <span>—</span>- )}- </div>- {metricType === InsightType.TRENDS ? (- <>- <div className="flex justify-between items-center">- <span className="text-secondary font-semibold">- {metricType === InsightType.TRENDS && result.exposure_query?.series?.[0]?.math ? (- <span>Total</span>- ) : (- <span>Count</span>- )}- <span>:</span>- </span>- <span className="font-semibold">- {(() => {- const count = countDataForVariant(result, tooltipData.variant)- return count !== null ? humanFriendlyNumber(count) : <span>—</span>- })()}- </span>- </div>- <div className="flex justify-between items-center">- <span className="text-secondary font-semibold">Exposure:</span>- <span className="font-semibold">- {(() => {- const exposure = exposureCountDataForVariant(result, tooltipData.variant)- return exposure !== null ? humanFriendlyNumber(exposure) : '—'- })()}- </span>- </div>- <div className="flex justify-between items-center">- <span className="text-secondary font-semibold">Mean:</span>- <span className="font-semibold">- {(() => {- const variant = result.variants.find(- (v: TrendExperimentVariant) => v.key === tooltipData.variant- )- return variant?.count && variant?.absolute_exposure- ? (variant.count / variant.absolute_exposure).toFixed(2)- : '—'- })()}- </span>- </div>- </>- ) : (- <div className="flex justify-between items-center">- <span className="text-secondary font-semibold">Conversion rate:</span>- <span className="font-semibold">- {conversionRateForVariant(result, tooltipData.variant)?.toFixed(2)}%- </span>- </div>- )}- <div className="flex justify-between items-center">- <span className="text-secondary font-semibold">Delta:</span>- <span className="font-semibold">- {tooltipData.variant === 'control' ? (- <em className="text-secondary">Baseline</em>- ) : (- (() => {- const deltaResult = legacyCalculateDelta(result, tooltipData.variant, metricType)- if (!deltaResult) {- return '—'- }-- return (- <span className={deltaResult.isPositive ? 'text-success' : 'text-danger'}>- {`${deltaResult.isPositive ? '+' : ''}${deltaResult.deltaPercent.toFixed(2)}%`}- </span>- )- })()- )}- </span>- </div>- <div className="flex justify-between items-center">- <span className="text-secondary font-semibold">Credible interval:</span>- <span className="font-semibold">- {(() => {- const interval = credibleIntervalForVariant(result, tooltipData.variant, metricType)- const [lower, upper] = interval ? [interval[0] / 100, interval[1] / 100] : [0, 0]- return `[${lower > 0 ? '+' : ''}${(lower * 100).toFixed(2)}%, ${upper > 0 ? '+' : ''}${(- upper * 100- ).toFixed(2)}%]`- })()}- </span>- </div>- </div>- </div>- )-}diff --git a/products/experiments/frontend/legacy/metricsView/legacyColors.ts b/products/experiments/frontend/legacy/metricsView/legacyColors.tsdeleted file mode 100644index 8aa9ed1ff30a..000000000000--- a/products/experiments/frontend/legacy/metricsView/legacyColors.ts+++ /dev/null@@ -1,61 +0,0 @@-import { useValues } from 'kea'--import { themeLogic } from '~/layout/navigation-3000/themeLogic'--/**- * @deprecated- * These color utilities support legacy experiment metrics.- * Frozen copy for legacy experiments - do not modify.- */--export interface LegacyChartColors {- TICK_TEXT_COLOR: string- BOUNDARY_LINES: string- ZERO_LINE: string- BAR_NEGATIVE: string- BAR_POSITIVE: string- BAR_DEFAULT: string- BAR_CONTROL: string- BAR_MIDDLE_POINT: string- BAR_MIDDLE_POINT_CONTROL: string- EXPOSURES_AXIS_LINES: string-}--/**- * @deprecated- * Use useChartColors instead.- */-export function useLegacyChartColors(): LegacyChartColors {- const { isDarkModeOn } = useValues(themeLogic)-- return {- TICK_TEXT_COLOR: 'var(--color-text-tertiary)',- BOUNDARY_LINES: 'var(--color-border-primary)',- ZERO_LINE: isDarkModeOn ? 'rgba(255, 255, 255, 0.35)' : 'rgba(0, 0, 0, 0.25)',- BAR_NEGATIVE: isDarkModeOn ? '#c32f45' : '#f84257',- BAR_POSITIVE: isDarkModeOn ? '#12a461' : '#36cd6f',- BAR_DEFAULT: isDarkModeOn ? 'rgb(121 121 121)' : 'rgb(217 217 217)',- BAR_CONTROL: isDarkModeOn ? 'rgba(217, 217, 217, 0.2)' : 'rgba(217, 217, 217, 0.4)',- BAR_MIDDLE_POINT: 'black',- BAR_MIDDLE_POINT_CONTROL: 'rgba(0, 0, 0, 0.4)',- EXPOSURES_AXIS_LINES: isDarkModeOn ? 'rgba(217, 217, 217, 0.2)' : 'rgba(217, 217, 217, 0.4)',- }-}--/**- * @deprecated- * Use useChartColors instead.- * Default colors for imports that don't need the hook- */-export const LEGACY_COLORS: LegacyChartColors = {- TICK_TEXT_COLOR: 'var(--color-text-tertiary)',- BOUNDARY_LINES: 'var(--color-border-primary)',- ZERO_LINE: 'rgba(0, 0, 0, 0.25)',- BAR_NEGATIVE: '#f84257',- BAR_POSITIVE: '#36cd6f',- BAR_DEFAULT: 'rgb(217 217 217)',- BAR_CONTROL: 'rgba(217, 217, 217, 0.4)',- BAR_MIDDLE_POINT: 'black',- BAR_MIDDLE_POINT_CONTROL: 'rgba(0, 0, 0, 0.4)',- EXPOSURES_AXIS_LINES: 'rgba(217, 217, 217, 0.4)',-}diff --git a/products/experiments/frontend/legacy/metricsView/legacyUtils.ts b/products/experiments/frontend/legacy/metricsView/legacyUtils.tsdeleted file mode 100644index 7cca2b5f230c..000000000000--- a/products/experiments/frontend/legacy/metricsView/legacyUtils.ts+++ /dev/null@@ -1,96 +0,0 @@-/**- * @deprecated- * These utility functions support legacy experiment metrics.- * Frozen copy for legacy experiments - do not modify.- */-export function legacyFormatTickValue(value: number): string {- if (value === 0) {- return '0%'- }-- // Determine number of decimal places needed- const absValue = Math.abs(value)- let decimals = 0-- if (absValue < 0.01) {- decimals = 3- } else if (absValue < 0.1) {- decimals = 2- } else if (absValue < 1) {- decimals = 1- } else {- decimals = 0- }-- const percentage = value * 100- // Drop unnecessary trailing decimals (e.g. "50.0%" → "50%")- if (decimals > 0 && percentage === Math.round(percentage)) {- decimals = 0- }-- return `${percentage.toFixed(decimals)}%`-}--/**- * @deprecated- * Converts a metric value to an X coordinate for chart rendering- *- * @param value The metric value to convert- * @param chartBound The maximum absolute value in the chart (with padding)- * @param viewBoxWidth The width of the SVG viewBox- * @param horizontalPadding Padding to apply on both sides of the chart- * @returns X coordinate in the SVG coordinate system- */-export function legacyValueToXCoordinate(- value: number,- axisRange: number,- viewBoxWidth: number,- svgEdgeMargin: number = 20-): number {- // Scale the value to fit within the padded area- const percentage = (value / axisRange + 1) / 2- return svgEdgeMargin + percentage * (viewBoxWidth - 2 * svgEdgeMargin)-}--/**- * @deprecated- * Creates appropriately spaced tick values for experiment charts- *- * @param maxAbsValue The maximum absolute value to cover (typically the chart bound)- * @param tickRangeFactor How much of the chart to cover (default 0.9 to not get to close to the edge of the chart)- * @returns Array of nicely rounded tick values- */-export function legacyGetNiceTickValues(maxAbsValue: number, tickRangeFactor: number = 0.9): number[] {- // Round up maxAbsValue to ensure we cover all values- maxAbsValue = Math.ceil(maxAbsValue * 10) / 10-- const magnitude = Math.floor(Math.log10(maxAbsValue))- const power = Math.pow(10, magnitude)-- let baseUnit- const normalizedMax = maxAbsValue / power- if (normalizedMax <= 1) {- baseUnit = 0.2 * power- } else if (normalizedMax <= 2) {- baseUnit = 0.5 * power- } else if (normalizedMax <= 5) {- baseUnit = 1 * power- } else {- baseUnit = 2 * power- }-- const maxAllowedValue = maxAbsValue * tickRangeFactor- const unitsNeeded = Math.ceil(maxAllowedValue / baseUnit)- const decimalPlaces = Math.max(0, -magnitude + 1)-- const ticks: number[] = []- for (let i = -unitsNeeded; i <= unitsNeeded; i++) {- // Round each tick value to avoid floating point precision issues- const tickValue = Number((baseUnit * i).toFixed(decimalPlaces))- // Only include ticks within the allowed range- if (Math.abs(tickValue) <= maxAllowedValue) {- ticks.push(tickValue)- }- }- return ticks-}diff --git a/products/experiments/frontend/legacy/metricsView/legacyViolinUtils.ts b/products/experiments/frontend/legacy/metricsView/legacyViolinUtils.tsdeleted file mode 100644index e30feaf8938d..000000000000--- a/products/experiments/frontend/legacy/metricsView/legacyViolinUtils.ts+++ /dev/null@@ -1,65 +0,0 @@-/**- * @deprecated- * Legacy violin plot utility function.- * Frozen copy for legacy experiments - do not modify.- */--/**- * Generates an SVG path for a violin plot visualization- *- * @param x1 - Left boundary of the violin- * @param x2 - Right boundary of the violin- * @param y - Vertical position of the violin- * @param height - Height of the violin- * @param deltaX - Position of the delta marker- * @returns SVG path string- */-export function legacyGenerateViolinPath(x1: number, x2: number, y: number, height: number, deltaX: number): string {- // Create points for the violin curve- const points: [number, number][] = []- const steps = 20- const maxWidth = height / 2-- // Generate left side points (x1 to deltaX)- for (let i = 0; i <= steps; i++) {- const t = i / steps- const x = x1 + (deltaX - x1) * t- // Standard normal distribution PDF from x1 to deltaX- const z = (t - 1) * 2 // Reduced scale factor from 2.5 to 2 for thicker tails- const width = Math.exp(-0.5 * z * z) * maxWidth- points.push([x, y + height / 2 - width])- }-- // Generate right side points (deltaX to x2)- for (let i = 0; i <= steps; i++) {- const t = i / steps- const x = deltaX + (x2 - deltaX) * t- // Standard normal distribution PDF from deltaX to x2- const z = t * 2 // Reduced scale factor from 2.5 to 2 for thicker tails- const width = Math.exp(-0.5 * z * z) * maxWidth- points.push([x, y + height / 2 - width])- }-- // Generate bottom curve points (mirror of top)- for (let i = steps; i >= 0; i--) {- const t = i / steps- const x = deltaX + (x2 - deltaX) * t- const z = t * 2- const width = Math.exp(-0.5 * z * z) * maxWidth- points.push([x, y + height / 2 + width])- }- for (let i = steps; i >= 0; i--) {- const t = i / steps- const x = x1 + (deltaX - x1) * t- const z = (t - 1) * 2- const width = Math.exp(-0.5 * z * z) * maxWidth- points.push([x, y + height / 2 + width])- }-- // Create SVG path- return `- M ${points[0][0]} ${points[0][1]}- ${points.map((point) => `L ${point[0]} ${point[1]}`).join(' ')}- Z- `-}diff --git a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx b/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsxdeleted file mode 100644index 4cc5afa4ebd4..000000000000--- a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedFunnelsMetricForm.tsx+++ /dev/null@@ -1,205 +0,0 @@-import { useActions, useValues } from 'kea'--import { LemonBanner } from '@posthog/lemon-ui'--import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'-import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'-import { EXPERIMENT_DEFAULT_DURATION } from 'lib/constants'-import { SeriesActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'-import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'-import { cleanSeriesNodes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'-import { getHogQLValue } from 'scenes/insights/filters/aggregationTarget'-import { teamLogic } from 'scenes/teamLogic'--import { Query } from '~/queries/Query/Query'-import { ExperimentFunnelsQuery, FunnelsQuery, NodeKind } from '~/queries/schema/schema-general'-import { hasBreakdownFilter } from '~/queries/utils'-import { commonActionFilterProps } from '~/scenes/experiments/Metrics/Selectors'-import { sharedMetricLogic } from '~/scenes/experiments/SharedMetrics/sharedMetricLogic'-import { BreakdownAttributionType, InsightType } from '~/types'--import {- LegacyFunnelAttributionSelect,- LegacyFunnelConversionWindowFilter,- LegacyFunnelAggregationSelect,-} from 'products/experiments/frontend/legacy'--export function LegacySharedFunnelsMetricForm(): JSX.Element {- const { sharedMetric } = useValues(sharedMetricLogic)- const { setSharedMetric } = useActions(sharedMetricLogic)-- const { currentTeam } = useValues(teamLogic)- const hasFilters = (currentTeam?.test_account_filters || []).length > 0-- const actionFilterProps = {- ...commonActionFilterProps,- actionsTaxonomicGroupTypes: [TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions],- }-- if (!sharedMetric?.query) {- return <></>- }-- const sharedMetricQuery = sharedMetric.query as ExperimentFunnelsQuery-- return (- <>- <SeriesActionFilter- bordered- series={sharedMetricQuery.funnels_query.series}- insightType={InsightType.FUNNELS}- hasBreakdown={hasBreakdownFilter(sharedMetricQuery.funnels_query.breakdownFilter)}- onChange={(series) => {- if (!sharedMetric?.query) {- return- }-- setSharedMetric({- query: {- ...sharedMetricQuery,- funnels_query: {- ...sharedMetricQuery.funnels_query,- series: cleanSeriesNodes(series, MathAvailability.None) as FunnelsQuery['series'],- },- },- })- }}- typeKey="experiment-metric"- mathAvailability={MathAvailability.None}- buttonCopy="Add funnel step"- showSeriesIndicator={true}- seriesIndicatorType="numeric"- sortable={true}- showNestedArrow={true}- {...actionFilterProps}- />- <div className="mt-4 deprecated-space-y-4">- <LegacyFunnelAggregationSelect- value={getHogQLValue(- sharedMetricQuery.funnels_query.aggregation_group_type_index ?? undefined,- sharedMetricQuery.funnels_query.funnelsFilter?.funnelAggregateByHogQL ?? undefined- )}- onChange={(value) => {- setSharedMetric({- query: {- ...sharedMetricQuery,- funnels_query: {- ...sharedMetricQuery.funnels_query,- funnelsFilter: {- ...sharedMetricQuery.funnels_query.funnelsFilter,- funnelAggregateByHogQL: value,- },- },- },- })- }}- />- <LegacyFunnelConversionWindowFilter- funnelWindowInterval={sharedMetricQuery.funnels_query?.funnelsFilter?.funnelWindowInterval}- funnelWindowIntervalUnit={sharedMetricQuery.funnels_query?.funnelsFilter?.funnelWindowIntervalUnit}- onFunnelWindowIntervalChange={(funnelWindowInterval) => {- setSharedMetric({- query: {- ...sharedMetricQuery,- funnels_query: {- ...sharedMetricQuery.funnels_query,- // funnelWindowInterval: funnelWindowInterval,- funnelsFilter: {- ...sharedMetricQuery.funnels_query.funnelsFilter,- funnelWindowInterval: funnelWindowInterval,- },- },- },- })- }}- onFunnelWindowIntervalUnitChange={(funnelWindowIntervalUnit) => {- setSharedMetric({- query: {- ...sharedMetricQuery,- funnels_query: {- ...sharedMetricQuery.funnels_query,- funnelsFilter: {- ...sharedMetricQuery.funnels_query.funnelsFilter,- funnelWindowIntervalUnit: funnelWindowIntervalUnit || undefined,- },- },- },- })- }}- />- <LegacyFunnelAttributionSelect- value={(() => {- const breakdownAttributionType =- sharedMetricQuery.funnels_query?.funnelsFilter?.breakdownAttributionType- const breakdownAttributionValue =- sharedMetricQuery.funnels_query?.funnelsFilter?.breakdownAttributionValue-- const currentValue: BreakdownAttributionType | `${BreakdownAttributionType.Step}/${number}` =- !breakdownAttributionType- ? BreakdownAttributionType.FirstTouch- : breakdownAttributionType === BreakdownAttributionType.Step- ? `${breakdownAttributionType}/${breakdownAttributionValue || 0}`- : breakdownAttributionType-- return currentValue- })()}- onChange={(value) => {- const [breakdownAttributionType, breakdownAttributionValue] = (value || '').split('/')- setSharedMetric({- query: {- ...sharedMetricQuery,- funnels_query: {- ...sharedMetricQuery.funnels_query,- funnelsFilter: {- ...sharedMetricQuery.funnels_query.funnelsFilter,- breakdownAttributionType: breakdownAttributionType as BreakdownAttributionType,- breakdownAttributionValue: breakdownAttributionValue- ? parseInt(breakdownAttributionValue)- : undefined,- },- },- },- })- }}- stepsLength={sharedMetricQuery.funnels_query?.series?.length}- />- <TestAccountFilterSwitch- checked={(() => {- const val = sharedMetricQuery.funnels_query?.filterTestAccounts- return hasFilters ? !!val : false- })()}- onChange={(checked: boolean) => {- setSharedMetric({- query: {- ...sharedMetricQuery,- funnels_query: {- ...sharedMetricQuery.funnels_query,- filterTestAccounts: checked,- },- },- })- }}- fullWidth- />- </div>-- <LemonBanner type="info" className="mt-3 mb-3">- Preview insights are generated based on {EXPERIMENT_DEFAULT_DURATION} days of data. This can cause a- mismatch between the preview and the actual results.- </LemonBanner>-- <div className="mt-4">- <Query- query={{- kind: NodeKind.InsightVizNode,- source: sharedMetricQuery.funnels_query,- showTable: false,- showLastComputation: true,- showLastComputationRefresh: false,- }}- readOnly- />- </div>- </>- )-}diff --git a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedTrendsMetricForm.tsx b/products/experiments/frontend/legacy/sharedMetrics/LegacySharedTrendsMetricForm.tsxdeleted file mode 100644index f5f2a5c48ead..000000000000--- a/products/experiments/frontend/legacy/sharedMetrics/LegacySharedTrendsMetricForm.tsx+++ /dev/null@@ -1,281 +0,0 @@-import { useActions, useValues } from 'kea'-import { useState } from 'react'--import { IconCheckCircle } from '@posthog/icons'-import { LemonBanner, LemonTabs, LemonTag } from '@posthog/lemon-ui'--import { TestAccountFilterSwitch } from 'lib/components/TestAccountFiltersSwitch'-import { DISPLAY_TYPES_TO_CATEGORIES, EXPERIMENT_DEFAULT_DURATION } from 'lib/constants'-import { dayjs } from 'lib/dayjs'-import { SeriesActionFilter } from 'scenes/insights/filters/ActionFilter/ActionFilter'-import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/types'-import { cleanSeriesNodes } from 'scenes/insights/filters/ActionFilter/cleanSeriesNodes'-import { teamLogic } from 'scenes/teamLogic'--import { Query } from '~/queries/Query/Query'-import { ExperimentTrendsQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'-import { hasBreakdownFilter } from '~/queries/utils'-import { commonActionFilterProps } from '~/scenes/experiments/Metrics/Selectors'-import { sharedMetricLogic } from '~/scenes/experiments/SharedMetrics/sharedMetricLogic'-import { BaseMathType, ChartDisplayCategory, ChartDisplayType, InsightType } from '~/types'--import { LEGACY_EXPERIMENT_ALLOWED_MATH_TYPES } from 'products/experiments/frontend/constants'--function displayCategory(query: TrendsQuery): ChartDisplayCategory {- return DISPLAY_TYPES_TO_CATEGORIES[query.trendsFilter?.display || ChartDisplayType.ActionsLineGraph]-}--export function LegacySharedTrendsMetricForm(): JSX.Element {- const { sharedMetric } = useValues(sharedMetricLogic)- const { setSharedMetric } = useActions(sharedMetricLogic)- const { currentTeam } = useValues(teamLogic)- const hasFilters = (currentTeam?.test_account_filters || []).length > 0- const [activeTab, setActiveTab] = useState('main')-- if (!sharedMetric?.query) {- return <></>- }-- const sharedMetricQuery = sharedMetric.query as ExperimentTrendsQuery-- return (- <>- <LemonTabs- activeKey={activeTab}- onChange={(newKey) => setActiveTab(newKey)}- tabs={[- {- key: 'main',- label: 'Main metric',- content: (- <>- <SeriesActionFilter- bordered- series={sharedMetricQuery.count_query.series}- insightType={InsightType.TRENDS}- hasBreakdown={hasBreakdownFilter(sharedMetricQuery.count_query.breakdownFilter)}- trendsDisplayCategory={displayCategory(sharedMetricQuery.count_query)}- onChange={(series) => {- setSharedMetric({- query: {- ...sharedMetricQuery,- count_query: {- ...sharedMetricQuery.count_query,- series: cleanSeriesNodes(- series,- MathAvailability.All- ) as TrendsQuery['series'],- },- },- })- }}- typeKey="experiment-metric"- buttonCopy="Add graph series"- showSeriesIndicator={true}- entitiesLimit={1}- showNumericalPropsOnly={true}- allowedMathTypes={LEGACY_EXPERIMENT_ALLOWED_MATH_TYPES}- {...commonActionFilterProps}- />- <div className="mt-4 deprecated-space-y-4">- <TestAccountFilterSwitch- checked={(() => {- const val = sharedMetricQuery.count_query?.filterTestAccounts- return hasFilters ? !!val : false- })()}- onChange={(checked: boolean) => {- setSharedMetric({- query: {- ...sharedMetricQuery,- count_query: {- ...sharedMetricQuery.count_query,- filterTestAccounts: checked,- },- },- })- }}- fullWidth- />- </div>- <LemonBanner type="info" className="mt-3 mb-3">- Preview insights are generated based on {EXPERIMENT_DEFAULT_DURATION} days of data.- This can cause a mismatch between the preview and the actual results.- </LemonBanner>- <div className="mt-4">- <Query- query={{- kind: NodeKind.InsightVizNode,- source: sharedMetricQuery.count_query,- showTable: false,- showLastComputation: true,- showLastComputationRefresh: false,- }}- readOnly- />- </div>- </>- ),- },- {- key: 'exposure',- label: 'Exposure',- content: (- <>- <div className="flex gap-4 mb-4">- <div- className={`flex-1 cursor-pointer p-4 rounded border ${- !sharedMetricQuery.exposure_query- ? 'border-accent bg-accent-highlight-secondary'- : 'border-primary'- }`}- onClick={() => {- setSharedMetric({- query: {- ...sharedMetricQuery,- exposure_query: undefined,- },- })- }}- >- <div className="font-semibold flex justify-between items-center">- <span>Default</span>- {!sharedMetricQuery.exposure_query && (- <IconCheckCircle fontSize={18} color="var(--color-accent)" />- )}- </div>- <div className="text-secondary text-sm leading-relaxed">- Uses the number of unique users who trigger the{' '}- <LemonTag>$feature_flag_called</LemonTag> event as your exposure count. This- is the recommended setting for most experiments, as it accurately tracks- variant exposure.- </div>- </div>- <div- className={`flex-1 cursor-pointer p-4 rounded border ${- sharedMetricQuery.exposure_query- ? 'border-accent bg-accent-highlight-secondary'- : 'border-primary'- }`}- onClick={() => {- setSharedMetric({- query: {- ...sharedMetricQuery,- exposure_query: {- kind: NodeKind.TrendsQuery,- series: [- {- kind: NodeKind.EventsNode,- name: '$feature_flag_called',- event: '$feature_flag_called',- math: BaseMathType.UniqueUsers,- },- ],- interval: 'day',- dateRange: {- date_from: dayjs()- .subtract(EXPERIMENT_DEFAULT_DURATION, 'day')- .format('YYYY-MM-DDTHH:mm'),- date_to: dayjs().endOf('d').format('YYYY-MM-DDTHH:mm'),- explicitDate: true,- },- trendsFilter: {- display: ChartDisplayType.ActionsLineGraph,- },- filterTestAccounts: true,- },- },- })- }}- >- <div className="font-semibold flex justify-between items-center">- <span>Custom</span>- {sharedMetricQuery.exposure_query && (- <IconCheckCircle fontSize={18} color="var(--color-accent)" />- )}- </div>- <div className="text-secondary text-sm leading-relaxed">- Define your own exposure metric for specific use cases, such as counting by- sessions instead of users. This gives you full control but requires careful- configuration.- </div>- </div>- </div>- {sharedMetricQuery.exposure_query && (- <>- <SeriesActionFilter- bordered- series={sharedMetricQuery.exposure_query.series}- insightType={InsightType.TRENDS}- hasBreakdown={hasBreakdownFilter(- sharedMetricQuery.exposure_query.breakdownFilter- )}- trendsDisplayCategory={displayCategory(sharedMetricQuery.exposure_query)}- onChange={(series) => {- setSharedMetric({- query: {- ...sharedMetricQuery,- exposure_query: {- ...sharedMetricQuery.exposure_query,- series: cleanSeriesNodes(- series,- MathAvailability.All- ) as TrendsQuery['series'],- },- },- })- }}- typeKey="experiment-metric"- buttonCopy="Add graph series"- showSeriesIndicator={true}- entitiesLimit={1}- showNumericalPropsOnly={true}- allowedMathTypes={LEGACY_EXPERIMENT_ALLOWED_MATH_TYPES}- {...commonActionFilterProps}- />- <div className="mt-4 deprecated-space-y-4">- <TestAccountFilterSwitch- checked={(() => {- const val = sharedMetricQuery.exposure_query?.filterTestAccounts- return hasFilters ? !!val : false- })()}- onChange={(checked: boolean) => {- setSharedMetric({- query: {- ...sharedMetricQuery,- exposure_query: {- ...sharedMetricQuery.exposure_query,- filterTestAccounts: checked,- },- },- })- }}- fullWidth- />- </div>- <LemonBanner type="info" className="mt-3 mb-3">- Preview insights are generated based on {EXPERIMENT_DEFAULT_DURATION} days- of data. This can cause a mismatch between the preview and the actual- results.- </LemonBanner>- <div className="mt-4">- <Query- query={{- kind: NodeKind.InsightVizNode,- source: sharedMetricQuery.exposure_query,- showTable: false,- showLastComputation: true,- showLastComputationRefresh: false,- }}- readOnly- />- </div>- </>- )}- </>- ),- },- ]}- />- </>- )-}diff --git a/products/experiments/frontend/modals/DetailsModal/DetailsModal.tsx b/products/experiments/frontend/modals/DetailsModal/DetailsModal.tsxindex 73f2f4b53f1c..77f76770ae7e 100644--- a/products/experiments/frontend/modals/DetailsModal/DetailsModal.tsx+++ b/products/experiments/frontend/modals/DetailsModal/DetailsModal.tsx@@ -2,13 +2,13 @@ import { LemonButton, LemonModal } from '@posthog/lemon-ui'import { ResultDetails } from 'scenes/experiments/MetricsView/new/ResultDetails'-import { ExperimentFunnelsQuery, ExperimentMetric, ExperimentTrendsQuery } from '~/queries/schema/schema-general'+import { ExperimentMetric } from '~/queries/schema/schema-general'import type { Experiment } from '~/types'interface DetailsModalProps {isOpen: booleanonClose: () => void- metric: ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery+ metric: ExperimentMetricresult: anyexperiment: Experiment}@@ -26,12 +26,7 @@ export function DetailsModal({ isOpen, onClose, metric, result, experiment }: De</LemonButton>}>- <ResultDetails- result={result}- experiment={experiment}- metric={metric as ExperimentMetric}- surface="details_modal"- />+ <ResultDetails result={result} experiment={experiment} metric={metric} surface="details_modal" /></LemonModal>)}diff --git a/products/experiments/frontend/modals/SharedMetricModal/SharedMetricModal.tsx b/products/experiments/frontend/modals/SharedMetricModal/SharedMetricModal.tsxindex 2dfba8809776..815375a88aa3 100644--- a/products/experiments/frontend/modals/SharedMetricModal/SharedMetricModal.tsx+++ b/products/experiments/frontend/modals/SharedMetricModal/SharedMetricModal.tsx@@ -10,7 +10,6 @@ import { sharedMetricsLogic } from 'scenes/experiments/SharedMetrics/sharedMetriimport { urls } from 'scenes/urls'import { tagsModel } from '~/models/tagsModel'-import { NodeKind } from '~/queries/schema/schema-general'import { Experiment } from '~/types'import { MetricContext } from 'products/experiments/frontend/modals/ExperimentMetricModal/experimentMetricModalLogic'@@ -239,12 +238,7 @@ export function SharedMetricModal({{title: 'Type',key: 'type',- render: (_, metric: SharedMetric) => {- if (metric.query.kind === NodeKind.ExperimentMetric) {- return metric.query.metric_type- }- return metric.query.kind === NodeKind.ExperimentTrendsQuery ? 'Trend' : 'Funnel'- },+ render: (_, metric: SharedMetric) => metric.query.metric_type,},]}footer={diff --git a/products/experiments/frontend/scenes/ExperimentsScene.tsx b/products/experiments/frontend/scenes/ExperimentsScene.tsxindex 8c014dd42ee9..ee3a2374c1a3 100644--- a/products/experiments/frontend/scenes/ExperimentsScene.tsx+++ b/products/experiments/frontend/scenes/ExperimentsScene.tsx@@ -294,7 +294,7 @@ const ExperimentsTable = ({)}{experiment.is_legacy && (<Tooltip- title="This experiment uses the legacy engine, so some features and improvements may be missing."+ title="This experiment uses the legacy engine, so its results are no longer available."docLink="https://posthog.com/docs/experiments/new-experimentation-engine"><LemonTag type="warning" className="ml-1">diff --git a/products/experiments/frontend/scenes/ExperimentsSharedMetricsScene.tsx b/products/experiments/frontend/scenes/ExperimentsSharedMetricsScene.tsxindex f3571d226663..df369fb84b33 100644--- a/products/experiments/frontend/scenes/ExperimentsSharedMetricsScene.tsx+++ b/products/experiments/frontend/scenes/ExperimentsSharedMetricsScene.tsx@@ -77,7 +77,7 @@ export function ExperimentsSharedMetricsScene(): JSX.Element {{stringWithWBR(sharedMetric.name, 17)}{isLegacySharedMetric(sharedMetric) && (<Tooltip- title="This metric uses the legacy engine, so some features and improvements may be missing."+ title="This metric uses the legacy engine, so it can no longer be edited."docLink="https://posthog.com/docs/experiments/new-experimentation-engine"><LemonTag type="warning" className="ml-1">@@ -145,6 +145,11 @@ export function ExperimentsSharedMetricsScene(): JSX.Element {fullWidthsize="small"icon={<IconCopy />}+ disabledReason={+ isLegacySharedMetric(sharedMetric)+ ? 'Legacy shared metrics can no longer be duplicated'+ : undefined+ }onClick={() => {router.actions.push(urls.experimentsSharedMetric(sharedMetric.id, 'duplicate'))}}