: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(dashboards): add experiments list and results dashboard widgets (#62578)
Matt Pua37f095cae68e
diff --git a/.agents/skills/manage-dashboard-widgets/SKILL.md b/.agents/skills/manage-dashboard-widgets/SKILL.mdindex 531640078f22..717611ad04a3 100644--- a/.agents/skills/manage-dashboard-widgets/SKILL.md+++ b/.agents/skills/manage-dashboard-widgets/SKILL.md@@ -44,7 +44,7 @@ Shipped types (code truth): [architecture.md § Shipped types](references/archit### Execute-After spec confirmation → [checklist-new-widget-type.md](references/checklist-new-widget-type.md) **§1 → §8**. §5b after MVP tests green.+After spec confirmation → [checklist-new-widget-type.md](references/checklist-new-widget-type.md) **§1 → §8**. §5b (dedicated stories — required before the PR, not a follow-up) is sequenced once MVP tests are green.## 3. Update a shipped type@@ -82,7 +82,7 @@ New `widget_type` strings need **no migration** — register registries + catalo## 6. Verify-**Ship (MVP):**+**MVP smoke (renders + core tests — not a ship point):**```bashhogli test products/dashboards/backend/api/test/test_run_widgets.py@@ -90,7 +90,7 @@ hogli test products/dashboards/backend/api/test/test_dashboard_widgets.pyhogli test products/dashboards/frontend/widgets/registry.test.tsx```-**Ship (before PR):** [checklist §8](references/checklist-new-widget-type.md#8-tests) + `hogli build:openapi`.+**Ship gate (required before the PR):** [checklist §8](references/checklist-new-widget-type.md#8-tests) + `hogli build:openapi` + dedicated Storybook stories per [checklist §5b](references/checklist-new-widget-type.md#5b-storybook) (component + edit modal — required, not just the catalog overview).**Config SSOT changes** (also run after `widget_specs/` edits):diff --git a/.agents/skills/manage-dashboard-widgets/references/checklist-new-widget-type.md b/.agents/skills/manage-dashboard-widgets/references/checklist-new-widget-type.mdindex 5a457a846ea7..61c1c5363392 100644--- a/.agents/skills/manage-dashboard-widgets/references/checklist-new-widget-type.md+++ b/.agents/skills/manage-dashboard-widgets/references/checklist-new-widget-type.md@@ -4,7 +4,7 @@1. Complete [widget-intake.md](widget-intake.md) — infer, batched questions, **spec confirmation** (mandatory).2. Work **§1 → §8 below in order**. Do not skip step 2 (permissions).-3. **§5b** after MVP tests green; **skill docs** per [skill-maintenance.md](skill-maintenance.md) if workflow changed.+3. **§5b** (dedicated stories — required before the PR, not a follow-up) once MVP tests are green; **skill docs** per [skill-maintenance.md](skill-maintenance.md) if workflow changed.Copy spine: [widget-intake.md § Defaults](widget-intake.md#defaults-and-inference).@@ -138,6 +138,8 @@ See [composition.md](composition.md) for WidgetCard rules.## 5b. Storybook+**Required, not optional.** Every new `widget_type` ships a dedicated `<YourWidget>.stories.tsx` — plus an `Edit*WidgetModal.stories.tsx` when it has an edit modal — matching the sibling pattern (error tracking, session replay, activity each have both). The catalog overview story (`getWidgetOverviewDemoState`) is **not** a substitute: it renders a single demo state per type and covers none of the per-widget states, tile-filter read-only, loading, empty, or the edit modal. A PR that adds a widget without dedicated stories is incomplete.+File: `products/dashboards/frontend/widgets/<product>/<YourWidget>.stories.tsx`Reference: `products/dashboards/frontend/widgets/error_tracking/ErrorTrackingWidget.stories.tsx`@@ -154,7 +156,7 @@ Reference: `products/dashboards/frontend/widgets/error_tracking/ErrorTrackingWid- **Error** — when the component renders `error` (pass a string or error-shaped prop your component expects)- [ ] Include `tileId`, `config` (defaults from catalog), and stub `onUpdateConfig` / `onRefresh` where the component needs them- [ ] Add **`getWidgetOverviewDemoState`** case in `components/WidgetCard/widgetOverviewStoryFixtures.ts` (exhaustive switch — overview story breaks if missing)-- [ ] Optional: `Edit*WidgetModal.stories.tsx` — mirror `EditErrorTrackingWidgetModal.stories.tsx` / `EditSessionReplayWidgetModal.stories.tsx`+- [ ] **`Edit*WidgetModal.stories.tsx`** when the type has an edit modal — required, mirror `EditErrorTrackingWidgetModal.stories.tsx` / `EditSessionReplayWidgetModal.stories.tsx`. If the modal (or a tile filter) hits an API (e.g. an experiment picker), mock it with `mswDecorator` from `~/mocks/browser`Run locally:diff --git a/.agents/skills/manage-dashboard-widgets/references/widget-intake.md b/.agents/skills/manage-dashboard-widgets/references/widget-intake.mdindex 3d4977239815..299fdf849c03 100644--- a/.agents/skills/manage-dashboard-widgets/references/widget-intake.md+++ b/.agents/skills/manage-dashboard-widgets/references/widget-intake.md@@ -192,7 +192,7 @@ After discover + [defaults](#defaults-and-inference), skip locked rows. Cap **6| Access | RBAC vs sibling; setup gate pattern; throttles; custom denial copy || Sharing / MCP | Custom `sharedPlaceholder`; extra `WidgetSpec.description` beyond `config_schema` |-Chart-primary discovery or request → stop ([architecture.md § Charts](architecture.md#charts--use-insight-tiles-not-widgets)). Defer Storybook, fixtures, OpenAPI regen to post-MVP unless engineer asks.+Chart-primary discovery or request → stop ([architecture.md § Charts](architecture.md#charts--use-insight-tiles-not-widgets)). Storybook, fixtures, and OpenAPI regen come **after** the MVP renders — but they are required to ship a new `widget_type`, never optional. Every new widget gets dedicated stories (component + edit modal) matching the sibling pattern; do not stop at the catalog overview story. Sequence them post-MVP, but do not skip them.## Spec fields to lockdiff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1e821715abc4..f9369bb0c1dd 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1617,9 +1617,9 @@ snapshots:components-verticalnesteddnd--base--light:hash: v1.k794b7964.b210ce352a085f9ed57aed4675cc78d23db5d2312f276ec790040b2ce27e293a.duU6Lgj4ID4h_Qo76s2bErUZYu2IuRIHoy4D7_tCGT4dashboards-dashboard-widgets-overview--all-widget-types--dark:- hash: v1.k794b7964.f52e0205a5ac2829de355b60d5dd2ecde62076be4cf3caeaf7e390e988d712b7.gd-OHkFpKbvglBEVBI22llGCOjRureI9vX9wa5Lsaw8+ hash: v1.k794b7964.a1da2fa996d731f6e7397cb834ba6b08e9272cc641fa42b7281106b8b7d64c81.Gpun-k8Y3gVnXQnDOhFSzgkmM3br2G73KKTtWmOOIAEdashboards-dashboard-widgets-overview--all-widget-types--light:- hash: v1.k794b7964.a86aac3220bd8904355fd89b5b5591471b1642066db99b170f559a37836a55b5.jNCMlnyBeGoMlXri65uF0ypLu7Bs1sbAE7sjbxjQiwM+ hash: v1.k794b7964.a6d429113c47ea7ac2a71ceef5cce7e38ac782b6d573cc0d7eab657d1c122b10.fuAwCLFT-OPDnLrhTbH6tcKEZbR-5XUiv-PnTt9fUakdashboards-dashboard-widgets-widget-types-activity-recent-events--default--dark:hash: v1.k794b7964.97188569bbab124430a6a0c91f746f8d119a7ecbeb0e116c50366aa6294a12e9.CIJBmnHIDHMFKDdJNupis99nTg4U_k0843VdEctiQvcdashboards-dashboard-widgets-widget-types-activity-recent-events--default--light:@@ -1664,6 +1664,46 @@ snapshots:hash: v1.k794b7964.aec959497f395afca3960d2ebf4e82e9f6fe72334c825533722a7a369313efe2.09zUcQOLWCd7nAXBzkR6D0wEFuq4DsXAOYjdFvPJqPQdashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--default--light:hash: v1.k794b7964.af604b406115bf252f107bd8599029b5e34b473e76cac0c368f12228895186ed.xLjKRF0exewyVhp-Zz52PwMmAJbqO6trsSNRtXbzIEY+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results--default--dark:+ hash: v1.k794b7964.e25eaef2234e9ed84db9b1b57bc50f1bed03f128bb1b0127c6884405e2fe50c7.YBac7PIKuFBDwRtnI0zQz-vtIsOdowRuAtnwZvBVg7s+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results--default--light:+ hash: v1.k794b7964.ea210d91e743b016718cf2f65fec85a10d71c69d55354d7d9b8af54fb5e1ab65.u9QBcO13s-Bi6Jf_AtNQ5ou2xZGQyLTBf-q3xJizlzg+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results--loading--dark:+ hash: v1.k794b7964.879fe4b3a1e34deb4c156e61c9b4f6dc67167ea68907835a986a8ef4873c987a.N1KElSIU_TgDom6aXCR3ZwrSUvjt0t6l49goFfwMoUs+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results--loading--light:+ hash: v1.k794b7964.028e0bafb6bdfb17412b93032ba75a65c90349f3695d594e45a7411c9e13551a.9SVtMI2pcn9JIb4coDMBYJ1_EbI59o1-7iiNxPZxAOo+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results--not-configured--dark:+ hash: v1.k794b7964.d29f72447339bae8b61f77359c15e17e9f3bc5f73f36049fe84f26825608ac12.y9URGys_J0AqlasEqTCOiO3ivhES6ojfdYmJ-ytoWKs+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results--not-configured--light:+ hash: v1.k794b7964.23d27257841a7d79a91e42ea03a1fa70a3654c70c32982dbe4bfef3ce2892a75.4DTjVKlJIQO6fsarI2l0BzXnIgK5LvDfji0nkOe591Q+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results--tile-filters-read-only--dark:+ hash: v1.k794b7964.8deec0a065e0cb3259dc51ab0582e265e487b44f9bd8b6c104a063ab5de7827e.wlb8-VGtyZpd704h9HL_qTEF09vwi_uXCrMUCxXbGH0+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results--tile-filters-read-only--light:+ hash: v1.k794b7964.1d4ea040dfd09cbcdf18eac89a2bac0b25d3da8ed241f8baa17ad062014c09b3.oa1GbgxCoOIrjF74LE373GT-JNhekkLoSrGoBgCpfZY+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results-widget-settings--default--dark:+ hash: v1.k794b7964.2dfdb4d48acafac3ba1af8c7bfceafc485886ae6ceb7bfe48996a5fb660179bf.dRGhPGstCK6T_H45ICVMzGPypYcOQNhkVgPP1ErE0-o+ dashboards-dashboard-widgets-widget-types-experiments-experiment-results-widget-settings--default--light:+ hash: v1.k794b7964.a976f354803d43b9f88908f2ea5317d34a9bfb57fe53361d25450e7d3e666131.ti73u4QyJ_nqF4N91drkwD_c1qwWGxk8ESW_D6Dp68w+ dashboards-dashboard-widgets-widget-types-experiments-experiments--default--dark:+ hash: v1.k794b7964.65031052baa2ab01ac06aa02d6d72dc7e7754bbd60787acfd22a0a3d5278c6ee.0_hUOzOiHQUeSrxD1yD0MOdGXVLczbse_0MLL1O_H8M+ dashboards-dashboard-widgets-widget-types-experiments-experiments--default--light:+ hash: v1.k794b7964.564ebb676a2d6ce5ca2f2e9450931c7d3308efea83ddcab59c2c4fff78c14722.GYScshbOANodCmdlcQuKk39LDU3buDNG-uC8Sk-8KHk+ dashboards-dashboard-widgets-widget-types-experiments-experiments--empty--dark:+ hash: v1.k794b7964.8a16af42953fcb74f684eb3f694b657d5acd4c9921ece829ee1e267a5fa5ca01.bDlTf_Lyh4DTvUmkjKpk3w1EgdBaiNV6CpI4o9vcjUw+ dashboards-dashboard-widgets-widget-types-experiments-experiments--empty--light:+ hash: v1.k794b7964.56e17fa4c4b2523d4c900381ecbee5eb896b56cd00b8f733e59960ba9400c1ea.wT3j5Y47I03Q6GFX4NiLxhM1lsCWT3-UdNC-fE2nHDs+ dashboards-dashboard-widgets-widget-types-experiments-experiments--loading--dark:+ hash: v1.k794b7964.91f94b287637f3f643a07b1e3ca4ff2f3e297d09bdb78838a06ff7f4dc34c885._q8aCvzp-CfEKvoJugOJqQ1uPL-p8DCnKtTDb4KBs0Q+ dashboards-dashboard-widgets-widget-types-experiments-experiments--loading--light:+ hash: v1.k794b7964.791462dbbdfba3f2b655b7de8002e3dec6ad7874ab1e8f49f075b187a388c975.TAO5kixJcJPI4so0DaRTPnP6rL0aTb5iS09v2_4_lX4+ dashboards-dashboard-widgets-widget-types-experiments-experiments--tile-filters-read-only--dark:+ hash: v1.k794b7964.49c647f11872864fbebb2f41de5a0fa8215869dbd35513664b9a73c9512b3be2.ydYuECtpVuDGNtZaNGWHH-S5LYLnFCBvwvudBbBjNPs+ dashboards-dashboard-widgets-widget-types-experiments-experiments--tile-filters-read-only--light:+ hash: v1.k794b7964.3e812c5c4bf82c725c0ffd301b304f255377b3e19b8009e30e21385792dd1bf0.UbcqjxiOFB2ZD6WaGpHtE0tSE-RS1AzEUobx-YE5qh4+ dashboards-dashboard-widgets-widget-types-experiments-experiments-widget-settings--default--dark:+ hash: v1.k794b7964.36c039ca5a5530ad1271f73bdf22b34554ed93496949ea1488b16a14bb5ba029.j7gTAPQ3J8pdVisoXvSHDUgS8Kl5vlBmF9hU3VnCw0o+ dashboards-dashboard-widgets-widget-types-experiments-experiments-widget-settings--default--light:+ hash: v1.k794b7964.8715a7b54c54caeceabc7ada435074e73e2b0b3d8bada7d9f7f53e56b305d815.BNfFt-AV0Y6mZeXlQVNA3CZrm_kkfncCe-uU5dvbTg4dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--default--dark:hash: v1.k794b7964.1a5baf14a6ff53a6072ebc87ed92ec20014d81c90e9718dd144c869c7c0f1a6d.mntf80pED3WsfNCXd5dto32xdxLBogMzx9mjVP0E4Qkdashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--default--light:diff --git a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambrindex 09e777d7ebe4..daaa730d0a2c 100644--- a/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr+++ b/posthog/models/resource_transfer/test/__snapshots__/test_visitor_field_snapshots.ambr@@ -701,6 +701,7 @@'save','start_date','status',+ 'status_label','team_id','updated_at',])diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex a15815c3c1e6..246a23da3b2a 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -566,6 +566,8 @@ SPECTACULAR_SETTINGS = {"ActivityEventsListWidgetTypeEnum": ["activity_events_list"],"ErrorTrackingListWidgetTypeEnum": ["error_tracking_list"],"SessionReplayListWidgetTypeEnum": ["session_replay_list"],+ "ExperimentsListWidgetTypeEnum": ["experiments_list"],+ "ExperimentResultsWidgetTypeEnum": ["experiment_results"],"OrderByEnum": ["latest", "earliest"],"PropertyGroupTypeEnum": ["cohort", "person", "group"],"ExistenceOperatorEnum": ["is_set", "is_not_set"],diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex b59ce27946ef..3c18f0538f5f 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -98,6 +98,8 @@ from products.dashboards.backend.widget_query_throttle import get_dashboard_widgfrom products.dashboards.backend.widget_registry import (EXPECTED_WIDGET_TYPES,SESSION_REPLAY_LIST_WIDGET_TYPE,+ count_active_widget_filters,+ extract_widget_filters,get_widget_registry_entry,validate_widget_config,)@@ -1494,7 +1496,7 @@ class DashboardSerializer(DashboardMetadataSerializer):if patch_widget_type is not None and str(patch_widget_type) != widget.widget_type:raise serializers.ValidationError({"widget": "widget_type cannot be changed."})- previous_widget_filters = (widget.config or {}).get("widgetFilters")+ previous_widget_filters = extract_widget_filters(widget.widget_type, widget.config)if "config" in widget_data:widget.config = validate_widget_config(widget.widget_type,@@ -1508,7 +1510,7 @@ class DashboardSerializer(DashboardMetadataSerializer):widget.last_modified_at = now()widget.save()- new_widget_filters = (widget.config or {}).get("widgetFilters")+ new_widget_filters = extract_widget_filters(widget.widget_type, widget.config)if "config" in widget_data and new_widget_filters != previous_widget_filters:report_user_action(user,@@ -1517,7 +1519,7 @@ class DashboardSerializer(DashboardMetadataSerializer):"widget_type": widget.widget_type,"dashboard_id": dashboard.id,"widget_id": str(widget.id),- "filters_count": len(new_widget_filters) if new_widget_filters else 0,+ "filters_count": count_active_widget_filters(widget.widget_type, widget.config),},team=dashboard.team,request=request,diff --git a/products/dashboards/backend/api/test/test_dashboard_widgets.py b/products/dashboards/backend/api/test/test_dashboard_widgets.pyindex d5c21013f3ce..69e3a09c31fb 100644--- a/products/dashboards/backend/api/test/test_dashboard_widgets.py+++ b/products/dashboards/backend/api/test/test_dashboard_widgets.py@@ -874,6 +874,40 @@ class TestDashboardWidgets(APIBaseTest):assert filters_updated_calls[0][0][2]["widget_id"] == tile["widget"]["id"]assert filters_updated_calls[0][0][2]["filters_count"] == 1+ @parameterized.expand(+ [+ ("experiments_list", {"limit": 10, "status": "all"}, {"limit": 10, "status": "running"}, 1),+ ("experiments_list", {"limit": 10}, {"limit": 10, "createdBy": 7}, 1),+ ("experiment_results", {}, {"experimentId": 123}, 1),+ ]+ )+ @override_settings(IN_UNIT_TESTING=True)+ @patch("products.dashboards.backend.api.dashboard.report_user_action")+ def test_experiments_widget_top_level_filter_change_fires_filters_updated_event(+ self, widget_type, initial_config, changed_config, expected_count, mock_report_user_action+ ) -> None:+ dashboard_id, dashboard_json = self.dashboard_api.create_widget_tile(+ dashboard_id=self.dashboard_api.create_dashboard({"name": "dashboard"})[0],+ widget_type=widget_type,+ config=initial_config,+ )+ tile = dashboard_json["tiles"][0]+ tile["widget"]["config"] = changed_config+ mock_report_user_action.reset_mock()++ response = self.client.patch(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}",+ {"tiles": [tile]},+ )+ assert response.status_code == status.HTTP_200_OK++ filters_updated_calls = [+ call for call in mock_report_user_action.call_args_list if call[0][1] == "dashboard widget filters updated"+ ]+ assert len(filters_updated_calls) == 1+ assert filters_updated_calls[0][0][2]["widget_type"] == widget_type+ assert filters_updated_calls[0][0][2]["filters_count"] == expected_count+@override_settings(IN_UNIT_TESTING=True)@patch("products.dashboards.backend.api.dashboard.report_user_action")def test_update_widget_config_without_filters_change_does_not_fire_filters_updated_event(diff --git a/products/dashboards/backend/api/test/test_experiment_widgets.py b/products/dashboards/backend/api/test/test_experiment_widgets.pynew file mode 100644index 000000000000..ed6106144cef--- /dev/null+++ b/products/dashboards/backend/api/test/test_experiment_widgets.py@@ -0,0 +1,409 @@+from concurrent.futures import Future+from typing import Any++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.utils import timezone++from parameterized import parameterized++from posthog.api.test.dashboards import DashboardAPI+from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, Team, User++from products.dashboards.backend.constants import DEFAULT_WIDGET_LIST_LIMIT+from products.dashboards.backend.widget_registry import (+ EXPERIMENT_RESULTS_WIDGET_TYPE,+ EXPERIMENTS_LIST_WIDGET_TYPE,+ validate_widget_config,+)+from products.dashboards.backend.widgets.experiment_results import (+ MAX_EXPERIMENT_RESULTS_WIDGET_METRICS,+ run_experiment_results_widget,+)+from products.dashboards.backend.widgets.experiments_list import run_experiments_list_widget+from products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.models.feature_flag import FeatureFlag+++def _block_experiment_for_member(team: Team, experiment: Experiment, member: User) -> None:+ from ee.models.rbac.access_control import AccessControl # noqa: PLC0415++ team.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": "Access control"}]+ team.organization.save()+ membership = OrganizationMembership.objects.get(organization=team.organization, user=member)+ AccessControl.objects.create(+ team=team,+ resource="experiment",+ resource_id=str(experiment.id),+ organization_member=membership,+ access_level="none",+ )+++def _experiment_metric(uuid: str, name: str) -> dict[str, Any]:+ return {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "uuid": uuid,+ "name": name,+ "source": {"kind": "EventsNode", "event": "$pageview"},+ }+++class TestExperimentWidgetConfigs(APIBaseTest):+ def test_experiments_list_config_defaults(self) -> None:+ validated = validate_widget_config(EXPERIMENTS_LIST_WIDGET_TYPE, {})+ assert validated["limit"] == DEFAULT_WIDGET_LIST_LIMIT+ assert validated["status"] == "all"+ assert validated.get("createdBy") is None++ def test_experiment_results_config_defaults_to_unconfigured(self) -> None:+ validated = validate_widget_config(EXPERIMENT_RESULTS_WIDGET_TYPE, {})+ assert validated.get("experimentId") is None++ @parameterized.expand(+ [+ ("invalid_status", EXPERIMENTS_LIST_WIDGET_TYPE, {"status": "archived"}),+ ("high_limit", EXPERIMENTS_LIST_WIDGET_TYPE, {"limit": 100}),+ ("unknown_key", EXPERIMENTS_LIST_WIDGET_TYPE, {"evil": True}),+ ("non_int_experiment", EXPERIMENT_RESULTS_WIDGET_TYPE, {"experimentId": "abc"}),+ ("unknown_key_results", EXPERIMENT_RESULTS_WIDGET_TYPE, {"evil": True}),+ ]+ )+ def test_rejects_invalid_config(self, _label: str, widget_type: str, config: dict[str, Any]) -> None:+ with self.assertRaises(Exception):+ validate_widget_config(widget_type, config)+++class TestExperimentsListWidget(APIBaseTest):+ def _create_experiment(+ self,+ name: str,+ *,+ created_by: User | None = None,+ start_date: Any = None,+ end_date: Any = None,+ flag_active: bool = True,+ ) -> Experiment:+ feature_flag = FeatureFlag.objects.create(+ team=self.team,+ key=f"flag-{name}",+ created_by=created_by or self.user,+ active=flag_active,+ )+ return Experiment.objects.create(+ team=self.team,+ name=name,+ feature_flag=feature_flag,+ created_by=created_by or self.user,+ start_date=start_date,+ end_date=end_date,+ )++ def test_lists_experiments_with_serialized_rows(self) -> None:+ experiment = self._create_experiment("Running test", start_date=timezone.now())++ result = run_experiments_list_widget(self.team, {}, user=self.user)++ assert result["totalCount"] == 1+ assert result["hasMore"] is False+ row = result["results"][0]+ assert row["id"] == experiment.id+ assert row["name"] == "Running test"+ assert row["status"] == "running"+ assert row["feature_flag_key"] == experiment.feature_flag.key+ assert row["created_by"]["email"] == self.user.email++ @parameterized.expand(+ [+ ("draft", "draft"),+ ("running", "running"),+ ("paused", "paused"),+ ("stopped", "stopped"),+ ]+ )+ def test_filters_by_status(self, _label: str, status_filter: str) -> None:+ now = timezone.now()+ expected_names = {+ "draft": "Draft exp",+ "running": "Running exp",+ "paused": "Paused exp",+ "stopped": "Stopped exp",+ }+ self._create_experiment("Draft exp")+ self._create_experiment("Running exp", start_date=now)+ self._create_experiment("Paused exp", start_date=now, flag_active=False)+ self._create_experiment("Stopped exp", start_date=now, end_date=now)++ result = run_experiments_list_widget(self.team, {"status": status_filter}, user=self.user)++ assert [row["name"] for row in result["results"]] == [expected_names[status_filter]]+ assert result["results"][0]["status"] == status_filter++ def test_filters_by_creator(self) -> None:+ other_user = User.objects.create_and_join(self.organization, "[email protected]", None)+ self._create_experiment("Mine")+ self._create_experiment("Theirs", created_by=other_user)++ result = run_experiments_list_widget(self.team, {"createdBy": other_user.id}, user=self.user)++ assert [row["name"] for row in result["results"]] == ["Theirs"]++ def test_excludes_deleted_and_other_team_experiments(self) -> None:+ deleted = self._create_experiment("Deleted")+ deleted.deleted = True+ deleted.save()+ self._create_experiment("Kept")++ result = run_experiments_list_widget(self.team, {}, user=self.user)++ assert [row["name"] for row in result["results"]] == ["Kept"]++ def test_caps_results_at_limit_and_reports_has_more(self) -> None:+ for index in range(3):+ self._create_experiment(f"Experiment {index}")++ result = run_experiments_list_widget(self.team, {"limit": 2}, user=self.user)++ assert len(result["results"]) == 2+ assert result["totalCount"] == 3+ assert result["hasMore"] is True++ def test_excludes_experiments_the_user_cannot_access(self) -> None:+ visible = self._create_experiment("Visible")+ blocked = self._create_experiment("Blocked")+ member = User.objects.create_and_join(self.organization, "[email protected]", "pw")+ _block_experiment_for_member(self.team, blocked, member)++ result = run_experiments_list_widget(self.team, {}, user=member)++ assert {row["name"] for row in result["results"]} == {"Visible"}+ assert visible.id in {row["id"] for row in result["results"]}+++class TestExperimentResultsWidget(APIBaseTest):+ def _create_experiment(+ self,+ name: str = "Results test",+ *,+ start_date: Any = None,+ metrics: list[dict[str, Any]] | None = None,+ ) -> Experiment:+ feature_flag = FeatureFlag.objects.create(team=self.team, key=f"flag-{name}", created_by=self.user)+ return Experiment.objects.create(+ team=self.team,+ name=name,+ feature_flag=feature_flag,+ created_by=self.user,+ start_date=start_date,+ metrics=metrics or [],+ )++ def test_returns_needs_configuration_when_no_experiment_selected(self) -> None:+ result = run_experiment_results_widget(self.team, {}, user=self.user)++ assert result == {+ "experiment": None,+ "metrics": [],+ "needsConfiguration": True,+ "hasExperiments": False,+ }++ def test_needs_configuration_reports_existing_experiments(self) -> None:+ self._create_experiment(name="Some experiment")+ result = run_experiment_results_widget(self.team, {}, user=self.user)++ assert result["needsConfiguration"] is True+ assert result["hasExperiments"] is True++ def test_returns_not_found_for_missing_experiment(self) -> None:+ result = run_experiment_results_widget(self.team, {"experimentId": 999999}, user=self.user)++ assert result == {"experiment": None, "metrics": [], "experimentNotFound": True}++ def test_returns_not_found_for_other_team_experiment(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="other")+ flag = FeatureFlag.objects.create(team=other_team, key="other-flag", created_by=self.user)+ experiment = Experiment.objects.create(+ team=other_team, name="Other team", feature_flag=flag, created_by=self.user+ )++ result = run_experiment_results_widget(self.team, {"experimentId": experiment.id}, user=self.user)++ assert result == {"experiment": None, "metrics": [], "experimentNotFound": True}++ def test_returns_not_found_for_experiment_the_user_cannot_access(self) -> None:+ experiment = self._create_experiment(start_date=timezone.now())+ member = User.objects.create_and_join(self.organization, "[email protected]", "pw")+ _block_experiment_for_member(self.team, experiment, member)++ result = run_experiment_results_widget(self.team, {"experimentId": experiment.id}, user=member)++ assert result == {"experiment": None, "metrics": [], "experimentNotFound": True}++ def test_draft_experiment_returns_summary_without_metrics(self) -> None:+ experiment = self._create_experiment(metrics=[_experiment_metric("uuid-1", "Mean metric")])++ result = run_experiment_results_widget(self.team, {"experimentId": experiment.id}, user=self.user)++ assert result["experiment"]["id"] == experiment.id+ assert result["experiment"]["status"] == "draft"+ assert result["metrics"] == []+ assert "totalMetricsCount" not in result++ @patch("products.dashboards.backend.widgets.experiment_results.ExperimentQueryRunner")+ def test_computes_results_for_primary_metrics(self, mock_runner_cls: MagicMock) -> None:+ mock_runner_cls.return_value.run.return_value = MagicMock(+ model_dump=lambda mode="json": {+ "kind": "NewExperimentQueryResponse",+ "baseline": {"key": "control", "number_of_samples": 100, "sum": 40, "sum_squares": 30},+ "variant_results": [{"key": "test", "number_of_samples": 100, "sum": 55, "sum_squares": 40}],+ "clickhouse_sql": "SELECT secret",+ }+ )+ experiment = self._create_experiment(+ start_date=timezone.now(),+ metrics=[_experiment_metric("uuid-1", "Mean metric")],+ )++ result = run_experiment_results_widget(self.team, {"experimentId": experiment.id}, user=self.user)++ assert result["experiment"]["status"] == "running"+ assert result["totalMetricsCount"] == 1+ entry = result["metrics"][0]+ assert entry["name"] == "Mean metric"+ assert entry["error"] is None+ assert entry["metric"]["metric_type"] == "mean"+ assert entry["result"]["baseline"]["key"] == "control"+ assert "clickhouse_sql" not in entry["result"]+ query = mock_runner_cls.call_args.kwargs["query"]+ assert query.experiment_id == experiment.id++ @patch("products.dashboards.backend.widgets.experiment_results.ExperimentQueryRunner")+ def test_caps_computed_metrics_and_reports_total(self, mock_runner_cls: MagicMock) -> None:+ mock_runner_cls.return_value.run.return_value = MagicMock(model_dump=lambda mode="json": {})+ metrics = [+ _experiment_metric(f"uuid-{index}", f"Metric {index}")+ for index in range(MAX_EXPERIMENT_RESULTS_WIDGET_METRICS + 2)+ ]+ experiment = self._create_experiment(start_date=timezone.now(), metrics=metrics)++ result = run_experiment_results_widget(self.team, {"experimentId": experiment.id}, user=self.user)++ assert result["totalMetricsCount"] == MAX_EXPERIMENT_RESULTS_WIDGET_METRICS + 2+ assert len(result["metrics"]) == MAX_EXPERIMENT_RESULTS_WIDGET_METRICS+ assert mock_runner_cls.return_value.run.call_count == MAX_EXPERIMENT_RESULTS_WIDGET_METRICS++ def test_legacy_metric_reports_unsupported_error(self) -> None:+ experiment = self._create_experiment(+ start_date=timezone.now(),+ metrics=[{"kind": "ExperimentTrendsQuery", "uuid": "uuid-legacy", "name": "Legacy"}],+ )++ result = run_experiment_results_widget(self.team, {"experimentId": experiment.id}, user=self.user)++ entry = result["metrics"][0]+ assert entry["error"] == "Legacy metrics are not supported in this widget."+ assert entry["result"] is None++ @patch("products.dashboards.backend.widgets.experiment_results.ExperimentQueryRunner")+ def test_metric_failure_is_isolated_and_sanitized(self, mock_runner_cls: MagicMock) -> None:+ mock_runner_cls.return_value.run.side_effect = Exception("SELECT * FROM secret_table")+ experiment = self._create_experiment(+ start_date=timezone.now(),+ metrics=[_experiment_metric("uuid-1", "Broken metric")],+ )++ result = run_experiment_results_widget(self.team, {"experimentId": experiment.id}, user=self.user)++ entry = result["metrics"][0]+ assert entry["error"] == "Could not compute results for this metric."+ assert "secret_table" not in str(entry)+++class _InlineExecutor:+ """Runs run_widgets work items on the test thread so widget queries can see+ data created inside the test transaction (real threads get new DB connections)."""++ def __init__(self, max_workers: int | None = None) -> None:+ pass++ def __enter__(self) -> "_InlineExecutor":+ return self++ def __exit__(self, *args: object) -> None:+ pass++ def submit(self, fn: Any, *args: Any, **kwargs: Any) -> "Future[Any]":+ future: Future[Any] = Future()+ future.set_result(fn(*args, **kwargs))+ return future+++class TestExperimentWidgetsViaRunWidgetsEndpoint(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.dashboard_api = DashboardAPI(self.client, self.team, self.assertEqual)+ self.executor_patcher = patch(+ "products.dashboards.backend.api.dashboard.ThreadPoolExecutor",+ _InlineExecutor,+ )+ self.executor_patcher.start()+ self.widgets_flag_patcher = patch(+ "products.dashboards.backend.api.dashboard.dashboard_widgets_enabled",+ return_value=True,+ )+ self.widget_create_flag_patcher = patch(+ "products.dashboards.backend.widget_create.dashboard_widgets_enabled",+ return_value=True,+ )+ self.widgets_flag_patcher.start()+ self.widget_create_flag_patcher.start()++ def tearDown(self) -> None:+ self.executor_patcher.stop()+ self.widget_create_flag_patcher.stop()+ self.widgets_flag_patcher.stop()+ super().tearDown()++ def _run(self, dashboard_id: int, tile_ids: list[int]) -> dict[str, Any]:+ response = self.client.get(+ f"/api/projects/{self.team.id}/dashboards/{dashboard_id}/run_widgets/",+ {"tile_ids": ",".join(str(tile_id) for tile_id in tile_ids)},+ )+ self.assertEqual(response.status_code, 200, response.content)+ return response.json()++ def test_runs_experiments_list_widget_tile(self) -> None:+ feature_flag = FeatureFlag.objects.create(team=self.team, key="endpoint-flag", created_by=self.user)+ Experiment.objects.create(+ team=self.team, name="Endpoint experiment", feature_flag=feature_flag, created_by=self.user+ )+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ _, dashboard_json = self.dashboard_api.create_widget_tile(+ dashboard_id, widget_type="experiments_list", config={"limit": 5}+ )+ tile_id = dashboard_json["tiles"][0]["id"]++ body = self._run(dashboard_id, [tile_id])++ tile_result = body["results"][0]+ assert tile_result["widget_type"] == "experiments_list"+ assert tile_result["error"] is None+ assert tile_result["result"]["results"][0]["name"] == "Endpoint experiment"++ def test_runs_experiment_results_widget_tile_unconfigured(self) -> None:+ dashboard_id, _ = self.dashboard_api.create_dashboard({"name": "dash"})+ _, dashboard_json = self.dashboard_api.create_widget_tile(+ dashboard_id, widget_type="experiment_results", config={}+ )+ tile_id = dashboard_json["tiles"][0]["id"]++ body = self._run(dashboard_id, [tile_id])++ tile_result = body["results"][0]+ assert tile_result["widget_type"] == "experiment_results"+ assert tile_result["error"] is None+ assert tile_result["result"]["needsConfiguration"] is Truediff --git a/products/dashboards/backend/api/test/test_widget_config_schema_parity.py b/products/dashboards/backend/api/test/test_widget_config_schema_parity.pyindex b0b21428129d..5481768c26a0 100644--- a/products/dashboards/backend/api/test/test_widget_config_schema_parity.py+++ b/products/dashboards/backend/api/test/test_widget_config_schema_parity.py@@ -25,10 +25,14 @@ class TestWidgetConfigSchemaParity(BaseTest):def test_widget_config_limit_constraints_match_ssot(self) -> None:for widget_type, spec in WIDGET_SPECS.items():+ properties = spec.config_model.model_json_schema(mode="serialization")["properties"]+ if "limit" not in properties:+ # Non-list widgets (e.g. experiment_results) have no row limit.+ continueexpected_max, expected_default = WIDGET_LIMIT_BOUNDS.get(widget_type, (MAX_WIDGET_RESULT_LIMIT, DEFAULT_WIDGET_LIST_LIMIT))- limit_schema = spec.config_model.model_json_schema(mode="serialization")["properties"]["limit"]+ limit_schema = properties["limit"]assert limit_schema["minimum"] == 1assert limit_schema["maximum"] == expected_maxassert limit_schema["default"] == expected_defaultdiff --git a/products/dashboards/backend/constants.py b/products/dashboards/backend/constants.pyindex 8a5b51706475..95339a1704c3 100644--- a/products/dashboards/backend/constants.py+++ b/products/dashboards/backend/constants.py@@ -15,9 +15,22 @@ ACTIVITY_EVENTS_DEFAULT_LIMIT = 25MAX_WIDGETS_BATCH_SIZE = 10# Preset relative ranges only — widgets don't accept arbitrary HogQL date strings.-WIDGET_DATE_FROM_VALUES_ORDERED: tuple[str, ...] = ("-1h", "-3h", "-24h", "-7d", "-14d", "-30d", "-90d")+# Note: `M` is minutes, `m` would be months (see posthog.utils relative-date parsing).+WIDGET_DATE_FROM_VALUES_ORDERED: tuple[str, ...] = (+ "-1M",+ "-30M",+ "-1h",+ "-3h",+ "-24h",+ "-7d",+ "-14d",+ "-30d",+ "-90d",+)WIDGET_DATE_FROM_LABELS: dict[str, str] = {+ "-1M": "Last minute",+ "-30M": "Last 30 minutes","-1h": "Last hour","-3h": "Last 3 hours","-24h": "Last 24 hours",diff --git a/products/dashboards/backend/widget_registry.py b/products/dashboards/backend/widget_registry.pyindex c1c61689f3ac..acc6f0c120ea 100644--- a/products/dashboards/backend/widget_registry.py+++ b/products/dashboards/backend/widget_registry.py@@ -9,6 +9,8 @@ from __future__ import annotationsfrom products.dashboards.backend.widget_specs.configs import (ACTIVITY_EVENTS_LIST_WIDGET_TYPE,ERROR_TRACKING_LIST_WIDGET_TYPE,+ EXPERIMENT_RESULTS_WIDGET_TYPE,+ EXPERIMENTS_LIST_WIDGET_TYPE,SESSION_REPLAY_LIST_WIDGET_TYPE,)from products.dashboards.backend.widget_specs.registry import (@@ -16,6 +18,8 @@ from products.dashboards.backend.widget_specs.registry import (WIDGET_SPECS,DashboardWidgetType,WidgetRegistryEntry,+ count_active_widget_filters,+ extract_widget_filters,get_widget_registry_entry,validate_widget_config,)@@ -29,12 +33,16 @@ WIDGET_REGISTRY: dict[str, WidgetRegistryEntry] = {__all__ = ["ACTIVITY_EVENTS_LIST_WIDGET_TYPE","ERROR_TRACKING_LIST_WIDGET_TYPE",+ "EXPERIMENT_RESULTS_WIDGET_TYPE",+ "EXPERIMENTS_LIST_WIDGET_TYPE","SESSION_REPLAY_LIST_WIDGET_TYPE","EXPECTED_WIDGET_TYPES","DashboardWidgetType","WidgetRegistryEntry","WIDGET_SPECS","WIDGET_REGISTRY",+ "count_active_widget_filters",+ "extract_widget_filters","get_widget_registry_entry","validate_widget_config",]diff --git a/products/dashboards/backend/widget_specs/common.py b/products/dashboards/backend/widget_specs/common.pyindex ca034e2977ca..05054689d98a 100644--- a/products/dashboards/backend/widget_specs/common.py+++ b/products/dashboards/backend/widget_specs/common.py@@ -14,7 +14,7 @@ from products.dashboards.backend.constants import (WIDGET_DATE_FROM_VALUES = frozenset(WIDGET_DATE_FROM_VALUES_ORDERED)-WidgetDateFrom = Literal["-1h", "-3h", "-24h", "-7d", "-14d", "-30d", "-90d"]+WidgetDateFrom = Literal["-1M", "-30M", "-1h", "-3h", "-24h", "-7d", "-14d", "-30d", "-90d"]WidgetOrderDirection = Literal["ASC", "DESC"]diff --git a/products/dashboards/backend/widget_specs/configs.py b/products/dashboards/backend/widget_specs/configs.pyindex 30af693651ac..297a1401281b 100644--- a/products/dashboards/backend/widget_specs/configs.py+++ b/products/dashboards/backend/widget_specs/configs.py@@ -15,6 +15,8 @@ from products.dashboards.backend.widget_specs.common import (ACTIVITY_EVENTS_LIST_WIDGET_TYPE = "activity_events_list"ERROR_TRACKING_LIST_WIDGET_TYPE = "error_tracking_list"SESSION_REPLAY_LIST_WIDGET_TYPE = "session_replay_list"+EXPERIMENTS_LIST_WIDGET_TYPE = "experiments_list"+EXPERIMENT_RESULTS_WIDGET_TYPE = "experiment_results"ErrorTrackingOrderBy = Literal["last_seen", "first_seen", "occurrences", "users", "sessions"]ErrorTrackingWidgetStatus = Literal["archived", "active", "resolved", "pending_release", "suppressed", "all"]@@ -22,6 +24,8 @@ SessionReplayOrderBy = Literal["start_time", "activity_score", "recording_duration", "duration", "click_count", "console_error_count"]WidgetAssigneeType = Literal["user", "role"]+ExperimentsWidgetStatus = Literal["draft", "running", "paused", "stopped", "all"]+ExperimentsWidgetOrderBy = Literal["created_at", "name", "start_date"]class WidgetAssigneeFilter(BaseModel):@@ -68,3 +72,24 @@ class ActivityEventsListWidgetConfig(WidgetListConfigBase):limit: ActivityWidgetLimit = Field(default=ACTIVITY_EVENTS_DEFAULT_LIMIT, description="Maximum number of events to return.")+++class ExperimentsListWidgetConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")++ limit: WidgetLimit = Field(+ default=DEFAULT_WIDGET_LIST_LIMIT, description="Maximum number of experiments to return."+ )+ orderBy: ExperimentsWidgetOrderBy = Field(default="created_at", description="Experiment list sort column.")+ orderDirection: WidgetOrderDirection = Field(default="DESC", description="Sort direction for orderBy.")+ status: ExperimentsWidgetStatus = Field(default="all", description="Experiment status filter.")+ createdBy: int | None = Field(default=None, description="Filter by creator (user id). Omit for any creator.")+++class ExperimentResultsWidgetConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")++ experimentId: int | None = Field(+ default=None,+ description="Experiment to show results for. Null until the user picks one in the widget settings.",+ )diff --git a/products/dashboards/backend/widget_specs/registry.py b/products/dashboards/backend/widget_specs/registry.pyindex 857e7c0c6c68..c1b5a56e49b6 100644--- a/products/dashboards/backend/widget_specs/registry.py+++ b/products/dashboards/backend/widget_specs/registry.py@@ -10,13 +10,19 @@ from rest_framework.exceptions import ValidationError as DRFValidationErrorfrom products.dashboards.backend.widget_specs.configs import (ACTIVITY_EVENTS_LIST_WIDGET_TYPE,ERROR_TRACKING_LIST_WIDGET_TYPE,+ EXPERIMENT_RESULTS_WIDGET_TYPE,+ EXPERIMENTS_LIST_WIDGET_TYPE,SESSION_REPLAY_LIST_WIDGET_TYPE,ActivityEventsListWidgetConfig,ErrorTrackingListWidgetConfig,+ ExperimentResultsWidgetConfig,+ ExperimentsListWidgetConfig,SessionReplayListWidgetConfig,)-DashboardWidgetType = Literal["activity_events_list", "error_tracking_list", "session_replay_list"]+DashboardWidgetType = Literal[+ "activity_events_list", "error_tracking_list", "session_replay_list", "experiments_list", "experiment_results"+]__all__ = ["DashboardWidgetType",@@ -24,6 +30,8 @@ __all__ = ["WidgetRegistryEntry","WidgetSpec","WIDGET_SPECS",+ "count_active_widget_filters",+ "extract_widget_filters","get_widget_registry_entry","get_widget_spec","validate_widget_config",@@ -44,6 +52,14 @@ class WidgetSpec:product_access_denied_message: str | Noneavailability_requirements: tuple[str, ...]form_fields: tuple[str, ...]+ # Config keys whose value represents an on-tile filter. A change to any of these emits the+ # "dashboard widget filters updated" analytics event. Filters stored under a single `widgetFilters`+ # record list that key; widgets that keep filters as top-level config keys (e.g. experiments) list each.+ filter_fields: tuple[str, ...]+++# Status filters use this sentinel for "no status filter applied" — it must not count as an active filter.+_STATUS_ANY_SENTINEL = "all"def validate_widget_config(widget_type: str, config: dict[str, Any]) -> dict[str, Any]:@@ -65,6 +81,8 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:run_activity_events_list_widget,)from products.dashboards.backend.widgets.error_tracking_list import run_error_tracking_list_widget # noqa: PLC0415+ from products.dashboards.backend.widgets.experiment_results import run_experiment_results_widget # noqa: PLC0415+ from products.dashboards.backend.widgets.experiments_list import run_experiments_list_widget # noqa: PLC0415from products.dashboards.backend.widgets.session_replay_list import run_session_replay_list_widget # noqa: PLC0415return {@@ -81,6 +99,7 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:product_access_denied_message=None,availability_requirements=(),form_fields=("limit", "dateRange", "filterTestAccounts"),+ filter_fields=(),),ERROR_TRACKING_LIST_WIDGET_TYPE: WidgetSpec(widget_type=ERROR_TRACKING_LIST_WIDGET_TYPE,@@ -95,6 +114,7 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:product_access_denied_message="You do not have access to error tracking.",availability_requirements=("exception_autocapture",),form_fields=("limit", "orderBy", "orderDirection", "dateRange", "filterTestAccounts", "status"),+ filter_fields=("widgetFilters",),),SESSION_REPLAY_LIST_WIDGET_TYPE: WidgetSpec(widget_type=SESSION_REPLAY_LIST_WIDGET_TYPE,@@ -109,6 +129,37 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:product_access_denied_message="You do not have access to session replay.",availability_requirements=("session_replay_enabled",),form_fields=("limit", "orderBy", "orderDirection", "dateRange", "filterTestAccounts"),+ filter_fields=("widgetFilters",),+ ),+ EXPERIMENTS_LIST_WIDGET_TYPE: WidgetSpec(+ widget_type=EXPERIMENTS_LIST_WIDGET_TYPE,+ config_model=ExperimentsListWidgetConfig,+ query_fn=run_experiments_list_widget,+ required_scopes=("experiment:read",),+ group_id="experiments",+ group_label="Experiments",+ label="Experiments list",+ description="List of experiments filtered by status and creator.",+ required_product_access="experiment",+ product_access_denied_message="You do not have access to experiments.",+ availability_requirements=(),+ form_fields=("limit", "orderBy", "orderDirection", "status", "createdBy"),+ filter_fields=("status", "createdBy"),+ ),+ EXPERIMENT_RESULTS_WIDGET_TYPE: WidgetSpec(+ widget_type=EXPERIMENT_RESULTS_WIDGET_TYPE,+ config_model=ExperimentResultsWidgetConfig,+ query_fn=run_experiment_results_widget,+ required_scopes=("experiment:read",),+ group_id="experiments",+ group_label="Experiments",+ label="Experiment results",+ description="Current results for the primary metrics of a selected experiment.",+ required_product_access="experiment",+ product_access_denied_message="You do not have access to experiments.",+ availability_requirements=(),+ form_fields=("experimentId",),+ filter_fields=("experimentId",),),}@@ -137,3 +188,29 @@ def get_widget_registry_entry(widget_type: str) -> WidgetRegistryEntry | None:def get_widget_spec(widget_type: str) -> WidgetSpec | None:return WIDGET_SPECS.get(widget_type)+++def extract_widget_filters(widget_type: str, config: dict[str, Any] | None) -> dict[str, Any]:+ """Filter-bearing subset of a widget config, used to detect tile-filter changes for analytics."""+ spec = WIDGET_SPECS.get(widget_type)+ if spec is None or config is None:+ return {}+ return {field: config.get(field) for field in spec.filter_fields}+++def count_active_widget_filters(widget_type: str, config: dict[str, Any] | None) -> int:+ """How many filters are actively applied on the tile (0 = no filters, e.g. just cleared)."""+ spec = WIDGET_SPECS.get(widget_type)+ if spec is None or config is None:+ return 0+ count = 0+ for field in spec.filter_fields:+ value = config.get(field)+ if isinstance(value, (dict, list)):+ count += len(value)+ elif field == "status":+ if value not in (None, _STATUS_ANY_SENTINEL):+ count += 1+ elif value is not None:+ count += 1+ return countdiff --git a/products/dashboards/backend/widgets/experiment_results.py b/products/dashboards/backend/widgets/experiment_results.pynew file mode 100644index 000000000000..66f7a3ba4cd3--- /dev/null+++ b/products/dashboards/backend/widgets/experiment_results.py@@ -0,0 +1,157 @@+from __future__ import annotations++import logging+from typing import Any++from pydantic import BaseModel++from posthog.schema import (+ ExperimentFunnelMetric,+ ExperimentMeanMetric,+ ExperimentQuery,+ ExperimentRatioMetric,+ ExperimentRetentionMetric,+)++from posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models.team import Team+from posthog.models.user import User+from posthog.rbac.user_access_control import UserAccessControl++from products.dashboards.backend.widget_specs.configs import EXPERIMENT_RESULTS_WIDGET_TYPE+from products.dashboards.backend.widget_specs.registry import validate_widget_config+from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner+from products.experiments.backend.models.experiment import Experiment++logger = logging.getLogger(__name__)++# Cap on metrics computed per tile so one widget can't fan out into many ClickHouse queries.+MAX_EXPERIMENT_RESULTS_WIDGET_METRICS = 3++_METRIC_BUILDERS: dict[str, type[BaseModel]] = {+ "mean": ExperimentMeanMetric,+ "funnel": ExperimentFunnelMetric,+ "ratio": ExperimentRatioMetric,+ "retention": ExperimentRetentionMetric,+}+++def _serialize_experiment_summary(experiment: Experiment) -> dict[str, Any]:+ return {+ "id": experiment.id,+ "name": experiment.name,+ "status": experiment.status_label,+ "start_date": experiment.start_date.isoformat() if experiment.start_date else None,+ "end_date": experiment.end_date.isoformat() if experiment.end_date else None,+ "feature_flag_key": experiment.feature_flag.key,+ }+++def _collect_primary_metric_dicts(experiment: Experiment) -> list[dict[str, Any]]:+ """Inline primary metrics plus saved metrics linked as primary, in display order when known."""+ metric_dicts: list[dict[str, Any]] = [dict(metric) for metric in (experiment.metrics or [])]++ for link in experiment.experimenttosavedmetric_set.select_related("saved_metric").all():+ metadata = link.metadata or {}+ if metadata.get("type", "primary") != "primary":+ continue+ saved_query = link.saved_metric.query+ if not saved_query:+ continue+ metric_dicts.append({**saved_query, "name": saved_query.get("name") or link.saved_metric.name})++ ordered_uuids = experiment.primary_metrics_ordered_uuids+ if ordered_uuids:+ order = {uuid: index for index, uuid in enumerate(ordered_uuids)}+ metric_dicts.sort(key=lambda metric: order.get(metric.get("uuid"), len(order)))++ return metric_dicts+++def _compute_metric_entry(+ team: Team, experiment: Experiment, metric_dict: dict[str, Any], index: int+) -> dict[str, Any]:+ entry: dict[str, Any] = {+ "uuid": metric_dict.get("uuid"),+ "name": metric_dict.get("name") or f"Metric {index + 1}",+ "metric": None,+ "result": None,+ "error": None,+ }++ metric_builder = _METRIC_BUILDERS.get(metric_dict.get("metric_type", ""))+ if metric_dict.get("kind") != "ExperimentMetric" or metric_builder is None:+ entry["error"] = "Legacy metrics are not supported in this widget."+ return entry++ try:+ metric = metric_builder.model_validate(metric_dict)+ runner = ExperimentQueryRunner(+ query=ExperimentQuery(experiment_id=experiment.id, metric=metric),+ team=team,+ )+ response = runner.run(execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE)+ result_dict = response.model_dump(mode="json")+ entry["metric"] = metric.model_dump(mode="json")+ # Strip per-variant session payloads and debug SQL — the widget only renders the scorecard.+ for key in ("clickhouse_sql", "hogql", "insight", "query_status"):+ result_dict.pop(key, None)+ entry["result"] = result_dict+ except Exception:+ logger.exception(+ "experiment_results_widget_metric_failed",+ extra={"experiment_id": experiment.id, "metric_uuid": metric_dict.get("uuid")},+ )+ entry["error"] = "Could not compute results for this metric."++ return entry+++def run_experiment_results_widget(+ team: Team,+ config: dict[str, Any],+ user: User | None = None,+ *,+ include_total_count: bool = True,+) -> dict[str, Any]:+ typed_config = validate_widget_config(EXPERIMENT_RESULTS_WIDGET_TYPE, config)+ experiment_id = typed_config.get("experimentId")++ # Honor object-level experiment access controls, matching the REST endpoint — a user denied+ # access to a specific experiment must not see it (or its results) through the widget.+ access_control = UserAccessControl(user=user, team=team) if user is not None else None++ if experiment_id is None:+ accessible = Experiment.objects.filter(team=team, deleted=False)+ if access_control is not None:+ accessible = access_control.filter_queryset_by_access_level(accessible)+ return {"experiment": None, "metrics": [], "needsConfiguration": True, "hasExperiments": accessible.exists()}++ experiment_queryset = Experiment.objects.filter(id=experiment_id, team=team, deleted=False).select_related(+ "feature_flag"+ )+ if access_control is not None:+ experiment_queryset = access_control.filter_queryset_by_access_level(experiment_queryset)+ experiment = experiment_queryset.first()+ if experiment is None:+ return {"experiment": None, "metrics": [], "experimentNotFound": True}++ payload: dict[str, Any] = {+ "experiment": _serialize_experiment_summary(experiment),+ "metrics": [],+ }++ if experiment.start_date is None:+ # Draft experiments have no exposure data yet — nothing to compute.+ return payload++ metric_dicts = _collect_primary_metric_dicts(experiment)+ if include_total_count:+ payload["totalMetricsCount"] = len(metric_dicts)++ with tags_context(product=Product.EXPERIMENTS, feature=Feature.QUERY, team_id=team.pk):+ for index, metric_dict in enumerate(metric_dicts[:MAX_EXPERIMENT_RESULTS_WIDGET_METRICS]):+ payload["metrics"].append(_compute_metric_entry(team, experiment, metric_dict, index))++ return payloaddiff --git a/products/dashboards/backend/widgets/experiments_list.py b/products/dashboards/backend/widgets/experiments_list.pynew file mode 100644index 000000000000..97583e4dc70e--- /dev/null+++ b/products/dashboards/backend/widgets/experiments_list.py@@ -0,0 +1,81 @@+from __future__ import annotations++from typing import Any++from posthog.models.team import Team+from posthog.models.user import User+from posthog.rbac.user_access_control import UserAccessControl++from products.dashboards.backend.constants import MAX_WIDGET_RESULT_LIMIT+from products.dashboards.backend.widget_specs.configs import EXPERIMENTS_LIST_WIDGET_TYPE+from products.dashboards.backend.widget_specs.registry import validate_widget_config+from products.dashboards.backend.widgets.list_widget import ListWidgetPage, run_list_widget+from products.experiments.backend.models.experiment import Experiment++ValidatedExperimentsListWidgetConfig = dict[str, Any]+++def _serialize_experiment_row(experiment: Experiment) -> dict[str, Any]:+ created_by = experiment.created_by+ return {+ "id": experiment.id,+ "name": experiment.name,+ "status": experiment.status_label,+ "conclusion": experiment.conclusion,+ "start_date": experiment.start_date.isoformat() if experiment.start_date else None,+ "end_date": experiment.end_date.isoformat() if experiment.end_date else None,+ "created_at": experiment.created_at.isoformat() if experiment.created_at else None,+ "feature_flag_key": experiment.feature_flag.key,+ "created_by": (+ {+ "id": created_by.id,+ "first_name": created_by.first_name,+ "email": created_by.email,+ }+ if created_by+ else None+ ),+ }+++def run_experiments_list_widget(+ team: Team,+ config: dict[str, Any],+ user: User | None = None,+ *,+ include_total_count: bool = True,+) -> dict[str, Any]:+ # ExperimentService transitively imports the dashboard API, which loads the widget registry,+ # which imports this module — deferring the import breaks that cycle.+ from products.experiments.backend.experiment_service import ExperimentService # noqa: PLC0415++ typed_config = validate_widget_config(EXPERIMENTS_LIST_WIDGET_TYPE, config)+ limit = typed_config["limit"]++ order_by = typed_config.get("orderBy", "created_at")+ order_prefix = "-" if typed_config.get("orderDirection", "DESC") == "DESC" else ""+ query_params: dict[str, Any] = {"status": typed_config["status"], "order": f"{order_prefix}{order_by}"}+ created_by = typed_config.get("createdBy")+ if created_by is not None:+ query_params["created_by_id"] = created_by++ base_queryset = Experiment.objects.filter(team=team).select_related("created_by", "feature_flag")+ service = ExperimentService(team=team, user=user)+ queryset = service.filter_experiments_queryset(base_queryset, action="list", query_params=query_params)++ if user is not None:+ # Honor object-level experiment access controls, matching the REST list endpoint.+ queryset = UserAccessControl(user=user, team=team).filter_queryset_by_access_level(queryset)++ def fetch_page(page_limit: int) -> ListWidgetPage:+ rows = list(queryset[: page_limit + 1])+ return ListWidgetPage(results=rows[:page_limit], has_more=len(rows) > page_limit, next_offset=page_limit)++ return run_list_widget(+ limit=limit,+ count_cap=MAX_WIDGET_RESULT_LIMIT,+ include_total_count=include_total_count,+ fetch_page=fetch_page,+ transform_row=_serialize_experiment_row,+ log_key="experiments_list_widget_total_count_failed",+ )diff --git a/products/dashboards/frontend/bin/generate-widget-config-zod.mjs b/products/dashboards/frontend/bin/generate-widget-config-zod.mjsindex 342e1af99888..26f63334d28f 100644--- a/products/dashboards/frontend/bin/generate-widget-config-zod.mjs+++ b/products/dashboards/frontend/bin/generate-widget-config-zod.mjs@@ -148,18 +148,25 @@ function buildBarrelImports(copiedSchemas, configModelNames) {const aliasLines = []const exportedComponentNames = new Set([...configModelNames, WIDGET_FILTER_ENTRY_MODEL])+ // When the friendly type export matches the Orval component name (config models without a+ // "List" infix), the import must be aliased or it collides with the exported type.+ const friendlyTypeNames = new Set(configModelNames.map((name) => configModelNameToFriendlyNames(name).type))+ const importLocalName = (componentName) =>+ friendlyTypeNames.has(componentName) ? `${componentName}Component` : componentNamefor (const { componentName, fileName } of copiedSchemas) {if (!exportedComponentNames.has(componentName)) {continue}const importPath = `./${SCHEMAS_SUBDIR_NAME}/${fileName.replace(/\.ts$/, '')}`- importLines.push(`import { ${componentName} } from '${importPath}'`)+ const localName = importLocalName(componentName)+ const importSpecifier = localName === componentName ? componentName : `${componentName} as ${localName}`+ importLines.push(`import { ${importSpecifier} } from '${importPath}'`)}for (const configModelName of configModelNames) {const { schema, orvalExport } = configModelNameToFriendlyNames(configModelName)- aliasLines.push(`export const ${schema} = /* @__PURE__ */ ${orvalExport}`)+ aliasLines.push(`export const ${schema} = /* @__PURE__ */ ${importLocalName(orvalExport)}`)}const filterEntryImport = copiedSchemas.find((entry) => entry.componentName === WIDGET_FILTER_ENTRY_MODEL)diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.tsxindex c0ae6b780bf5..b919e8b25c1b 100644--- a/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.tsx+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.tsx@@ -231,6 +231,7 @@ export type WidgetListCountNoun = {export const WIDGET_LIST_COUNT_EVENTS: WidgetListCountNoun = { singular: 'event', plural: 'events' }export const WIDGET_LIST_COUNT_ISSUES: WidgetListCountNoun = { singular: 'issue', plural: 'issues' }export const WIDGET_LIST_COUNT_RECORDINGS: WidgetListCountNoun = { singular: 'recording', plural: 'recordings' }+export const WIDGET_LIST_COUNT_EXPERIMENTS: WidgetListCountNoun = { singular: 'experiment', plural: 'experiments' }export function formatWidgetListCountFooter(shown: number,diff --git a/products/dashboards/frontend/components/WidgetCard/index.ts b/products/dashboards/frontend/components/WidgetCard/index.tsindex f26ce21d8d17..b95ca97d4d77 100644--- a/products/dashboards/frontend/components/WidgetCard/index.ts+++ b/products/dashboards/frontend/components/WidgetCard/index.ts@@ -9,6 +9,7 @@ export {WidgetCardSharedPlaceholderBody,type WidgetCardSharedPlaceholderCopy,WIDGET_LIST_COUNT_EVENTS,+ WIDGET_LIST_COUNT_EXPERIMENTS,WIDGET_LIST_COUNT_ISSUES,WIDGET_LIST_COUNT_RECORDINGS,WidgetLoadingState,diff --git a/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts b/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.tsindex c47086a6248b..4423ab1f42d4 100644--- a/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts+++ b/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts@@ -151,6 +151,88 @@ export const sessionReplaySampleRecordings = [},]+export const experimentsSampleListRows = [+ {+ id: 101,+ name: 'New signup CTA',+ status: 'running',+ conclusion: null,+ start_date: '2026-05-12T00:00:00.000Z',+ end_date: null,+ created_at: '2026-05-10T09:00:00.000Z',+ feature_flag_key: 'new-signup-cta',+ created_by: { id: 1, first_name: 'Alex', email: '[email protected]' },+ },+ {+ id: 102,+ name: 'Pricing page layout',+ status: 'draft',+ conclusion: null,+ start_date: null,+ end_date: null,+ created_at: '2026-05-18T14:30:00.000Z',+ feature_flag_key: 'pricing-page-layout',+ created_by: { id: 2, first_name: 'Sam', email: '[email protected]' },+ },+ {+ id: 103,+ name: 'Onboarding checklist copy',+ status: 'stopped',+ conclusion: 'won',+ start_date: '2026-04-01T00:00:00.000Z',+ end_date: '2026-04-22T00:00:00.000Z',+ created_at: '2026-03-28T11:00:00.000Z',+ feature_flag_key: 'onboarding-checklist-copy',+ created_by: { id: 1, first_name: 'Alex', email: '[email protected]' },+ },+]++export const experimentResultsSamplePayload = {+ experiment: {+ id: 101,+ name: 'New signup CTA',+ status: 'running',+ start_date: '2026-05-12T00:00:00.000Z',+ end_date: null,+ feature_flag_key: 'new-signup-cta',+ },+ metrics: [+ {+ uuid: 'metric-1',+ name: 'Signup conversion',+ metric: {+ kind: 'ExperimentMetric',+ metric_type: 'funnel',+ uuid: 'metric-1',+ name: 'Signup conversion',+ series: [{ kind: 'EventsNode', event: 'signed_up' }],+ },+ result: {+ baseline: {+ key: 'control',+ number_of_samples: 4321,+ sum: 980,+ sum_squares: 980,+ },+ variant_results: [+ {+ key: 'test',+ method: 'bayesian',+ number_of_samples: 4287,+ sum: 1112,+ sum_squares: 1112,+ chance_to_win: 0.92,+ credible_interval: [0.012, 0.131],+ significant: false,+ },+ ],+ },+ error: null,+ },+ ],+ totalMetricsCount: 1,+}+/** New widget types: add a case here. See products/dashboards/CONTRIBUTING.md. */export function getWidgetOverviewDemoState(catalogKey: DashboardWidgetCatalogKey): WidgetOverviewDemoState {const catalogEntry = getDashboardWidgetCatalogEntry(catalogKey)@@ -201,6 +283,30 @@ export function getWidgetOverviewDemoState(catalogKey: DashboardWidgetCatalogKeytotalCountCapped: true,},}+ case 'experiments_list':+ return {+ title: defaultTitle,+ description: catalogEntry.description,+ showDescription: true,+ config: defaultConfig,+ loading: false,+ result: {+ results: experimentsSampleListRows,+ hasMore: true,+ limit: 10,+ totalCount: 12,+ totalCountCapped: false,+ },+ }+ case 'experiment_results':+ return {+ title: defaultTitle,+ description: catalogEntry.description,+ showDescription: true,+ config: { ...defaultConfig, experimentId: 101 },+ loading: false,+ result: experimentResultsSamplePayload,+ }default: {const exhaustiveCheck: never = catalogKeyreturn exhaustiveCheckdiff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 39f07be15af3..777e76798912 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -367,6 +367,8 @@ export interface DashboardCollaboratorApi {/*** * `activity_events_list` - activity_events_list* * `error_tracking_list` - error_tracking_list+ * * `experiment_results` - experiment_results+ * * `experiments_list` - experiments_list* * `session_replay_list` - session_replay_list*/export type DashboardPatchWidgetOpenApiWidgetTypeEnumApi =@@ -375,6 +377,8 @@ export type DashboardPatchWidgetOpenApiWidgetTypeEnumApi =export const DashboardPatchWidgetOpenApiWidgetTypeEnumApi = {ActivityEventsList: 'activity_events_list',ErrorTrackingList: 'error_tracking_list',+ ExperimentResults: 'experiment_results',+ ExperimentsList: 'experiments_list',SessionReplayList: 'session_replay_list',} as const@@ -383,6 +387,8 @@ export type WidgetDateRangeApiDateFrom =| nullexport const WidgetDateRangeApiDateFrom = {+ '1m': '-1M',+ '30m': '-30M','1h': '-1h','3h': '-3h','24h': '-24h',@@ -580,10 +586,71 @@ export interface SessionReplayListWidgetConfigApi {savedFilterId?: string | null}+/**+ * Experiment list sort column.+ */+export type ExperimentsListWidgetConfigApiOrderBy =+ (typeof ExperimentsListWidgetConfigApiOrderBy)[keyof typeof ExperimentsListWidgetConfigApiOrderBy]++export const ExperimentsListWidgetConfigApiOrderBy = {+ CreatedAt: 'created_at',+ Name: 'name',+ StartDate: 'start_date',+} as const++/**+ * Sort direction for orderBy.+ */+export type ExperimentsListWidgetConfigApiOrderDirection =+ (typeof ExperimentsListWidgetConfigApiOrderDirection)[keyof typeof ExperimentsListWidgetConfigApiOrderDirection]++export const ExperimentsListWidgetConfigApiOrderDirection = {+ Asc: 'ASC',+ Desc: 'DESC',+} as const++/**+ * Experiment status filter.+ */+export type ExperimentsListWidgetConfigApiStatus =+ (typeof ExperimentsListWidgetConfigApiStatus)[keyof typeof ExperimentsListWidgetConfigApiStatus]++export const ExperimentsListWidgetConfigApiStatus = {+ Draft: 'draft',+ Running: 'running',+ Paused: 'paused',+ Stopped: 'stopped',+ All: 'all',+} as const++export interface ExperimentsListWidgetConfigApi {+ /**+ * Maximum number of experiments to return.+ * @minimum 1+ * @maximum 25+ */+ limit?: number+ /** Experiment list sort column. */+ orderBy?: ExperimentsListWidgetConfigApiOrderBy+ /** Sort direction for orderBy. */+ orderDirection?: ExperimentsListWidgetConfigApiOrderDirection+ /** Experiment status filter. */+ status?: ExperimentsListWidgetConfigApiStatus+ /** Filter by creator (user id). Omit for any creator. */+ createdBy?: number | null+}++export interface ExperimentResultsWidgetConfigApi {+ /** Experiment to show results for. Null until the user picks one in the widget settings. */+ experimentId?: number | null+}+export type DashboardWidgetConfigApi =| ActivityEventsListWidgetConfigApi| ErrorTrackingListWidgetConfigApi| SessionReplayListWidgetConfigApi+ | ExperimentsListWidgetConfigApi+ | ExperimentResultsWidgetConfigApiexport interface DashboardPatchWidgetOpenApiApi {/** Existing widget row ID when updating a widget tile via dashboard PATCH. */@@ -592,6 +659,8 @@ export interface DashboardPatchWidgetOpenApiApi {** * `activity_events_list` - activity_events_list* * `error_tracking_list` - error_tracking_list+ * * `experiment_results` - experiment_results+ * * `experiments_list` - experiments_list* * `session_replay_list` - session_replay_list */widget_type?: DashboardPatchWidgetOpenApiWidgetTypeEnumApi/** Widget-specific configuration. Shape depends on the tile's widget_type. */@@ -8001,17 +8070,69 @@ export interface SessionReplayListWidgetAddRequestOpenApiApi {config: SessionReplayListWidgetConfigApi}+export type ExperimentsListWidgetAddRequestOpenApiApiWidgetType =+ (typeof ExperimentsListWidgetAddRequestOpenApiApiWidgetType)[keyof typeof ExperimentsListWidgetAddRequestOpenApiApiWidgetType]++export const ExperimentsListWidgetAddRequestOpenApiApiWidgetType = {+ ExperimentsList: 'experiments_list',+} as const++export interface ExperimentsListWidgetAddRequestOpenApiApi {+ /**+ * Optional custom display name for the widget tile.+ * @maxLength 400+ * @nullable+ */+ name?: string | null+ /** Optional markdown description shown when show_description is enabled. */+ description?: string+ /** Optional react-grid-layout positions keyed by breakpoint (sm, xs). */+ layouts?: _WidgetTileLayoutsOpenApiApi+ /** Whether to show the description on the dashboard tile. */+ show_description?: boolean+ widget_type: ExperimentsListWidgetAddRequestOpenApiApiWidgetType+ /** Configuration for the experiments list widget. */+ config: ExperimentsListWidgetConfigApi+}++export type ExperimentResultsWidgetAddRequestOpenApiApiWidgetType =+ (typeof ExperimentResultsWidgetAddRequestOpenApiApiWidgetType)[keyof typeof ExperimentResultsWidgetAddRequestOpenApiApiWidgetType]++export const ExperimentResultsWidgetAddRequestOpenApiApiWidgetType = {+ ExperimentResults: 'experiment_results',+} as const++export interface ExperimentResultsWidgetAddRequestOpenApiApi {+ /**+ * Optional custom display name for the widget tile.+ * @maxLength 400+ * @nullable+ */+ name?: string | null+ /** Optional markdown description shown when show_description is enabled. */+ description?: string+ /** Optional react-grid-layout positions keyed by breakpoint (sm, xs). */+ layouts?: _WidgetTileLayoutsOpenApiApi+ /** Whether to show the description on the dashboard tile. */+ show_description?: boolean+ widget_type: ExperimentResultsWidgetAddRequestOpenApiApiWidgetType+ /** Configuration for the experiment results widget. */+ config: ExperimentResultsWidgetConfigApi+}+export type AddDashboardWidgetRequestApi =| ActivityEventsListWidgetAddRequestOpenApiApi| ErrorTrackingListWidgetAddRequestOpenApiApi| SessionReplayListWidgetAddRequestOpenApiApi+ | ExperimentsListWidgetAddRequestOpenApiApi+ | ExperimentResultsWidgetAddRequestOpenApiApi/*** OpenAPI-only batch-add schema with widget_type-discriminated config shapes for agents.*/export interface AddDashboardWidgetsBatchRequestOpenApiApi {/**- * Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).+ * Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, experiment_results, experiments_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).* @minItems 1* @maxItems 10*/@@ -8124,10 +8245,50 @@ export interface SessionReplayListWidgetCatalogEntryOpenApiApi {required_product_access?: string | null}+export type ExperimentsListWidgetCatalogEntryOpenApiApiWidgetType =+ (typeof ExperimentsListWidgetCatalogEntryOpenApiApiWidgetType)[keyof typeof ExperimentsListWidgetCatalogEntryOpenApiApiWidgetType]++export const ExperimentsListWidgetCatalogEntryOpenApiApiWidgetType = {+ ExperimentsList: 'experiments_list',+} as const++export interface ExperimentsListWidgetCatalogEntryOpenApiApi {+ widget_type: ExperimentsListWidgetCatalogEntryOpenApiApiWidgetType+ group_id: string+ group_label: string+ label: string+ description: string+ /** OpenAPI config shape for this widget type (documentation; matches batch-add/PATCH schemas). */+ readonly config_schema: ExperimentsListWidgetConfigApi+ /** @nullable */+ required_product_access?: string | null+}++export type ExperimentResultsWidgetCatalogEntryOpenApiApiWidgetType =+ (typeof ExperimentResultsWidgetCatalogEntryOpenApiApiWidgetType)[keyof typeof ExperimentResultsWidgetCatalogEntryOpenApiApiWidgetType]++export const ExperimentResultsWidgetCatalogEntryOpenApiApiWidgetType = {+ ExperimentResults: 'experiment_results',+} as const++export interface ExperimentResultsWidgetCatalogEntryOpenApiApi {+ widget_type: ExperimentResultsWidgetCatalogEntryOpenApiApiWidgetType+ group_id: string+ group_label: string+ label: string+ description: string+ /** OpenAPI config shape for this widget type (documentation; matches batch-add/PATCH schemas). */+ readonly config_schema: ExperimentResultsWidgetConfigApi+ /** @nullable */+ required_product_access?: string | null+}+export type WidgetCatalogEntryApi =| ActivityEventsListWidgetCatalogEntryOpenApiApi| ErrorTrackingListWidgetCatalogEntryOpenApiApi| SessionReplayListWidgetCatalogEntryOpenApiApi+ | ExperimentsListWidgetCatalogEntryOpenApiApi+ | ExperimentResultsWidgetCatalogEntryOpenApiApiexport interface WidgetCatalogResponseApi {/** Registered dashboard widget types available when dashboard-widgets is enabled. */@@ -8195,6 +8356,26 @@ export const SessionReplayListWidgetTypeEnumApi = {SessionReplayList: 'session_replay_list',} as const+/**+ * * `experiments_list` - experiments_list+ */+export type ExperimentsListWidgetTypeEnumApi =+ (typeof ExperimentsListWidgetTypeEnumApi)[keyof typeof ExperimentsListWidgetTypeEnumApi]++export const ExperimentsListWidgetTypeEnumApi = {+ ExperimentsList: 'experiments_list',+} as const++/**+ * * `experiment_results` - experiment_results+ */+export type ExperimentResultsWidgetTypeEnumApi =+ (typeof ExperimentResultsWidgetTypeEnumApi)[keyof typeof ExperimentResultsWidgetTypeEnumApi]++export const ExperimentResultsWidgetTypeEnumApi = {+ ExperimentResults: 'experiment_results',+} as const+export type DashboardTemplatesListParams = {/*** Omit for all templates. When set, filter by featured flag; parsed with str_to_bool (same as other API query booleans).diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.tsindex b1804266e1d6..5f98d8293204 100644--- a/products/dashboards/frontend/generated/api.zod.ts+++ b/products/dashboards/frontend/generated/api.zod.ts@@ -225,6 +225,12 @@ export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeLimitMaxexport const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeOrderByDefault = `start_time`export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeOrderDirectionDefault = `DESC`+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitDefault = 10+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitMax = 25++export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderByDefault = `created_at`+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderDirectionDefault = `DESC`+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourStatusDefault = `all`export const dashboardsPartialUpdateBodyTilesItemWidgetOneNameMax = 400export const dashboardsPartialUpdateBodyDeleteInsightsDefault = false@@ -253,13 +259,19 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod.optional().describe('Existing widget row ID when updating a widget tile via dashboard PATCH.'),widget_type: zod- .enum(['activity_events_list', 'error_tracking_list', 'session_replay_list'])+ .enum([+ 'activity_events_list',+ 'error_tracking_list',+ 'experiment_results',+ 'experiments_list',+ 'session_replay_list',+ ]).describe(- '\* `activity_events_list` - activity_events_list\n\* `error_tracking_list` - error_tracking_list\n\* `session_replay_list` - session_replay_list'+ '\* `activity_events_list` - activity_events_list\n\* `error_tracking_list` - error_tracking_list\n\* `experiment_results` - experiment_results\n\* `experiments_list` - experiments_list\n\* `session_replay_list` - session_replay_list').optional().describe(- 'Widget type identifier (cannot be changed on update).\n\n\* `activity_events_list` - activity_events_list\n\* `error_tracking_list` - error_tracking_list\n\* `session_replay_list` - session_replay_list'+ 'Widget type identifier (cannot be changed on update).\n\n\* `activity_events_list` - activity_events_list\n\* `error_tracking_list` - error_tracking_list\n\* `experiment_results` - experiment_results\n\* `experiments_list` - experiments_list\n\* `session_replay_list` - session_replay_list'),config: zod.union([@@ -270,6 +282,8 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zoddate_from: zod.union([zod.enum([+ '-1M',+ '-30M','-1h','-3h','-24h',@@ -354,6 +368,8 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zoddate_from: zod.union([zod.enum([+ '-1M',+ '-30M','-1h','-3h','-24h',@@ -475,6 +491,8 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zoddate_from: zod.union([zod.enum([+ '-1M',+ '-30M','-1h','-3h','-24h',@@ -577,6 +595,46 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod'short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply.'),}),+ zod.object({+ limit: zod+ .number()+ .min(1)+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitMax)+ .default(+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitDefault+ )+ .describe('Maximum number of experiments to return.'),+ orderBy: zod+ .enum(['created_at', 'name', 'start_date'])+ .default(+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderByDefault+ )+ .describe('Experiment list sort column.'),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .default(+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderDirectionDefault+ )+ .describe('Sort direction for orderBy.'),+ status: zod+ .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .default(+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourStatusDefault+ )+ .describe('Experiment status filter.'),+ createdBy: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('Filter by creator (user id). Omit for any creator.'),+ }),+ zod.object({+ experimentId: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Experiment to show results for. Null until the user picks one in the widget settings.'+ ),+ }),]).optional().describe("Widget-specific configuration. Shape depends on the tile's widget_type."),@@ -782,6 +840,16 @@ export const dashboardsWidgetsBatchCreateBodyWidgetsItemThreeConfigOneLimitMax =export const dashboardsWidgetsBatchCreateBodyWidgetsItemThreeConfigOneOrderByDefault = `start_time`export const dashboardsWidgetsBatchCreateBodyWidgetsItemThreeConfigOneOrderDirectionDefault = `DESC`+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourNameMax = 400++export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneLimitDefault = 10+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneLimitMax = 25++export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneOrderByDefault = `created_at`+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneOrderDirectionDefault = `DESC`+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneStatusDefault = `all`+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFiveNameMax = 400+export const dashboardsWidgetsBatchCreateBodyWidgetsMax = 10export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod@@ -854,7 +922,17 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zodzod.object({date_from: zod.union([- zod.enum(['-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d']),+ zod.enum([+ '-1M',+ '-30M',+ '-1h',+ '-3h',+ '-24h',+ '-7d',+ '-14d',+ '-30d',+ '-90d',+ ]),zod.null(),]).optional(),@@ -989,7 +1067,17 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zodzod.object({date_from: zod.union([- zod.enum(['-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d']),+ zod.enum([+ '-1M',+ '-30M',+ '-1h',+ '-3h',+ '-24h',+ '-7d',+ '-14d',+ '-30d',+ '-90d',+ ]),zod.null(),]).optional(),@@ -1148,7 +1236,17 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zodzod.object({date_from: zod.union([- zod.enum(['-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d']),+ zod.enum([+ '-1M',+ '-30M',+ '-1h',+ '-3h',+ '-24h',+ '-7d',+ '-14d',+ '-30d',+ '-90d',+ ]),zod.null(),]).optional(),@@ -1241,12 +1339,168 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod}).describe('Configuration for the recent recordings widget.'),}),+ zod.object({+ name: zod+ .string()+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemFourNameMax)+ .nullish()+ .describe('Optional custom display name for the widget tile.'),+ description: zod+ .string()+ .optional()+ .describe('Optional markdown description shown when show_description is enabled.'),+ layouts: zod+ .object({+ sm: zod+ .object({+ x: zod+ .number()+ .optional()+ .describe('Column position in the dashboard grid (0-indexed).'),+ y: zod+ .number()+ .optional()+ .describe('Row position in the dashboard grid (0-indexed).'),+ w: zod+ .number()+ .optional()+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),+ h: zod.number().optional().describe('Height in grid rows.'),+ })+ .optional()+ .describe(+ 'Layout for the standard (desktop) breakpoint. The grid is 12 columns wide.'+ ),+ xs: zod+ .object({+ x: zod+ .number()+ .optional()+ .describe('Column position in the dashboard grid (0-indexed).'),+ y: zod+ .number()+ .optional()+ .describe('Row position in the dashboard grid (0-indexed).'),+ w: zod+ .number()+ .optional()+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),+ h: zod.number().optional().describe('Height in grid rows.'),+ })+ .optional()+ .describe('Layout for the small (mobile) breakpoint. The grid is 1 column wide.'),+ })+ .optional()+ .describe('Optional react-grid-layout positions keyed by breakpoint (sm, xs).'),+ show_description: zod+ .boolean()+ .optional()+ .describe('Whether to show the description on the dashboard tile.'),+ widget_type: zod.enum(['experiments_list']),+ config: zod+ .object({+ limit: zod+ .number()+ .min(1)+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneLimitMax)+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneLimitDefault)+ .describe('Maximum number of experiments to return.'),+ orderBy: zod+ .enum(['created_at', 'name', 'start_date'])+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneOrderByDefault)+ .describe('Experiment list sort column.'),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .default(+ dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneOrderDirectionDefault+ )+ .describe('Sort direction for orderBy.'),+ status: zod+ .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneStatusDefault)+ .describe('Experiment status filter.'),+ createdBy: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('Filter by creator (user id). Omit for any creator.'),+ })+ .describe('Configuration for the experiments list widget.'),+ }),+ zod.object({+ name: zod+ .string()+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemFiveNameMax)+ .nullish()+ .describe('Optional custom display name for the widget tile.'),+ description: zod+ .string()+ .optional()+ .describe('Optional markdown description shown when show_description is enabled.'),+ layouts: zod+ .object({+ sm: zod+ .object({+ x: zod+ .number()+ .optional()+ .describe('Column position in the dashboard grid (0-indexed).'),+ y: zod+ .number()+ .optional()+ .describe('Row position in the dashboard grid (0-indexed).'),+ w: zod+ .number()+ .optional()+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),+ h: zod.number().optional().describe('Height in grid rows.'),+ })+ .optional()+ .describe(+ 'Layout for the standard (desktop) breakpoint. The grid is 12 columns wide.'+ ),+ xs: zod+ .object({+ x: zod+ .number()+ .optional()+ .describe('Column position in the dashboard grid (0-indexed).'),+ y: zod+ .number()+ .optional()+ .describe('Row position in the dashboard grid (0-indexed).'),+ w: zod+ .number()+ .optional()+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),+ h: zod.number().optional().describe('Height in grid rows.'),+ })+ .optional()+ .describe('Layout for the small (mobile) breakpoint. The grid is 1 column wide.'),+ })+ .optional()+ .describe('Optional react-grid-layout positions keyed by breakpoint (sm, xs).'),+ show_description: zod+ .boolean()+ .optional()+ .describe('Whether to show the description on the dashboard tile.'),+ widget_type: zod.enum(['experiment_results']),+ config: zod+ .object({+ experimentId: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Experiment to show results for. Null until the user picks one in the widget settings.'+ ),+ })+ .describe('Configuration for the experiment results widget.'),+ }),])).min(1).max(dashboardsWidgetsBatchCreateBodyWidgetsMax).describe(- 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).'+ 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, experiment_results, experiments_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).'),}).describe('OpenAPI-only batch-add schema with widget_type-discriminated config shapes for agents.')diff --git a/products/dashboards/frontend/generated/widget-config-property-keys.json b/products/dashboards/frontend/generated/widget-config-property-keys.jsonindex 93db9f77f813..9d9415985998 100644--- a/products/dashboards/frontend/generated/widget-config-property-keys.json+++ b/products/dashboards/frontend/generated/widget-config-property-keys.json@@ -19,13 +19,15 @@"orderDirection","savedFilterId","widgetFilters"- ]+ ],+ "experiments_list": ["createdBy", "limit", "orderBy", "orderDirection", "status"],+ "experiment_results": ["experimentId"]},"configPropertyTrees": {"activity_events_list": {"dateRange": {"date_from": {- "$enum": ["-14d", "-1h", "-24h", "-30d", "-3h", "-7d", "-90d"]+ "$enum": ["-14d", "-1M", "-1h", "-24h", "-30M", "-30d", "-3h", "-7d", "-90d"]}},"filterTestAccounts": {@@ -92,7 +94,7 @@"error_tracking_list": {"dateRange": {"date_from": {- "$enum": ["-14d", "-1h", "-24h", "-30d", "-3h", "-7d", "-90d"]+ "$enum": ["-14d", "-1M", "-1h", "-24h", "-30M", "-30d", "-3h", "-7d", "-90d"]}},"filterTestAccounts": {@@ -176,7 +178,7 @@"session_replay_list": {"dateRange": {"date_from": {- "$enum": ["-14d", "-1h", "-24h", "-30d", "-3h", "-7d", "-90d"]+ "$enum": ["-14d", "-1M", "-1h", "-24h", "-30M", "-30d", "-3h", "-7d", "-90d"]}},"filterTestAccounts": {@@ -255,6 +257,28 @@"savedFilterId": {"$type": "string"}+ },+ "experiments_list": {+ "limit": {+ "$type": "integer"+ },+ "orderBy": {+ "$enum": ["created_at", "name", "start_date"]+ },+ "orderDirection": {+ "$enum": ["ASC", "DESC"]+ },+ "status": {+ "$enum": ["all", "draft", "paused", "running", "stopped"]+ },+ "createdBy": {+ "$type": "integer"+ }+ },+ "experiment_results": {+ "experimentId": {+ "$type": "integer"+ }}}}diff --git a/products/dashboards/frontend/generated/widget-config-schemas/experimentResultsWidgetConfig.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/experimentResultsWidgetConfig.zod.tsnew file mode 100644index 000000000000..7e53c505a57d--- /dev/null+++ b/products/dashboards/frontend/generated/widget-config-schemas/experimentResultsWidgetConfig.zod.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v8.14.0 🍺+ * Do not edit manually.+ * PostHog API - 1 ops+ * OpenAPI spec version: 1.0.0+ */+import { z as zod } from 'zod'++export const ExperimentResultsWidgetConfig = /* @__PURE__ */ zod.object({+ experimentId: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('Experiment to show results for. Null until the user picks one in the widget settings.'),+})++export type ExperimentResultsWidgetConfig = zod.input<typeof ExperimentResultsWidgetConfig>+export type ExperimentResultsWidgetConfigOutput = zod.output<typeof ExperimentResultsWidgetConfig>diff --git a/products/dashboards/frontend/generated/widget-config-schemas/experimentsListWidgetConfig.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/experimentsListWidgetConfig.zod.tsnew file mode 100644index 000000000000..2ab7de66bb07--- /dev/null+++ b/products/dashboards/frontend/generated/widget-config-schemas/experimentsListWidgetConfig.zod.ts@@ -0,0 +1,42 @@+/**+ * Generated by orval v8.14.0 🍺+ * Do not edit manually.+ * PostHog API - 1 ops+ * OpenAPI spec version: 1.0.0+ */+import { z as zod } from 'zod'++export const experimentsListWidgetConfigLimitDefault = 10+export const experimentsListWidgetConfigLimitMax = 25++export const experimentsListWidgetConfigOrderByDefault = `created_at`+export const experimentsListWidgetConfigOrderDirectionDefault = `DESC`+export const experimentsListWidgetConfigStatusDefault = `all`++export const ExperimentsListWidgetConfig = /* @__PURE__ */ zod.object({+ limit: zod+ .number()+ .min(1)+ .max(experimentsListWidgetConfigLimitMax)+ .default(experimentsListWidgetConfigLimitDefault)+ .describe('Maximum number of experiments to return.'),+ orderBy: zod+ .enum(['created_at', 'name', 'start_date'])+ .default(experimentsListWidgetConfigOrderByDefault)+ .describe('Experiment list sort column.'),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .default(experimentsListWidgetConfigOrderDirectionDefault)+ .describe('Sort direction for orderBy.'),+ status: zod+ .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .default(experimentsListWidgetConfigStatusDefault)+ .describe('Experiment status filter.'),+ createdBy: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('Filter by creator (user id). Omit for any creator.'),+})++export type ExperimentsListWidgetConfig = zod.input<typeof ExperimentsListWidgetConfig>+export type ExperimentsListWidgetConfigOutput = zod.output<typeof ExperimentsListWidgetConfig>diff --git a/products/dashboards/frontend/generated/widget-config-schemas/widgetDateRange.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/widgetDateRange.zod.tsindex f45220672911..b30796e5c46a 100644--- a/products/dashboards/frontend/generated/widget-config-schemas/widgetDateRange.zod.ts+++ b/products/dashboards/frontend/generated/widget-config-schemas/widgetDateRange.zod.ts@@ -7,7 +7,9 @@import { z as zod } from 'zod'export const WidgetDateRange = /* @__PURE__ */ zod.object({- date_from: zod.union([zod.enum(['-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d']), zod.null()]).optional(),+ date_from: zod+ .union([zod.enum(['-1M', '-30M', '-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d']), zod.null()])+ .optional(),})export type WidgetDateRange = zod.input<typeof WidgetDateRange>diff --git a/products/dashboards/frontend/generated/widget-configs.zod.ts b/products/dashboards/frontend/generated/widget-configs.zod.tsindex 589f22bc186f..4721b823afdf 100644--- a/products/dashboards/frontend/generated/widget-configs.zod.ts+++ b/products/dashboards/frontend/generated/widget-configs.zod.ts@@ -5,16 +5,22 @@ import { z as zod } from 'zod'import { ActivityEventsListWidgetConfig } from './widget-config-schemas/activityEventsListWidgetConfig.zod'import { ErrorTrackingListWidgetConfig } from './widget-config-schemas/errorTrackingListWidgetConfig.zod'+import { ExperimentResultsWidgetConfig as ExperimentResultsWidgetConfigComponent } from './widget-config-schemas/experimentResultsWidgetConfig.zod'+import { ExperimentsListWidgetConfig } from './widget-config-schemas/experimentsListWidgetConfig.zod'import { SessionReplayListWidgetConfig } from './widget-config-schemas/sessionReplayListWidgetConfig.zod'import { WidgetFilterEntry } from './widget-config-schemas/widgetFilterEntry.zod'export const activityEventsWidgetConfigSchema = /* @__PURE__ */ ActivityEventsListWidgetConfigexport const errorTrackingWidgetConfigSchema = /* @__PURE__ */ ErrorTrackingListWidgetConfig+export const experimentResultsWidgetConfigSchema = /* @__PURE__ */ ExperimentResultsWidgetConfigComponent+export const experimentsWidgetConfigSchema = /* @__PURE__ */ ExperimentsListWidgetConfigexport const sessionReplayWidgetConfigSchema = /* @__PURE__ */ SessionReplayListWidgetConfigexport const widgetFilterEntrySchema = /* @__PURE__ */ WidgetFilterEntryexport type ActivityEventsWidgetConfig = zod.infer<typeof activityEventsWidgetConfigSchema>export type ErrorTrackingWidgetConfig = zod.infer<typeof errorTrackingWidgetConfigSchema>+export type ExperimentResultsWidgetConfig = zod.infer<typeof experimentResultsWidgetConfigSchema>+export type ExperimentsWidgetConfig = zod.infer<typeof experimentsWidgetConfigSchema>export type SessionReplayWidgetConfig = zod.infer<typeof sessionReplayWidgetConfigSchema>type WidgetFiltersRecord = NonNullable<ActivityEventsWidgetConfig['widgetFilters']>@@ -37,6 +43,18 @@ export const errorTrackingWidgetFormSchema = errorTrackingWidgetConfigSchema.picstatus: true,})+export const experimentResultsWidgetFormSchema = experimentResultsWidgetConfigSchema.pick({+ experimentId: true,+})++export const experimentsWidgetFormSchema = experimentsWidgetConfigSchema.pick({+ limit: true,+ orderBy: true,+ orderDirection: true,+ status: true,+ createdBy: true,+})+export const sessionReplayWidgetFormSchema = sessionReplayWidgetConfigSchema.pick({limit: true,orderBy: true,diff --git a/products/dashboards/frontend/generated/widget-date-from-options.json b/products/dashboards/frontend/generated/widget-date-from-options.jsonindex 4aa41e6a9a00..6ccae1d053cf 100644--- a/products/dashboards/frontend/generated/widget-date-from-options.json+++ b/products/dashboards/frontend/generated/widget-date-from-options.json@@ -1,5 +1,13 @@{"options": [+ {+ "value": "-1M",+ "label": "Last minute"+ },+ {+ "value": "-30M",+ "label": "Last 30 minutes"+ },{"value": "-1h","label": "Last hour"diff --git a/products/dashboards/frontend/generated/widget-form-fields.json b/products/dashboards/frontend/generated/widget-form-fields.jsonindex 91d3ce45c55b..75d03ef6c988 100644--- a/products/dashboards/frontend/generated/widget-form-fields.json+++ b/products/dashboards/frontend/generated/widget-form-fields.json@@ -12,6 +12,18 @@"formSchemaExport": "errorTrackingWidgetFormSchema","formFields": ["limit", "orderBy", "orderDirection", "dateRange", "filterTestAccounts", "status"]},+ "experiment_results": {+ "configSchemaExport": "experimentResultsWidgetConfigSchema",+ "configTypeExport": "ExperimentResultsWidgetConfig",+ "formSchemaExport": "experimentResultsWidgetFormSchema",+ "formFields": ["experimentId"]+ },+ "experiments_list": {+ "configSchemaExport": "experimentsWidgetConfigSchema",+ "configTypeExport": "ExperimentsWidgetConfig",+ "formSchemaExport": "experimentsWidgetFormSchema",+ "formFields": ["limit", "orderBy", "orderDirection", "status", "createdBy"]+ },"session_replay_list": {"configSchemaExport": "sessionReplayWidgetConfigSchema","configTypeExport": "SessionReplayWidgetConfig",diff --git a/products/dashboards/frontend/types.ts b/products/dashboards/frontend/types.tsindex 8156985301a4..813944565793 100644--- a/products/dashboards/frontend/types.ts+++ b/products/dashboards/frontend/types.ts@@ -1,4 +1,4 @@/*** Product RBAC for gated widget types. New types: extend union here — see products/dashboards/CONTRIBUTING.md.*/-export type DashboardWidgetProductAccess = 'error_tracking' | 'session_recording'+export type DashboardWidgetProductAccess = 'error_tracking' | 'session_recording' | 'experiment'diff --git a/products/dashboards/frontend/widgetProductAccess.ts b/products/dashboards/frontend/widgetProductAccess.tsindex fdd6cbbfd08e..e54e836ead0b 100644--- a/products/dashboards/frontend/widgetProductAccess.ts+++ b/products/dashboards/frontend/widgetProductAccess.ts@@ -8,6 +8,7 @@ const WIDGET_PRODUCT_ACCESS_CHECKS = {// New gated widget types: add a case here — CONTRIBUTING.mderror_tracking: () => userHasAccess(AccessControlResourceType.ErrorTracking, AccessControlLevel.Viewer),session_recording: () => userHasAccess(AccessControlResourceType.SessionRecording, AccessControlLevel.Viewer),+ experiment: () => userHasAccess(AccessControlResourceType.Experiment, AccessControlLevel.Viewer),} satisfies Record<DashboardWidgetProductAccess, () => boolean>export function userHasDashboardWidgetProductAccess(productAccess: DashboardWidgetProductAccess | undefined): boolean {diff --git a/products/dashboards/frontend/widget_types/catalog.ts b/products/dashboards/frontend/widget_types/catalog.tsindex a1bc6b8ee44a..baee36ddddd2 100644--- a/products/dashboards/frontend/widget_types/catalog.ts+++ b/products/dashboards/frontend/widget_types/catalog.ts@@ -6,11 +6,17 @@ import { ActivityTab } from '~/types'import {activityEventsWidgetConfigSchema,errorTrackingWidgetConfigSchema,+ experimentResultsWidgetConfigSchema,+ experimentsWidgetConfigSchema,sessionReplayWidgetConfigSchema,} from '../generated/widget-configs.zod'import type { DashboardWidgetProductAccess } from '../types'import { ActivityEventsWidgetPreview } from '../widgets/previews/ActivityEventsWidgetPreview'import { ErrorTrackingWidgetPreview } from '../widgets/previews/ErrorTrackingWidgetPreview'+import {+ ExperimentResultsWidgetPreview,+ ExperimentsListWidgetPreview,+} from '../widgets/previews/ExperimentsWidgetPreviews'import { SessionReplayWidgetPreview } from '../widgets/previews/SessionReplayWidgetPreview'import type { WidgetAvailabilityConfig } from './widgetAvailability'@@ -68,6 +74,7 @@ export const DASHBOARD_WIDGET_GROUP_LABELS = {activity: 'Activity',error_tracking: 'Error tracking',session_replay: 'Session replay',+ experiments: 'Experiments',} as const satisfies Record<string, string>export function getDashboardWidgetGroupLabel(groupId: string): string {@@ -157,6 +164,37 @@ export const DASHBOARD_WIDGET_CATALOG = {allowedPropertyNames: SESSION_REPLAY_LIST_TILE_FILTER_PROPERTIES,},},+ experiments_list: {+ groupId: 'experiments',+ label: 'Experiments list',+ description: 'List of experiments filtered by status and creator.',+ headerTitle: 'Experiments',+ // Filtered by status/creator, not a date range — don't show a (defaulted) date in the header.+ headerMeta: { showDateRange: false },+ defaultConfig: experimentsWidgetConfigSchema.parse({}),+ defaultLayout: { w: 6, h: 5, minW: 3, minH: 3 },+ productAccess: 'experiment',+ titleHref: urls.experiments(),+ sharedPlaceholder: {+ title: 'Experiments',+ message: 'Log in to PostHog to see experiments from this dashboard.',+ },+ },+ experiment_results: {+ groupId: 'experiments',+ label: 'Experiment results',+ description: 'Current results for the primary metrics of a selected experiment.',+ headerTitle: 'Experiment results',+ // Shows a selected experiment's current results — there's no date range to surface.+ headerMeta: { showDateRange: false },+ defaultConfig: experimentResultsWidgetConfigSchema.parse({}),+ defaultLayout: { w: 6, h: 5, minW: 3, minH: 3 },+ productAccess: 'experiment',+ sharedPlaceholder: {+ title: 'Experiment results',+ message: 'Log in to PostHog to see experiment results from this dashboard.',+ },+ },activity_events_list: {groupId: 'activity',label: 'Recent events',@@ -181,6 +219,8 @@ export const DASHBOARD_WIDGET_PREVIEWS: Record<DashboardWidgetCatalogKey, () =>activity_events_list: ActivityEventsWidgetPreview,error_tracking_list: ErrorTrackingWidgetPreview,session_replay_list: SessionReplayWidgetPreview,+ experiments_list: ExperimentsListWidgetPreview,+ experiment_results: ExperimentResultsWidgetPreview,}export type ResolvedDashboardWidgetCatalogEntry = DashboardWidgetCatalogEntry & {diff --git a/products/dashboards/frontend/widgets/AddWidgetModal.tsx b/products/dashboards/frontend/widgets/AddWidgetModal.tsxindex 270d98883257..4c48848f1f4a 100644--- a/products/dashboards/frontend/widgets/AddWidgetModal.tsx+++ b/products/dashboards/frontend/widgets/AddWidgetModal.tsx@@ -114,7 +114,7 @@ export function AddWidgetModal({ isOpen, onClose, loading, onAdd }: AddWidgetMod><div className="@container/add-widget-modal"><div- className="grid grid-cols-1 @min-[36rem]/add-widget-modal:grid-cols-2 gap-x-3 gap-y-4"+ className="grid grid-cols-1 @min-[48rem]/add-widget-modal:grid-cols-2 gap-x-3 gap-y-4"aria-label="Widget types">{DASHBOARD_WIDGET_CATALOG_GROUPS.map((group, groupIndex) => (diff --git a/products/dashboards/frontend/widgets/experiments/EditExperimentResultsWidgetModal.stories.tsx b/products/dashboards/frontend/widgets/experiments/EditExperimentResultsWidgetModal.stories.tsxnew file mode 100644index 000000000000..ab0385bf63df--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/EditExperimentResultsWidgetModal.stories.tsx@@ -0,0 +1,74 @@+import type { Meta, StoryObj } from '@storybook/react'++import { mswDecorator } from '~/mocks/browser'++import { widgetStorybookParameters } from '../../components/WidgetCard/widgetCardStoryFixtures'+import { experimentsSampleListRows } from '../../components/WidgetCard/widgetOverviewStoryFixtures'+import { getDashboardWidgetCatalogEntry } from '../../widget_types/catalog'+import type { DashboardWidgetEditModalProps } from '../registry'+import { EditExperimentResultsWidgetModal } from './EditExperimentResultsWidgetModal'++const EXPERIMENT_RESULTS_CATALOG = getDashboardWidgetCatalogEntry('experiment_results')!+const DEFAULT_CONFIG = EXPERIMENT_RESULTS_CATALOG.defaultConfig as Record<string, unknown>++// The settings modal embeds the searchable experiment picker (experimentPickerLogic) — mock the+// list/retrieve endpoints so the options and the selected experiment resolve.+const pickerExperiments = experimentsSampleListRows.map(({ id, name, created_by }) => ({ id, name, created_by }))+const experimentsApiDecorator = mswDecorator({+ get: {+ '/api/projects/:team_id/experiments/': () => [+ 200,+ { results: pickerExperiments, count: pickerExperiments.length },+ ],+ '/api/projects/:team_id/experiments/:id/': ({ params }) => {+ const id = Number(params.id)+ return [200, pickerExperiments.find((experiment) => experiment.id === id) ?? pickerExperiments[0]]+ },+ },+})++type EditExperimentResultsWidgetModalStoryProps = Partial<DashboardWidgetEditModalProps>++function EditExperimentResultsWidgetModalStory({+ isOpen = true,+ onClose = () => undefined,+ onSave = () => Promise.resolve(),+ config = DEFAULT_CONFIG,+ name = 'Experiment results',+ defaultTitle = EXPERIMENT_RESULTS_CATALOG.headerTitle ?? EXPERIMENT_RESULTS_CATALOG.label,+ description = EXPERIMENT_RESULTS_CATALOG.description,+ ...props+}: EditExperimentResultsWidgetModalStoryProps): JSX.Element {+ return (+ <EditExperimentResultsWidgetModal+ isOpen={isOpen}+ onClose={onClose}+ config={config}+ onSave={onSave}+ name={name}+ defaultTitle={defaultTitle}+ description={description}+ {...props}+ />+ )+}++// Storybook CSF requires a string literal `title` derived from catalog groupLabel/label.+const meta: Meta<typeof EditExperimentResultsWidgetModalStory> = {+ title: 'Dashboards/Dashboard Widgets/Widget types/Experiments/Experiment results/Widget settings',+ component: EditExperimentResultsWidgetModalStory,+ parameters: {+ layout: 'fullscreen',+ ...widgetStorybookParameters,+ },+ decorators: [experimentsApiDecorator],+ args: {+ config: { ...DEFAULT_CONFIG, experimentId: 101 },+ },+}++export default meta++type Story = StoryObj<typeof EditExperimentResultsWidgetModalStory>++export const Default: Story = {}diff --git a/products/dashboards/frontend/widgets/experiments/EditExperimentResultsWidgetModal.tsx b/products/dashboards/frontend/widgets/experiments/EditExperimentResultsWidgetModal.tsxnew file mode 100644index 000000000000..12d7100813a9--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/EditExperimentResultsWidgetModal.tsx@@ -0,0 +1,73 @@+import { BindLogic, useActions, useValues } from 'kea'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonModal } from 'lib/lemon-ui/LemonModal'++import { EditWidgetModalTileDetailsSection } from '../EditWidgetModalTileDetailsSection'+import type { DashboardWidgetEditModalProps } from '../registry'+import { editExperimentResultsWidgetModalLogic } from './editExperimentResultsWidgetModalLogic'++function EditExperimentResultsWidgetModalContents(): JSX.Element {+ const { tileName, tileDescription, saving, saveDisabledReason, onClose, defaultTitle } = useValues(+ editExperimentResultsWidgetModalLogic+ )+ const { setTileName, setTileDescription, submit } = useActions(editExperimentResultsWidgetModalLogic)++ return (+ <LemonModal+ isOpen+ onClose={onClose}+ title="Widget settings"+ description="Configure the tile details. Pick which experiment's results to show from the tile's filter bar."+ width={680}+ footer={+ <>+ <div className="flex-1" />+ <LemonButton type="secondary" onClick={onClose} disabled={saving}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ loading={saving}+ disabledReason={saveDisabledReason}+ onClick={() => submit()}+ >+ Save+ </LemonButton>+ </>+ }+ >+ <EditWidgetModalTileDetailsSection+ tileName={tileName}+ tileDescription={tileDescription}+ defaultTitle={defaultTitle}+ saving={saving}+ setTileName={setTileName}+ setTileDescription={setTileDescription}+ />+ </LemonModal>+ )+}++export function EditExperimentResultsWidgetModal({+ isOpen,+ onClose,+ config,+ onSave,+ name,+ defaultTitle,+ description,+}: DashboardWidgetEditModalProps): JSX.Element | null {+ if (!isOpen) {+ return null+ }++ return (+ <BindLogic+ logic={editExperimentResultsWidgetModalLogic}+ props={{ onClose, config, onSave, name, defaultTitle, description }}+ >+ <EditExperimentResultsWidgetModalContents />+ </BindLogic>+ )+}diff --git a/products/dashboards/frontend/widgets/experiments/EditExperimentsListWidgetModal.stories.tsx b/products/dashboards/frontend/widgets/experiments/EditExperimentsListWidgetModal.stories.tsxnew file mode 100644index 000000000000..2f9715ef388f--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/EditExperimentsListWidgetModal.stories.tsx@@ -0,0 +1,55 @@+import type { Meta, StoryObj } from '@storybook/react'++import { widgetStorybookParameters } from '../../components/WidgetCard/widgetCardStoryFixtures'+import { getDashboardWidgetCatalogEntry } from '../../widget_types/catalog'+import type { DashboardWidgetEditModalProps } from '../registry'+import { EditExperimentsListWidgetModal } from './EditExperimentsListWidgetModal'++const EXPERIMENTS_LIST_CATALOG = getDashboardWidgetCatalogEntry('experiments_list')!+const DEFAULT_CONFIG = EXPERIMENTS_LIST_CATALOG.defaultConfig as Record<string, unknown>++type EditExperimentsListWidgetModalStoryProps = Partial<DashboardWidgetEditModalProps>++function EditExperimentsListWidgetModalStory({+ isOpen = true,+ onClose = () => undefined,+ onSave = () => Promise.resolve(),+ config = DEFAULT_CONFIG,+ name = 'Experiments',+ defaultTitle = EXPERIMENTS_LIST_CATALOG.headerTitle ?? EXPERIMENTS_LIST_CATALOG.label,+ description = EXPERIMENTS_LIST_CATALOG.description,+ ...props+}: EditExperimentsListWidgetModalStoryProps): JSX.Element {+ return (+ <EditExperimentsListWidgetModal+ isOpen={isOpen}+ onClose={onClose}+ config={config}+ onSave={onSave}+ name={name}+ defaultTitle={defaultTitle}+ description={description}+ {...props}+ />+ )+}++// Storybook CSF requires a string literal `title` derived from catalog groupLabel/label.+const meta: Meta<typeof EditExperimentsListWidgetModalStory> = {+ title: 'Dashboards/Dashboard Widgets/Widget types/Experiments/Experiments/Widget settings',+ component: EditExperimentsListWidgetModalStory,+ parameters: {+ layout: 'fullscreen',+ ...widgetStorybookParameters,+ },+ decorators: [],+ args: {+ config: { ...DEFAULT_CONFIG, status: 'running', orderBy: 'created_at', orderDirection: 'DESC' },+ },+}++export default meta++type Story = StoryObj<typeof EditExperimentsListWidgetModalStory>++export const Default: Story = {}diff --git a/products/dashboards/frontend/widgets/experiments/EditExperimentsListWidgetModal.tsx b/products/dashboards/frontend/widgets/experiments/EditExperimentsListWidgetModal.tsxnew file mode 100644index 000000000000..bfd2f5b8c89e--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/EditExperimentsListWidgetModal.tsx@@ -0,0 +1,146 @@+import { BindLogic, useActions, useValues } from 'kea'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'+import { LemonField } from 'lib/lemon-ui/LemonField/LemonField'+import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'+import { LemonModal } from 'lib/lemon-ui/LemonModal'+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'++import { getDashboardWidgetGroupLabel } from '../../widget_types/catalog'+import { EditWidgetModalTileDetailsSection } from '../EditWidgetModalTileDetailsSection'+import type { DashboardWidgetEditModalProps } from '../registry'+import { editExperimentsListWidgetModalLogic } from './editExperimentsListWidgetModalLogic'+import {+ EXPERIMENTS_WIDGET_ORDER_BY_OPTIONS,+ EXPERIMENTS_WIDGET_ORDER_DIRECTION_OPTIONS,+} from './experimentsWidgetConfigValidation'++function EditExperimentsListWidgetModalContents(): JSX.Element {+ const {+ limit,+ orderBy,+ orderDirection,+ tileName,+ tileDescription,+ activeFieldErrors,+ saving,+ saveDisabledReason,+ onClose,+ defaultTitle,+ } = useValues(editExperimentsListWidgetModalLogic)+ const { setLimit, setOrderBy, setOrderDirection, setTileName, setTileDescription, clearFieldError, submit } =+ useActions(editExperimentsListWidgetModalLogic)++ return (+ <LemonModal+ isOpen+ onClose={onClose}+ title="Widget settings"+ description="Configure tile details and which experiments appear on this dashboard."+ width={680}+ footer={+ <>+ <div className="flex-1" />+ <LemonButton type="secondary" onClick={onClose} disabled={saving}>+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ loading={saving}+ disabledReason={saveDisabledReason}+ onClick={() => submit()}+ >+ Save+ </LemonButton>+ </>+ }+ >+ <div className="flex flex-col gap-4">+ <EditWidgetModalTileDetailsSection+ tileName={tileName}+ tileDescription={tileDescription}+ defaultTitle={defaultTitle}+ saving={saving}+ setTileName={setTileName}+ setTileDescription={setTileDescription}+ />+ <LemonDivider className="my-0" />+ <section className="flex flex-col gap-3">+ <h5 className="text-sm font-semibold m-0">{getDashboardWidgetGroupLabel('experiments')}</h5>+ <p className="m-0 text-xs text-muted">+ Filter by status and creator directly on the tile using the filter bar.+ </p>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">+ <LemonField.Pure label="Sort by" error={activeFieldErrors.orderBy}>+ <LemonSelect+ fullWidth+ value={orderBy}+ onChange={(value) => {+ if (value) {+ setOrderBy(value)+ clearFieldError('orderBy')+ }+ }}+ options={EXPERIMENTS_WIDGET_ORDER_BY_OPTIONS}+ />+ </LemonField.Pure>+ <LemonField.Pure label="Direction" error={activeFieldErrors.orderDirection}>+ <LemonSelect+ fullWidth+ value={orderDirection}+ onChange={(value) => {+ if (value) {+ setOrderDirection(value)+ clearFieldError('orderDirection')+ }+ }}+ options={EXPERIMENTS_WIDGET_ORDER_DIRECTION_OPTIONS}+ />+ </LemonField.Pure>+ </div>+ <LemonField.Pure+ label="Number of experiments"+ help="Show up to 25 experiments on the tile."+ error={activeFieldErrors.limit}+ >+ <LemonInput+ type="number"+ min={1}+ max={25}+ fullWidth+ value={limit}+ onChange={(value) => {+ setLimit(Number(value))+ clearFieldError('limit')+ }}+ />+ </LemonField.Pure>+ </section>+ </div>+ </LemonModal>+ )+}++export function EditExperimentsListWidgetModal({+ isOpen,+ onClose,+ config,+ onSave,+ name,+ defaultTitle,+ description,+}: DashboardWidgetEditModalProps): JSX.Element | null {+ if (!isOpen) {+ return null+ }++ return (+ <BindLogic+ logic={editExperimentsListWidgetModalLogic}+ props={{ onClose, config, onSave, name, defaultTitle, description }}+ >+ <EditExperimentsListWidgetModalContents />+ </BindLogic>+ )+}diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.scss b/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.scssnew file mode 100644index 000000000000..0be799f6554c--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.scss@@ -0,0 +1,8 @@+// Scoped to this picker's dropdown only: let each option's label fill the row so the+// creator can right-align. Avoids changing the shared LemonInputSelect for everyone.+.ExperimentPickerSelect__dropdown {+ .LemonButton__content > span {+ flex: 1;+ min-width: 0;+ }+}diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.tsxnew file mode 100644index 000000000000..a90f8d7cfaca--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/ExperimentPickerSelect.tsx@@ -0,0 +1,102 @@+import './ExperimentPickerSelect.scss'++import { useActions, useValues } from 'kea'+import { useEffect, useMemo } from 'react'++import { LemonInputSelect, type LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { fullName } from 'lib/utils/strings'++import type { ExperimentApi } from 'products/experiments/frontend/generated/api.schemas'++import { experimentPickerLogic } from './experimentPickerLogic'++export type ExperimentPickerSelectProps = {+ /** Isolates picker state per mount (modal vs. each tile). */+ pickerKey: string+ value: number | null+ onChange: (experimentId: number | null) => void+ disabled?: boolean+ size?: 'small' | 'medium'+ fullWidth?: boolean+ dataAttr?: string+}++function ExperimentOptionLabel({ experiment }: { experiment: ExperimentApi }): JSX.Element {+ const creator = experiment.created_by+ const creatorName = creator ? fullName(creator) || creator.email : null+ return (+ <span className="flex w-full items-center justify-between gap-2">+ <span className="min-w-0 flex-1 truncate">{experiment.name}</span>+ {creator ? (+ <span className="inline-flex shrink-0 items-center gap-1 text-xs text-muted">+ <ProfilePicture+ user={{ first_name: creator.first_name, last_name: creator.last_name, email: creator.email }}+ size="sm"+ />+ <span className="max-w-32 truncate">{creatorName}</span>+ </span>+ ) : null}+ </span>+ )+}++export function ExperimentPickerSelect({+ pickerKey,+ value,+ onChange,+ disabled,+ size = 'small',+ fullWidth = false,+ dataAttr,+}: ExperimentPickerSelectProps): JSX.Element {+ const logic = experimentPickerLogic({ pickerKey })+ const { experimentOptions, experimentOptionsLoading, selectedExperiment, search } = useValues(logic)+ const { ensureOptionsLoaded, setSearch, ensureSelectedLoaded } = useActions(logic)++ // Resolve the selected label even when it falls outside the loaded/searched page.+ useEffect(() => {+ if (value != null) {+ ensureSelectedLoaded(value)+ }+ }, [value, ensureSelectedLoaded])++ const options = useMemo((): LemonInputSelectOption[] => {+ const byId = new Map<number, ExperimentApi>()+ if (selectedExperiment) {+ byId.set(selectedExperiment.id, selectedExperiment)+ }+ for (const experiment of experimentOptions) {+ byId.set(experiment.id, experiment)+ }+ return Array.from(byId.values(), (experiment) => ({+ key: String(experiment.id),+ label: experiment.name,+ labelComponent: <ExperimentOptionLabel experiment={experiment} />,+ }))+ }, [experimentOptions, selectedExperiment])++ return (+ <LemonInputSelect+ mode="single"+ size={size}+ fullWidth={fullWidth}+ popoverClassName="ExperimentPickerSelect__dropdown"+ placeholder="Select an experiment"+ loading={experimentOptionsLoading}+ disabled={disabled}+ disableFiltering+ value={value != null ? [String(value)] : []}+ options={options}+ emptyStateComponent={+ <p className="text-secondary italic p-1">+ {search ? `No experiments matching "${search}"` : 'No experiments yet'}+ </p>+ }+ onFocus={() => ensureOptionsLoaded()}+ onInputChange={(text) => setSearch(text)}+ onChange={(values) => onChange(values.length > 0 ? Number(values[0]) : null)}+ data-attr={dataAttr}+ />+ )+}diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.stories.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.stories.tsxnew file mode 100644index 000000000000..aa3369080e69--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.stories.tsx@@ -0,0 +1,167 @@+import type { Meta, StoryObj } from '@storybook/react'+import type { ReactNode } from 'react'++import { mswDecorator } from '~/mocks/browser'+import { DashboardPlacement } from '~/types'++import { WidgetCard } from '../../components/WidgetCard/WidgetCard'+import { WidgetCardBody } from '../../components/WidgetCard/WidgetCardBody'+import { WidgetCardHeader, widgetCardShouldHideMoreButton } from '../../components/WidgetCard/WidgetCardHeader'+import {+ mockMoreOverlay,+ widgetStorybookParameters,+ widgetTileFrameDecorator,+} from '../../components/WidgetCard/widgetCardStoryFixtures'+import {+ experimentResultsSamplePayload,+ experimentsSampleListRows,+} from '../../components/WidgetCard/widgetOverviewStoryFixtures'+import { getDashboardWidgetCatalogEntry, getDashboardWidgetGroupLabel } from '../../widget_types/catalog'+import { useWidgetAvailability } from '../../widget_types/widgetAvailability'+import { DASHBOARD_WIDGET_TILE_FILTERS_READONLY_REASON } from '../constants'+import type { DashboardWidgetComponentProps } from '../registry'+import { ExperimentResultsWidget } from './ExperimentResultsWidget'+import { ExperimentResultsWidgetTileFilters } from './ExperimentResultsWidgetTileFilters'++const EXPERIMENT_RESULTS_CATALOG = getDashboardWidgetCatalogEntry('experiment_results')!+const DEFAULT_CONFIG = EXPERIMENT_RESULTS_CATALOG.defaultConfig as Record<string, unknown>++// The results tile filter (and its read-only value) drives experimentPickerLogic, which fetches+// experiments to resolve the selected name — mock the list/retrieve endpoints so it renders cleanly.+const pickerExperiments = experimentsSampleListRows.map(({ id, name, created_by }) => ({ id, name, created_by }))+const experimentsApiDecorator = mswDecorator({+ get: {+ '/api/projects/:team_id/experiments/': () => [+ 200,+ { results: pickerExperiments, count: pickerExperiments.length },+ ],+ '/api/projects/:team_id/experiments/:id/': ({ params }) => {+ const id = Number(params.id)+ return [200, pickerExperiments.find((experiment) => experiment.id === id) ?? pickerExperiments[0]]+ },+ },+})++type ExperimentResultsWidgetTileStoryProps = DashboardWidgetComponentProps & {+ title?: string+ description?: string+ showDescription?: boolean+ body?: ReactNode+ /** When true, tile filter bar matches view-only dashboard access (no edit permissions). */+ tileFiltersReadOnly?: boolean+}++function ExperimentResultsWidgetTileStory({+ title = '',+ description = EXPERIMENT_RESULTS_CATALOG.description,+ showDescription = true,+ body,+ tileFiltersReadOnly = false,+ ...widgetProps+}: ExperimentResultsWidgetTileStoryProps): JSX.Element {+ const widgetTypeLabel = getDashboardWidgetGroupLabel(EXPERIMENT_RESULTS_CATALOG.groupId)+ const defaultTitle = EXPERIMENT_RESULTS_CATALOG.headerTitle ?? EXPERIMENT_RESULTS_CATALOG.label+ const { isAvailable: showTileFilters } = useWidgetAvailability(EXPERIMENT_RESULTS_CATALOG.availability)++ return (+ <WidgetCard className="h-full">+ <WidgetCardHeader+ layout={EXPERIMENT_RESULTS_CATALOG.headerLayout}+ title={title}+ defaultTitle={defaultTitle}+ titleHref={EXPERIMENT_RESULTS_CATALOG.titleHref}+ widgetTypeLabel={widgetTypeLabel}+ config={widgetProps.config}+ headerMeta={EXPERIMENT_RESULTS_CATALOG.headerMeta}+ description={description}+ showDescription={showDescription}+ loading={widgetProps.loading}+ shouldHideMoreButton={widgetCardShouldHideMoreButton(DashboardPlacement.Dashboard, false)}+ moreButtonOverlay={mockMoreOverlay}+ />+ {showTileFilters ? (+ <ExperimentResultsWidgetTileFilters+ tileId={widgetProps.tileId}+ config={widgetProps.config}+ onUpdateConfig={tileFiltersReadOnly ? undefined : widgetProps.onUpdateConfig}+ disabledReason={tileFiltersReadOnly ? DASHBOARD_WIDGET_TILE_FILTERS_READONLY_REASON : undefined}+ />+ ) : null}+ <WidgetCardBody>{body ?? <ExperimentResultsWidget {...widgetProps} />}</WidgetCardBody>+ </WidgetCard>+ )+}++// Storybook CSF requires a string literal `title` derived from catalog groupLabel/label.+const meta: Meta<typeof ExperimentResultsWidgetTileStory> = {+ title: 'Dashboards/Dashboard Widgets/Widget types/Experiments/Experiment results',+ component: ExperimentResultsWidgetTileStory,+ parameters: {+ layout: 'padded',+ ...widgetStorybookParameters,+ },+ decorators: [experimentsApiDecorator, ...widgetTileFrameDecorator],+ args: {+ tileId: 1,+ config: { ...DEFAULT_CONFIG, experimentId: 101 },+ loading: false,+ result: null,+ onUpdateConfig: () => undefined,+ onRefresh: () => undefined,+ },+}++export default meta++type Story = StoryObj<typeof ExperimentResultsWidgetTileStory>++export const Default: Story = {+ args: {+ title: 'Experiment results',+ loading: false,+ result: experimentResultsSamplePayload,+ },+}++export const TileFiltersReadOnly: Story = {+ args: {+ title: 'Experiment results',+ tileFiltersReadOnly: true,+ loading: false,+ result: experimentResultsSamplePayload,+ },+ parameters: {+ docs: {+ description: {+ story: 'Tile filter bar when the viewer lacks dashboard edit access — the selected experiment is shown as a read-only value.',+ },+ },+ },+}++export const Loading: Story = {+ args: {+ title: 'Experiment results',+ loading: true,+ result: null,+ },+ parameters: {+ testOptions: { waitForLoadersToDisappear: false },+ },+}++export const NotConfigured: Story = {+ args: {+ title: 'Experiment results',+ config: DEFAULT_CONFIG,+ loading: false,+ result: { experiment: null, metrics: [], needsConfiguration: true, hasExperiments: true },+ },+ parameters: {+ docs: {+ description: {+ story: 'Prompt to pick an experiment when the tile has none selected yet.',+ },+ },+ },+}diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.tsxnew file mode 100644index 000000000000..285b5263e820--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.tsx@@ -0,0 +1,207 @@+import posthog from 'posthog-js'++import { LemonSkeleton } from '@posthog/lemon-ui'++import { ExperimentsHog } from 'lib/components/hedgehogs'+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { Link } from 'lib/lemon-ui/Link'+import { StatusTag } from 'scenes/experiments/ExperimentView/StatusTag'+import { urls } from 'scenes/urls'++import type { ExperimentMetric, NewExperimentQueryResponse } from '~/queries/schema/schema-general'+import type { ExperimentStatus } from '~/types'++import { WidgetCardBodyMessage, WidgetCardContent } from '../../components/WidgetCard'+import type { DashboardWidgetComponentProps } from '../registry'+import { NotebookCompactTable } from './LazyNotebookCompactTable'++export type ExperimentResultsWidgetMetricEntry = {+ uuid: string | null+ name: string+ metric: ExperimentMetric | null+ result: NewExperimentQueryResponse | null+ error: string | null+}++export type ExperimentResultsWidgetResult = {+ experiment: {+ id: number+ name: string+ status: string+ start_date: string | null+ end_date: string | null+ feature_flag_key: string+ } | null+ metrics: ExperimentResultsWidgetMetricEntry[]+ needsConfiguration?: boolean+ experimentNotFound?: boolean+ hasExperiments?: boolean+ totalMetricsCount?: number+}++function ExperimentResultsWidgetMessage({+ title,+ message,+ cta,+}: {+ title: string+ message: string+ cta?: JSX.Element+}): JSX.Element {+ return (+ <WidgetCardContent>+ <WidgetCardBodyMessage>+ <div+ className="flex max-w-xs flex-col items-center gap-2 px-2 text-balance"+ data-attr="experiment-results-widget-message"+ >+ <ExperimentsHog className="size-20 shrink-0" />+ <p className="m-0 text-base font-semibold text-primary">{title}</p>+ <p className="m-0 text-sm text-muted">{message}</p>+ {cta}+ </div>+ </WidgetCardBodyMessage>+ </WidgetCardContent>+ )+}++function ExperimentResultsWidgetMetric({ entry }: { entry: ExperimentResultsWidgetMetricEntry }): JSX.Element {+ return (+ <div className="flex flex-col gap-1">+ <h6 className="m-0 text-xs font-semibold text-muted">{entry.name}</h6>+ {entry.error || !entry.metric || !entry.result ? (+ <LemonBanner type="info" className="text-sm">+ {entry.error ?? 'No results available for this metric yet.'}+ </LemonBanner>+ ) : (+ <NotebookCompactTable result={entry.result} metric={entry.metric} />+ )}+ </div>+ )+}++function ExperimentResultsLoadingSkeleton(): JSX.Element {+ return (+ <WidgetCardContent>+ <div className="flex flex-col gap-3 p-2" aria-busy aria-label="Loading experiment results">+ <div className="flex items-center justify-between gap-2" aria-hidden>+ <LemonSkeleton className="h-4 w-1/3 max-w-xs" />+ <LemonSkeleton className="h-5 w-20 rounded" />+ </div>+ <div className="flex flex-col gap-2" aria-hidden>+ <LemonSkeleton className="h-3 w-24" />+ <div className="flex flex-col gap-2 rounded border p-2">+ {Array.from({ length: 3 }, (_, index) => (+ <div key={index} className="flex items-center justify-between gap-4">+ <LemonSkeleton className="h-3 w-1/4" />+ <LemonSkeleton className="h-3 w-1/5" />+ <LemonSkeleton className="h-3 w-1/6" />+ </div>+ ))}+ </div>+ </div>+ </div>+ </WidgetCardContent>+ )+}++export function ExperimentResultsWidget({+ tileId,+ result,+ loading,+ onUpdateConfig,+}: DashboardWidgetComponentProps): JSX.Element {+ const payload = result as ExperimentResultsWidgetResult | null | undefined++ if (loading) {+ return <ExperimentResultsLoadingSkeleton />+ }++ if (!payload || payload.needsConfiguration) {+ // No experiments in the project yet — mirror the list widget's "create one" CTA.+ if (onUpdateConfig && payload && payload.hasExperiments === false) {+ return (+ <ExperimentResultsWidgetMessage+ title="No experiments yet"+ message="Run A/B tests to measure the impact of changes on your product."+ cta={+ <LemonButton+ type="primary"+ size="small"+ to={urls.experiment('new')}+ targetBlank+ onClick={() =>+ posthog.capture('dashboard widget create experiment clicked', {+ widget_type: 'experiment_results',+ tile_id: tileId,+ })+ }+ >+ New experiment+ </LemonButton>+ }+ />+ )+ }+ return (+ <ExperimentResultsWidgetMessage+ title="No experiment selected"+ message={+ onUpdateConfig+ ? 'Pick an experiment from the selector above to see its results here.'+ : 'No experiment has been selected for this tile yet.'+ }+ />+ )+ }++ if (payload.experimentNotFound || !payload.experiment) {+ return (+ <ExperimentResultsWidgetMessage+ title="Experiment not found"+ message="This experiment may have been deleted. Pick another one in the widget settings."+ />+ )+ }++ const { experiment, metrics } = payload+ const isDraft = experiment.status === 'draft'++ return (+ <WidgetCardContent>+ <div className="flex flex-col gap-3 p-2" data-attr="experiment-results-widget-body">+ <div className="flex items-center justify-between gap-2">+ <Link+ to={urls.experiment(experiment.id)}+ target="_blank"+ className="truncate font-semibold text-primary"+ title={experiment.name}+ >+ {experiment.name}+ </Link>+ <StatusTag status={experiment.status as ExperimentStatus} />+ </div>+ {isDraft ? (+ <LemonBanner type="info" className="text-sm">+ This experiment has not launched yet. Results will appear once it is running.+ </LemonBanner>+ ) : metrics.length === 0 ? (+ <LemonBanner type="info" className="text-sm">+ This experiment has no primary metrics to show.+ </LemonBanner>+ ) : (+ metrics.map((entry, index) => (+ <ExperimentResultsWidgetMetric key={entry.uuid ?? index} entry={entry} />+ ))+ )}+ {payload.totalMetricsCount && payload.totalMetricsCount > metrics.length ? (+ <span className="text-xs text-muted">+ Showing the first {metrics.length} of {payload.totalMetricsCount} primary metrics. Open the+ experiment to see all of them.+ </span>+ ) : null}+ </div>+ </WidgetCardContent>+ )+}diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidgetTileFilters.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidgetTileFilters.tsxnew file mode 100644index 000000000000..0b302ea04fcd--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidgetTileFilters.tsx@@ -0,0 +1,84 @@+import { useActions, useValues } from 'kea'+import { useEffect, useRef } from 'react'++import type { DashboardWidgetTileFiltersProps } from '../registry'+import { useWidgetTileConfigPersist } from '../widgetTileFiltersHooks'+import { WidgetTileFilterReadOnlyValue, WidgetTileFiltersBar } from '../widgetTileFiltersReadOnly'+import { experimentPickerLogic } from './experimentPickerLogic'+import { ExperimentPickerSelect } from './ExperimentPickerSelect'+import {+ parseExperimentResultsWidgetConfig,+ patchExperimentResultsWidgetConfig,+} from './experimentsWidgetConfigValidation'++function ExperimentResultsReadOnlyValue({+ tileId,+ experimentId,+}: {+ tileId: number+ experimentId: number+}): JSX.Element {+ const logic = experimentPickerLogic({ pickerKey: `results-tile-${tileId}` })+ const { selectedExperiment } = useValues(logic)+ const { ensureSelectedLoaded } = useActions(logic)+ useEffect(() => {+ ensureSelectedLoaded(experimentId)+ }, [experimentId, ensureSelectedLoaded])+ return (+ <WidgetTileFilterReadOnlyValue>+ <span className="text-secondary">Experiment:</span>{' '}+ {selectedExperiment?.id === experimentId ? selectedExperiment.name : `#${experimentId}`}+ </WidgetTileFilterReadOnlyValue>+ )+}++export function ExperimentResultsWidgetTileFilters({+ tileId,+ config,+ onUpdateConfig,+ disabledReason,+}: DashboardWidgetTileFiltersProps): JSX.Element {+ const parsed = parseExperimentResultsWidgetConfig(config)+ const experimentId = parsed.experimentId ?? null++ const configRef = useRef(config)+ configRef.current = config+ const { persistConfigNow } = useWidgetTileConfigPersist(onUpdateConfig)++ const applyExperimentId = async (value: number | null): Promise<void> => {+ const nextConfig = patchExperimentResultsWidgetConfig(configRef.current, value)+ configRef.current = nextConfig+ await persistConfigNow(nextConfig)+ }++ if (!onUpdateConfig) {+ return (+ <WidgetTileFiltersBar dataAttr="experiment-results-widget-tile-filters-readonly">+ {experimentId != null ? (+ <ExperimentResultsReadOnlyValue tileId={tileId} experimentId={experimentId} />+ ) : (+ <WidgetTileFilterReadOnlyValue>+ <span className="text-secondary">Experiment:</span> None selected+ </WidgetTileFilterReadOnlyValue>+ )}+ </WidgetTileFiltersBar>+ )+ }++ return (+ <WidgetTileFiltersBar dataAttr="experiment-results-widget-tile-filters">+ <div className="w-64 max-w-full">+ <ExperimentPickerSelect+ pickerKey={`results-tile-${tileId}`}+ value={experimentId}+ disabled={!!disabledReason}+ fullWidth+ onChange={(value) => {+ void applyExperimentId(value)+ }}+ dataAttr="experiment-results-widget-tile-experiment-select"+ />+ </div>+ </WidgetTileFiltersBar>+ )+}diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentsListWidget.stories.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentsListWidget.stories.tsxnew file mode 100644index 000000000000..7080b8d3dca3--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/ExperimentsListWidget.stories.tsx@@ -0,0 +1,159 @@+import type { Meta, StoryObj } from '@storybook/react'+import type { ReactNode } from 'react'++import { DashboardPlacement } from '~/types'++import { WidgetCard } from '../../components/WidgetCard/WidgetCard'+import { WidgetCardBody } from '../../components/WidgetCard/WidgetCardBody'+import { WidgetCardHeader, widgetCardShouldHideMoreButton } from '../../components/WidgetCard/WidgetCardHeader'+import {+ mockMoreOverlay,+ widgetStorybookParameters,+ widgetTileFrameDecorator,+} from '../../components/WidgetCard/widgetCardStoryFixtures'+import { experimentsSampleListRows } from '../../components/WidgetCard/widgetOverviewStoryFixtures'+import { getDashboardWidgetCatalogEntry, getDashboardWidgetGroupLabel } from '../../widget_types/catalog'+import { useWidgetAvailability } from '../../widget_types/widgetAvailability'+import { DASHBOARD_WIDGET_TILE_FILTERS_READONLY_REASON } from '../constants'+import type { DashboardWidgetComponentProps } from '../registry'+import { ExperimentsListWidget } from './ExperimentsListWidget'+import { ExperimentsListWidgetTileFilters } from './ExperimentsListWidgetTileFilters'++const EXPERIMENTS_LIST_CATALOG = getDashboardWidgetCatalogEntry('experiments_list')!+const DEFAULT_CONFIG = EXPERIMENTS_LIST_CATALOG.defaultConfig as Record<string, unknown>++type ExperimentsListWidgetTileStoryProps = DashboardWidgetComponentProps & {+ title?: string+ description?: string+ showDescription?: boolean+ body?: ReactNode+ /** When true, tile filter bar matches view-only dashboard access (no edit permissions). */+ tileFiltersReadOnly?: boolean+}++function ExperimentsListWidgetTileStory({+ title = '',+ description = EXPERIMENTS_LIST_CATALOG.description,+ showDescription = true,+ body,+ tileFiltersReadOnly = false,+ ...widgetProps+}: ExperimentsListWidgetTileStoryProps): JSX.Element {+ const widgetTypeLabel = getDashboardWidgetGroupLabel(EXPERIMENTS_LIST_CATALOG.groupId)+ const defaultTitle = EXPERIMENTS_LIST_CATALOG.headerTitle ?? EXPERIMENTS_LIST_CATALOG.label+ const { isAvailable: showTileFilters } = useWidgetAvailability(EXPERIMENTS_LIST_CATALOG.availability)++ return (+ <WidgetCard className="h-full">+ <WidgetCardHeader+ layout={EXPERIMENTS_LIST_CATALOG.headerLayout}+ title={title}+ defaultTitle={defaultTitle}+ titleHref={EXPERIMENTS_LIST_CATALOG.titleHref}+ widgetTypeLabel={widgetTypeLabel}+ config={widgetProps.config}+ headerMeta={EXPERIMENTS_LIST_CATALOG.headerMeta}+ description={description}+ showDescription={showDescription}+ loading={widgetProps.loading}+ shouldHideMoreButton={widgetCardShouldHideMoreButton(DashboardPlacement.Dashboard, false)}+ moreButtonOverlay={mockMoreOverlay}+ />+ {showTileFilters ? (+ <ExperimentsListWidgetTileFilters+ tileId={widgetProps.tileId}+ config={widgetProps.config}+ onUpdateConfig={tileFiltersReadOnly ? undefined : widgetProps.onUpdateConfig}+ disabledReason={tileFiltersReadOnly ? DASHBOARD_WIDGET_TILE_FILTERS_READONLY_REASON : undefined}+ />+ ) : null}+ <WidgetCardBody>{body ?? <ExperimentsListWidget {...widgetProps} />}</WidgetCardBody>+ </WidgetCard>+ )+}++// Storybook CSF requires a string literal `title` derived from catalog groupLabel/label.+const meta: Meta<typeof ExperimentsListWidgetTileStory> = {+ title: 'Dashboards/Dashboard Widgets/Widget types/Experiments/Experiments',+ component: ExperimentsListWidgetTileStory,+ parameters: {+ layout: 'padded',+ ...widgetStorybookParameters,+ },+ decorators: [...widgetTileFrameDecorator],+ args: {+ tileId: 1,+ config: DEFAULT_CONFIG,+ loading: false,+ result: null,+ onUpdateConfig: () => undefined,+ onRefresh: () => undefined,+ },+}++export default meta++type Story = StoryObj<typeof ExperimentsListWidgetTileStory>++export const Default: Story = {+ args: {+ title: 'Experiments',+ loading: false,+ result: {+ results: experimentsSampleListRows,+ hasMore: true,+ limit: 10,+ totalCount: 12,+ totalCountCapped: false,+ },+ },+}++export const TileFiltersReadOnly: Story = {+ args: {+ title: 'Experiments',+ config: { ...DEFAULT_CONFIG, status: 'running' },+ tileFiltersReadOnly: true,+ loading: false,+ result: {+ results: experimentsSampleListRows,+ hasMore: true,+ limit: 10,+ totalCount: 12,+ totalCountCapped: false,+ },+ },+ parameters: {+ docs: {+ description: {+ story: 'Tile filter bar when the viewer lacks dashboard edit access — filters shown as read-only values.',+ },+ },+ },+}++export const Loading: Story = {+ args: {+ title: 'Experiments',+ loading: true,+ result: null,+ },+ parameters: {+ testOptions: { waitForLoadersToDisappear: false },+ },+}++export const Empty: Story = {+ args: {+ title: 'Experiments',+ loading: false,+ result: { results: [] },+ },+ parameters: {+ docs: {+ description: {+ story: 'Empty state with a "New experiment" CTA when the project has no experiments yet.',+ },+ },+ },+}diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentsListWidget.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentsListWidget.tsxnew file mode 100644index 000000000000..f9177b648d8f--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/ExperimentsListWidget.tsx@@ -0,0 +1,186 @@+import { clsx } from 'clsx'+import posthog from 'posthog-js'++import { LemonSkeleton } from '@posthog/lemon-ui'++import { ExperimentsHog } from 'lib/components/hedgehogs'+import { TZLabel } from 'lib/components/TZLabel'+import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { Link } from 'lib/lemon-ui/Link'+import { CONCLUSION_DISPLAY_CONFIG } from 'scenes/experiments/constants'+import { StatusTag } from 'scenes/experiments/ExperimentView/StatusTag'+import { urls } from 'scenes/urls'++import { type ExperimentConclusion, type ExperimentStatus } from '~/types'++import {+ WIDGET_LIST_COUNT_EXPERIMENTS,+ WidgetCardBodyMessage,+ WidgetCardContent,+ WidgetContentFooter,+ WidgetListCount,+} from '../../components/WidgetCard'+import type { DashboardWidgetComponentProps } from '../registry'+import { parseExperimentsListWidgetConfig } from './experimentsWidgetConfigValidation'++export type ExperimentsListWidgetRow = {+ id: number+ name: string+ status: string+ conclusion: ExperimentConclusion | null+ start_date: string | null+ end_date: string | null+ created_at: string | null+ feature_flag_key: string+ created_by: {+ id: number+ first_name: string+ email: string+ } | null+}++export type ExperimentsListWidgetResult = {+ results?: ExperimentsListWidgetRow[]+ hasMore?: boolean+ limit?: number+ totalCount?: number+ totalCountCapped?: boolean+}++function ExperimentConclusionLabel({ conclusion }: { conclusion: ExperimentConclusion }): JSX.Element {+ const config = CONCLUSION_DISPLAY_CONFIG[conclusion]+ return (+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap text-xs text-muted">+ <span className={clsx('size-2 shrink-0 rounded-full', config?.color)} />+ {config?.title ?? conclusion}+ </span>+ )+}++function ExperimentsListWidgetRowItem({ experiment }: { experiment: ExperimentsListWidgetRow }): JSX.Element {+ const creatorName = experiment.created_by?.first_name || experiment.created_by?.email++ return (+ <div className="flex items-center justify-between gap-2 border-b px-2 py-2">+ <div className="flex min-w-0 flex-col">+ <Link+ to={urls.experiment(experiment.id)}+ target="_blank"+ className="truncate font-semibold text-primary"+ title={experiment.name}+ >+ {experiment.name}+ </Link>+ <div className="flex min-w-0 items-center gap-1 text-xs text-muted">+ {experiment.created_at ? (+ <span className="inline-flex items-center gap-1 whitespace-nowrap">+ Created <TZLabel time={experiment.created_at} />+ </span>+ ) : null}+ {creatorName ? <span className="truncate">by {creatorName}</span> : null}+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {experiment.conclusion ? <ExperimentConclusionLabel conclusion={experiment.conclusion} /> : null}+ <StatusTag status={experiment.status as ExperimentStatus} />+ </div>+ </div>+ )+}++function ExperimentsListLoadingSkeleton(): JSX.Element {+ return (+ <div className="flex w-full flex-col" aria-busy aria-label="Loading experiments">+ {Array.from({ length: 5 }, (_, index) => (+ <div key={index} className="flex items-center justify-between gap-2 border-b px-2 py-2" aria-hidden>+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <LemonSkeleton className="h-4 w-[55%] max-w-xs" />+ <LemonSkeleton className="h-3 w-[35%] max-w-40" />+ </div>+ <LemonSkeleton className="h-5 w-16 rounded" />+ </div>+ ))}+ </div>+ )+}++export function ExperimentsListWidget({ tileId, config, result, loading }: DashboardWidgetComponentProps): JSX.Element {+ const payload = result as ExperimentsListWidgetResult | null | undefined+ const experiments = payload?.results ?? []+ const parsedConfig = parseExperimentsListWidgetConfig(config)+ const hasActiveFilters = (parsedConfig.status ?? 'all') !== 'all' || parsedConfig.createdBy != null++ if (loading) {+ return (+ <WidgetCardContent>+ <ExperimentsListLoadingSkeleton />+ </WidgetCardContent>+ )+ }++ if (experiments.length === 0) {+ return (+ <WidgetCardContent>+ <WidgetCardBodyMessage>+ <div+ className="flex max-w-xs flex-col items-center gap-2 px-2 text-balance"+ data-attr="experiments-list-widget-empty-state"+ >+ <ExperimentsHog className="size-20 shrink-0" />+ {hasActiveFilters ? (+ <>+ <p className="m-0 text-base font-semibold text-primary">No experiments found</p>+ <p className="m-0 text-sm text-muted">+ No experiments matched the status and creator filters.+ </p>+ </>+ ) : (+ <>+ <p className="m-0 text-base font-semibold text-primary">No experiments yet</p>+ <p className="m-0 text-sm text-muted">+ Run A/B tests to measure the impact of changes on your product.+ </p>+ <LemonButton+ type="primary"+ size="small"+ to={urls.experiment('new')}+ targetBlank+ onClick={() =>+ posthog.capture('dashboard widget create experiment clicked', {+ widget_type: 'experiments_list',+ tile_id: tileId,+ })+ }+ >+ New experiment+ </LemonButton>+ </>+ )}+ </div>+ </WidgetCardBodyMessage>+ </WidgetCardContent>+ )+ }++ return (+ <>+ <WidgetCardContent>+ <div className="flex flex-col">+ {experiments.map((experiment) => (+ <ExperimentsListWidgetRowItem key={experiment.id} experiment={experiment} />+ ))}+ </div>+ </WidgetCardContent>+ <WidgetContentFooter>+ <WidgetListCount+ shown={experiments.length}+ totalCount={payload?.totalCount}+ totalCountIsLowerBound={payload?.totalCountCapped}+ noun={WIDGET_LIST_COUNT_EXPERIMENTS}+ hasMore={payload?.hasMore}+ dataAttr="experiments-list-widget-count"+ />+ </WidgetContentFooter>+ </>+ )+}diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentsListWidgetTileFilters.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentsListWidgetTileFilters.tsxnew file mode 100644index 000000000000..e9e32b730740--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/ExperimentsListWidgetTileFilters.tsx@@ -0,0 +1,78 @@+import { useRef } from 'react'++import { MemberSelect } from 'lib/components/MemberSelect'+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'++import type { DashboardWidgetTileFiltersProps } from '../registry'+import { useWidgetTileConfigPersist } from '../widgetTileFiltersHooks'+import { WidgetTileFilterReadOnlyValue, WidgetTileFiltersBar } from '../widgetTileFiltersReadOnly'+import {+ EXPERIMENTS_WIDGET_STATUS_OPTIONS,+ type ExperimentsListWidgetStatus,+ parseExperimentsListWidgetConfig,+ patchExperimentsListWidgetConfig,+} from './experimentsWidgetConfigValidation'++export function ExperimentsListWidgetTileFilters({+ config,+ onUpdateConfig,+ disabledReason,+}: DashboardWidgetTileFiltersProps): JSX.Element {+ const parsed = parseExperimentsListWidgetConfig(config)+ const status = parsed.status ?? 'all'+ const createdBy = parsed.createdBy ?? null++ const configRef = useRef(config)+ configRef.current = config+ const { persistConfigNow } = useWidgetTileConfigPersist(onUpdateConfig)++ const canUpdate = !!onUpdateConfig && !disabledReason++ const applyStatus = async (value: ExperimentsListWidgetStatus): Promise<void> => {+ const nextConfig = patchExperimentsListWidgetConfig(configRef.current, { status: value })+ configRef.current = nextConfig+ await persistConfigNow(nextConfig)+ }++ const applyCreatedBy = async (userId: number | null): Promise<void> => {+ const nextConfig = patchExperimentsListWidgetConfig(configRef.current, { createdBy: userId })+ configRef.current = nextConfig+ await persistConfigNow(nextConfig)+ }++ if (!onUpdateConfig) {+ const statusLabel = EXPERIMENTS_WIDGET_STATUS_OPTIONS.find((option) => option.value === status)?.label ?? status+ return (+ <WidgetTileFiltersBar dataAttr="experiments-list-widget-tile-filters-readonly">+ <WidgetTileFilterReadOnlyValue>+ <span className="text-secondary">Status:</span> {statusLabel}+ </WidgetTileFilterReadOnlyValue>+ </WidgetTileFiltersBar>+ )+ }++ return (+ <WidgetTileFiltersBar dataAttr="experiments-list-widget-tile-filters">+ <LemonSelect+ size="small"+ value={status}+ disabled={!canUpdate}+ disabledReason={disabledReason ?? undefined}+ options={EXPERIMENTS_WIDGET_STATUS_OPTIONS}+ onChange={(value) => {+ if (value) {+ void applyStatus(value)+ }+ }}+ />+ <MemberSelect+ type="secondary"+ size="small"+ value={createdBy}+ onChange={(user) => {+ void applyCreatedBy(user?.id ?? null)+ }}+ />+ </WidgetTileFiltersBar>+ )+}diff --git a/products/dashboards/frontend/widgets/experiments/LazyNotebookCompactTable.tsx b/products/dashboards/frontend/widgets/experiments/LazyNotebookCompactTable.tsxnew file mode 100644index 000000000000..4a1411d2efed--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/LazyNotebookCompactTable.tsx@@ -0,0 +1,27 @@+import { lazy, Suspense } from 'react'++import { LemonSkeleton } from '@posthog/lemon-ui'++import type { ExperimentMetric, NewExperimentQueryResponse } from '~/queries/schema/schema-general'++type NotebookCompactTableProps = {+ result: NewExperimentQueryResponse+ metric: ExperimentMetric+}++// Lazy facade: the real table reuses the experiments scene (experimentLogic, featureFlagLogic, luxon,+// cron-parser) — ~1.5 MiB. A static import would pull all of that into the always-loaded dashboard+// graph; behind a dynamic import it loads only when a results widget actually renders.+const LazyTable = lazy(() =>+ import('scenes/experiments/notebook/NotebookCompactTable').then((module) => ({+ default: module.NotebookCompactTable,+ }))+)++export function NotebookCompactTable(props: NotebookCompactTableProps): JSX.Element {+ return (+ <Suspense fallback={<LemonSkeleton className="h-16 w-full" />}>+ <LazyTable {...props} />+ </Suspense>+ )+}diff --git a/products/dashboards/frontend/widgets/experiments/editExperimentResultsWidgetModalLogic.ts b/products/dashboards/frontend/widgets/experiments/editExperimentResultsWidgetModalLogic.tsnew file mode 100644index 000000000000..bbffc3eae82c--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/editExperimentResultsWidgetModalLogic.ts@@ -0,0 +1,151 @@+import { actions, defaults, kea, listeners, path, props, reducers, selectors } from 'kea'++import { isWidgetConfigValidationError } from '../../utils'+import {+ widgetEditModalPropSelectors,+ widgetEditModalTileActions,+ buildWidgetTileMetadataPatch,+ getWidgetEditModalTileDefaults,+} from '../editWidgetModalBuilders'+import type { DashboardWidgetEditModalProps } from '../registry'+import type { editExperimentResultsWidgetModalLogicType } from './editExperimentResultsWidgetModalLogicType'+import {+ parseExperimentResultsWidgetConfig,+ validateExperimentResultsWidgetConfigInput,+ type ExperimentResultsWidgetFieldErrors,+} from './experimentsWidgetConfigValidation'++export type EditExperimentResultsWidgetModalLogicProps = Omit<DashboardWidgetEditModalProps, 'isOpen'>++export const editExperimentResultsWidgetModalLogic = kea<editExperimentResultsWidgetModalLogicType>([+ path(['products', 'dashboards', 'widgets', 'experiments', 'editExperimentResultsWidgetModalLogic']),++ props({+ config: {},+ onSave: async () => {},+ onClose: () => {},+ name: '',+ defaultTitle: 'Untitled',+ description: '',+ } as EditExperimentResultsWidgetModalLogicProps),++ actions({+ ...widgetEditModalTileActions,+ setFieldErrors: (fieldErrors: ExperimentResultsWidgetFieldErrors) => ({ fieldErrors }),+ clearFieldError: (field: keyof ExperimentResultsWidgetFieldErrors) => ({ field }),+ submit: true,+ submitSuccess: true,+ submitFailure: true,+ }),++ reducers({+ tileName: [+ '',+ {+ setTileName: (_: string, { tileName }: { tileName: string }) => tileName,+ },+ ],+ tileDescription: [+ '',+ {+ setTileDescription: (_: string, { tileDescription }: { tileDescription: string }) => tileDescription,+ },+ ],+ fieldErrors: [+ {} as ExperimentResultsWidgetFieldErrors,+ {+ setFieldErrors: (+ _: ExperimentResultsWidgetFieldErrors,+ { fieldErrors }: { fieldErrors: ExperimentResultsWidgetFieldErrors }+ ) => fieldErrors,+ clearFieldError: (+ state: ExperimentResultsWidgetFieldErrors,+ { field }: { field: keyof ExperimentResultsWidgetFieldErrors }+ ) => {+ if (!state[field]) {+ return state+ }+ const next = { ...state }+ delete next[field]+ return next+ },+ },+ ],+ saving: [+ false,+ {+ submit: (_state: boolean, _payload: { value: true }) => true,+ submitSuccess: (_state: boolean, _payload: { value: true }) => false,+ submitFailure: (_state: boolean, _payload: { value: true }) => false,+ },+ ],+ }),++ selectors({+ ...widgetEditModalPropSelectors,+ validation: [+ // The experiment is chosen on the tile filter bar; read it from the persisted config so saving+ // the tile name/description preserves the selection.+ () => [(_, props) => props.config],+ (config) =>+ validateExperimentResultsWidgetConfigInput({+ experimentId: parseExperimentResultsWidgetConfig(config).experimentId ?? null,+ }),+ ],+ activeFieldErrors: [+ (s) => [s.validation, s.fieldErrors],+ (validation, fieldErrors): ExperimentResultsWidgetFieldErrors => {+ if (!validation.success) {+ return { ...validation.fieldErrors, ...fieldErrors }+ }+ return fieldErrors+ },+ ],+ saveDisabledReason: [+ (s) => [s.saving, s.validation],+ (saving, validation): string | undefined => {+ if (saving) {+ return 'Saving…'+ }+ if (!validation.success) {+ return 'Fix validation errors to save'+ }+ return undefined+ },+ ],+ }),++ defaults(({ props }) => ({+ ...getWidgetEditModalTileDefaults(props),+ fieldErrors: {},+ saving: false,+ })),++ listeners(({ actions, props, values }) => ({+ submit: async () => {+ const result = values.validation++ if (!result.success) {+ actions.setFieldErrors(result.fieldErrors)+ return+ }++ try {+ await props.onSave(+ result.config,+ buildWidgetTileMetadataPatch(props, values.tileName, values.tileDescription)+ )+ actions.setFieldErrors({})+ props.onClose()+ actions.submitSuccess()+ } catch (error) {+ actions.submitFailure()+ if (isWidgetConfigValidationError(error)) {+ actions.setFieldErrors(error.fieldErrors as ExperimentResultsWidgetFieldErrors)+ return+ }+ throw error+ }+ },+ })),+])diff --git a/products/dashboards/frontend/widgets/experiments/editExperimentsListWidgetModalLogic.ts b/products/dashboards/frontend/widgets/experiments/editExperimentsListWidgetModalLogic.tsnew file mode 100644index 000000000000..6d9e94d7ece1--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/editExperimentsListWidgetModalLogic.ts@@ -0,0 +1,191 @@+import { actions, defaults, kea, listeners, path, props, reducers, selectors } from 'kea'++import { isWidgetConfigValidationError } from '../../utils'+import {+ widgetEditModalPropSelectors,+ widgetEditModalTileActions,+ buildWidgetTileMetadataPatch,+ getWidgetEditModalTileDefaults,+} from '../editWidgetModalBuilders'+import type { DashboardWidgetEditModalProps } from '../registry'+import type { editExperimentsListWidgetModalLogicType } from './editExperimentsListWidgetModalLogicType'+import {+ parseExperimentsListWidgetConfig,+ validateExperimentsListWidgetConfigInput,+ type ExperimentsListWidgetFieldErrors,+ type ExperimentsListWidgetOrderBy,+ type ExperimentsListWidgetOrderDirection,+} from './experimentsWidgetConfigValidation'++export type EditExperimentsListWidgetModalLogicProps = Omit<DashboardWidgetEditModalProps, 'isOpen'>++export const editExperimentsListWidgetModalLogic = kea<editExperimentsListWidgetModalLogicType>([+ path(['products', 'dashboards', 'widgets', 'experiments', 'editExperimentsListWidgetModalLogic']),++ props({+ config: {},+ onSave: async () => {},+ onClose: () => {},+ name: '',+ defaultTitle: 'Untitled',+ description: '',+ } as EditExperimentsListWidgetModalLogicProps),++ actions({+ setLimit: (limit: number) => ({ limit }),+ setOrderBy: (orderBy: ExperimentsListWidgetOrderBy) => ({ orderBy }),+ setOrderDirection: (orderDirection: ExperimentsListWidgetOrderDirection) => ({ orderDirection }),+ ...widgetEditModalTileActions,+ setFieldErrors: (fieldErrors: ExperimentsListWidgetFieldErrors) => ({ fieldErrors }),+ clearFieldError: (field: keyof ExperimentsListWidgetFieldErrors) => ({ field }),+ submit: true,+ submitSuccess: true,+ submitFailure: true,+ }),++ reducers({+ limit: [+ 10,+ {+ setLimit: (_: number, { limit }: { limit: number }) => limit,+ },+ ],+ orderBy: [+ 'created_at' as ExperimentsListWidgetOrderBy,+ {+ setOrderBy: (_: ExperimentsListWidgetOrderBy, { orderBy }: { orderBy: ExperimentsListWidgetOrderBy }) =>+ orderBy,+ },+ ],+ orderDirection: [+ 'DESC' as ExperimentsListWidgetOrderDirection,+ {+ setOrderDirection: (+ _: ExperimentsListWidgetOrderDirection,+ { orderDirection }: { orderDirection: ExperimentsListWidgetOrderDirection }+ ) => orderDirection,+ },+ ],+ tileName: [+ '',+ {+ setTileName: (_: string, { tileName }: { tileName: string }) => tileName,+ },+ ],+ tileDescription: [+ '',+ {+ setTileDescription: (_: string, { tileDescription }: { tileDescription: string }) => tileDescription,+ },+ ],+ fieldErrors: [+ {} as ExperimentsListWidgetFieldErrors,+ {+ setFieldErrors: (+ _: ExperimentsListWidgetFieldErrors,+ { fieldErrors }: { fieldErrors: ExperimentsListWidgetFieldErrors }+ ) => fieldErrors,+ clearFieldError: (+ state: ExperimentsListWidgetFieldErrors,+ { field }: { field: keyof ExperimentsListWidgetFieldErrors }+ ) => {+ if (!state[field]) {+ return state+ }+ const next = { ...state }+ delete next[field]+ return next+ },+ },+ ],+ saving: [+ false,+ {+ submit: (_state: boolean, _payload: { value: true }) => true,+ submitSuccess: (_state: boolean, _payload: { value: true }) => false,+ submitFailure: (_state: boolean, _payload: { value: true }) => false,+ },+ ],+ }),++ selectors({+ ...widgetEditModalPropSelectors,+ validation: [+ // status + creator live on the tile filter bar; read them from the persisted config so saving+ // the limit/name here preserves the active filters.+ (s) => [s.limit, s.orderBy, s.orderDirection, (_, props) => props.config],+ (limit, orderBy, orderDirection, config) => {+ const baseConfig = parseExperimentsListWidgetConfig(config)+ return validateExperimentsListWidgetConfigInput({+ limit,+ orderBy,+ orderDirection,+ status: baseConfig.status ?? 'all',+ createdBy: baseConfig.createdBy ?? null,+ })+ },+ ],+ activeFieldErrors: [+ (s) => [s.validation, s.fieldErrors],+ (validation, fieldErrors): ExperimentsListWidgetFieldErrors => {+ if (!validation.success) {+ return { ...validation.fieldErrors, ...fieldErrors }+ }+ return fieldErrors+ },+ ],+ saveDisabledReason: [+ (s) => [s.saving, s.validation],+ (saving, validation): string | undefined => {+ if (saving) {+ return 'Saving…'+ }+ if (!validation.success) {+ return 'Fix validation errors to save'+ }+ return undefined+ },+ ],+ }),++ defaults(({ props }) => {+ const baseConfig = parseExperimentsListWidgetConfig(props.config)++ return {+ limit: baseConfig.limit,+ orderBy: baseConfig.orderBy ?? 'created_at',+ orderDirection: baseConfig.orderDirection ?? 'DESC',+ ...getWidgetEditModalTileDefaults(props),+ fieldErrors: {},+ saving: false,+ }+ }),++ listeners(({ actions, props, values }) => ({+ submit: async () => {+ const result = values.validation++ if (!result.success) {+ actions.setFieldErrors(result.fieldErrors)+ return+ }++ try {+ await props.onSave(+ result.config,+ buildWidgetTileMetadataPatch(props, values.tileName, values.tileDescription)+ )+ actions.setFieldErrors({})+ props.onClose()+ actions.submitSuccess()+ } catch (error) {+ actions.submitFailure()+ if (isWidgetConfigValidationError(error)) {+ actions.setFieldErrors(error.fieldErrors as ExperimentsListWidgetFieldErrors)+ return+ }+ throw error+ }+ },+ })),+])diff --git a/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.test.ts b/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.test.tsnew file mode 100644index 000000000000..ef27aeb8d7d5--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.test.ts@@ -0,0 +1,82 @@+import { waitFor } from '@testing-library/react'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { experimentPickerLogic } from './experimentPickerLogic'++const creator = { id: 1, uuid: 'u-1', email: '[email protected]', first_name: 'Alex', last_name: 'Chen' }+const experiment = (id: number, name: string): Record<string, unknown> => ({ id, name, created_by: creator })++describe('experimentPickerLogic', () => {+ let logic: ReturnType<typeof experimentPickerLogic.build>+ let listMock: jest.Mock+ let retrieveMock: jest.Mock+ let lastSearch: string | null = null++ beforeEach(() => {+ lastSearch = null+ listMock = jest.fn(({ request }) => {+ lastSearch = new URL(request.url).searchParams.get('search')+ return [200, { results: [experiment(101, 'New signup CTA'), experiment(102, 'Pricing page')], count: 2 }]+ })+ retrieveMock = jest.fn(({ params }) => [200, experiment(Number(params.id), `Experiment ${params.id}`)])+ useMocks({+ get: {+ '/api/projects/:team_id/experiments/': listMock,+ '/api/projects/:team_id/experiments/:id/': retrieveMock,+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('does not load experiments until the dropdown is opened', async () => {+ logic = experimentPickerLogic({ pickerKey: 'tile-1' })+ logic.mount()+ expect(logic.values.experimentOptions).toEqual([])+ expect(listMock).not.toHaveBeenCalled()++ logic.actions.ensureOptionsLoaded()+ await waitFor(() => expect(logic.values.experimentOptions).toHaveLength(2))+ expect(logic.values.hasLoadedOptions).toBe(true)+ })++ it('only loads the option list once across repeated focus', async () => {+ logic = experimentPickerLogic({ pickerKey: 'tile-1' })+ logic.mount()+ logic.actions.ensureOptionsLoaded()+ await waitFor(() => expect(logic.values.hasLoadedOptions).toBe(true))+ logic.actions.ensureOptionsLoaded()+ await new Promise((resolve) => setTimeout(resolve, 50))+ expect(listMock).toHaveBeenCalledTimes(1)+ })++ it('runs a server-side search and passes the term', async () => {+ logic = experimentPickerLogic({ pickerKey: 'tile-1' })+ logic.mount()+ logic.actions.setSearch('signup')+ await waitFor(() => expect(lastSearch).toBe('signup'))+ })++ it('resolves the selected experiment by id and skips reloading the same id', async () => {+ logic = experimentPickerLogic({ pickerKey: 'tile-1' })+ logic.mount()+ logic.actions.ensureSelectedLoaded(555)+ await waitFor(() => expect(logic.values.selectedExperiment?.id).toBe(555))+ expect(retrieveMock).toHaveBeenCalledTimes(1)++ logic.actions.ensureSelectedLoaded(555)+ await new Promise((resolve) => setTimeout(resolve, 50))+ expect(retrieveMock).toHaveBeenCalledTimes(1)+ })++ it('isolates state across distinct picker keys', () => {+ const tileLogic = experimentPickerLogic({ pickerKey: 'tile-1' })+ const modalLogic = experimentPickerLogic({ pickerKey: 'results-modal' })+ expect(tileLogic.pathString).not.toEqual(modalLogic.pathString)+ })+})diff --git a/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.ts b/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.tsnew file mode 100644index 000000000000..b646e5d59b86--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/experimentPickerLogic.ts@@ -0,0 +1,84 @@+import { actions, connect, kea, key, listeners, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { experimentsList, experimentsRetrieve } from 'products/experiments/frontend/generated/api'+import type { ExperimentApi } from 'products/experiments/frontend/generated/api.schemas'++import type { experimentPickerLogicType } from './experimentPickerLogicType'++/** One page is plenty — search narrows the rest server-side, so we never paginate the dropdown. */+const EXPERIMENT_OPTIONS_LIMIT = 50+const SEARCH_DEBOUNCE_MS = 300++export type ExperimentPickerLogicProps = { pickerKey: string }++export const experimentPickerLogic = kea<experimentPickerLogicType>([+ path((key) => ['products', 'dashboards', 'widgets', 'experiments', 'experimentPickerLogic', key]),+ props({} as ExperimentPickerLogicProps),+ key((props) => props.pickerKey),++ connect(() => ({+ values: [teamLogic, ['currentProjectId']],+ })),++ actions({+ setSearch: (search: string) => ({ search }),+ ensureOptionsLoaded: true,+ ensureSelectedLoaded: (experimentId: number) => ({ experimentId }),+ }),++ reducers({+ search: ['', { setSearch: (_: string, { search }: { search: string }) => search }],+ hasLoadedOptions: [false, { loadOptionsSuccess: () => true }],+ }),++ loaders(({ values }) => ({+ experimentOptions: [+ [] as ExperimentApi[],+ {+ loadOptions: async (+ { debounce }: { debounce: boolean } = { debounce: false },+ breakpoint+ ): Promise<ExperimentApi[]> => {+ // Debounce keystroke-driven searches; the initial focus load should open the dropdown immediately.+ if (debounce) {+ await breakpoint(SEARCH_DEBOUNCE_MS)+ }+ const response = await experimentsList(String(values.currentProjectId), {+ limit: EXPERIMENT_OPTIONS_LIMIT,+ order: '-created_at',+ search: values.search || undefined,+ })+ breakpoint()+ return response.results ?? []+ },+ },+ ],+ selectedExperiment: [+ null as ExperimentApi | null,+ {+ loadSelectedExperiment: async ({ experimentId }: { experimentId: number }): Promise<ExperimentApi> =>+ experimentsRetrieve(String(values.currentProjectId), experimentId),+ },+ ],+ })),++ listeners(({ actions, values }) => ({+ setSearch: () => {+ actions.loadOptions({ debounce: true })+ },+ ensureOptionsLoaded: () => {+ if (!values.hasLoadedOptions && !values.experimentOptionsLoading) {+ actions.loadOptions({ debounce: false })+ }+ },+ ensureSelectedLoaded: ({ experimentId }) => {+ if (values.selectedExperiment?.id === experimentId || values.selectedExperimentLoading) {+ return+ }+ actions.loadSelectedExperiment({ experimentId })+ },+ })),+])diff --git a/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.test.ts b/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.test.tsnew file mode 100644index 000000000000..c529bbb51f50--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.test.ts@@ -0,0 +1,88 @@+import { experimentResultsWidgetConfigSchema, experimentsWidgetConfigSchema } from '../../generated/widget-configs.zod'+import {+ EXPERIMENTS_WIDGET_FORM_FIELD_NAMES,+ patchExperimentResultsWidgetConfig,+ patchExperimentsListWidgetConfig,+ validateExperimentResultsWidgetConfigInput,+ validateExperimentsListWidgetConfigInput,+} from './experimentsWidgetConfigValidation'++describe('experimentsWidgetConfigValidation', () => {+ describe('experiments_list', () => {+ it('form picked fields exist on the generated config schema', () => {+ const shape = experimentsWidgetConfigSchema.shape+ for (const field of EXPERIMENTS_WIDGET_FORM_FIELD_NAMES) {+ expect(shape).toHaveProperty(field)+ }+ })++ it('rejects limit above 25 with an inline-friendly message', () => {+ const result = validateExperimentsListWidgetConfigInput({+ limit: 30,+ orderBy: 'created_at',+ orderDirection: 'DESC',+ status: 'all',+ createdBy: null,+ })+ expect(result.success).toBe(false)+ if (!result.success) {+ expect(result.fieldErrors.limit).toBe('Too big: expected number to be <=25')+ }+ })++ it('accepts a valid sort + status + creator filter', () => {+ const result = validateExperimentsListWidgetConfigInput({+ limit: 10,+ orderBy: 'name',+ orderDirection: 'ASC',+ status: 'running',+ createdBy: 7,+ })+ expect(result.success).toBe(true)+ if (result.success) {+ expect(result.config.limit).toBe(10)+ expect(result.config.orderBy).toBe('name')+ expect(result.config.orderDirection).toBe('ASC')+ expect(result.config.status).toBe('running')+ expect(result.config.createdBy).toBe(7)+ }+ })++ it('patches status while preserving limit', () => {+ const base = experimentsWidgetConfigSchema.parse({ limit: 5, status: 'all', createdBy: 7 })+ const next = patchExperimentsListWidgetConfig(base, { status: 'paused' })+ expect(next.status).toBe('paused')+ expect(next.limit).toBe(5)+ expect(next.createdBy).toBe(7)+ })++ it('clears the creator filter without touching status', () => {+ const base = experimentsWidgetConfigSchema.parse({ limit: 5, status: 'running', createdBy: 7 })+ const next = patchExperimentsListWidgetConfig(base, { createdBy: null })+ expect(next.createdBy ?? null).toBeNull()+ expect(next.status).toBe('running')+ })+ })++ describe('experiment_results', () => {+ it('accepts a selected experiment', () => {+ const result = validateExperimentResultsWidgetConfigInput({ experimentId: 123 })+ expect(result.success).toBe(true)+ if (result.success) {+ expect(result.config.experimentId).toBe(123)+ }+ })++ it('sets the selected experiment on an existing config', () => {+ const base = experimentResultsWidgetConfigSchema.parse({})+ const next = patchExperimentResultsWidgetConfig(base, 123)+ expect(next.experimentId).toBe(123)+ })++ it('clears the selection back to null', () => {+ const base = experimentResultsWidgetConfigSchema.parse({ experimentId: 123 })+ const next = patchExperimentResultsWidgetConfig(base, null)+ expect(next.experimentId ?? null).toBeNull()+ })+ })+})diff --git a/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.ts b/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.tsnew file mode 100644index 000000000000..de04cca28714--- /dev/null+++ b/products/dashboards/frontend/widgets/experiments/experimentsWidgetConfigValidation.ts@@ -0,0 +1,167 @@+import { z } from 'zod'++import { ApiError } from 'lib/api-error'++import {+ experimentResultsWidgetConfigSchema,+ experimentResultsWidgetFormSchema,+ experimentsWidgetConfigSchema,+ experimentsWidgetFormSchema,+ type ExperimentResultsWidgetConfig,+ type ExperimentsWidgetConfig,+} from '../../generated/widget-configs.zod'+import { fieldErrorsFromZodError, parseWidgetConfig } from '../widgetConfigValidation'++export const EXPERIMENTS_WIDGET_FORM_FIELD_NAMES = Object.keys(+ experimentsWidgetFormSchema.shape+) as (keyof typeof experimentsWidgetFormSchema.shape)[]++type ExperimentsListWidgetFormField = keyof z.infer<typeof experimentsWidgetFormSchema>++export type ExperimentsListWidgetFieldErrors = Partial<Record<ExperimentsListWidgetFormField, string>>++export type ExperimentsListWidgetStatus = NonNullable<ExperimentsWidgetConfig['status']>+export type ExperimentsListWidgetOrderBy = NonNullable<ExperimentsWidgetConfig['orderBy']>+export type ExperimentsListWidgetOrderDirection = NonNullable<ExperimentsWidgetConfig['orderDirection']>++export const EXPERIMENTS_WIDGET_STATUS_OPTIONS: { value: ExperimentsListWidgetStatus; label: string }[] = [+ { value: 'all', label: 'Any status' },+ { value: 'draft', label: 'Draft' },+ { value: 'running', label: 'Running' },+ { value: 'paused', label: 'Paused' },+ { value: 'stopped', label: 'Complete' },+]++export const EXPERIMENTS_WIDGET_ORDER_BY_OPTIONS: { value: ExperimentsListWidgetOrderBy; label: string }[] = [+ { value: 'created_at', label: 'Created date' },+ { value: 'name', label: 'Name' },+ { value: 'start_date', label: 'Start date' },+]++export const EXPERIMENTS_WIDGET_ORDER_DIRECTION_OPTIONS: {+ value: ExperimentsListWidgetOrderDirection+ label: string+}[] = [+ { value: 'DESC', label: 'Descending' },+ { value: 'ASC', label: 'Ascending' },+]++const experimentsConfigDefaults = experimentsWidgetConfigSchema.parse({})++export function parseExperimentsListWidgetConfig(config: Record<string, unknown>): ExperimentsWidgetConfig {+ return parseWidgetConfig(experimentsWidgetConfigSchema, config)+}++/** Merge a partial status/creator change into an existing config, returning the full validated config. */+export function patchExperimentsListWidgetConfig(+ config: Record<string, unknown>,+ patch: { status?: ExperimentsListWidgetStatus; createdBy?: number | null }+): ExperimentsWidgetConfig {+ const parsed = parseExperimentsListWidgetConfig(config)+ return experimentsWidgetConfigSchema.parse({+ ...parsed,+ ...(patch.status !== undefined ? { status: patch.status } : {}),+ ...(patch.createdBy !== undefined ? { createdBy: patch.createdBy } : {}),+ })+}++export function validateExperimentsListWidgetConfigInput(input: {+ limit: number+ orderBy: ExperimentsListWidgetOrderBy+ orderDirection: ExperimentsListWidgetOrderDirection+ status: ExperimentsListWidgetStatus+ createdBy: number | null+}):+ | { success: true; config: ExperimentsWidgetConfig }+ | { success: false; fieldErrors: ExperimentsListWidgetFieldErrors } {+ const parsed = experimentsWidgetFormSchema.safeParse({+ limit: input.limit,+ orderBy: input.orderBy,+ orderDirection: input.orderDirection,+ status: input.status,+ createdBy: input.createdBy,+ })++ if (!parsed.success) {+ return { success: false, fieldErrors: fieldErrorsFromZodError(parsed.error) }+ }++ return { success: true, config: experimentsWidgetConfigSchema.parse(parsed.data) }+}++export function parseExperimentsListWidgetConfigApiError(+ error: unknown,+ config: Record<string, unknown>+): ExperimentsListWidgetFieldErrors | null {+ if (!(error instanceof ApiError)) {+ return null+ }++ const parsedConfig = experimentsWidgetConfigSchema.safeParse(config)+ if (parsedConfig.success) {+ return null+ }++ const parsedForm = experimentsWidgetFormSchema.safeParse({+ limit: (config.limit as number) ?? experimentsConfigDefaults.limit ?? 0,+ orderBy: (config.orderBy as ExperimentsListWidgetOrderBy) ?? experimentsConfigDefaults.orderBy ?? 'created_at',+ orderDirection:+ (config.orderDirection as ExperimentsListWidgetOrderDirection) ??+ experimentsConfigDefaults.orderDirection ??+ 'DESC',+ status: (config.status as ExperimentsListWidgetStatus) ?? experimentsConfigDefaults.status ?? 'all',+ createdBy: (config.createdBy as number | null) ?? null,+ })+ if (!parsedForm.success) {+ return fieldErrorsFromZodError(parsedForm.error)+ }++ return fieldErrorsFromZodError(parsedConfig.error)+}++type ExperimentResultsWidgetFormField = keyof z.infer<typeof experimentResultsWidgetFormSchema>++export type ExperimentResultsWidgetFieldErrors = Partial<Record<ExperimentResultsWidgetFormField, string>>++export function parseExperimentResultsWidgetConfig(config: Record<string, unknown>): ExperimentResultsWidgetConfig {+ return parseWidgetConfig(experimentResultsWidgetConfigSchema, config)+}++/** Set the selected experiment on an existing config, returning the full validated config. */+export function patchExperimentResultsWidgetConfig(+ config: Record<string, unknown>,+ experimentId: number | null+): ExperimentResultsWidgetConfig {+ const parsed = parseExperimentResultsWidgetConfig(config)+ return experimentResultsWidgetConfigSchema.parse({ ...parsed, experimentId })+}++export function validateExperimentResultsWidgetConfigInput(input: {+ experimentId: number | null+}):+ | { success: true; config: ExperimentResultsWidgetConfig }+ | { success: false; fieldErrors: ExperimentResultsWidgetFieldErrors } {+ const parsed = experimentResultsWidgetFormSchema.safeParse({ experimentId: input.experimentId })++ if (!parsed.success) {+ return { success: false, fieldErrors: fieldErrorsFromZodError(parsed.error) }+ }++ return { success: true, config: experimentResultsWidgetConfigSchema.parse(parsed.data) }+}++export function parseExperimentResultsWidgetConfigApiError(+ error: unknown,+ config: Record<string, unknown>+): ExperimentResultsWidgetFieldErrors | null {+ if (!(error instanceof ApiError)) {+ return null+ }++ const parsedConfig = experimentResultsWidgetConfigSchema.safeParse(config)+ if (parsedConfig.success) {+ return null+ }++ return fieldErrorsFromZodError(parsedConfig.error)+}diff --git a/products/dashboards/frontend/widgets/previews/ExperimentsWidgetPreviews.tsx b/products/dashboards/frontend/widgets/previews/ExperimentsWidgetPreviews.tsxnew file mode 100644index 000000000000..1134bbcecc7e--- /dev/null+++ b/products/dashboards/frontend/widgets/previews/ExperimentsWidgetPreviews.tsx@@ -0,0 +1,62 @@+import { clsx } from 'clsx'++import { CONCLUSION_DISPLAY_CONFIG } from 'scenes/experiments/constants'+import { StatusTag } from 'scenes/experiments/ExperimentView/StatusTag'++import type { ExperimentMetric, NewExperimentQueryResponse } from '~/queries/schema/schema-general'+import { type ExperimentConclusion, type ExperimentStatus } from '~/types'++import {+ experimentResultsSamplePayload,+ experimentsSampleListRows,+} from '../../components/WidgetCard/widgetOverviewStoryFixtures'+import { NotebookCompactTable } from '../experiments/LazyNotebookCompactTable'++export function ExperimentsListWidgetPreview(): JSX.Element {+ return (+ <div className="pointer-events-none flex flex-col shadow-sm">+ {experimentsSampleListRows.map((experiment) => {+ const creatorName = experiment.created_by?.first_name || experiment.created_by?.email+ const conclusionConfig = experiment.conclusion+ ? CONCLUSION_DISPLAY_CONFIG[experiment.conclusion as ExperimentConclusion]+ : null+ return (+ <div key={experiment.id} className="flex items-center justify-between gap-2 border-b px-2 py-2">+ <div className="flex min-w-0 flex-col">+ <span className="truncate font-semibold text-primary">{experiment.name}</span>+ {creatorName ? (+ <span className="truncate text-xs text-muted">Created by {creatorName}</span>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {conclusionConfig ? (+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap text-xs text-muted">+ <span className={clsx('size-2 shrink-0 rounded-full', conclusionConfig.color)} />+ {conclusionConfig.title}+ </span>+ ) : null}+ <StatusTag status={experiment.status as ExperimentStatus} />+ </div>+ </div>+ )+ })}+ </div>+ )+}++export function ExperimentResultsWidgetPreview(): JSX.Element {+ const experiment = experimentResultsSamplePayload.experiment+ const metric = experimentResultsSamplePayload.metrics[0]+ return (+ <div className="pointer-events-none flex flex-col gap-2 p-2 shadow-sm">+ <div className="flex items-center justify-between gap-2">+ <span className="truncate font-semibold">{experiment.name}</span>+ <StatusTag status={experiment.status as ExperimentStatus} />+ </div>+ <NotebookCompactTable+ result={metric.result as unknown as NewExperimentQueryResponse}+ metric={metric.metric as unknown as ExperimentMetric}+ />+ </div>+ )+}diff --git a/products/dashboards/frontend/widgets/registry.tsx b/products/dashboards/frontend/widgets/registry.tsxindex 594729444fac..0b4bf456c20a 100644--- a/products/dashboards/frontend/widgets/registry.tsx+++ b/products/dashboards/frontend/widgets/registry.tsx@@ -24,6 +24,16 @@ import { EditErrorTrackingWidgetModal } from './error_tracking/EditErrorTrackingimport { ErrorTrackingWidget } from './error_tracking/ErrorTrackingWidget'import { parseErrorTrackingWidgetConfigApiError } from './error_tracking/errorTrackingWidgetConfigValidation'import { ErrorTrackingWidgetTileFilters } from './error_tracking/ErrorTrackingWidgetTileFilters'+import { EditExperimentResultsWidgetModal } from './experiments/EditExperimentResultsWidgetModal'+import { EditExperimentsListWidgetModal } from './experiments/EditExperimentsListWidgetModal'+import { ExperimentResultsWidget } from './experiments/ExperimentResultsWidget'+import { ExperimentResultsWidgetTileFilters } from './experiments/ExperimentResultsWidgetTileFilters'+import { ExperimentsListWidget } from './experiments/ExperimentsListWidget'+import { ExperimentsListWidgetTileFilters } from './experiments/ExperimentsListWidgetTileFilters'+import {+ parseExperimentResultsWidgetConfigApiError,+ parseExperimentsListWidgetConfigApiError,+} from './experiments/experimentsWidgetConfigValidation'import { EditSessionReplayWidgetModal } from './session_replay/EditSessionReplayWidgetModal'import { SessionReplayWidget, SessionReplayWidgetTopHeading } from './session_replay/SessionReplayWidget'import { parseSessionReplayWidgetConfigApiError } from './session_replay/sessionReplayWidgetConfigValidation'@@ -150,6 +160,20 @@ export const DASHBOARD_WIDGET_REGISTRY = {productAccess: 'session_recording',parseConfigApiError: parseSessionReplayWidgetConfigApiError,},+ experiments_list: {+ Component: ExperimentsListWidget,+ TileFilters: ExperimentsListWidgetTileFilters,+ EditModal: EditExperimentsListWidgetModal,+ productAccess: 'experiment',+ parseConfigApiError: parseExperimentsListWidgetConfigApiError,+ },+ experiment_results: {+ Component: ExperimentResultsWidget,+ TileFilters: ExperimentResultsWidgetTileFilters,+ EditModal: EditExperimentResultsWidgetModal,+ productAccess: 'experiment',+ parseConfigApiError: parseExperimentResultsWidgetConfigApiError,+ },} satisfies Record<DashboardWidgetCatalogKey, DashboardWidgetDefinition>function isDashboardWidgetRegistryKey(widgetType: string): widgetType is DashboardWidgetCatalogKey {diff --git a/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts b/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.tsindex 0a7991b3d559..dd00d1dc0d85 100644--- a/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts+++ b/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts@@ -3,6 +3,8 @@ import configPropertyMetadata from '../generated/widget-config-property-keys.jsoimport {activityEventsWidgetConfigSchema,errorTrackingWidgetConfigSchema,+ experimentResultsWidgetConfigSchema,+ experimentsWidgetConfigSchema,sessionReplayWidgetConfigSchema,widgetFilterEntrySchema,} from '../generated/widget-configs.zod'@@ -11,6 +13,8 @@ const WIDGET_CONFIG_SCHEMAS = {activity_events_list: activityEventsWidgetConfigSchema,error_tracking_list: errorTrackingWidgetConfigSchema,session_replay_list: sessionReplayWidgetConfigSchema,+ experiments_list: experimentsWidgetConfigSchema,+ experiment_results: experimentResultsWidgetConfigSchema,} as consttype SchemaNode = { _zod?: { def?: ZodDef } }diff --git a/products/experiments/backend/models/experiment.py b/products/experiments/backend/models/experiment.pyindex de70ea0c92da..e2f1b75a44f6 100644--- a/products/experiments/backend/models/experiment.py+++ b/products/experiments/backend/models/experiment.py@@ -143,6 +143,14 @@ class Experiment(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models.return Experiment.Status.RUNNINGreturn Experiment.Status.DRAFT+ @property+ def status_label(self) -> str:+ """Public status string (draft/running/paused/stopped) — single source for the API+ serializer and dashboard widgets."""+ if self.is_paused:+ return "paused"+ return self.status or self.computed_status.value+def get_feature_flag_key(self):# Strip the soft-delete tombstone so the API and analytics surface the original# key, matching what the query runners resolve against historical events.diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.pyindex 55bed6047443..d5f4d5d4f38a 100644--- a/products/experiments/backend/presentation/serializers.py+++ b/products/experiments/backend/presentation/serializers.py@@ -247,9 +247,7 @@ class ExperimentSerializer(UserAccessControlSerializerMixin, serializers.ModelSe@extend_schema_field({"type": "string", "enum": ["draft", "running", "paused", "stopped"]})def get_status(self, instance: Experiment) -> str:- if instance.is_paused:- return "paused"- return instance.status or instance.computed_status.value+ return instance.status_labelclass Meta:model = Experimentdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9e594a7faeab..e5598c19690c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -1663,6 +1663,8 @@ export namespace Schemas {export const WidgetDateRangeDateFrom = {+ '1m': '-1M',+ '30m': '-30M','1h': '-1h','3h': '-3h','24h': '-24h',@@ -4093,14 +4095,123 @@ export namespace Schemas {config: SessionReplayListWidgetConfig;}- export type AddDashboardWidgetRequest = ActivityEventsListWidgetAddRequestOpenApi | ErrorTrackingListWidgetAddRequestOpenApi | SessionReplayListWidgetAddRequestOpenApi;+ export type ExperimentsListWidgetAddRequestOpenApiWidgetType = typeof ExperimentsListWidgetAddRequestOpenApiWidgetType[keyof typeof ExperimentsListWidgetAddRequestOpenApiWidgetType];+++ export const ExperimentsListWidgetAddRequestOpenApiWidgetType = {+ ExperimentsList: 'experiments_list',+ } as const;++ /**+ * Experiment list sort column.+ */+ export type ExperimentsListWidgetConfigOrderBy = typeof ExperimentsListWidgetConfigOrderBy[keyof typeof ExperimentsListWidgetConfigOrderBy];+++ export const ExperimentsListWidgetConfigOrderBy = {+ CreatedAt: 'created_at',+ Name: 'name',+ StartDate: 'start_date',+ } as const;++ /**+ * Sort direction for orderBy.+ */+ export type ExperimentsListWidgetConfigOrderDirection = typeof ExperimentsListWidgetConfigOrderDirection[keyof typeof ExperimentsListWidgetConfigOrderDirection];+++ export const ExperimentsListWidgetConfigOrderDirection = {+ Asc: 'ASC',+ Desc: 'DESC',+ } as const;++ /**+ * Experiment status filter.+ */+ export type ExperimentsListWidgetConfigStatus = typeof ExperimentsListWidgetConfigStatus[keyof typeof ExperimentsListWidgetConfigStatus];+++ export const ExperimentsListWidgetConfigStatus = {+ Draft: 'draft',+ Running: 'running',+ Paused: 'paused',+ Stopped: 'stopped',+ All: 'all',+ } as const;++ export interface ExperimentsListWidgetConfig {+ /**+ * Maximum number of experiments to return.+ * @minimum 1+ * @maximum 25+ */+ limit?: number;+ /** Experiment list sort column. */+ orderBy?: ExperimentsListWidgetConfigOrderBy;+ /** Sort direction for orderBy. */+ orderDirection?: ExperimentsListWidgetConfigOrderDirection;+ /** Experiment status filter. */+ status?: ExperimentsListWidgetConfigStatus;+ /** Filter by creator (user id). Omit for any creator. */+ createdBy?: number | null;+ }++ export interface ExperimentsListWidgetAddRequestOpenApi {+ /**+ * Optional custom display name for the widget tile.+ * @maxLength 400+ * @nullable+ */+ name?: string | null;+ /** Optional markdown description shown when show_description is enabled. */+ description?: string;+ /** Optional react-grid-layout positions keyed by breakpoint (sm, xs). */+ layouts?: _WidgetTileLayoutsOpenApi;+ /** Whether to show the description on the dashboard tile. */+ show_description?: boolean;+ widget_type: ExperimentsListWidgetAddRequestOpenApiWidgetType;+ /** Configuration for the experiments list widget. */+ config: ExperimentsListWidgetConfig;+ }++ export type ExperimentResultsWidgetAddRequestOpenApiWidgetType = typeof ExperimentResultsWidgetAddRequestOpenApiWidgetType[keyof typeof ExperimentResultsWidgetAddRequestOpenApiWidgetType];+++ export const ExperimentResultsWidgetAddRequestOpenApiWidgetType = {+ ExperimentResults: 'experiment_results',+ } as const;++ export interface ExperimentResultsWidgetConfig {+ /** Experiment to show results for. Null until the user picks one in the widget settings. */+ experimentId?: number | null;+ }++ export interface ExperimentResultsWidgetAddRequestOpenApi {+ /**+ * Optional custom display name for the widget tile.+ * @maxLength 400+ * @nullable+ */+ name?: string | null;+ /** Optional markdown description shown when show_description is enabled. */+ description?: string;+ /** Optional react-grid-layout positions keyed by breakpoint (sm, xs). */+ layouts?: _WidgetTileLayoutsOpenApi;+ /** Whether to show the description on the dashboard tile. */+ show_description?: boolean;+ widget_type: ExperimentResultsWidgetAddRequestOpenApiWidgetType;+ /** Configuration for the experiment results widget. */+ config: ExperimentResultsWidgetConfig;+ }++ export type AddDashboardWidgetRequest = ActivityEventsListWidgetAddRequestOpenApi | ErrorTrackingListWidgetAddRequestOpenApi | SessionReplayListWidgetAddRequestOpenApi | ExperimentsListWidgetAddRequestOpenApi | ExperimentResultsWidgetAddRequestOpenApi;/*** OpenAPI-only batch-add schema with widget_type-discriminated config shapes for agents.*/export interface AddDashboardWidgetsBatchRequestOpenApi {/**- * Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).+ * Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, experiment_results, experiments_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).* @minItems 1* @maxItems 10*/@@ -7083,7 +7194,7 @@ export namespace Schemas {team: number;}- export type DashboardWidgetConfig = ActivityEventsListWidgetConfig | ErrorTrackingListWidgetConfig | SessionReplayListWidgetConfig;+ export type DashboardWidgetConfig = ActivityEventsListWidgetConfig | ErrorTrackingListWidgetConfig | SessionReplayListWidgetConfig | ExperimentsListWidgetConfig | ExperimentResultsWidgetConfig;export interface DashboardWidget {readonly id: string;@@ -13797,6 +13908,8 @@ export namespace Schemas {/*** * `activity_events_list` - activity_events_list* * `error_tracking_list` - error_tracking_list+ * * `experiment_results` - experiment_results+ * * `experiments_list` - experiments_list* * `session_replay_list` - session_replay_list*/export type DashboardPatchWidgetOpenApiWidgetTypeEnum = typeof DashboardPatchWidgetOpenApiWidgetTypeEnum[keyof typeof DashboardPatchWidgetOpenApiWidgetTypeEnum];@@ -13805,6 +13918,8 @@ export namespace Schemas {export const DashboardPatchWidgetOpenApiWidgetTypeEnum = {ActivityEventsList: 'activity_events_list',ErrorTrackingList: 'error_tracking_list',+ ExperimentResults: 'experiment_results',+ ExperimentsList: 'experiments_list',SessionReplayList: 'session_replay_list',} as const;@@ -13815,6 +13930,8 @@ export namespace Schemas {** * `activity_events_list` - activity_events_list* * `error_tracking_list` - error_tracking_list+ * * `experiment_results` - experiment_results+ * * `experiments_list` - experiments_list* * `session_replay_list` - session_replay_list */widget_type?: DashboardPatchWidgetOpenApiWidgetTypeEnum;/** Widget-specific configuration. Shape depends on the tile's widget_type. */@@ -20265,6 +20382,35 @@ export namespace Schemas {readonly results: readonly MetricRecalculationResult[];}+ export type ExperimentResultsWidgetCatalogEntryOpenApiWidgetType = typeof ExperimentResultsWidgetCatalogEntryOpenApiWidgetType[keyof typeof ExperimentResultsWidgetCatalogEntryOpenApiWidgetType];+++ export const ExperimentResultsWidgetCatalogEntryOpenApiWidgetType = {+ ExperimentResults: 'experiment_results',+ } as const;++ export interface ExperimentResultsWidgetCatalogEntryOpenApi {+ widget_type: ExperimentResultsWidgetCatalogEntryOpenApiWidgetType;+ group_id: string;+ group_label: string;+ label: string;+ description: string;+ /** OpenAPI config shape for this widget type (documentation; matches batch-add/PATCH schemas). */+ readonly config_schema: ExperimentResultsWidgetConfig;+ /** @nullable */+ required_product_access?: string | null;+ }++ /**+ * * `experiment_results` - experiment_results+ */+ export type ExperimentResultsWidgetTypeEnum = typeof ExperimentResultsWidgetTypeEnum[keyof typeof ExperimentResultsWidgetTypeEnum];+++ export const ExperimentResultsWidgetTypeEnum = {+ ExperimentResults: 'experiment_results',+ } as const;+/*** Mixin for serializers to add user access control fields*/@@ -20294,6 +20440,35 @@ export namespace Schemas {readonly user_access_level: string | null;}+ export type ExperimentsListWidgetCatalogEntryOpenApiWidgetType = typeof ExperimentsListWidgetCatalogEntryOpenApiWidgetType[keyof typeof ExperimentsListWidgetCatalogEntryOpenApiWidgetType];+++ export const ExperimentsListWidgetCatalogEntryOpenApiWidgetType = {+ ExperimentsList: 'experiments_list',+ } as const;++ export interface ExperimentsListWidgetCatalogEntryOpenApi {+ widget_type: ExperimentsListWidgetCatalogEntryOpenApiWidgetType;+ group_id: string;+ group_label: string;+ label: string;+ description: string;+ /** OpenAPI config shape for this widget type (documentation; matches batch-add/PATCH schemas). */+ readonly config_schema: ExperimentsListWidgetConfig;+ /** @nullable */+ required_product_access?: string | null;+ }++ /**+ * * `experiments_list` - experiments_list+ */+ export type ExperimentsListWidgetTypeEnum = typeof ExperimentsListWidgetTypeEnum[keyof typeof ExperimentsListWidgetTypeEnum];+++ export const ExperimentsListWidgetTypeEnum = {+ ExperimentsList: 'experiments_list',+ } as const;+export interface ExplainRequest {/** UUID of the log entry to explain */uuid: string;@@ -48355,7 +48530,7 @@ export namespace Schemas {is_organization_first_user: boolean;}- export type WidgetCatalogEntry = ActivityEventsListWidgetCatalogEntryOpenApi | ErrorTrackingListWidgetCatalogEntryOpenApi | SessionReplayListWidgetCatalogEntryOpenApi;+ export type WidgetCatalogEntry = ActivityEventsListWidgetCatalogEntryOpenApi | ErrorTrackingListWidgetCatalogEntryOpenApi | SessionReplayListWidgetCatalogEntryOpenApi | ExperimentsListWidgetCatalogEntryOpenApi | ExperimentResultsWidgetCatalogEntryOpenApi;export interface WidgetCatalogResponse {/** Registered dashboard widget types available when dashboard-widgets is enabled. */diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.tsindex 6b7179b9ca50..4a2796158556 100644--- a/services/mcp/src/generated/dashboards/api.ts+++ b/services/mcp/src/generated/dashboards/api.ts@@ -129,6 +129,12 @@ export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeLimitMaxexport const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeOrderByDefault = `start_time`export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneThreeOrderDirectionDefault = `DESC`+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitDefault = 10+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitMax = 25++export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderByDefault = `created_at`+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderDirectionDefault = `DESC`+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourStatusDefault = `all`export const dashboardsPartialUpdateBodyTilesItemWidgetOneNameMax = 400export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod@@ -155,13 +161,19 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod.optional().describe('Existing widget row ID when updating a widget tile via dashboard PATCH.'),widget_type: zod- .enum(['activity_events_list', 'error_tracking_list', 'session_replay_list'])+ .enum([+ 'activity_events_list',+ 'error_tracking_list',+ 'experiment_results',+ 'experiments_list',+ 'session_replay_list',+ ]).describe(- '* `activity_events_list` - activity_events_list\n* `error_tracking_list` - error_tracking_list\n* `session_replay_list` - session_replay_list'+ '* `activity_events_list` - activity_events_list\n* `error_tracking_list` - error_tracking_list\n* `experiment_results` - experiment_results\n* `experiments_list` - experiments_list\n* `session_replay_list` - session_replay_list').optional().describe(- 'Widget type identifier (cannot be changed on update).\n\n* `activity_events_list` - activity_events_list\n* `error_tracking_list` - error_tracking_list\n* `session_replay_list` - session_replay_list'+ 'Widget type identifier (cannot be changed on update).\n\n* `activity_events_list` - activity_events_list\n* `error_tracking_list` - error_tracking_list\n* `experiment_results` - experiment_results\n* `experiments_list` - experiments_list\n* `session_replay_list` - session_replay_list'),config: zod.union([@@ -172,6 +184,8 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zoddate_from: zod.union([zod.enum([+ '-1M',+ '-30M','-1h','-3h','-24h',@@ -256,6 +270,8 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zoddate_from: zod.union([zod.enum([+ '-1M',+ '-30M','-1h','-3h','-24h',@@ -377,6 +393,8 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zoddate_from: zod.union([zod.enum([+ '-1M',+ '-30M','-1h','-3h','-24h',@@ -479,6 +497,46 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod'short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply.'),}),+ zod.object({+ limit: zod+ .number()+ .min(1)+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitMax)+ .default(+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitDefault+ )+ .describe('Maximum number of experiments to return.'),+ orderBy: zod+ .enum(['created_at', 'name', 'start_date'])+ .default(+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderByDefault+ )+ .describe('Experiment list sort column.'),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .default(+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderDirectionDefault+ )+ .describe('Sort direction for orderBy.'),+ status: zod+ .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .default(+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourStatusDefault+ )+ .describe('Experiment status filter.'),+ createdBy: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('Filter by creator (user id). Omit for any creator.'),+ }),+ zod.object({+ experimentId: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Experiment to show results for. Null until the user picks one in the widget settings.'+ ),+ }),]).optional().describe("Widget-specific configuration. Shape depends on the tile's widget_type."),@@ -836,6 +894,16 @@ export const dashboardsWidgetsBatchCreateBodyWidgetsItemThreeConfigOneLimitMax =export const dashboardsWidgetsBatchCreateBodyWidgetsItemThreeConfigOneOrderByDefault = `start_time`export const dashboardsWidgetsBatchCreateBodyWidgetsItemThreeConfigOneOrderDirectionDefault = `DESC`+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourNameMax = 400++export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneLimitDefault = 10+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneLimitMax = 25++export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneOrderByDefault = `created_at`+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneOrderDirectionDefault = `DESC`+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneStatusDefault = `all`+export const dashboardsWidgetsBatchCreateBodyWidgetsItemFiveNameMax = 400+export const dashboardsWidgetsBatchCreateBodyWidgetsMax = 10export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod@@ -908,7 +976,17 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zodzod.object({date_from: zod.union([- zod.enum(['-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d']),+ zod.enum([+ '-1M',+ '-30M',+ '-1h',+ '-3h',+ '-24h',+ '-7d',+ '-14d',+ '-30d',+ '-90d',+ ]),zod.null(),]).optional(),@@ -1043,7 +1121,17 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zodzod.object({date_from: zod.union([- zod.enum(['-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d']),+ zod.enum([+ '-1M',+ '-30M',+ '-1h',+ '-3h',+ '-24h',+ '-7d',+ '-14d',+ '-30d',+ '-90d',+ ]),zod.null(),]).optional(),@@ -1202,7 +1290,17 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zodzod.object({date_from: zod.union([- zod.enum(['-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d']),+ zod.enum([+ '-1M',+ '-30M',+ '-1h',+ '-3h',+ '-24h',+ '-7d',+ '-14d',+ '-30d',+ '-90d',+ ]),zod.null(),]).optional(),@@ -1295,12 +1393,168 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod}).describe('Configuration for the recent recordings widget.'),}),+ zod.object({+ name: zod+ .string()+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemFourNameMax)+ .nullish()+ .describe('Optional custom display name for the widget tile.'),+ description: zod+ .string()+ .optional()+ .describe('Optional markdown description shown when show_description is enabled.'),+ layouts: zod+ .object({+ sm: zod+ .object({+ x: zod+ .number()+ .optional()+ .describe('Column position in the dashboard grid (0-indexed).'),+ y: zod+ .number()+ .optional()+ .describe('Row position in the dashboard grid (0-indexed).'),+ w: zod+ .number()+ .optional()+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),+ h: zod.number().optional().describe('Height in grid rows.'),+ })+ .optional()+ .describe(+ 'Layout for the standard (desktop) breakpoint. The grid is 12 columns wide.'+ ),+ xs: zod+ .object({+ x: zod+ .number()+ .optional()+ .describe('Column position in the dashboard grid (0-indexed).'),+ y: zod+ .number()+ .optional()+ .describe('Row position in the dashboard grid (0-indexed).'),+ w: zod+ .number()+ .optional()+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),+ h: zod.number().optional().describe('Height in grid rows.'),+ })+ .optional()+ .describe('Layout for the small (mobile) breakpoint. The grid is 1 column wide.'),+ })+ .optional()+ .describe('Optional react-grid-layout positions keyed by breakpoint (sm, xs).'),+ show_description: zod+ .boolean()+ .optional()+ .describe('Whether to show the description on the dashboard tile.'),+ widget_type: zod.enum(['experiments_list']),+ config: zod+ .object({+ limit: zod+ .number()+ .min(1)+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneLimitMax)+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneLimitDefault)+ .describe('Maximum number of experiments to return.'),+ orderBy: zod+ .enum(['created_at', 'name', 'start_date'])+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneOrderByDefault)+ .describe('Experiment list sort column.'),+ orderDirection: zod+ .enum(['ASC', 'DESC'])+ .default(+ dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneOrderDirectionDefault+ )+ .describe('Sort direction for orderBy.'),+ status: zod+ .enum(['draft', 'running', 'paused', 'stopped', 'all'])+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemFourConfigOneStatusDefault)+ .describe('Experiment status filter.'),+ createdBy: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe('Filter by creator (user id). Omit for any creator.'),+ })+ .describe('Configuration for the experiments list widget.'),+ }),+ zod.object({+ name: zod+ .string()+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemFiveNameMax)+ .nullish()+ .describe('Optional custom display name for the widget tile.'),+ description: zod+ .string()+ .optional()+ .describe('Optional markdown description shown when show_description is enabled.'),+ layouts: zod+ .object({+ sm: zod+ .object({+ x: zod+ .number()+ .optional()+ .describe('Column position in the dashboard grid (0-indexed).'),+ y: zod+ .number()+ .optional()+ .describe('Row position in the dashboard grid (0-indexed).'),+ w: zod+ .number()+ .optional()+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),+ h: zod.number().optional().describe('Height in grid rows.'),+ })+ .optional()+ .describe(+ 'Layout for the standard (desktop) breakpoint. The grid is 12 columns wide.'+ ),+ xs: zod+ .object({+ x: zod+ .number()+ .optional()+ .describe('Column position in the dashboard grid (0-indexed).'),+ y: zod+ .number()+ .optional()+ .describe('Row position in the dashboard grid (0-indexed).'),+ w: zod+ .number()+ .optional()+ .describe('Width in grid columns. The desktop grid is 12 columns wide.'),+ h: zod.number().optional().describe('Height in grid rows.'),+ })+ .optional()+ .describe('Layout for the small (mobile) breakpoint. The grid is 1 column wide.'),+ })+ .optional()+ .describe('Optional react-grid-layout positions keyed by breakpoint (sm, xs).'),+ show_description: zod+ .boolean()+ .optional()+ .describe('Whether to show the description on the dashboard tile.'),+ widget_type: zod.enum(['experiment_results']),+ config: zod+ .object({+ experimentId: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ 'Experiment to show results for. Null until the user picks one in the widget settings.'+ ),+ })+ .describe('Configuration for the experiment results widget.'),+ }),])).min(1).max(dashboardsWidgetsBatchCreateBodyWidgetsMax).describe(- 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).'+ 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, experiment_results, experiments_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).'),}).describe('OpenAPI-only batch-add schema with widget_type-discriminated config shapes for agents.')diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.jsonindex f595e4792f12..44c5956c7825 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json@@ -95,6 +95,8 @@"anyOf": [{"enum": [+ "-1M",+ "-30M","-1h","-3h","-24h",@@ -267,6 +269,8 @@"anyOf": [{"enum": [+ "-1M",+ "-30M","-1h","-3h","-24h",@@ -436,6 +440,8 @@"anyOf": [{"enum": [+ "-1M",+ "-30M","-1h","-3h","-24h",@@ -599,6 +605,63 @@}},"type": "object"+ },+ {+ "properties": {+ "createdBy": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Filter by creator (user id). Omit for any creator."+ },+ "limit": {+ "default": 10,+ "description": "Maximum number of experiments to return.",+ "maximum": 25,+ "minimum": 1,+ "type": "number"+ },+ "orderBy": {+ "default": "created_at",+ "description": "Experiment list sort column.",+ "enum": ["created_at", "name", "start_date"],+ "type": "string"+ },+ "orderDirection": {+ "default": "DESC",+ "description": "Sort direction for orderBy.",+ "enum": ["ASC", "DESC"],+ "type": "string"+ },+ "status": {+ "default": "all",+ "description": "Experiment status filter.",+ "enum": ["draft", "running", "paused", "stopped", "all"],+ "type": "string"+ }+ },+ "type": "object"+ },+ {+ "properties": {+ "experimentId": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Experiment to show results for. Null until the user picks one in the widget settings."+ }+ },+ "type": "object"}],"description": "Widget-specific configuration. Shape depends on the tile's widget_type."@@ -624,8 +687,14 @@"description": "Optional custom display name for the widget tile."},"widget_type": {- "description": "Widget type identifier (cannot be changed on update).\n\n* `activity_events_list` - activity_events_list\n* `error_tracking_list` - error_tracking_list\n* `session_replay_list` - session_replay_list",- "enum": ["activity_events_list", "error_tracking_list", "session_replay_list"],+ "description": "Widget type identifier (cannot be changed on update).\n\n* `activity_events_list` - activity_events_list\n* `error_tracking_list` - error_tracking_list\n* `experiment_results` - experiment_results\n* `experiments_list` - experiments_list\n* `session_replay_list` - session_replay_list",+ "enum": [+ "activity_events_list",+ "error_tracking_list",+ "experiment_results",+ "experiments_list",+ "session_replay_list"+ ],"type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.jsonindex e228d4987b6b..2cf54dd872fc 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json@@ -6,7 +6,7 @@"type": "number"},"widgets": {- "description": "Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).",+ "description": "Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, experiment_results, experiments_list, session_replay_list. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).","items": {"anyOf": [{@@ -22,6 +22,8 @@"anyOf": [{"enum": [+ "-1M",+ "-30M","-1h","-3h","-24h",@@ -270,6 +272,8 @@"anyOf": [{"enum": [+ "-1M",+ "-30M","-1h","-3h","-24h",@@ -515,6 +519,8 @@"anyOf": [{"enum": [+ "-1M",+ "-30M","-1h","-3h","-24h",@@ -751,6 +757,225 @@},"required": ["widget_type", "config"],"type": "object"+ },+ {+ "properties": {+ "config": {+ "description": "Configuration for the experiments list widget.",+ "properties": {+ "createdBy": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Filter by creator (user id). Omit for any creator."+ },+ "limit": {+ "default": 10,+ "description": "Maximum number of experiments to return.",+ "maximum": 25,+ "minimum": 1,+ "type": "number"+ },+ "orderBy": {+ "default": "created_at",+ "description": "Experiment list sort column.",+ "enum": ["created_at", "name", "start_date"],+ "type": "string"+ },+ "orderDirection": {+ "default": "DESC",+ "description": "Sort direction for orderBy.",+ "enum": ["ASC", "DESC"],+ "type": "string"+ },+ "status": {+ "default": "all",+ "description": "Experiment status filter.",+ "enum": ["draft", "running", "paused", "stopped", "all"],+ "type": "string"+ }+ },+ "type": "object"+ },+ "description": {+ "description": "Optional markdown description shown when show_description is enabled.",+ "type": "string"+ },+ "layouts": {+ "description": "Optional react-grid-layout positions keyed by breakpoint (sm, xs).",+ "properties": {+ "sm": {+ "description": "Layout for the standard (desktop) breakpoint. The grid is 12 columns wide.",+ "properties": {+ "h": {+ "description": "Height in grid rows.",+ "type": "number"+ },+ "w": {+ "description": "Width in grid columns. The desktop grid is 12 columns wide.",+ "type": "number"+ },+ "x": {+ "description": "Column position in the dashboard grid (0-indexed).",+ "type": "number"+ },+ "y": {+ "description": "Row position in the dashboard grid (0-indexed).",+ "type": "number"+ }+ },+ "type": "object"+ },+ "xs": {+ "description": "Layout for the small (mobile) breakpoint. The grid is 1 column wide.",+ "properties": {+ "h": {+ "description": "Height in grid rows.",+ "type": "number"+ },+ "w": {+ "description": "Width in grid columns. The desktop grid is 12 columns wide.",+ "type": "number"+ },+ "x": {+ "description": "Column position in the dashboard grid (0-indexed).",+ "type": "number"+ },+ "y": {+ "description": "Row position in the dashboard grid (0-indexed).",+ "type": "number"+ }+ },+ "type": "object"+ }+ },+ "type": "object"+ },+ "name": {+ "anyOf": [+ {+ "maxLength": 400,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional custom display name for the widget tile."+ },+ "show_description": {+ "description": "Whether to show the description on the dashboard tile.",+ "type": "boolean"+ },+ "widget_type": {+ "enum": ["experiments_list"],+ "type": "string"+ }+ },+ "required": ["widget_type", "config"],+ "type": "object"+ },+ {+ "properties": {+ "config": {+ "description": "Configuration for the experiment results widget.",+ "properties": {+ "experimentId": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Experiment to show results for. Null until the user picks one in the widget settings."+ }+ },+ "type": "object"+ },+ "description": {+ "description": "Optional markdown description shown when show_description is enabled.",+ "type": "string"+ },+ "layouts": {+ "description": "Optional react-grid-layout positions keyed by breakpoint (sm, xs).",+ "properties": {+ "sm": {+ "description": "Layout for the standard (desktop) breakpoint. The grid is 12 columns wide.",+ "properties": {+ "h": {+ "description": "Height in grid rows.",+ "type": "number"+ },+ "w": {+ "description": "Width in grid columns. The desktop grid is 12 columns wide.",+ "type": "number"+ },+ "x": {+ "description": "Column position in the dashboard grid (0-indexed).",+ "type": "number"+ },+ "y": {+ "description": "Row position in the dashboard grid (0-indexed).",+ "type": "number"+ }+ },+ "type": "object"+ },+ "xs": {+ "description": "Layout for the small (mobile) breakpoint. The grid is 1 column wide.",+ "properties": {+ "h": {+ "description": "Height in grid rows.",+ "type": "number"+ },+ "w": {+ "description": "Width in grid columns. The desktop grid is 12 columns wide.",+ "type": "number"+ },+ "x": {+ "description": "Column position in the dashboard grid (0-indexed).",+ "type": "number"+ },+ "y": {+ "description": "Row position in the dashboard grid (0-indexed).",+ "type": "number"+ }+ },+ "type": "object"+ }+ },+ "type": "object"+ },+ "name": {+ "anyOf": [+ {+ "maxLength": 400,+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional custom display name for the widget tile."+ },+ "show_description": {+ "description": "Whether to show the description on the dashboard tile.",+ "type": "boolean"+ },+ "widget_type": {+ "enum": ["experiment_results"],+ "type": "string"+ }+ },+ "required": ["widget_type", "config"],+ "type": "object"}]},diff --git a/tach.toml b/tach.tomlindex 964bb93b7196..91bc71e553e3 100644--- a/tach.toml+++ b/tach.toml@@ -198,6 +198,8 @@ depends_on = ["products.alerts","products.ai_observability","products.error_tracking",+ "products.experiments",+ "products.feature_flags","products.mcp_analytics","products.product_analytics",]