Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(dashboards): add survey results widget (#66397)

Matt Pua4432c8803c6b
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.md
index cc38ec838553..ccc22994bea0 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
@@ -110,6 +110,7 @@ Directory: `products/dashboards/frontend/widgets/<product>/` (snake_case product
- [ ] Setup gating: catalog `availability` for simple team-flag checks, or private setup gate inside the widget `Component` for richer rules — do not modify product `SetupPrompt`
- [ ] **Own loading UI** — early-return with `WidgetLoadingState` (typed skeleton as `children` when helpful)
- [ ] Use `WidgetCardContent` for scrollable lists/tables; `WidgetCardBodyMessage` for empty states
+- [ ] **Adoption CTA on the "no entities yet" empty state** — when the product has nothing to show yet (no surveys, no experiments), render a primary `LemonButton` (`targetBlank`) to the product's create flow and fire `posthog.capture('dashboard widget create <product> clicked', { widget_type, tile_id })` on click. Measures adoption driven _from_ the widget, distinct from the platform `dashboard widget added` event. See [§ Product-adoption tracking](#product-adoption-tracking).
- [ ] **List widgets:** follow [list-widget-patterns.md](list-widget-patterns.md) — `hasMore`, footer, tile filter bar, `titleHref`
- [ ] Do **not** render card chrome — `DashboardWidgetItem` + catalog handle headers/menus
@@ -196,4 +197,56 @@ Run [SKILL.md §6 Verify](../SKILL.md#6-verify). Minimum for a new type:
- [ ] Test create/update config validation, activity logging, permission denial in `run_widgets`
- [ ] MCP: `services/mcp/tests/tools/dashboards.integration.test.ts` when catalog/OpenAPI surfaces change
- [ ] Analytics: first insert fires `dashboard tile added` and `dashboard widget added` with `widget_type` on PATCH and POST add paths (`test_dashboard_widgets.py`)
+- [ ] Adoption CTA (if the widget has a "no entities yet" empty state) fires `dashboard widget create <product> clicked` with `widget_type` + `tile_id` — see [§ Product-adoption tracking](#product-adoption-tracking)
- [ ] No empty test scaffolds — every `.test.tsx` must assert real behavior
+
+## Product-adoption tracking
+
+Platform analytics (`dashboard widget added`, `dashboard tile added`) measure widget _placement_. To measure adoption driven _from_ a widget — a user landing on an empty widget and going on to create their first entity — fire a product-scoped capture on the empty-state CTA.
+
+**Convention:** when the widget renders a "no entities yet" empty state (no surveys, no experiments in the project), give the create CTA an `onClick` that captures:
+
+```tsx
+<LemonButton
+ type="primary"
+ size="small"
+ to={urls.surveys()} // product's create / list flow
+ targetBlank
+ onClick={() =>
+ posthog.capture('dashboard widget create survey clicked', {
+ widget_type: 'survey_results',
+ tile_id: tileId,
+ })
+ }
+>
+ New survey
+</LemonButton>
+```
+
+- Event name: `dashboard widget create <product> clicked` (e.g. `... create experiment clicked`, `... create survey clicked`).
+- Always include `widget_type` and `tile_id` so funnels can attribute by both the widget variant and the specific tile.
+- Only the "product is empty" branch needs it — not the "no entity selected for this tile" picker state.
+
+Shipped examples: `widgets/experiments/ExperimentResultsWidget.tsx` + `ExperimentsListWidget.tsx` (`dashboard widget create experiment clicked`), `widgets/surveys/SurveyResultsWidget.tsx` (`dashboard widget create survey clicked`). Related cross-product nudges: `WidgetAvailabilitySetupPrompt.tsx` fires `dashboard widget cross product activated` when a setup gate is satisfied.
+
+### Click-through (open the entity)
+
+Capture when a user follows a widget link _into_ the product — the other half of the funnel after placement. Detail (results) widgets fire `dashboard widget open <product> clicked` on the body's "See more" link, with `widget_type`, `tile_id`, and the entity id:
+
+```tsx
+<Link
+ to={urls.survey(survey.id)}
+ target="_blank"
+ onClick={() =>
+ posthog.capture('dashboard widget open survey clicked', {
+ widget_type: 'survey_results',
+ tile_id: tileId,
+ survey_id: survey.id,
+ })
+ }
+>
+ See more
+</Link>
+```
+
+Shipped examples: `SurveyResultsWidget.tsx` (`dashboard widget open survey clicked`), `ExperimentResultsWidget.tsx` (`dashboard widget open experiment clicked`).
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4666b8731f1b..a8e2367c7147 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -337,17 +337,17 @@ snapshots:
components-date-picker--past-only--light:
hash: v1.k794b7964.ffdac5431d4f98723b5e2bd51a7e8dcf13b9e4c1c0cd298018a8633419439b44.wKvYaWVSHr61dXMjL569dC82ynBF2KK3myXSvNL5Syo
components-date-picker--quill-custom-class--dark:
- hash: v1.k794b7964.bf7f43ffd259cfd63d3254bb6c958615e252229f68cc00efb6f97827c2b54f9f.t99znqN6dNzpcq7l5X36J1i7LxnJVDKxNPJMlOgKpsQ
+ hash: v1.k794b7964.c7077284936a2db42385995caa3595b77c1883bed82facf42b628219d12f079c.lwWkfrqRaiJSRD06HOsWcuncbxzcytaszv22SaHfd_M
components-date-picker--quill-custom-class--light:
- hash: v1.k794b7964.143ef687b56150fe70923f507cacaaa3cfe1ebb13f2dc536097a281ecf257fdc.bbAAzZZjOWlBTJACthV7HNptDVtAz6h9N5FFyYgh0JA
+ hash: v1.k794b7964.f6003c63d3e16b69691faee290367d502695beba400fbcecd2c7c0a24f8499b0.SJoBeiYsxa0PHdSUjR7p3DG1DaADbnfTMcNdSHrW8Ic
components-date-picker--quill-empty--dark:
hash: v1.k794b7964.44cfdb6fe956961256a9825c7d7a5cf0c596e937ecfb9994a4e133037ec8d76e.L_ZWqAvhq1iodO1C3KlnycjGH2PFxkGruf577T5Gb9Y
components-date-picker--quill-empty--light:
hash: v1.k794b7964.d40c13438b057467aa3719c70f62f7f0114635a397b394207833d764431b447a.xVNP5qzKlFD1WLEU_INK1YNK6oiuRQsrZvGNTHfXHKU
components-date-picker--quill-small-secondary--dark:
- hash: v1.k794b7964.e05f37dbdce40b499cd7cdd9aa2de50f760d103439d45cae4165bfaa3e192e9e.wkOu6VlXKigWpMQ5BdHTUv0pYdWOzp0Bd7U0xSUYV_s
+ hash: v1.k794b7964.1046ab596430e702204ef5821f50d51daa646066f533a2b2d093bde6d55f0956.u7_4Q_33HSZY_S_uVz8nKO4E6-w9gQ7X4ZPw8IQOTK8
components-date-picker--quill-small-secondary--light:
- hash: v1.k794b7964.c75138c4400c78bfb12d2609e40c5f555bd4634a4d12e2d7f9b3faec11adc7ff.56RffhN3R6HrdWzK_WXIGf5aXtAEDvXueknziKRMstY
+ hash: v1.k794b7964.551245cbafade7ee4238d2c7c6f5cfa6455c8c8f8efcaf087282935c601e1989.VS63LAFNCCXVOXwYOgAx0uAgAhRLfLjzbmdmZe0oUrE
components-date-picker--quill-with-time--dark:
hash: v1.k794b7964.296c9fae5b8898cdd66e6632e3b77bce658fd5bac4a9efef9f193cd23fe537eb.djn0ZVAivkFqN76E4bu5CobhOFU-2JwjqA1KlwgyaRo
components-date-picker--quill-with-time--light:
@@ -1383,7 +1383,7 @@ snapshots:
components-playerinspector--with-logs-filter--dark:
hash: v1.k794b7964.4a27837802248b94d5c146c18b6962bfc713ce40ec3da10a23d4fc89639cf794.PRcX4NksDqdhgKXU-BTlmrZ4mkRVcQIAlLsj5nbUq9I
components-playerinspector--with-logs-filter--light:
- hash: v1.k794b7964.92f552147017e8b361ea4c2eff62c087ce37fedfc44d40945ba40dbf12e01f08.KBu7dt9Qb1dmTqIGmFIKmCjktRGu8gAFQa0YzD86djA
+ hash: v1.k794b7964.97c396a5d41b78e6f653cdcb59a7e59dce49c44d08a9c3903dd69324eb20fdd6.UcFWQBXiTFaua5umBEqB8d8UUCI6aLN4cXg2abaVyJ0
components-playerinspector--with-logs-filter-upsell--dark:
hash: v1.k794b7964.5e4afe863e34df7278c0dd092946adfd396ee778f0cd0a41e5e3f5e1771a9601.SBOdVp0jJnn1w2H4fMR-3Vf2ac00QSBFQjsl93AbcYA
components-playerinspector--with-logs-filter-upsell--light:
@@ -1805,9 +1805,9 @@ snapshots:
components-verticalnesteddnd--base--light:
hash: v1.k794b7964.d5489b1b81f5796e1828217bfd382f980062e90cae10ebe23fb4e8aa5aea07e6.12qSy0lIe-5pOxJ9lBpDJoSa1oh-a24bC0-yeEIbfrg
dashboards-dashboard-widgets-overview--all-widget-types--dark:
- hash: v1.k794b7964.407ed5b93e3c2d00fcd6d4637369d8419e3fee3973e3c645a65ce137a9993627.Dso2g62KvCkGLUMysE1n5UTS3cJkggbGPG7AxKgEA48
+ hash: v1.k794b7964.e2f03c8d0dbcc2fa624b2129de5041821d981aed84b4ebc369f876ec38bcff1b.yj6prw4W6mm27hg8ujDwFwRM4Fd5ui1xalilijfJCVQ
dashboards-dashboard-widgets-overview--all-widget-types--light:
- hash: v1.k794b7964.d0769f5077567eb4de2b2634772a2fece64ac1aabbc52b85dd28142a3a7262ac.E_OZ70niNlPgxnkYTcJV7D05l-DpvEfiChtqyMYeaQQ
+ hash: v1.k794b7964.59fb61901d264c3bf3cd29dd681c9ace3520a5e14a4fcd0e8d11f44994a52600.tvKjlXPoKEJOPZWaP3E52rAkO4FRlDQjaB0SJVPY_6k
dashboards-dashboard-widgets-widget-types-activity-recent-events--default--dark:
hash: v1.k794b7964.2452910051f06a264c5af21e003ab5286fa4b7be350b8e4c193aff454778e5b9.nowYT2exrkg_P27P5mOBomdP2jOUawjYAx6tD9v72OI
dashboards-dashboard-widgets-widget-types-activity-recent-events--default--light:
@@ -1936,6 +1936,34 @@ snapshots:
hash: v1.k794b7964.157ece6a208752da8f398061271c7f53a50f171c8b7d644350e5bce3525cc1c2.0Vta5eOYfMppwLfvIZRVk09jCKuJN-XrUcjdAEOmbvw
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings-widget-settings--default--light:
hash: v1.k794b7964.9aead420de584ee54a57eb52344452181d38a1da1fcf3f3b8fb3b556bdf5bf0a.D20bZWKorcXqhICVBKYA8mvwVK51dWGRU6rH5jEzMYQ
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--default--dark:
+ hash: v1.k794b7964.1e3ffed914508498dabcde95ee60a7850fc93d3cf146777e986eaa42e824bae6.vA3DlcvGhS9M97tqWtcuX31fAasOOTcy9D3PZ4ScDmI
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--default--light:
+ hash: v1.k794b7964.dd6dad69ec6cf09f46a041374bbe22aa29e182d7c2f9775c49d8012a52ab4603.pvppzVgycMzMvGOFpnqFtMOH1h4RtDNEFDb1Poyy3dE
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--empty--dark:
+ hash: v1.k794b7964.ec464d72e59c37cf72a651ebcf792733eacd7270b816683dc87a5d2a6bd3d2ff.H9PqK0_dRn3vmxgFAZKrczcw81qKPQTlcQXGYfYdKaA
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--empty--light:
+ hash: v1.k794b7964.e2846c34b08c6e9ad8d382e7a4492930a5e6b713b17cd6d1b208951661d37c6e.AXpxswkcz3kls2C-BQtGjtasxm8L60qEkjVzHaZTZ-8
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--loading--dark:
+ hash: v1.k794b7964.2489f31cdb31b3211864ac94156c8ebc9444456db188b585c1840d2a04379912.RgFyKTD-7L6WSR02P3RAwCgJ_hB9veRCWgvICgOBjOs
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--loading--light:
+ hash: v1.k794b7964.f0f53afce5948561363715a906aab4ccdd7abb2158cb843a7fb5af87f7776b05.8u61uJUuTb6QXMg4LZ6N0WphXZ-OvGvavbHPviun1LM
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--not-configured--dark:
+ hash: v1.k794b7964.8bfecc198ac2734f20d25e6f4899a55a727f791d3052f5bd4f11591661e476d1.PhoHTPZIB6DhzZM6beRWPF1YpwWM_IW1AKM0FgczSqk
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--not-configured--light:
+ hash: v1.k794b7964.245eeb6113628cea280a841db78929c24280eccc7d2702484c5cf49be17fafa8.DsJfFc0qDsZEB35nhmqDWwKA5F3gO8kMw4dHdJDdu4I
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--survey-not-found--dark:
+ hash: v1.k794b7964.dd3f2a8973faa52fac12e31f09091cd5a12398840f08a0bea1f9e4d5d693d3d3.8b0VILKEcTs5UV-z5gxcAMpx-di_qIyVqjC0rAi-Hyw
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--survey-not-found--light:
+ hash: v1.k794b7964.e7ceee5af9546b9cd3bd6fc12e396d31d725ebf100e9c6037e815d68e542d947.o-BQm9OOsVqzuexTdhBupeaoMYkcG43HmeDOte4rn28
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--tile-filters-read-only--dark:
+ hash: v1.k794b7964.c3be17f4609f7e297bded5ab37f596f50a55938897b3852a75015b7b491772d7.4oA8rF7KQw-vOawgqxWZM81tlJ0SN6HGVY_0hRkaC6s
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results--tile-filters-read-only--light:
+ hash: v1.k794b7964.aa1168c86cd8944d573fb9f3212163a7f72b5f41e67888086e0e5b503610d115.7hQTRtkUVe-yHNIxpgrdNJfhYAi4dG6YN8iCufpozvI
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results-widget-settings--default--dark:
+ hash: v1.k794b7964.033fccd93730eb20949b5d46c3fa28a2cf70195b831b592445452e542355746b.R9lTDKFuptO-285ot6Q5RxydhuNXACbgtLQZ7RWY9qY
+ dashboards-dashboard-widgets-widget-types-surveys-survey-results-widget-settings--default--light:
+ hash: v1.k794b7964.85485342a6d22ecd7a4d50e8ed982bce66757c977acabc707114d33dca16c026.2d_5h5qa80-qkKNhhZv4UuC95SSf_8rTNepPhr7vDX8
dashboards-dashboard-widgets-widgetcard--default--dark:
hash: v1.k794b7964.59dd4103fefd6fa5b0f0d5ed2cbed7284f64ffcd88f2a48780e63deebfe1f201.xkzNbg2dec23PErS8TH58_TSdeiYhlRAJDBwn7chSH0
dashboards-dashboard-widgets-widgetcard--default--light:
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 4f0813b75070..0d6188788316 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -617,6 +617,7 @@ SPECTACULAR_SETTINGS = {
"SessionReplayListWidgetTypeEnum": ["session_replay_list"],
"ExperimentsListWidgetTypeEnum": ["experiments_list"],
"ExperimentResultsWidgetTypeEnum": ["experiment_results"],
+ "SurveyResultsWidgetTypeEnum": ["survey_results"],
"LogsListWidgetTypeEnum": ["logs_list"],
"OrderByEnum": ["latest", "earliest"],
"PropertyGroupTypeEnum": ["cohort", "person", "group"],
diff --git a/products/dashboards/backend/api/test/test_survey_widgets.py b/products/dashboards/backend/api/test/test_survey_widgets.py
new file mode 100644
index 000000000000..db5492c21802
--- /dev/null
+++ b/products/dashboards/backend/api/test/test_survey_widgets.py
@@ -0,0 +1,132 @@
+from datetime import UTC, datetime
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, Team, User
+from posthog.test.persons import create_person
+
+from products.dashboards.backend.constants import DEFAULT_WIDGET_LIST_LIMIT
+from products.dashboards.backend.widget_registry import SURVEY_RESULTS_WIDGET_TYPE, validate_widget_config
+from products.dashboards.backend.widgets.survey_results import _resolve_person_display_names, run_survey_results_widget
+from products.surveys.backend.models import Survey
+from products.surveys.backend.responses.fetch_rows import SurveyResponseRow
+
+
+def _block_survey_for_member(team: Team, survey: Survey, 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="survey",
+ resource_id=str(survey.id),
+ organization_member=membership,
+ access_level="none",
+ )
+
+
+class TestSurveyResultsWidgetConfig(APIBaseTest):
+ def test_config_defaults_to_unconfigured(self) -> None:
+ validated = validate_widget_config(SURVEY_RESULTS_WIDGET_TYPE, {})
+ assert validated.get("surveyId") is None
+ assert validated["limit"] == DEFAULT_WIDGET_LIST_LIMIT
+
+ def test_blank_survey_id_normalizes_to_none(self) -> None:
+ validated = validate_widget_config(SURVEY_RESULTS_WIDGET_TYPE, {"surveyId": ""})
+ assert validated.get("surveyId") is None
+
+ @parameterized.expand(
+ [
+ ("limit_too_high", {"limit": 100}),
+ ("unknown_key", {"evil": True}),
+ ("bad_date_from", {"dateRange": {"date_from": "-2y"}}),
+ ]
+ )
+ def test_rejects_invalid_config(self, _name: str, config: dict[str, Any]) -> None:
+ from rest_framework.exceptions import ValidationError # noqa: PLC0415
+
+ with self.assertRaises(ValidationError):
+ validate_widget_config(SURVEY_RESULTS_WIDGET_TYPE, config)
+
+
+class TestSurveyResultsWidgetRunner(APIBaseTest):
+ def _create_survey(self, *, name: str = "Feedback", archived: bool = False) -> Survey:
+ return Survey.objects.create(
+ team=self.team,
+ name=name,
+ type="popover",
+ archived=archived,
+ created_by=self.user,
+ questions=[{"type": "open", "id": "q1", "question": "What can we improve?"}],
+ )
+
+ def test_returns_needs_configuration_when_no_survey_selected(self) -> None:
+ result = run_survey_results_widget(self.team, {}, user=self.user)
+
+ assert result == {
+ "survey": None,
+ "responses": [],
+ "needsConfiguration": True,
+ "hasSurveys": False,
+ }
+
+ def test_needs_configuration_reports_existing_surveys(self) -> None:
+ self._create_survey()
+ result = run_survey_results_widget(self.team, {}, user=self.user)
+
+ assert result["needsConfiguration"] is True
+ assert result["hasSurveys"] is True
+
+ def test_archived_surveys_do_not_count_as_existing(self) -> None:
+ self._create_survey(archived=True)
+ result = run_survey_results_widget(self.team, {}, user=self.user)
+
+ assert result["hasSurveys"] is False
+
+ def test_returns_not_found_for_missing_survey(self) -> None:
+ result = run_survey_results_widget(
+ self.team, {"surveyId": "00000000-0000-0000-0000-000000000000"}, user=self.user
+ )
+
+ assert result == {"survey": None, "responses": [], "surveyNotFound": True}
+
+ def test_returns_not_found_for_other_team_survey(self) -> None:
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ survey = Survey.objects.create(team=other_team, name="Other team", type="popover", created_by=self.user)
+
+ result = run_survey_results_widget(self.team, {"surveyId": str(survey.id)}, user=self.user)
+
+ assert result == {"survey": None, "responses": [], "surveyNotFound": True}
+
+ def test_returns_not_found_for_survey_the_user_cannot_access(self) -> None:
+ survey = self._create_survey()
+ member = User.objects.create_and_join(self.organization, "[email protected]", "pw")
+ _block_survey_for_member(self.team, survey, member)
+
+ result = run_survey_results_widget(self.team, {"surveyId": str(survey.id)}, user=member)
+
+ assert result == {"survey": None, "responses": [], "surveyNotFound": True}
+
+ def test_resolves_person_display_names_for_responses(self) -> None:
+ create_person(team=self.team, distinct_ids=["known"], properties={"email": "[email protected]"})
+
+ def _row(distinct_id: str) -> SurveyResponseRow:
+ return SurveyResponseRow(
+ uuid="uuid",
+ distinct_id=distinct_id,
+ session_id=None,
+ submitted_at=datetime.now(UTC),
+ answers=[],
+ )
+
+ display_names = _resolve_person_display_names(self.team, [_row("known"), _row("anonymous")])
+
+ # Matched person resolves to its email; unmatched distinct_id is omitted so the
+ # frontend can fall back to the raw distinct_id.
+ assert display_names == {"known": "[email protected]"}
diff --git a/products/dashboards/backend/widget_registry.py b/products/dashboards/backend/widget_registry.py
index acc6f0c120ea..bf22caf8e789 100644
--- a/products/dashboards/backend/widget_registry.py
+++ b/products/dashboards/backend/widget_registry.py
@@ -12,6 +12,7 @@ from products.dashboards.backend.widget_specs.configs import (
EXPERIMENT_RESULTS_WIDGET_TYPE,
EXPERIMENTS_LIST_WIDGET_TYPE,
SESSION_REPLAY_LIST_WIDGET_TYPE,
+ SURVEY_RESULTS_WIDGET_TYPE,
)
from products.dashboards.backend.widget_specs.registry import (
EXPECTED_WIDGET_TYPES,
@@ -36,6 +37,7 @@ __all__ = [
"EXPERIMENT_RESULTS_WIDGET_TYPE",
"EXPERIMENTS_LIST_WIDGET_TYPE",
"SESSION_REPLAY_LIST_WIDGET_TYPE",
+ "SURVEY_RESULTS_WIDGET_TYPE",
"EXPECTED_WIDGET_TYPES",
"DashboardWidgetType",
"WidgetRegistryEntry",
diff --git a/products/dashboards/backend/widget_specs/configs.py b/products/dashboards/backend/widget_specs/configs.py
index f4a63878df4d..759b4642b406 100644
--- a/products/dashboards/backend/widget_specs/configs.py
+++ b/products/dashboards/backend/widget_specs/configs.py
@@ -12,6 +12,7 @@ from products.dashboards.backend.constants import (
from products.dashboards.backend.widget_specs.common import (
ActivityWidgetLimit,
LogsWidgetLimit,
+ WidgetDateRange,
WidgetDateRangeConfigBase,
WidgetLimit,
WidgetListConfigBase,
@@ -23,6 +24,7 @@ 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"
+SURVEY_RESULTS_WIDGET_TYPE = "survey_results"
LOGS_LIST_WIDGET_TYPE = "logs_list"
ErrorTrackingOrderBy = Literal["last_seen", "first_seen", "occurrences", "users", "sessions"]
@@ -121,6 +123,28 @@ class ExperimentResultsWidgetConfig(BaseModel):
)
+class SurveyResultsWidgetConfig(WidgetDateRangeConfigBase):
+ dateRange: WidgetDateRange | None = Field(
+ default=None, description="Null or omitted means all time (the survey's full lifetime)."
+ )
+ surveyId: str | None = Field(
+ default=None,
+ description="Survey to show performance stats and recent responses for. Null until the user picks one.",
+ )
+ limit: WidgetLimit = Field(
+ default=DEFAULT_WIDGET_LIST_LIMIT, description="Maximum number of recent responses to return."
+ )
+
+ @field_validator("surveyId", mode="before")
+ @classmethod
+ def validate_survey_id(cls, value: object) -> str | None:
+ if value is None or value == "":
+ return None
+ if not isinstance(value, str):
+ raise ValueError("surveyId must be a string.")
+ return value
+
+
class LogsListWidgetConfig(WidgetDateRangeConfigBase):
limit: LogsWidgetLimit = Field(
default=LOGS_LIST_DEFAULT_LIMIT, description="Maximum number of log lines to return."
diff --git a/products/dashboards/backend/widget_specs/registry.py b/products/dashboards/backend/widget_specs/registry.py
index 6426819e2e49..198830f49f76 100644
--- a/products/dashboards/backend/widget_specs/registry.py
+++ b/products/dashboards/backend/widget_specs/registry.py
@@ -14,12 +14,14 @@ from products.dashboards.backend.widget_specs.configs import (
EXPERIMENTS_LIST_WIDGET_TYPE,
LOGS_LIST_WIDGET_TYPE,
SESSION_REPLAY_LIST_WIDGET_TYPE,
+ SURVEY_RESULTS_WIDGET_TYPE,
ActivityEventsListWidgetConfig,
ErrorTrackingListWidgetConfig,
ExperimentResultsWidgetConfig,
ExperimentsListWidgetConfig,
LogsListWidgetConfig,
SessionReplayListWidgetConfig,
+ SurveyResultsWidgetConfig,
)
DashboardWidgetType = Literal[
@@ -28,6 +30,7 @@ DashboardWidgetType = Literal[
"session_replay_list",
"experiments_list",
"experiment_results",
+ "survey_results",
"logs_list",
]
@@ -92,6 +95,7 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:
from products.dashboards.backend.widgets.experiments_list import run_experiments_list_widget # noqa: PLC0415
from products.dashboards.backend.widgets.logs_list import run_logs_list_widget # noqa: PLC0415
from products.dashboards.backend.widgets.session_replay_list import run_session_replay_list_widget # noqa: PLC0415
+ from products.dashboards.backend.widgets.survey_results import run_survey_results_widget # noqa: PLC0415
return {
ACTIVITY_EVENTS_LIST_WIDGET_TYPE: WidgetSpec(
@@ -169,6 +173,23 @@ def _load_widget_specs() -> dict[str, WidgetSpec]:
form_fields=("experimentId",),
filter_fields=("experimentId",),
),
+ SURVEY_RESULTS_WIDGET_TYPE: WidgetSpec(
+ widget_type=SURVEY_RESULTS_WIDGET_TYPE,
+ config_model=SurveyResultsWidgetConfig,
+ query_fn=run_survey_results_widget,
+ required_scopes=("survey:read", "query:read", "person:read"),
+ group_id="surveys",
+ group_label="Surveys",
+ label="Survey results",
+ description="Performance stats and recent responses for a selected survey.",
+ required_product_access="survey",
+ product_access_denied_message="You do not have access to surveys.",
+ availability_requirements=(),
+ form_fields=("surveyId", "limit", "dateRange"),
+ # surveyId is chosen on the tile filter bar (like experiment_results' experimentId), so it
+ # counts as a filter change — include it so "dashboard widget filters updated" fires on re-pick.
+ filter_fields=("surveyId", "dateRange"),
+ ),
LOGS_LIST_WIDGET_TYPE: WidgetSpec(
widget_type=LOGS_LIST_WIDGET_TYPE,
config_model=LogsListWidgetConfig,
diff --git a/products/dashboards/backend/widgets/survey_results.py b/products/dashboards/backend/widgets/survey_results.py
new file mode 100644
index 000000000000..67fdb1d716cb
--- /dev/null
+++ b/products/dashboards/backend/widgets/survey_results.py
@@ -0,0 +1,138 @@
+from __future__ import annotations
+
+import logging
+from datetime import datetime
+from typing import Any
+
+from posthog.api.person import get_person_name
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.person.util import get_persons_mapped_by_distinct_id
+from posthog.models.team import Team
+from posthog.models.user import User
+from posthog.rbac.user_access_control import UserAccessControl
+from posthog.utils import relative_date_parse
+
+from products.dashboards.backend.widget_specs.configs import SURVEY_RESULTS_WIDGET_TYPE
+from products.dashboards.backend.widget_specs.registry import validate_widget_config
+from products.surveys.backend.models import Survey
+from products.surveys.backend.responses import SurveyResponseRow, fetch_response_rows, get_survey_stats
+
+logger = logging.getLogger(__name__)
+
+
+def _serialize_survey_summary(survey: Survey) -> dict[str, Any]:
+ return {
+ "id": str(survey.id),
+ "name": survey.name,
+ "type": survey.type,
+ "archived": survey.archived,
+ "start_date": survey.start_date.isoformat() if survey.start_date else None,
+ "end_date": survey.end_date.isoformat() if survey.end_date else None,
+ }
+
+
+def _serialize_response_row(row: SurveyResponseRow, person_display_name: str | None) -> dict[str, Any]:
+ return {
+ "uuid": row.uuid,
+ "distinct_id": row.distinct_id,
+ "person_display_name": person_display_name,
+ "session_id": row.session_id,
+ "submitted_at": row.submitted_at.isoformat() if row.submitted_at else None,
+ "answers": [
+ {
+ "question_id": answer.question_id,
+ "question_text": answer.question_text,
+ "question_type": answer.question_type,
+ "answer": answer.answer,
+ }
+ for answer in row.answers
+ ],
+ }
+
+
+def _resolve_person_display_names(team: Team, rows: list[SurveyResponseRow]) -> dict[str, str]:
+ """Map each row's distinct_id to a human-friendly person display name (email/name).
+
+ Best-effort: distinct_ids without a matched person are simply omitted, and the
+ frontend falls back to the distinct_id itself.
+ """
+ distinct_ids = list({row.distinct_id for row in rows if row.distinct_id})
+ if not distinct_ids:
+ return {}
+ persons_by_distinct_id = get_persons_mapped_by_distinct_id(team.pk, distinct_ids)
+ return {distinct_id: get_person_name(team, person) for distinct_id, person in persons_by_distinct_id.items()}
+
+
+def _resolve_since(config: dict[str, Any], team: Team) -> datetime | None:
+ """Translate the widget's preset date range (e.g. ``-7d``) into a concrete lower bound.
+
+ Returns None when no range is set so stats and responses fall back to the survey's lifetime.
+ """
+ date_range = config.get("dateRange")
+ if not isinstance(date_range, dict):
+ return None
+ date_from = date_range.get("date_from")
+ if not isinstance(date_from, str):
+ return None
+ return relative_date_parse(date_from, team.timezone_info)
+
+
+def run_survey_results_widget(
+ team: Team,
+ config: dict[str, Any],
+ user: User | None = None,
+ *,
+ # Part of the shared run_widgets runner signature (always passed by the dispatcher). This widget
+ # reports per-section counts inline rather than a single capped total, so it has nothing to gate.
+ include_total_count: bool = True,
+) -> dict[str, Any]:
+ typed_config = validate_widget_config(SURVEY_RESULTS_WIDGET_TYPE, config)
+ survey_id = typed_config.get("surveyId")
+
+ # Honor object-level survey access controls, matching the REST endpoint — a user denied access
+ # to a specific survey must not see it (or its responses) through the widget.
+ access_control = UserAccessControl(user=user, team=team) if user is not None else None
+
+ if survey_id is None:
+ accessible = Survey.objects.filter(team=team, archived=False)
+ if access_control is not None:
+ accessible = access_control.filter_queryset_by_access_level(accessible)
+ return {"survey": None, "responses": [], "needsConfiguration": True, "hasSurveys": accessible.exists()}
+
+ survey_queryset = Survey.objects.filter(id=survey_id, team=team)
+ if access_control is not None:
+ survey_queryset = access_control.filter_queryset_by_access_level(survey_queryset)
+ survey = survey_queryset.first()
+ if survey is None:
+ return {"survey": None, "responses": [], "surveyNotFound": True}
+
+ since = _resolve_since(typed_config, team)
+
+ with tags_context(product=Product.SURVEYS, feature=Feature.QUERY, team_id=team.pk):
+ stats_payload = get_survey_stats(
+ team_id=team.pk,
+ date_from=since.isoformat() if since else None,
+ date_to=None,
+ survey_id=str(survey.id),
+ )
+
+ rows: list[SurveyResponseRow] = []
+ has_more = False
+ if survey.start_date is not None:
+ # Draft surveys have no responses yet — skip the (bounded-date) responses query.
+ rows, has_more = fetch_response_rows(
+ survey=survey,
+ team=team,
+ since=since,
+ limit=typed_config["limit"],
+ )
+
+ display_names = _resolve_person_display_names(team, rows)
+
+ return {
+ "survey": _serialize_survey_summary(survey),
+ "stats": stats_payload.get("stats", {}),
+ "rates": stats_payload.get("rates", {}),
+ "responses": [_serialize_response_row(row, display_names.get(row.distinct_id)) for row in rows],
+ "hasMore": has_more,
+ }
diff --git a/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts b/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts
index cb73a9a37170..41ffe5f8c486 100644
--- a/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts
+++ b/products/dashboards/frontend/components/WidgetCard/widgetOverviewStoryFixtures.ts
@@ -269,6 +269,76 @@ export const experimentResultsSamplePayload = {
totalSecondaryMetricsCount: 1,
}
+export const surveyResultsSamplePayload = {
+ survey: {
+ id: 'survey-101',
+ name: 'Post-purchase feedback',
+ type: 'popover',
+ archived: false,
+ start_date: '2026-05-12T00:00:00.000Z',
+ end_date: null,
+ },
+ stats: {
+ 'survey shown': {
+ total_count: 1840,
+ total_count_only_seen: 1180,
+ unique_persons: 1640,
+ unique_persons_only_seen: 1040,
+ first_seen: '2026-05-12T00:00:00.000Z',
+ last_seen: '2026-06-20T00:00:00.000Z',
+ },
+ 'survey dismissed': {
+ total_count: 240,
+ total_count_only_seen: 0,
+ unique_persons: 220,
+ unique_persons_only_seen: 0,
+ first_seen: '2026-05-12T00:00:00.000Z',
+ last_seen: '2026-06-20T00:00:00.000Z',
+ },
+ 'survey sent': {
+ total_count: 420,
+ total_count_only_seen: 0,
+ unique_persons: 400,
+ unique_persons_only_seen: 0,
+ first_seen: '2026-05-12T00:00:00.000Z',
+ last_seen: '2026-06-20T00:00:00.000Z',
+ },
+ },
+ rates: {
+ response_rate: 22.83,
+ dismissal_rate: 13.04,
+ unique_users_response_rate: 24.39,
+ unique_users_dismissal_rate: 13.41,
+ },
+ responses: [
+ {
+ uuid: 'response-1',
+ distinct_id: 'user_8421',
+ session_id: 'session-1',
+ submitted_at: '2026-06-20T14:31:00.000Z',
+ answers: [
+ { question_id: 'q1', question_text: 'How satisfied are you?', question_type: 'rating', answer: '9' },
+ {
+ question_id: 'q2',
+ question_text: 'What can we improve?',
+ question_type: 'open',
+ answer: 'Faster checkout would be great.',
+ },
+ ],
+ },
+ {
+ uuid: 'response-2',
+ distinct_id: 'user_5530',
+ session_id: 'session-2',
+ submitted_at: '2026-06-20T11:02:00.000Z',
+ answers: [
+ { question_id: 'q1', question_text: 'How satisfied are you?', question_type: 'rating', answer: '6' },
+ ],
+ },
+ ],
+ hasMore: true,
+}
+
/** New widget types: add a case here. See products/dashboards/CONTRIBUTING.md. */
export function getWidgetOverviewDemoState(catalogKey: DashboardWidgetCatalogKey): WidgetOverviewDemoState {
const catalogEntry = getDashboardWidgetCatalogEntry(catalogKey)
@@ -343,6 +413,15 @@ export function getWidgetOverviewDemoState(catalogKey: DashboardWidgetCatalogKey
loading: false,
result: experimentResultsSamplePayload,
}
+ case 'survey_results':
+ return {
+ title: defaultTitle,
+ description: catalogEntry.description,
+ showDescription: true,
+ config: { ...defaultConfig, surveyId: 'survey-101' },
+ loading: false,
+ result: surveyResultsSamplePayload,
+ }
case 'logs_list':
return {
title: defaultTitle,
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 73e984091da2..b15adf34d0c9 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -418,6 +418,7 @@ export interface DashboardFiltersOpenApiApi {
* * `experiments_list` - experiments_list
* * `logs_list` - logs_list
* * `session_replay_list` - session_replay_list
+ * * `survey_results` - survey_results
*/
export type DashboardPatchWidgetOpenApiWidgetTypeEnumApi =
(typeof DashboardPatchWidgetOpenApiWidgetTypeEnumApi)[keyof typeof DashboardPatchWidgetOpenApiWidgetTypeEnumApi]
@@ -429,6 +430,7 @@ export const DashboardPatchWidgetOpenApiWidgetTypeEnumApi = {
ExperimentsList: 'experiments_list',
LogsList: 'logs_list',
SessionReplayList: 'session_replay_list',
+ SurveyResults: 'survey_results',
} as const
export type WidgetDateRangeApiDateFrom =
@@ -698,6 +700,19 @@ export interface ExperimentResultsWidgetConfigApi {
experimentId?: number | null
}
+export interface SurveyResultsWidgetConfigApi {
+ /** Null or omitted means all time (the survey's full lifetime). */
+ dateRange?: WidgetDateRangeApi | null
+ /** Survey to show performance stats and recent responses for. Null until the user picks one. */
+ surveyId?: string | null
+ /**
+ * Maximum number of recent responses to return.
+ * @minimum 1
+ * @maximum 25
+ */
+ limit?: number
+}
+
/**
* Sort by newest (latest) or oldest (earliest) first.
*/
@@ -760,6 +775,7 @@ export type DashboardWidgetConfigApi =
| SessionReplayListWidgetConfigApi
| ExperimentsListWidgetConfigApi
| ExperimentResultsWidgetConfigApi
+ | SurveyResultsWidgetConfigApi
| LogsListWidgetConfigApi
export interface DashboardPatchWidgetOpenApiApi {
@@ -772,7 +788,8 @@ export interface DashboardPatchWidgetOpenApiApi {
* * `experiment_results` - experiment_results
* * `experiments_list` - experiments_list
* * `logs_list` - logs_list
- * * `session_replay_list` - session_replay_list */
+ * * `session_replay_list` - session_replay_list
+ * * `survey_results` - survey_results */
widget_type?: DashboardPatchWidgetOpenApiWidgetTypeEnumApi
/** Widget-specific configuration. Shape depends on the tile's widget_type. */
config?: DashboardWidgetConfigApi
@@ -8399,6 +8416,31 @@ export interface ExperimentResultsWidgetAddRequestOpenApiApi {
config: ExperimentResultsWidgetConfigApi
}
+export type SurveyResultsWidgetAddRequestOpenApiApiWidgetType =
+ (typeof SurveyResultsWidgetAddRequestOpenApiApiWidgetType)[keyof typeof SurveyResultsWidgetAddRequestOpenApiApiWidgetType]
+
+export const SurveyResultsWidgetAddRequestOpenApiApiWidgetType = {
+ SurveyResults: 'survey_results',
+} as const
+
+export interface SurveyResultsWidgetAddRequestOpenApiApi {
+ /**
+ * 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: SurveyResultsWidgetAddRequestOpenApiApiWidgetType
+ /** Configuration for the survey results widget. */
+ config: SurveyResultsWidgetConfigApi
+}
+
export type LogsListWidgetAddRequestOpenApiApiWidgetType =
(typeof LogsListWidgetAddRequestOpenApiApiWidgetType)[keyof typeof LogsListWidgetAddRequestOpenApiApiWidgetType]
@@ -8430,6 +8472,7 @@ export type AddDashboardWidgetRequestApi =
| SessionReplayListWidgetAddRequestOpenApiApi
| ExperimentsListWidgetAddRequestOpenApiApi
| ExperimentResultsWidgetAddRequestOpenApiApi
+ | SurveyResultsWidgetAddRequestOpenApiApi
| LogsListWidgetAddRequestOpenApiApi
/**
@@ -8437,7 +8480,7 @@ export type AddDashboardWidgetRequestApi =
*/
export interface AddDashboardWidgetsBatchRequestOpenApiApi {
/**
- * Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, experiment_results, experiments_list, logs_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, logs_list, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).
* @minItems 1
* @maxItems 10
*/
@@ -8564,6 +8607,29 @@ export interface ExperimentResultsWidgetUpdateRequestOpenApiApi {
config?: ExperimentResultsWidgetConfigApi
}
+export type SurveyResultsWidgetUpdateRequestOpenApiApiWidgetType =
+ (typeof SurveyResultsWidgetUpdateRequestOpenApiApiWidgetType)[keyof typeof SurveyResultsWidgetUpdateRequestOpenApiApiWidgetType]
+
+export const SurveyResultsWidgetUpdateRequestOpenApiApiWidgetType = {
+ SurveyResults: 'survey_results',
+} as const
+
+export interface SurveyResultsWidgetUpdateRequestOpenApiApi {
+ /** ID of the widget tile to update. Use dashboard-get to look up widget tile IDs. */
+ tile_id: number
+ /**
+ * New display name for the widget. Empty string or null clears it; omit to leave unchanged.
+ * @maxLength 400
+ * @nullable
+ */
+ name?: string | null
+ /** New markdown description for the widget. Omit to leave unchanged. */
+ description?: string
+ widget_type: SurveyResultsWidgetUpdateRequestOpenApiApiWidgetType
+ /** New configuration for the survey results widget. Omit to leave unchanged. */
+ config?: SurveyResultsWidgetConfigApi
+}
+
export type LogsListWidgetUpdateRequestOpenApiApiWidgetType =
(typeof LogsListWidgetUpdateRequestOpenApiApiWidgetType)[keyof typeof LogsListWidgetUpdateRequestOpenApiApiWidgetType]
@@ -8593,6 +8659,7 @@ export type UpdateDashboardWidgetRequestApi =
| SessionReplayListWidgetUpdateRequestOpenApiApi
| ExperimentsListWidgetUpdateRequestOpenApiApi
| ExperimentResultsWidgetUpdateRequestOpenApiApi
+ | SurveyResultsWidgetUpdateRequestOpenApiApi
| LogsListWidgetUpdateRequestOpenApiApi
/**
@@ -8751,6 +8818,25 @@ export interface ExperimentResultsWidgetCatalogEntryOpenApiApi {
required_product_access?: string | null
}
+export type SurveyResultsWidgetCatalogEntryOpenApiApiWidgetType =
+ (typeof SurveyResultsWidgetCatalogEntryOpenApiApiWidgetType)[keyof typeof SurveyResultsWidgetCatalogEntryOpenApiApiWidgetType]
+
+export const SurveyResultsWidgetCatalogEntryOpenApiApiWidgetType = {
+ SurveyResults: 'survey_results',
+} as const
+
+export interface SurveyResultsWidgetCatalogEntryOpenApiApi {
+ widget_type: SurveyResultsWidgetCatalogEntryOpenApiApiWidgetType
+ 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: SurveyResultsWidgetConfigApi
+ /** @nullable */
+ required_product_access?: string | null
+}
+
export type LogsListWidgetCatalogEntryOpenApiApiWidgetType =
(typeof LogsListWidgetCatalogEntryOpenApiApiWidgetType)[keyof typeof LogsListWidgetCatalogEntryOpenApiApiWidgetType]
@@ -8776,6 +8862,7 @@ export type WidgetCatalogEntryApi =
| SessionReplayListWidgetCatalogEntryOpenApiApi
| ExperimentsListWidgetCatalogEntryOpenApiApi
| ExperimentResultsWidgetCatalogEntryOpenApiApi
+ | SurveyResultsWidgetCatalogEntryOpenApiApi
| LogsListWidgetCatalogEntryOpenApiApi
export interface WidgetCatalogResponseApi {
@@ -8864,6 +8951,16 @@ export const ExperimentResultsWidgetTypeEnumApi = {
ExperimentResults: 'experiment_results',
} as const
+/**
+ * * `survey_results` - survey_results
+ */
+export type SurveyResultsWidgetTypeEnumApi =
+ (typeof SurveyResultsWidgetTypeEnumApi)[keyof typeof SurveyResultsWidgetTypeEnumApi]
+
+export const SurveyResultsWidgetTypeEnumApi = {
+ SurveyResults: 'survey_results',
+} as const
+
/**
* * `logs_list` - logs_list
*/
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index e9292930ce62..31ff69a64e3e 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -237,12 +237,15 @@ export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitMax
export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderByDefault = `created_at`
export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderDirectionDefault = `DESC`
export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourStatusDefault = `all`
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitDefault = 50
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitMax = 100
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitDefault = 10
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitMax = 25
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixOrderByDefault = `latest`
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixWrapLinesDefault = false
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixTimezoneDefault = `UTC`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitDefault = 50
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitMax = 100
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenOrderByDefault = `latest`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenWrapLinesDefault = false
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenTimezoneDefault = `UTC`
export const dashboardsPartialUpdateBodyTilesItemWidgetOneNameMax = 400
export const dashboardsPartialUpdateBodyDeleteInsightsDefault = false
@@ -306,13 +309,14 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
'experiments_list',
'logs_list',
'session_replay_list',
+ 'survey_results',
])
.describe(
- '\* `activity_events_list` - activity_events_list\n\* `error_tracking_list` - error_tracking_list\n\* `experiment_results` - experiment_results\n\* `experiments_list` - experiments_list\n\* `logs_list` - logs_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\* `logs_list` - logs_list\n\* `session_replay_list` - session_replay_list\n\* `survey_results` - survey_results'
)
.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\* `experiment_results` - experiment_results\n\* `experiments_list` - experiments_list\n\* `logs_list` - logs_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\* `logs_list` - logs_list\n\* `session_replay_list` - session_replay_list\n\* `survey_results` - survey_results'
),
config: zod
.union([
@@ -711,7 +715,14 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe("Null or omitted means all time (the survey's full lifetime)."),
+ surveyId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Survey to show performance stats and recent responses for. Null until the user picks one.'
+ ),
limit: zod
.number()
.min(1)
@@ -719,11 +730,44 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
.default(
dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitDefault
)
+ .describe('Maximum number of recent responses to return.'),
+ }),
+ zod.object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitDefault
+ )
.describe('Maximum number of log lines to return.'),
orderBy: zod
.enum(['latest', 'earliest'])
.default(
- dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixOrderByDefault
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenOrderByDefault
)
.describe('Sort by newest (latest) or oldest (earliest) first.'),
severityLevels: zod
@@ -739,7 +783,7 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
wrapLines: zod
.boolean()
.default(
- dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixWrapLinesDefault
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenWrapLinesDefault
)
.describe(
'Wrap long log lines instead of truncating them to a single row.'
@@ -747,7 +791,7 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
timezone: zod
.enum(['UTC', 'local'])
.default(
- dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixTimezoneDefault
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenTimezoneDefault
)
.describe(
"Render log timestamps in UTC or in each viewer's local timezone."
@@ -976,12 +1020,17 @@ export const dashboardsWidgetsBatchCreateBodyWidgetsItemFiveNameMax = 400
export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixNameMax = 400
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitDefault = 50
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitMax = 100
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitDefault = 10
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitMax = 25
+
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenNameMax = 400
+
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneLimitDefault = 50
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneLimitMax = 100
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneOrderByDefault = `latest`
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneWrapLinesDefault = false
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneTimezoneDefault = `UTC`
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneOrderByDefault = `latest`
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneWrapLinesDefault = false
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneTimezoneDefault = `UTC`
export const dashboardsWidgetsBatchCreateBodyWidgetsMax = 10
export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
@@ -1694,7 +1743,7 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
.boolean()
.optional()
.describe('Whether to show the description on the dashboard tile.'),
- widget_type: zod.enum(['logs_list']),
+ widget_type: zod.enum(['survey_results']),
config: zod
.object({
dateRange: zod
@@ -1719,16 +1768,115 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe("Null or omitted means all time (the survey's full lifetime)."),
+ surveyId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Survey to show performance stats and recent responses for. Null until the user picks one.'
+ ),
limit: zod
.number()
.min(1)
.max(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitMax)
.default(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitDefault)
+ .describe('Maximum number of recent responses to return.'),
+ })
+ .describe('Configuration for the survey results widget.'),
+ }),
+ zod.object({
+ name: zod
+ .string()
+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenNameMax)
+ .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(['logs_list']),
+ config: zod
+ .object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneLimitMax)
+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneLimitDefault)
.describe('Maximum number of log lines to return.'),
orderBy: zod
.enum(['latest', 'earliest'])
- .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneOrderByDefault)
+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneOrderByDefault)
.describe('Sort by newest (latest) or oldest (earliest) first.'),
severityLevels: zod
.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal']))
@@ -1740,11 +1888,11 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
.describe('Only show logs from these services. Empty shows all services.'),
wrapLines: zod
.boolean()
- .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneWrapLinesDefault)
+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneWrapLinesDefault)
.describe('Wrap long log lines instead of truncating them to a single row.'),
timezone: zod
.enum(['UTC', 'local'])
- .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneTimezoneDefault)
+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneTimezoneDefault)
.describe("Render log timestamps in UTC or in each viewer's local timezone."),
savedViewId: zod
.union([zod.string(), zod.null()])
@@ -1760,7 +1908,7 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
.min(1)
.max(dashboardsWidgetsBatchCreateBodyWidgetsMax)
.describe(
- 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, experiment_results, experiments_list, logs_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, logs_list, session_replay_list, survey_results. 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.')
@@ -1806,12 +1954,17 @@ export const dashboardsUpdateWidgetsBatchBodyWidgetsItemFiveNameMax = 400
export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixNameMax = 400
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitDefault = 50
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitMax = 100
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitDefault = 10
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitMax = 25
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneOrderByDefault = `latest`
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneWrapLinesDefault = false
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneTimezoneDefault = `UTC`
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenNameMax = 400
+
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneLimitDefault = 50
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneLimitMax = 100
+
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneOrderByDefault = `latest`
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneWrapLinesDefault = false
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneTimezoneDefault = `UTC`
export const dashboardsUpdateWidgetsBatchBodyWidgetsMax = 10
export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
@@ -2277,7 +2430,7 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
.string()
.optional()
.describe('New markdown description for the widget. Omit to leave unchanged.'),
- widget_type: zod.enum(['logs_list']),
+ widget_type: zod.enum(['survey_results']),
config: zod
.object({
dateRange: zod
@@ -2302,16 +2455,74 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe("Null or omitted means all time (the survey's full lifetime)."),
+ surveyId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Survey to show performance stats and recent responses for. Null until the user picks one.'
+ ),
limit: zod
.number()
.min(1)
.max(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitMax)
.default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitDefault)
+ .describe('Maximum number of recent responses to return.'),
+ })
+ .optional()
+ .describe('New configuration for the survey results widget. Omit to leave unchanged.'),
+ }),
+ zod.object({
+ tile_id: zod
+ .number()
+ .describe('ID of the widget tile to update. Use dashboard-get to look up widget tile IDs.'),
+ name: zod
+ .string()
+ .max(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenNameMax)
+ .nullish()
+ .describe(
+ 'New display name for the widget. Empty string or null clears it; omit to leave unchanged.'
+ ),
+ description: zod
+ .string()
+ .optional()
+ .describe('New markdown description for the widget. Omit to leave unchanged.'),
+ widget_type: zod.enum(['logs_list']),
+ config: zod
+ .object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneLimitMax)
+ .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneLimitDefault)
.describe('Maximum number of log lines to return.'),
orderBy: zod
.enum(['latest', 'earliest'])
- .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneOrderByDefault)
+ .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneOrderByDefault)
.describe('Sort by newest (latest) or oldest (earliest) first.'),
severityLevels: zod
.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal']))
@@ -2323,11 +2534,11 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
.describe('Only show logs from these services. Empty shows all services.'),
wrapLines: zod
.boolean()
- .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneWrapLinesDefault)
+ .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneWrapLinesDefault)
.describe('Wrap long log lines instead of truncating them to a single row.'),
timezone: zod
.enum(['UTC', 'local'])
- .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneTimezoneDefault)
+ .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneTimezoneDefault)
.describe("Render log timestamps in UTC or in each viewer's local timezone."),
savedViewId: zod
.union([zod.string(), zod.null()])
diff --git a/products/dashboards/frontend/generated/widget-config-property-keys.json b/products/dashboards/frontend/generated/widget-config-property-keys.json
index c6e798c33a3c..355369790fb6 100644
--- a/products/dashboards/frontend/generated/widget-config-property-keys.json
+++ b/products/dashboards/frontend/generated/widget-config-property-keys.json
@@ -23,6 +23,7 @@
],
"experiments_list": ["createdBy", "limit", "orderBy", "orderDirection", "status"],
"experiment_results": ["experimentId"],
+ "survey_results": ["dateRange", "limit", "surveyId"],
"logs_list": [
"dateRange",
"limit",
@@ -297,6 +298,19 @@
"$type": "integer"
}
},
+ "survey_results": {
+ "dateRange": {
+ "date_from": {
+ "$enum": ["-14d", "-1M", "-1h", "-24h", "-30M", "-30d", "-3h", "-7d", "-90d"]
+ }
+ },
+ "surveyId": {
+ "$type": "string"
+ },
+ "limit": {
+ "$type": "integer"
+ }
+ },
"logs_list": {
"dateRange": {
"date_from": {
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/surveyResultsWidgetConfig.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/surveyResultsWidgetConfig.zod.ts
new file mode 100644
index 000000000000..82c0f97cbefe
--- /dev/null
+++ b/products/dashboards/frontend/generated/widget-config-schemas/surveyResultsWidgetConfig.zod.ts
@@ -0,0 +1,32 @@
+/**
+ * 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'
+
+import { WidgetDateRange } from './widgetDateRange.zod'
+
+export const surveyResultsWidgetConfigLimitDefault = 10
+export const surveyResultsWidgetConfigLimitMax = 25
+
+export const SurveyResultsWidgetConfig = /* @__PURE__ */ zod.object({
+ dateRange: zod
+ .union([WidgetDateRange, zod.null()])
+ .optional()
+ .describe("Null or omitted means all time (the survey's full lifetime)."),
+ surveyId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe('Survey to show performance stats and recent responses for. Null until the user picks one.'),
+ limit: zod
+ .number()
+ .min(1)
+ .max(surveyResultsWidgetConfigLimitMax)
+ .default(surveyResultsWidgetConfigLimitDefault)
+ .describe('Maximum number of recent responses to return.'),
+})
+
+export type SurveyResultsWidgetConfig = zod.input<typeof SurveyResultsWidgetConfig>
+export type SurveyResultsWidgetConfigOutput = zod.output<typeof SurveyResultsWidgetConfig>
diff --git a/products/dashboards/frontend/generated/widget-configs.zod.ts b/products/dashboards/frontend/generated/widget-configs.zod.ts
index 9632a2a306db..8780080db0b6 100644
--- a/products/dashboards/frontend/generated/widget-configs.zod.ts
+++ b/products/dashboards/frontend/generated/widget-configs.zod.ts
@@ -9,6 +9,7 @@ import { ExperimentResultsWidgetConfig as ExperimentResultsWidgetConfigComponent
import { ExperimentsListWidgetConfig } from './widget-config-schemas/experimentsListWidgetConfig.zod'
import { LogsListWidgetConfig } from './widget-config-schemas/logsListWidgetConfig.zod'
import { SessionReplayListWidgetConfig } from './widget-config-schemas/sessionReplayListWidgetConfig.zod'
+import { SurveyResultsWidgetConfig as SurveyResultsWidgetConfigComponent } from './widget-config-schemas/surveyResultsWidgetConfig.zod'
import { WidgetFilterEntry } from './widget-config-schemas/widgetFilterEntry.zod'
export const activityEventsWidgetConfigSchema = /* @__PURE__ */ ActivityEventsListWidgetConfig
@@ -17,6 +18,7 @@ export const experimentResultsWidgetConfigSchema = /* @__PURE__ */ ExperimentRes
export const experimentsWidgetConfigSchema = /* @__PURE__ */ ExperimentsListWidgetConfig
export const logsWidgetConfigSchema = /* @__PURE__ */ LogsListWidgetConfig
export const sessionReplayWidgetConfigSchema = /* @__PURE__ */ SessionReplayListWidgetConfig
+export const surveyResultsWidgetConfigSchema = /* @__PURE__ */ SurveyResultsWidgetConfigComponent
export const widgetFilterEntrySchema = /* @__PURE__ */ WidgetFilterEntry
export type ActivityEventsWidgetConfig = zod.infer<typeof activityEventsWidgetConfigSchema>
@@ -25,6 +27,7 @@ export type ExperimentResultsWidgetConfig = zod.infer<typeof experimentResultsWi
export type ExperimentsWidgetConfig = zod.infer<typeof experimentsWidgetConfigSchema>
export type LogsWidgetConfig = zod.infer<typeof logsWidgetConfigSchema>
export type SessionReplayWidgetConfig = zod.infer<typeof sessionReplayWidgetConfigSchema>
+export type SurveyResultsWidgetConfig = zod.infer<typeof surveyResultsWidgetConfigSchema>
type WidgetFiltersRecord = NonNullable<ActivityEventsWidgetConfig['widgetFilters']>
export type WidgetFilterConfigEntry = WidgetFiltersRecord[string]
@@ -72,3 +75,9 @@ export const sessionReplayWidgetFormSchema = sessionReplayWidgetConfigSchema.pic
dateRange: true,
filterTestAccounts: true,
})
+
+export const surveyResultsWidgetFormSchema = surveyResultsWidgetConfigSchema.pick({
+ surveyId: true,
+ limit: true,
+ dateRange: true,
+})
diff --git a/products/dashboards/frontend/generated/widget-form-fields.json b/products/dashboards/frontend/generated/widget-form-fields.json
index 9e55c8ac2ba0..94f43bfbcb2a 100644
--- a/products/dashboards/frontend/generated/widget-form-fields.json
+++ b/products/dashboards/frontend/generated/widget-form-fields.json
@@ -35,6 +35,12 @@
"configTypeExport": "SessionReplayWidgetConfig",
"formSchemaExport": "sessionReplayWidgetFormSchema",
"formFields": ["limit", "orderBy", "orderDirection", "dateRange", "filterTestAccounts"]
+ },
+ "survey_results": {
+ "configSchemaExport": "surveyResultsWidgetConfigSchema",
+ "configTypeExport": "SurveyResultsWidgetConfig",
+ "formSchemaExport": "surveyResultsWidgetFormSchema",
+ "formFields": ["surveyId", "limit", "dateRange"]
}
}
}
diff --git a/products/dashboards/frontend/types.ts b/products/dashboards/frontend/types.ts
index ea8bee36d159..6658cb052f6b 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' | 'experiment' | 'logs'
+export type DashboardWidgetProductAccess = 'error_tracking' | 'session_recording' | 'experiment' | 'survey' | 'logs'
diff --git a/products/dashboards/frontend/widgetProductAccess.ts b/products/dashboards/frontend/widgetProductAccess.ts
index ab0ada0f513d..6d1a16244ef8 100644
--- a/products/dashboards/frontend/widgetProductAccess.ts
+++ b/products/dashboards/frontend/widgetProductAccess.ts
@@ -9,6 +9,7 @@ const WIDGET_PRODUCT_ACCESS_CHECKS = {
error_tracking: () => userHasAccess(AccessControlResourceType.ErrorTracking, AccessControlLevel.Viewer),
session_recording: () => userHasAccess(AccessControlResourceType.SessionRecording, AccessControlLevel.Viewer),
experiment: () => userHasAccess(AccessControlResourceType.Experiment, AccessControlLevel.Viewer),
+ survey: () => userHasAccess(AccessControlResourceType.Survey, AccessControlLevel.Viewer),
logs: () => userHasAccess(AccessControlResourceType.Logs, AccessControlLevel.Viewer),
} satisfies Record<DashboardWidgetProductAccess, () => boolean>
diff --git a/products/dashboards/frontend/widget_types/catalog.ts b/products/dashboards/frontend/widget_types/catalog.ts
index 924161feb5f2..b88c54cd1909 100644
--- a/products/dashboards/frontend/widget_types/catalog.ts
+++ b/products/dashboards/frontend/widget_types/catalog.ts
@@ -1,6 +1,6 @@
import type { ComponentType } from 'react'
-import { IconFlask, IconList, IconLive, IconRewindPlay, IconWarning } from '@posthog/icons'
+import { IconFlask, IconList, IconLive, IconMessage, IconRewindPlay, IconWarning } from '@posthog/icons'
import { urls } from 'scenes/urls'
@@ -14,6 +14,7 @@ import {
experimentsWidgetConfigSchema,
logsWidgetConfigSchema,
sessionReplayWidgetConfigSchema,
+ surveyResultsWidgetConfigSchema,
} from '../generated/widget-configs.zod'
import type { DashboardWidgetProductAccess } from '../types'
import { ActivityEventsWidgetPreview } from '../widgets/previews/ActivityEventsWidgetPreview'
@@ -24,6 +25,7 @@ import {
} from '../widgets/previews/ExperimentsWidgetPreviews'
import { LogsWidgetPreview } from '../widgets/previews/LogsWidgetPreview'
import { SessionReplayWidgetPreview } from '../widgets/previews/SessionReplayWidgetPreview'
+import { SurveyResultsWidgetPreview } from '../widgets/previews/SurveysWidgetPreviews'
import type { WidgetAvailabilityConfig, WidgetAvailabilityRequirementId } from './widgetAvailability'
export const DASHBOARD_WIDGET_HEADER_LAYOUTS = ['simple', 'dashboard_tile'] as const
@@ -81,6 +83,7 @@ export const DASHBOARD_WIDGET_GROUP_LABELS = {
error_tracking: 'Error tracking',
session_replay: 'Session replay',
experiments: 'Experiments',
+ surveys: 'Surveys',
logs: 'Logs',
} as const satisfies Record<string, string>
@@ -94,6 +97,7 @@ export const DASHBOARD_WIDGET_GROUP_ICONS = {
error_tracking: IconWarning,
session_replay: IconRewindPlay,
experiments: IconFlask,
+ surveys: IconMessage,
logs: IconList,
} as const satisfies Record<keyof typeof DASHBOARD_WIDGET_GROUP_LABELS, ComponentType<{ className?: string }>>
@@ -259,6 +263,20 @@ export const DASHBOARD_WIDGET_CATALOG = {
message: 'Log in to PostHog to see experiment results from this dashboard.',
},
},
+ survey_results: {
+ groupId: 'surveys',
+ label: 'Survey results',
+ description: 'Performance stats and recent responses for a selected survey.',
+ headerTitle: 'Survey results',
+ defaultConfig: surveyResultsWidgetConfigSchema.parse({}),
+ defaultLayout: { w: 6, h: 5, minW: 3, minH: 3 },
+ productAccess: 'survey',
+ titleHref: urls.surveys(),
+ sharedPlaceholder: {
+ title: 'Survey results',
+ message: 'Log in to PostHog to see survey results from this dashboard.',
+ },
+ },
activity_events_list: {
groupId: 'activity',
label: 'Recent events',
@@ -301,6 +319,7 @@ export const DASHBOARD_WIDGET_PREVIEWS: Record<DashboardWidgetCatalogKey, () =>
session_replay_list: SessionReplayWidgetPreview,
experiments_list: ExperimentsListWidgetPreview,
experiment_results: ExperimentResultsWidgetPreview,
+ survey_results: SurveyResultsWidgetPreview,
logs_list: LogsWidgetPreview,
}
@@ -379,7 +398,7 @@ function getDashboardWidgetCatalogGroups(): DashboardWidgetCatalogGroup[] {
group.widgets.push({ widgetType: widgetType as DashboardWidgetCatalogKey, entry })
}
- const groupDisplayOrder = ['session_replay', 'error_tracking', 'activity', 'logs', 'experiments']
+ const groupDisplayOrder = ['session_replay', 'error_tracking', 'activity', 'logs', 'experiments', 'surveys']
return [...groupsById.values()].sort((a, b) => {
const aIndex = groupDisplayOrder.indexOf(a.groupId)
diff --git a/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.tsx b/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.tsx
index 1a204f127cbe..64c43b15703c 100644
--- a/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.tsx
+++ b/products/dashboards/frontend/widgets/experiments/ExperimentResultsWidget.tsx
@@ -257,13 +257,20 @@ export function ExperimentResultsWidget({
<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">
+ {/* The experiment name already shows in the tile filter bar, so link out rather than repeat it. */}
<Link
to={urls.experiment(experiment.id)}
target="_blank"
- className="truncate font-semibold text-primary"
- title={experiment.name}
+ className="text-sm font-medium"
+ onClick={() =>
+ posthog.capture('dashboard widget open experiment clicked', {
+ widget_type: 'experiment_results',
+ tile_id: tileId,
+ experiment_id: experiment.id,
+ })
+ }
>
- {experiment.name}
+ See more
</Link>
<StatusTag status={experiment.status as ExperimentStatus} />
</div>
diff --git a/products/dashboards/frontend/widgets/previews/SurveysWidgetPreviews.tsx b/products/dashboards/frontend/widgets/previews/SurveysWidgetPreviews.tsx
new file mode 100644
index 000000000000..70a51cf864f3
--- /dev/null
+++ b/products/dashboards/frontend/widgets/previews/SurveysWidgetPreviews.tsx
@@ -0,0 +1,54 @@
+// Inline sample data keeps this preview off widgetOverviewStoryFixtures, which would import the
+// widget catalog back and form a dependency cycle.
+const SAMPLE_SURVEY = {
+ name: 'Post-purchase feedback',
+ shown: 1840,
+ responses: 420,
+ conversionRate: 22.83,
+}
+
+const SAMPLE_QUESTION = 'How was your checkout experience?'
+const SAMPLE_RESPONSES = [
+ { person: '[email protected]', answer: 'Fast and easy, no complaints!' },
+ { person: '[email protected]', answer: 'Wish there were more payment options.' },
+]
+
+export function SurveyResultsWidgetPreview(): JSX.Element {
+ 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">{SAMPLE_SURVEY.name}</span>
+ <span className="rounded-full bg-success/10 px-2 py-0.5 text-xs font-semibold text-success">
+ Active
+ </span>
+ </div>
+ <div className="flex items-stretch rounded border bg-bg-light/40">
+ {[
+ { title: 'Shown', value: SAMPLE_SURVEY.shown },
+ { title: 'Responses', value: SAMPLE_SURVEY.responses },
+ { title: 'Conversion', value: `${SAMPLE_SURVEY.conversionRate}%` },
+ ].map((item, index) => (
+ <div
+ key={item.title}
+ className={`flex flex-1 flex-col items-center px-2 py-1.5 text-center ${
+ index > 0 ? 'border-l border-border' : ''
+ }`}
+ >
+ <div className="text-2xs font-semibold uppercase tracking-wide text-muted">{item.title}</div>
+ <div className="text-lg font-semibold leading-tight">{item.value}</div>
+ </div>
+ ))}
+ </div>
+ <div className="flex flex-col gap-2">
+ <h5 className="m-0 text-2xs font-semibold uppercase tracking-wide text-muted">Recent responses</h5>
+ {SAMPLE_RESPONSES.map((response) => (
+ <div key={response.person} className="flex flex-col gap-1 rounded border p-2">
+ <span className="truncate text-xs font-medium text-primary">{response.person}</span>
+ <span className="text-xs text-muted">Q: {SAMPLE_QUESTION}</span>
+ <span className="text-sm text-primary">{response.answer}</span>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/widgets/registry.tsx b/products/dashboards/frontend/widgets/registry.tsx
index d89f072ffb8a..1a4ca7c601e8 100644
--- a/products/dashboards/frontend/widgets/registry.tsx
+++ b/products/dashboards/frontend/widgets/registry.tsx
@@ -24,6 +24,7 @@ import {
} from './experiments/experimentsWidgetConfigValidation'
import { parseLogsWidgetConfigApiError } from './logs/logsWidgetConfigValidation'
import { parseSessionReplayWidgetConfigApiError } from './session_replay/sessionReplayWidgetConfigValidation'
+import { parseSurveyResultsWidgetConfigApiError } from './surveys/surveysWidgetConfigValidation'
// Widget UI is code-split: the static graph keeps only config-error parsers, types, and the lazy
// factories below, so a logged-in page no longer eagerly downloads every widget's renderer, edit
@@ -94,6 +95,15 @@ const SessionReplayWidgetTileFilters = lazy(() =>
const EditSessionReplayWidgetModal = lazy(() =>
import('./session_replay/EditSessionReplayWidgetModal').then((m) => ({ default: m.EditSessionReplayWidgetModal }))
)
+const SurveyResultsWidget = lazy(() =>
+ import('./surveys/SurveyResultsWidget').then((m) => ({ default: m.SurveyResultsWidget }))
+)
+const SurveyResultsWidgetTileFilters = lazy(() =>
+ import('./surveys/SurveyResultsWidgetTileFilters').then((m) => ({ default: m.SurveyResultsWidgetTileFilters }))
+)
+const EditSurveyResultsWidgetModal = lazy(() =>
+ import('./surveys/EditSurveyResultsWidgetModal').then((m) => ({ default: m.EditSurveyResultsWidgetModal }))
+)
export type DashboardWidgetConfigApiErrorParser = (
error: unknown,
@@ -233,6 +243,13 @@ export const DASHBOARD_WIDGET_REGISTRY = {
productAccess: 'experiment',
parseConfigApiError: parseExperimentResultsWidgetConfigApiError,
},
+ survey_results: {
+ Component: SurveyResultsWidget,
+ TileFilters: SurveyResultsWidgetTileFilters,
+ EditModal: EditSurveyResultsWidgetModal,
+ productAccess: 'survey',
+ parseConfigApiError: parseSurveyResultsWidgetConfigApiError,
+ },
logs_list: {
Component: LogsWidget,
TileFilters: LogsWidgetTileFilters,
diff --git a/products/dashboards/frontend/widgets/surveys/EditSurveyResultsWidgetModal.stories.tsx b/products/dashboards/frontend/widgets/surveys/EditSurveyResultsWidgetModal.stories.tsx
new file mode 100644
index 000000000000..48e8e80af644
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/EditSurveyResultsWidgetModal.stories.tsx
@@ -0,0 +1,53 @@
+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 { EditSurveyResultsWidgetModal } from './EditSurveyResultsWidgetModal'
+
+const SURVEY_RESULTS_CATALOG = getDashboardWidgetCatalogEntry('survey_results')!
+const DEFAULT_CONFIG = SURVEY_RESULTS_CATALOG.defaultConfig as Record<string, unknown>
+
+type EditSurveyResultsWidgetModalStoryProps = Partial<DashboardWidgetEditModalProps>
+
+function EditSurveyResultsWidgetModalStory({
+ isOpen = true,
+ onClose = () => undefined,
+ onSave = () => Promise.resolve(),
+ config = DEFAULT_CONFIG,
+ name = 'Survey results',
+ defaultTitle = SURVEY_RESULTS_CATALOG.headerTitle ?? SURVEY_RESULTS_CATALOG.label,
+ description = SURVEY_RESULTS_CATALOG.description,
+ ...props
+}: EditSurveyResultsWidgetModalStoryProps): JSX.Element {
+ return (
+ <EditSurveyResultsWidgetModal
+ isOpen={isOpen}
+ onClose={onClose}
+ config={config}
+ onSave={onSave}
+ name={name}
+ defaultTitle={defaultTitle}
+ description={description}
+ {...props}
+ />
+ )
+}
+
+const meta: Meta<typeof EditSurveyResultsWidgetModalStory> = {
+ title: 'Dashboards/Dashboard Widgets/Widget types/Surveys/Survey results/Widget settings',
+ component: EditSurveyResultsWidgetModalStory,
+ parameters: {
+ layout: 'fullscreen',
+ ...widgetStorybookParameters,
+ },
+ args: {
+ config: { ...DEFAULT_CONFIG, surveyId: 'survey-101' },
+ },
+}
+
+export default meta
+
+type Story = StoryObj<typeof EditSurveyResultsWidgetModalStory>
+
+export const Default: Story = {}
diff --git a/products/dashboards/frontend/widgets/surveys/EditSurveyResultsWidgetModal.tsx b/products/dashboards/frontend/widgets/surveys/EditSurveyResultsWidgetModal.tsx
new file mode 100644
index 000000000000..97aa330de251
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/EditSurveyResultsWidgetModal.tsx
@@ -0,0 +1,130 @@
+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 { editSurveyResultsWidgetModalLogic } from './editSurveyResultsWidgetModalLogic'
+import { SURVEY_RESULTS_WIDGET_DATE_RANGE_OPTIONS } from './surveysWidgetConfigValidation'
+
+function EditSurveyResultsWidgetModalContents(): JSX.Element {
+ const {
+ limit,
+ dateFrom,
+ tileName,
+ tileDescription,
+ activeFieldErrors,
+ saving,
+ saveDisabledReason,
+ onClose,
+ defaultTitle,
+ } = useValues(editSurveyResultsWidgetModalLogic)
+ const { setLimit, setDateFrom, setTileName, setTileDescription, clearFieldError, submit } = useActions(
+ editSurveyResultsWidgetModalLogic
+ )
+
+ return (
+ <LemonModal
+ isOpen
+ onClose={onClose}
+ title="Widget settings"
+ description="Configure the tile details. Pick which survey 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>
+ </>
+ }
+ >
+ <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('surveys')}</h5>
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
+ <LemonField.Pure
+ label="Date range"
+ help="Scopes both the performance stats and the recent responses."
+ >
+ <LemonSelect
+ value={dateFrom}
+ disabled={saving}
+ options={SURVEY_RESULTS_WIDGET_DATE_RANGE_OPTIONS}
+ onChange={(value) => {
+ if (value) {
+ setDateFrom(value)
+ }
+ }}
+ fullWidth
+ />
+ </LemonField.Pure>
+ <LemonField.Pure
+ label="Number of responses"
+ help="Show up to 25 recent responses 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>
+ </div>
+ </section>
+ </div>
+ </LemonModal>
+ )
+}
+
+export function EditSurveyResultsWidgetModal({
+ isOpen,
+ onClose,
+ config,
+ onSave,
+ name,
+ defaultTitle,
+ description,
+}: DashboardWidgetEditModalProps): JSX.Element | null {
+ if (!isOpen) {
+ return null
+ }
+
+ return (
+ <BindLogic
+ logic={editSurveyResultsWidgetModalLogic}
+ props={{ onClose, config, onSave, name, defaultTitle, description }}
+ >
+ <EditSurveyResultsWidgetModalContents />
+ </BindLogic>
+ )
+}
diff --git a/products/dashboards/frontend/widgets/surveys/SurveyPickerSelect.scss b/products/dashboards/frontend/widgets/surveys/SurveyPickerSelect.scss
new file mode 100644
index 000000000000..6e3a41312365
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/SurveyPickerSelect.scss
@@ -0,0 +1,8 @@
+// Scoped to this picker's dropdown only: let each option's label fill the row so the
+// metadata can right-align. Avoids changing the shared LemonInputSelect for everyone.
+.SurveyPickerSelect__dropdown {
+ .LemonButton__content > span {
+ flex: 1;
+ min-width: 0;
+ }
+}
diff --git a/products/dashboards/frontend/widgets/surveys/SurveyPickerSelect.tsx b/products/dashboards/frontend/widgets/surveys/SurveyPickerSelect.tsx
new file mode 100644
index 000000000000..bad0e50a579d
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/SurveyPickerSelect.tsx
@@ -0,0 +1,111 @@
+import './SurveyPickerSelect.scss'
+
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { IconPlus } from '@posthog/icons'
+
+import { LemonInputSelect, type LemonInputSelectOption } from 'lib/lemon-ui/LemonInputSelect'
+import { urls } from 'scenes/urls'
+
+import type { SurveyApi } from 'products/surveys/frontend/generated/api.schemas'
+
+import { surveyPickerLogic } from './surveyPickerLogic'
+
+export type SurveyPickerSelectProps = {
+ /** Isolates picker state per mount (modal vs. each tile). */
+ pickerKey: string
+ value: string | null
+ onChange: (surveyId: string | null) => void
+ disabled?: boolean
+ size?: 'small' | 'medium'
+ fullWidth?: boolean
+ dataAttr?: string
+ /** Fired when the "New survey" action is clicked, before opening the create page — used for adoption tracking. */
+ onCreateNew?: () => void
+}
+
+function surveyStatusLabel(survey: SurveyApi): string {
+ if (survey.archived) {
+ return 'Archived'
+ }
+ if (!survey.start_date) {
+ return 'Draft'
+ }
+ return survey.end_date ? 'Ended' : 'Active'
+}
+
+function SurveyOptionLabel({ survey }: { survey: SurveyApi }): JSX.Element {
+ return (
+ <span className="flex w-full items-center justify-between gap-2">
+ <span className="min-w-0 flex-1 truncate">{survey.name}</span>
+ <span className="shrink-0 text-xs text-muted">{surveyStatusLabel(survey)}</span>
+ </span>
+ )
+}
+
+export function SurveyPickerSelect({
+ pickerKey,
+ value,
+ onChange,
+ disabled,
+ size = 'small',
+ fullWidth = false,
+ dataAttr,
+ onCreateNew,
+}: SurveyPickerSelectProps): JSX.Element {
+ const logic = surveyPickerLogic({ pickerKey, ensureSurveyId: value })
+ const { surveyOptions, surveyOptionsLoading, selectedSurvey, search } = useValues(logic)
+ const { ensureOptionsLoaded, setSearch } = useActions(logic)
+
+ const options = useMemo((): LemonInputSelectOption[] => {
+ const byId = new Map<string, SurveyApi>()
+ if (selectedSurvey) {
+ byId.set(selectedSurvey.id, selectedSurvey)
+ }
+ for (const survey of surveyOptions) {
+ byId.set(survey.id, survey)
+ }
+ return Array.from(byId.values(), (survey) => ({
+ key: survey.id,
+ label: survey.name,
+ labelComponent: <SurveyOptionLabel survey={survey} />,
+ }))
+ }, [surveyOptions, selectedSurvey])
+
+ return (
+ <LemonInputSelect
+ mode="single"
+ size={size}
+ fullWidth={fullWidth}
+ popoverClassName="SurveyPickerSelect__dropdown"
+ placeholder="Select a survey"
+ loading={surveyOptionsLoading}
+ disabled={disabled}
+ disableFiltering
+ value={value != null ? [value] : []}
+ options={options}
+ emptyStateComponent={
+ <p className="text-secondary italic p-1">
+ {search ? `No surveys matching "${search}"` : 'No surveys yet'}
+ </p>
+ }
+ onFocus={() => ensureOptionsLoaded()}
+ onInputChange={(text) => setSearch(text)}
+ onChange={(values) => onChange(values.length > 0 ? values[0] : null)}
+ action={{
+ // Open the create flow in a new tab so the dashboard (and this tile's selection) is kept.
+ onClick: () => {
+ onCreateNew?.()
+ window.open(urls.survey('new'), '_blank', 'noopener,noreferrer')
+ },
+ children: (
+ <span className="flex items-center gap-1">
+ <IconPlus /> New survey
+ </span>
+ ),
+ }}
+ data-attr={dataAttr}
+ />
+ )
+}
diff --git a/products/dashboards/frontend/widgets/surveys/SurveyResultsWidget.stories.tsx b/products/dashboards/frontend/widgets/surveys/SurveyResultsWidget.stories.tsx
new file mode 100644
index 000000000000..53a68b1fa373
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/SurveyResultsWidget.stories.tsx
@@ -0,0 +1,197 @@
+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 { surveyResultsSamplePayload } 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 { SurveyResultsWidget } from './SurveyResultsWidget'
+import { SurveyResultsWidgetTileFilters } from './SurveyResultsWidgetTileFilters'
+
+const SURVEY_RESULTS_CATALOG = getDashboardWidgetCatalogEntry('survey_results')!
+const DEFAULT_CONFIG = SURVEY_RESULTS_CATALOG.defaultConfig as Record<string, unknown>
+
+// The empty-state picker drives surveyPickerLogic, which fetches surveys to resolve the selected
+// name — mock the list/retrieve endpoints so it renders cleanly.
+const pickerSurveys = [
+ { id: 'survey-101', name: 'Post-purchase feedback', archived: false, start_date: '2026-05-12T00:00:00.000Z' },
+ { id: 'survey-102', name: 'NPS survey', archived: false, start_date: null },
+]
+const surveysApiDecorator = mswDecorator({
+ get: {
+ '/api/projects/:team_id/surveys/': () => [200, { results: pickerSurveys, count: pickerSurveys.length }],
+ '/api/projects/:team_id/surveys/:id/': ({ params }) => [
+ 200,
+ pickerSurveys.find((survey) => survey.id === params.id) ?? pickerSurveys[0],
+ ],
+ },
+})
+
+type SurveyResultsWidgetTileStoryProps = 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 SurveyResultsWidgetTileStory({
+ title = '',
+ description = SURVEY_RESULTS_CATALOG.description,
+ showDescription = true,
+ body,
+ tileFiltersReadOnly = false,
+ ...widgetProps
+}: SurveyResultsWidgetTileStoryProps): JSX.Element {
+ const widgetTypeLabel = getDashboardWidgetGroupLabel(SURVEY_RESULTS_CATALOG.groupId)
+ const defaultTitle = SURVEY_RESULTS_CATALOG.headerTitle ?? SURVEY_RESULTS_CATALOG.label
+ const { isAvailable: showTileFilters } = useWidgetAvailability(SURVEY_RESULTS_CATALOG.availability)
+
+ return (
+ <WidgetCard className="h-full">
+ <WidgetCardHeader
+ layout={SURVEY_RESULTS_CATALOG.headerLayout}
+ title={title}
+ defaultTitle={defaultTitle}
+ titleHref={SURVEY_RESULTS_CATALOG.titleHref}
+ widgetTypeLabel={widgetTypeLabel}
+ config={widgetProps.config}
+ headerMeta={SURVEY_RESULTS_CATALOG.headerMeta}
+ description={description}
+ showDescription={showDescription}
+ loading={widgetProps.loading}
+ shouldHideMoreButton={widgetCardShouldHideMoreButton(DashboardPlacement.Dashboard, false)}
+ moreButtonOverlay={mockMoreOverlay}
+ />
+ {showTileFilters ? (
+ <SurveyResultsWidgetTileFilters
+ tileId={widgetProps.tileId}
+ config={widgetProps.config}
+ onUpdateConfig={tileFiltersReadOnly ? undefined : widgetProps.onUpdateConfig}
+ disabledReason={tileFiltersReadOnly ? DASHBOARD_WIDGET_TILE_FILTERS_READONLY_REASON : undefined}
+ />
+ ) : null}
+ <WidgetCardBody>{body ?? <SurveyResultsWidget {...widgetProps} />}</WidgetCardBody>
+ </WidgetCard>
+ )
+}
+
+const meta: Meta<typeof SurveyResultsWidgetTileStory> = {
+ title: 'Dashboards/Dashboard Widgets/Widget types/Surveys/Survey results',
+ component: SurveyResultsWidgetTileStory,
+ parameters: {
+ layout: 'padded',
+ ...widgetStorybookParameters,
+ },
+ decorators: [surveysApiDecorator, ...widgetTileFrameDecorator],
+ args: {
+ tileId: 1,
+ config: { ...DEFAULT_CONFIG, surveyId: 'survey-101' },
+ loading: false,
+ result: null,
+ onUpdateConfig: () => undefined,
+ onRefresh: () => undefined,
+ },
+}
+
+export default meta
+
+type Story = StoryObj<typeof SurveyResultsWidgetTileStory>
+
+export const Default: Story = {
+ args: {
+ title: 'Survey results',
+ loading: false,
+ result: surveyResultsSamplePayload,
+ },
+}
+
+export const Loading: Story = {
+ args: {
+ title: 'Survey results',
+ loading: true,
+ result: null,
+ },
+ parameters: {
+ testOptions: { waitForLoadersToDisappear: false },
+ },
+}
+
+export const Empty: Story = {
+ args: {
+ title: 'Survey results',
+ loading: false,
+ result: {
+ ...surveyResultsSamplePayload,
+ responses: [],
+ hasMore: false,
+ },
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: 'Survey selected but no responses have come in yet.',
+ },
+ },
+ },
+}
+
+export const NotConfigured: Story = {
+ args: {
+ title: 'Survey results',
+ config: DEFAULT_CONFIG,
+ loading: false,
+ result: { survey: null, responses: [], needsConfiguration: true, hasSurveys: true },
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: 'Prompt to pick a survey when the tile has none selected yet.',
+ },
+ },
+ },
+}
+
+export const TileFiltersReadOnly: Story = {
+ args: {
+ title: 'Survey results',
+ loading: false,
+ result: surveyResultsSamplePayload,
+ tileFiltersReadOnly: true,
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: 'View-only dashboard access — the survey picker shows the selection read-only.',
+ },
+ },
+ },
+}
+
+export const SurveyNotFound: Story = {
+ args: {
+ title: 'Survey results',
+ loading: false,
+ result: { survey: null, responses: [], surveyNotFound: true },
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: 'The selected survey was deleted — prompt to pick another in settings.',
+ },
+ },
+ },
+}
diff --git a/products/dashboards/frontend/widgets/surveys/SurveyResultsWidget.tsx b/products/dashboards/frontend/widgets/surveys/SurveyResultsWidget.tsx
new file mode 100644
index 000000000000..9fcafb04a219
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/SurveyResultsWidget.tsx
@@ -0,0 +1,372 @@
+import posthog from 'posthog-js'
+import { useState } from 'react'
+
+import { LemonSkeleton } from '@posthog/lemon-ui'
+
+import { WavingHog } from 'lib/components/hedgehogs'
+import { TZLabel } from 'lib/components/TZLabel'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
+import { Link } from 'lib/lemon-ui/Link'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { PersonDisplay } from 'scenes/persons/PersonDisplay'
+import { StackedBar, type StackedBarSegment } from 'scenes/surveys/components/StackedBar'
+import { urls } from 'scenes/urls'
+
+import { SurveyEventName, type SurveyRates, type SurveyStats } from '~/types'
+
+import type { SurveyResponseAnswerApi, SurveyResponseRowApi } from 'products/surveys/frontend/generated/api.schemas'
+
+import { WidgetCardBodyMessage, WidgetCardContent } from '../../components/WidgetCard'
+import type { DashboardWidgetComponentProps } from '../registry'
+import { SurveyPickerSelect } from './SurveyPickerSelect'
+import { patchSurveyResultsWidgetConfig } from './surveysWidgetConfigValidation'
+
+// Reuse the survey responses API types (SurveyResponseRowApi / SurveyResponseAnswerApi) rather than
+// redeclaring them. The widget payload is a strict subset: it drops question_index and the extra
+// metadata block, and adds a resolved person display name.
+export type SurveyResultsWidgetResponseAnswer = Omit<SurveyResponseAnswerApi, 'question_index'>
+
+export type SurveyResultsWidgetResponse = Pick<SurveyResponseRowApi, 'uuid' | 'distinct_id' | 'session_id'> & {
+ person_display_name: string | null
+ submitted_at: string | null
+ answers: SurveyResultsWidgetResponseAnswer[]
+}
+
+export type SurveyResultsWidgetResult = {
+ survey: {
+ id: string
+ name: string
+ type: string
+ archived: boolean
+ start_date: string | null
+ end_date: string | null
+ } | null
+ stats?: SurveyStats
+ rates?: SurveyRates
+ responses: SurveyResultsWidgetResponse[]
+ hasMore?: boolean
+ needsConfiguration?: boolean
+ surveyNotFound?: boolean
+ hasSurveys?: boolean
+}
+
+type SurveyStatus = 'draft' | 'active' | 'ended' | 'archived'
+
+function surveyStatus(survey: NonNullable<SurveyResultsWidgetResult['survey']>): SurveyStatus {
+ if (survey.archived) {
+ return 'archived'
+ }
+ if (!survey.start_date) {
+ return 'draft'
+ }
+ return survey.end_date ? 'ended' : 'active'
+}
+
+const STATUS_TAG: Record<SurveyStatus, { label: string; type: 'success' | 'default' | 'danger' }> = {
+ active: { label: 'Active', type: 'success' },
+ draft: { label: 'Draft', type: 'default' },
+ ended: { label: 'Ended', type: 'danger' },
+ archived: { label: 'Archived', type: 'default' },
+}
+
+function formatAnswer(answer: unknown): string {
+ if (answer == null) {
+ return ''
+ }
+ // Multi-select answers can arrive as a JSON-encoded array string (e.g. `["a","b"]`); decode it.
+ let value = answer
+ if (typeof value === 'string' && value.trim().startsWith('[')) {
+ try {
+ value = JSON.parse(value)
+ } catch {
+ // Not JSON, show the string as-is.
+ }
+ }
+ return Array.isArray(value) ? value.map((item) => String(item)).join(', ') : String(value)
+}
+
+function captureCreateSurveyClicked(tileId: number): void {
+ posthog.capture('dashboard widget create survey clicked', { widget_type: 'survey_results', tile_id: tileId })
+}
+
+function SurveyResultsWidgetMessage({
+ 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="survey-results-widget-message"
+ >
+ <WavingHog className="size-24 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 SurveyStatsSummary({ stats, rates }: { stats: SurveyStats; rates: SurveyRates }): JSX.Element {
+ const shown = stats[SurveyEventName.SHOWN].total_count
+ const sent = stats[SurveyEventName.SENT].total_count
+ const dismissed = stats[SurveyEventName.DISMISSED].total_count
+ const onlySeen = stats[SurveyEventName.SHOWN].total_count_only_seen
+
+ const segments: StackedBarSegment[] = [
+ { count: sent, label: 'Submitted', colorClass: 'bg-success' },
+ { count: dismissed, label: 'Dismissed', colorClass: 'bg-warning' },
+ { count: onlySeen, label: 'Unanswered', colorClass: 'bg-brand-blue' },
+ ]
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-stretch overflow-x-auto rounded border bg-bg-light/40">
+ {[
+ { title: 'Shown', value: humanFriendlyNumber(shown), valueClass: 'text-primary' },
+ { title: 'Responses', value: humanFriendlyNumber(sent), valueClass: 'text-success' },
+ {
+ title: 'Conversion',
+ value: `${humanFriendlyNumber(rates.response_rate)}%`,
+ valueClass: 'text-primary',
+ },
+ ].map((item, index) => (
+ <div
+ key={item.title}
+ className={`flex min-w-[6rem] flex-1 flex-col items-center px-2 py-1.5 text-center ${
+ index > 0 ? 'border-l border-border' : ''
+ }`}
+ >
+ <div className="text-2xs font-semibold uppercase tracking-wide text-muted">{item.title}</div>
+ <div className={`text-lg font-semibold leading-tight ${item.valueClass}`}>{item.value}</div>
+ </div>
+ ))}
+ </div>
+ {shown > 0 ? <StackedBar segments={segments} size="sm" /> : null}
+ </div>
+ )
+}
+
+function SurveyResponseRow({ response }: { response: SurveyResultsWidgetResponse }): JSX.Element {
+ return (
+ <div className="flex flex-col gap-1 rounded border p-2">
+ <div className="flex items-center justify-between gap-2 text-xs text-muted">
+ {/* PersonDisplay has no target prop, so wrap it to open the profile in a new tab. */}
+ <Link
+ to={urls.personByDistinctId(response.distinct_id)}
+ target="_blank"
+ className="min-w-0 truncate font-medium text-primary"
+ >
+ <PersonDisplay
+ person={{ distinct_id: response.distinct_id, properties: {} }}
+ displayName={response.person_display_name ?? undefined}
+ withIcon
+ noPopover
+ noLink
+ />
+ </Link>
+ {response.submitted_at ? <TZLabel time={response.submitted_at} /> : null}
+ </div>
+ {response.answers.map((answer) => {
+ const formatted = formatAnswer(answer.answer)
+ if (!formatted) {
+ return null
+ }
+ return (
+ <div key={answer.question_id} className="flex flex-col">
+ <span className="text-xs text-muted">Q: {answer.question_text}</span>
+ <span className="text-sm text-primary">{formatted}</span>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
+
+function SurveyResultsLoadingSkeleton(): JSX.Element {
+ return (
+ <WidgetCardContent>
+ <div className="flex flex-col gap-3 p-2" aria-busy aria-label="Loading survey 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-16 rounded" />
+ </div>
+ <LemonSkeleton className="h-12 w-full rounded" aria-hidden />
+ <div className="flex flex-col gap-2" aria-hidden>
+ {Array.from({ length: 3 }, (_, index) => (
+ <LemonSkeleton key={index} className="h-12 w-full rounded" />
+ ))}
+ </div>
+ </div>
+ </WidgetCardContent>
+ )
+}
+
+// Editable tile with no survey chosen yet: owns the optimistic pick so the selection shows
+// immediately rather than waiting for the persist + refresh round-trip.
+function SurveyResultsEmptyStatePicker({
+ tileId,
+ config,
+ onUpdateConfig,
+}: Required<Pick<DashboardWidgetComponentProps, 'tileId' | 'config' | 'onUpdateConfig'>>): JSX.Element {
+ const [optimisticSurveyId, setOptimisticSurveyId] = useState<string | null>(null)
+ return (
+ <div className="w-64 max-w-full">
+ <SurveyPickerSelect
+ pickerKey={`results-tile-${tileId}`}
+ value={optimisticSurveyId}
+ fullWidth
+ onChange={async (value) => {
+ setOptimisticSurveyId(value)
+ try {
+ await onUpdateConfig(patchSurveyResultsWidgetConfig(config, value))
+ } catch {
+ // Persist failed, drop the optimistic pick so we don't show a selection that wasn't saved.
+ setOptimisticSurveyId((current) => (current === value ? null : current))
+ }
+ }}
+ onCreateNew={() => captureCreateSurveyClicked(tileId)}
+ dataAttr="survey-results-widget-empty-state-select"
+ />
+ </div>
+ )
+}
+
+function SurveyResultsContent({
+ tileId,
+ survey,
+ responses,
+ stats,
+ rates,
+ hasMore,
+}: {
+ tileId: number
+ survey: NonNullable<SurveyResultsWidgetResult['survey']>
+ responses: SurveyResultsWidgetResponse[]
+ stats?: SurveyStats
+ rates?: SurveyRates
+ hasMore?: boolean
+}): JSX.Element {
+ const tag = STATUS_TAG[surveyStatus(survey)]
+ return (
+ <WidgetCardContent>
+ <div className="flex flex-col gap-3 p-2" data-attr="survey-results-widget-body">
+ <div className="flex items-center justify-between gap-2">
+ <Link
+ to={urls.survey(survey.id)}
+ target="_blank"
+ className="text-sm font-medium"
+ onClick={() =>
+ posthog.capture('dashboard widget open survey clicked', {
+ widget_type: 'survey_results',
+ tile_id: tileId,
+ survey_id: survey.id,
+ })
+ }
+ >
+ See more
+ </Link>
+ <LemonTag type={tag.type}>{tag.label}</LemonTag>
+ </div>
+ {stats && rates ? <SurveyStatsSummary stats={stats} rates={rates} /> : null}
+ <div className="flex flex-col gap-2">
+ <h5 className="m-0 text-2xs font-semibold uppercase tracking-wide text-muted">Recent responses</h5>
+ {responses.length === 0 ? (
+ <span className="text-sm text-muted">No responses to show yet.</span>
+ ) : (
+ responses.map((response) => <SurveyResponseRow key={response.uuid} response={response} />)
+ )}
+ {hasMore ? (
+ <Link to={urls.survey(survey.id)} target="_blank" className="text-xs text-muted">
+ Open the survey to see all responses.
+ </Link>
+ ) : null}
+ </div>
+ </div>
+ </WidgetCardContent>
+ )
+}
+
+export function SurveyResultsWidget({
+ tileId,
+ config,
+ result,
+ loading,
+ onUpdateConfig,
+}: DashboardWidgetComponentProps): JSX.Element {
+ const payload = result as SurveyResultsWidgetResult | null | undefined
+
+ if (loading) {
+ return <SurveyResultsLoadingSkeleton />
+ }
+
+ if (!payload || payload.needsConfiguration) {
+ if (onUpdateConfig && payload && payload.hasSurveys === false) {
+ return (
+ <SurveyResultsWidgetMessage
+ title="No surveys yet"
+ message="Create a survey to start collecting feedback from your users."
+ cta={
+ <LemonButton
+ type="primary"
+ size="small"
+ to={urls.surveys()}
+ targetBlank
+ onClick={() => captureCreateSurveyClicked(tileId)}
+ >
+ New survey
+ </LemonButton>
+ }
+ />
+ )
+ }
+ return (
+ <SurveyResultsWidgetMessage
+ title="No survey selected"
+ message={
+ onUpdateConfig
+ ? 'Pick a survey to see its performance and recent responses here.'
+ : 'No survey has been selected for this tile yet.'
+ }
+ cta={
+ onUpdateConfig ? (
+ <SurveyResultsEmptyStatePicker
+ tileId={tileId}
+ config={config}
+ onUpdateConfig={onUpdateConfig}
+ />
+ ) : undefined
+ }
+ />
+ )
+ }
+
+ if (payload.surveyNotFound || !payload.survey) {
+ return (
+ <SurveyResultsWidgetMessage
+ title="Survey not found"
+ message="This survey may have been deleted. Pick another one in the widget settings."
+ />
+ )
+ }
+
+ return (
+ <SurveyResultsContent
+ tileId={tileId}
+ survey={payload.survey}
+ responses={payload.responses}
+ stats={payload.stats}
+ rates={payload.rates}
+ hasMore={payload.hasMore}
+ />
+ )
+}
diff --git a/products/dashboards/frontend/widgets/surveys/SurveyResultsWidgetTileFilters.tsx b/products/dashboards/frontend/widgets/surveys/SurveyResultsWidgetTileFilters.tsx
new file mode 100644
index 000000000000..dd68066fc411
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/SurveyResultsWidgetTileFilters.tsx
@@ -0,0 +1,88 @@
+import { useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useRef, useState } from 'react'
+
+import type { DashboardWidgetTileFiltersProps } from '../registry'
+import { useWidgetTileConfigPersist } from '../widgetTileFiltersHooks'
+import { WidgetTileFilterReadOnlyValue, WidgetTileFiltersBar } from '../widgetTileFiltersReadOnly'
+import { surveyPickerLogic } from './surveyPickerLogic'
+import { SurveyPickerSelect } from './SurveyPickerSelect'
+import { parseSurveyResultsWidgetConfig, patchSurveyResultsWidgetConfig } from './surveysWidgetConfigValidation'
+
+function SurveyResultsReadOnlyValue({ tileId, surveyId }: { tileId: number; surveyId: string }): JSX.Element {
+ const { selectedSurvey } = useValues(
+ surveyPickerLogic({ pickerKey: `results-tile-${tileId}`, ensureSurveyId: surveyId })
+ )
+ return (
+ <WidgetTileFilterReadOnlyValue>
+ <span className="text-secondary">Survey:</span>{' '}
+ {selectedSurvey?.id === surveyId ? selectedSurvey.name : 'Selected survey'}
+ </WidgetTileFilterReadOnlyValue>
+ )
+}
+
+export function SurveyResultsWidgetTileFilters({
+ tileId,
+ config,
+ onUpdateConfig,
+ disabledReason,
+}: DashboardWidgetTileFiltersProps): JSX.Element {
+ const surveyId = parseSurveyResultsWidgetConfig(config).surveyId ?? null
+
+ const configRef = useRef(config)
+ configRef.current = config
+ const { persistConfigNow } = useWidgetTileConfigPersist(onUpdateConfig)
+
+ // Reflect the pick immediately rather than waiting for the persist round-trip to update `config`.
+ const [optimisticSurveyId, setOptimisticSurveyId] = useState<string | null | undefined>(undefined)
+ const selectedSurveyId = optimisticSurveyId !== undefined ? optimisticSurveyId : surveyId
+
+ const applySurveyId = async (value: string | null): Promise<void> => {
+ setOptimisticSurveyId(value)
+ const nextConfig = patchSurveyResultsWidgetConfig(configRef.current, value)
+ configRef.current = nextConfig
+ try {
+ await persistConfigNow(nextConfig)
+ } finally {
+ // Only clear if a newer pick hasn't superseded this one.
+ setOptimisticSurveyId((current) => (current === value ? undefined : current))
+ }
+ }
+
+ if (!onUpdateConfig) {
+ return (
+ <WidgetTileFiltersBar dataAttr="survey-results-widget-tile-filters-readonly">
+ {surveyId != null ? (
+ <SurveyResultsReadOnlyValue tileId={tileId} surveyId={surveyId} />
+ ) : (
+ <WidgetTileFilterReadOnlyValue>
+ <span className="text-secondary">Survey:</span> None selected
+ </WidgetTileFilterReadOnlyValue>
+ )}
+ </WidgetTileFiltersBar>
+ )
+ }
+
+ return (
+ <WidgetTileFiltersBar dataAttr="survey-results-widget-tile-filters">
+ <div className="w-64 max-w-full">
+ <SurveyPickerSelect
+ pickerKey={`results-tile-${tileId}`}
+ value={selectedSurveyId}
+ disabled={!!disabledReason}
+ fullWidth
+ onChange={(value) => {
+ void applySurveyId(value)
+ }}
+ onCreateNew={() =>
+ posthog.capture('dashboard widget create survey clicked', {
+ widget_type: 'survey_results',
+ tile_id: tileId,
+ })
+ }
+ dataAttr="survey-results-widget-tile-survey-select"
+ />
+ </div>
+ </WidgetTileFiltersBar>
+ )
+}
diff --git a/products/dashboards/frontend/widgets/surveys/editSurveyResultsWidgetModalLogic.ts b/products/dashboards/frontend/widgets/surveys/editSurveyResultsWidgetModalLogic.ts
new file mode 100644
index 000000000000..ebbf131fef0a
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/editSurveyResultsWidgetModalLogic.ts
@@ -0,0 +1,182 @@
+import { actions, defaults, kea, listeners, path, props, reducers, selectors } from 'kea'
+
+import type { SurveyResultsWidgetConfig } from '../../generated/widget-configs.zod'
+import { isWidgetConfigValidationError } from '../../utils'
+import {
+ widgetEditModalPropSelectors,
+ widgetEditModalTileActions,
+ buildWidgetTileMetadataPatch,
+ getWidgetEditModalTileDefaults,
+} from '../editWidgetModalBuilders'
+import type { DashboardWidgetEditModalProps } from '../registry'
+import type { editSurveyResultsWidgetModalLogicType } from './editSurveyResultsWidgetModalLogicType'
+import {
+ dateFromValueForConfig,
+ parseSurveyResultsWidgetConfig,
+ validateSurveyResultsWidgetConfigInput,
+ SURVEY_DATE_ALL_TIME,
+ type SurveyResultsWidgetFieldErrors,
+ type SurveyWidgetDateFrom,
+} from './surveysWidgetConfigValidation'
+
+export type EditSurveyResultsWidgetModalLogicProps = Omit<DashboardWidgetEditModalProps, 'isOpen'>
+
+export const editSurveyResultsWidgetModalLogic = kea<editSurveyResultsWidgetModalLogicType>([
+ path(['products', 'dashboards', 'widgets', 'surveys', 'editSurveyResultsWidgetModalLogic']),
+
+ props({
+ config: {},
+ onSave: async () => {},
+ onClose: () => {},
+ name: '',
+ defaultTitle: 'Untitled',
+ description: '',
+ } as EditSurveyResultsWidgetModalLogicProps),
+
+ actions({
+ ...widgetEditModalTileActions,
+ setLimit: (limit: number) => ({ limit }),
+ setDateFrom: (dateFrom: SurveyWidgetDateFrom) => ({ dateFrom }),
+ setFieldErrors: (fieldErrors: SurveyResultsWidgetFieldErrors) => ({ fieldErrors }),
+ clearFieldError: (field: keyof SurveyResultsWidgetFieldErrors) => ({ field }),
+ submit: true,
+ submitSuccess: true,
+ submitFailure: true,
+ }),
+
+ reducers({
+ limit: [
+ 10,
+ {
+ setLimit: (_: number, { limit }: { limit: number }) => limit,
+ },
+ ],
+ dateFrom: [
+ SURVEY_DATE_ALL_TIME as SurveyWidgetDateFrom,
+ {
+ setDateFrom: (_: SurveyWidgetDateFrom, { dateFrom }: { dateFrom: SurveyWidgetDateFrom }) => dateFrom,
+ },
+ ],
+ tileName: [
+ '',
+ {
+ setTileName: (_: string, { tileName }: { tileName: string }) => tileName,
+ },
+ ],
+ tileDescription: [
+ '',
+ {
+ setTileDescription: (_: string, { tileDescription }: { tileDescription: string }) => tileDescription,
+ },
+ ],
+ fieldErrors: [
+ {} as SurveyResultsWidgetFieldErrors,
+ {
+ setFieldErrors: (
+ _: SurveyResultsWidgetFieldErrors,
+ { fieldErrors }: { fieldErrors: SurveyResultsWidgetFieldErrors }
+ ) => fieldErrors,
+ clearFieldError: (
+ state: SurveyResultsWidgetFieldErrors,
+ { field }: { field: keyof SurveyResultsWidgetFieldErrors }
+ ) => {
+ 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({
+ widgetConfig: [
+ (_, p) => [p.config],
+ (config): SurveyResultsWidgetConfig => parseSurveyResultsWidgetConfig(config),
+ ],
+ ...widgetEditModalPropSelectors,
+ validation: [
+ (s) => [s.limit, s.dateFrom, s.widgetConfig],
+ // The survey is chosen on the tile filter bar; read it from the persisted config so saving
+ // the date range / limit preserves the selection.
+ (limit, dateFrom, widgetConfig) =>
+ validateSurveyResultsWidgetConfigInput({
+ surveyId: widgetConfig.surveyId ?? null,
+ limit,
+ dateFrom,
+ baseConfig: widgetConfig,
+ }),
+ ],
+ activeFieldErrors: [
+ (s) => [s.validation, s.fieldErrors],
+ (validation, fieldErrors): SurveyResultsWidgetFieldErrors => {
+ 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 = parseSurveyResultsWidgetConfig(props.config)
+
+ return {
+ limit: baseConfig.limit ?? 10,
+ dateFrom: dateFromValueForConfig(baseConfig),
+ ...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 SurveyResultsWidgetFieldErrors)
+ return
+ }
+ throw error
+ }
+ },
+ })),
+])
diff --git a/products/dashboards/frontend/widgets/surveys/surveyPickerLogic.ts b/products/dashboards/frontend/widgets/surveys/surveyPickerLogic.ts
new file mode 100644
index 000000000000..e3486d451b9a
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/surveyPickerLogic.ts
@@ -0,0 +1,99 @@
+import { actions, afterMount, connect, kea, key, listeners, path, props, propsChanged, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { surveysList, surveysRetrieve } from 'products/surveys/frontend/generated/api'
+import type { SurveyApi } from 'products/surveys/frontend/generated/api.schemas'
+
+import type { surveyPickerLogicType } from './surveyPickerLogicType'
+
+/** One page is plenty — search narrows the rest server-side, so we never paginate the dropdown. */
+const SURVEY_OPTIONS_LIMIT = 50
+const SEARCH_DEBOUNCE_MS = 300
+
+export type SurveyPickerLogicProps = {
+ pickerKey: string
+ /** When set, the logic resolves this survey's name on mount/change — lets read-only callers show it without a component effect. */
+ ensureSurveyId?: string | null
+}
+
+export const surveyPickerLogic = kea<surveyPickerLogicType>([
+ path((key) => ['products', 'dashboards', 'widgets', 'surveys', 'surveyPickerLogic', key]),
+ props({} as SurveyPickerLogicProps),
+ key((props) => props.pickerKey),
+
+ connect(() => ({
+ values: [teamLogic, ['currentProjectId']],
+ })),
+
+ actions({
+ setSearch: (search: string) => ({ search }),
+ ensureOptionsLoaded: true,
+ ensureSelectedLoaded: (surveyId: string) => ({ surveyId }),
+ }),
+
+ reducers({
+ search: ['', { setSearch: (_: string, { search }: { search: string }) => search }],
+ hasLoadedOptions: [false, { loadOptionsSuccess: () => true }],
+ }),
+
+ loaders(({ values }) => ({
+ surveyOptions: [
+ [] as SurveyApi[],
+ {
+ loadOptions: async (
+ { debounce }: { debounce: boolean } = { debounce: false },
+ breakpoint
+ ): Promise<SurveyApi[]> => {
+ // Debounce keystroke-driven searches; the initial focus load should open the dropdown immediately.
+ if (debounce) {
+ await breakpoint(SEARCH_DEBOUNCE_MS)
+ }
+ const response = await surveysList(String(values.currentProjectId), {
+ limit: SURVEY_OPTIONS_LIMIT,
+ search: values.search || undefined,
+ })
+ breakpoint()
+ return response.results ?? []
+ },
+ },
+ ],
+ selectedSurvey: [
+ null as SurveyApi | null,
+ {
+ loadSelectedSurvey: async ({ surveyId }: { surveyId: string }): Promise<SurveyApi> =>
+ surveysRetrieve(String(values.currentProjectId), surveyId),
+ },
+ ],
+ })),
+
+ listeners(({ actions, values }) => ({
+ setSearch: () => {
+ actions.loadOptions({ debounce: true })
+ },
+ ensureOptionsLoaded: () => {
+ if (!values.hasLoadedOptions && !values.surveyOptionsLoading) {
+ actions.loadOptions({ debounce: false })
+ }
+ },
+ ensureSelectedLoaded: ({ surveyId }) => {
+ if (values.selectedSurvey?.id === surveyId || values.selectedSurveyLoading) {
+ return
+ }
+ actions.loadSelectedSurvey({ surveyId })
+ },
+ })),
+
+ afterMount(({ props, actions }) => {
+ if (props.ensureSurveyId) {
+ actions.ensureSelectedLoaded(props.ensureSurveyId)
+ }
+ }),
+
+ propsChanged(({ props, actions }, oldProps) => {
+ if (props.ensureSurveyId && props.ensureSurveyId !== oldProps.ensureSurveyId) {
+ actions.ensureSelectedLoaded(props.ensureSurveyId)
+ }
+ }),
+])
diff --git a/products/dashboards/frontend/widgets/surveys/surveysWidgetConfigValidation.ts b/products/dashboards/frontend/widgets/surveys/surveysWidgetConfigValidation.ts
new file mode 100644
index 000000000000..766be7bfeca5
--- /dev/null
+++ b/products/dashboards/frontend/widgets/surveys/surveysWidgetConfigValidation.ts
@@ -0,0 +1,95 @@
+import { z } from 'zod'
+
+import { ApiError } from 'lib/api-error'
+
+import {
+ surveyResultsWidgetConfigSchema,
+ surveyResultsWidgetFormSchema,
+ type SurveyResultsWidgetConfig,
+} from '../../generated/widget-configs.zod'
+import { WIDGET_DATE_RANGE_SELECT_OPTIONS, type WidgetDateFromValue } from '../../widget_types/widgetConfigShared'
+import { fieldErrorsFromZodError, parseWidgetConfig } from '../widgetConfigValidation'
+
+/** The "All time" date-range option: stored as no date range so the backend uses the survey's start/end. */
+export const SURVEY_DATE_ALL_TIME = 'all' as const
+export type SurveyWidgetDateFrom = WidgetDateFromValue | typeof SURVEY_DATE_ALL_TIME
+
+export const SURVEY_RESULTS_WIDGET_DATE_RANGE_OPTIONS: { value: SurveyWidgetDateFrom; label: string }[] = [
+ { value: SURVEY_DATE_ALL_TIME, label: 'All time' },
+ ...WIDGET_DATE_RANGE_SELECT_OPTIONS,
+]
+
+type SurveyResultsWidgetFormField = keyof z.infer<typeof surveyResultsWidgetFormSchema>
+
+export type SurveyResultsWidgetFieldErrors = Partial<Record<SurveyResultsWidgetFormField, string>>
+
+const surveyResultsConfigDefaults = surveyResultsWidgetConfigSchema.parse({})
+
+export function parseSurveyResultsWidgetConfig(config: Record<string, unknown>): SurveyResultsWidgetConfig {
+ return parseWidgetConfig(surveyResultsWidgetConfigSchema, config)
+}
+
+export function dateFromValueForConfig(config: SurveyResultsWidgetConfig): SurveyWidgetDateFrom {
+ return (config.dateRange?.date_from as WidgetDateFromValue | undefined) ?? SURVEY_DATE_ALL_TIME
+}
+
+function dateRangeForSelection(dateFrom: SurveyWidgetDateFrom): { date_from: WidgetDateFromValue } | null {
+ return dateFrom === SURVEY_DATE_ALL_TIME ? null : { date_from: dateFrom }
+}
+
+export function patchSurveyResultsWidgetConfig(
+ config: Record<string, unknown>,
+ surveyId: string | null
+): SurveyResultsWidgetConfig {
+ const parsed = parseSurveyResultsWidgetConfig(config)
+ return surveyResultsWidgetConfigSchema.parse({ ...parsed, surveyId })
+}
+
+export function validateSurveyResultsWidgetConfigInput(input: {
+ surveyId: string | null
+ limit: number
+ dateFrom: SurveyWidgetDateFrom
+ baseConfig: SurveyResultsWidgetConfig
+}):
+ | { success: true; config: SurveyResultsWidgetConfig }
+ | { success: false; fieldErrors: SurveyResultsWidgetFieldErrors } {
+ const parsed = surveyResultsWidgetFormSchema.safeParse({
+ surveyId: input.surveyId,
+ limit: input.limit,
+ dateRange: dateRangeForSelection(input.dateFrom),
+ })
+
+ if (!parsed.success) {
+ return { success: false, fieldErrors: fieldErrorsFromZodError(parsed.error) }
+ }
+
+ return {
+ success: true,
+ config: surveyResultsWidgetConfigSchema.parse({ ...input.baseConfig, ...parsed.data }),
+ }
+}
+
+export function parseSurveyResultsWidgetConfigApiError(
+ error: unknown,
+ config: Record<string, unknown>
+): SurveyResultsWidgetFieldErrors | null {
+ if (!(error instanceof ApiError)) {
+ return null
+ }
+
+ const parsedConfig = surveyResultsWidgetConfigSchema.safeParse(config)
+ if (parsedConfig.success) {
+ return null
+ }
+
+ const parsedForm = surveyResultsWidgetFormSchema.safeParse({
+ surveyId: (config.surveyId as string | null) ?? null,
+ limit: (config.limit as number) ?? surveyResultsConfigDefaults.limit ?? 0,
+ dateRange: (config.dateRange as { date_from?: string | null } | undefined) ?? null,
+ })
+ if (!parsedForm.success) {
+ return fieldErrorsFromZodError(parsedForm.error)
+ }
+
+ return fieldErrorsFromZodError(parsedConfig.error)
+}
diff --git a/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts b/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts
index af59cd4d8fa4..20cb234ad74f 100644
--- a/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts
+++ b/products/dashboards/frontend/widgets/widgetConfigSchemaParity.test.ts
@@ -7,6 +7,7 @@ import {
experimentsWidgetConfigSchema,
logsWidgetConfigSchema,
sessionReplayWidgetConfigSchema,
+ surveyResultsWidgetConfigSchema,
widgetFilterEntrySchema,
} from '../generated/widget-configs.zod'
@@ -17,6 +18,7 @@ const WIDGET_CONFIG_SCHEMAS = {
experiments_list: experimentsWidgetConfigSchema,
experiment_results: experimentResultsWidgetConfigSchema,
logs_list: logsWidgetConfigSchema,
+ survey_results: surveyResultsWidgetConfigSchema,
} as const
type SchemaNode = { _zod?: { def?: ZodDef } }
diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.py
index dab47fbc1b02..c58d1d6ff8ed 100644
--- a/products/surveys/backend/api/survey.py
+++ b/products/surveys/backend/api/survey.py
@@ -2,7 +2,7 @@ import re
import builtins
from contextlib import contextmanager
from datetime import UTC, datetime, timedelta
-from typing import Any, Optional, TypedDict, cast
+from typing import Any, Optional, cast
from urllib.parse import urlparse
from uuid import UUID
@@ -70,16 +70,25 @@ from products.feature_flags.backend.api.feature_flag import (
from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.product_analytics.backend.models.insight import Insight
from products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchive, ensure_question_ids
-from products.surveys.backend.responses import fetch_per_question_stats, fetch_response_rows
+from products.surveys.backend.responses import (
+ SurveyRates,
+ SurveyStats,
+ archived_responses_filter,
+ calculate_rates,
+ fetch_per_question_stats,
+ fetch_response_rows,
+ get_survey_stats,
+ partial_responses_filter,
+ process_survey_results,
+ validate_and_parse_dates,
+)
from products.surveys.backend.summarization import fetch_responses, format_as_markdown, summarize_responses
from products.surveys.backend.translation import generate_survey_translation
from products.surveys.backend.util import (
SurveyEventName,
SurveyEventProperties,
get_archived_response_uuids,
- get_survey_property_bool_expr,
get_survey_property_string_expr,
- get_unique_survey_event_uuids_sql_subquery,
)
from ee.surveys.summaries.headline_summary import generate_survey_headline
@@ -266,31 +275,9 @@ else:
READ_DB_FOR_SURVEYS = "default"
-class EventStats(TypedDict):
- total_count: int
- total_count_only_seen: int
- unique_persons: int
- unique_persons_only_seen: int # unique_persons - dismissed - sent
- first_seen: str | None
- last_seen: str | None
-
-
-class SurveyRates(TypedDict):
- response_rate: float
- dismissal_rate: float
- unique_users_response_rate: float
- unique_users_dismissal_rate: float
-
-
-# Ideally we'd use SurveyEventName here, but enum values are not valid as keys in TypedDicts
-SurveyStats = TypedDict(
- "SurveyStats",
- {
- "survey shown": EventStats,
- "survey dismissed": EventStats,
- "survey sent": EventStats,
- },
-)
+# EventStats / SurveyRates / SurveyStats and the stats-computation helpers now live in
+# products.surveys.backend.responses.stats so the survey widget shares one query path. They are
+# re-imported above and re-exported here for existing importers.
def get_survey_conditions_with_actions(
@@ -2088,7 +2075,11 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.
raise serializers.ValidationError(
{"search": f"Search query must be {MAX_SEARCH_LENGTH} characters or fewer."}
)
+ # Search applies its own exact-first relevance ordering — don't override it.
queryset = self._apply_search(queryset, search)
+ else:
+ # Newest first — stable order for pagination and surfaces recent surveys first in pickers.
+ queryset = queryset.order_by("-created_at")
return queryset
@tracer.start_as_current_span("SurveyViewSet.list")
@@ -2245,20 +2236,10 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.
return Response(SurveySerializer(survey, context=self.get_serializer_context()).data)
def _get_partial_responses_filter(self, base_conditions_sql: builtins.list[str]) -> str:
- unique_uuids_subquery = get_unique_survey_event_uuids_sql_subquery(
- base_conditions_sql=base_conditions_sql,
- )
-
- return f"uuid IN {unique_uuids_subquery}"
+ return partial_responses_filter(base_conditions_sql)
def _get_archived_responses_filter(self, survey_id: str | None = None) -> tuple[str, dict]:
- archived_uuids = get_archived_response_uuids(survey_id, self.team_id)
-
- if not archived_uuids:
- return "", {}
-
- params = {"archived_uuids": list(archived_uuids)}
- return "uuid NOT IN %(archived_uuids)s", params
+ return archived_responses_filter(survey_id, self.team_id)
@action(methods=["GET"], detail=False, required_scopes=["survey:read"])
def responses_count(self, request: request.Request, **kwargs):
@@ -2333,131 +2314,18 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.
def _validate_and_parse_dates(
self, date_from: str | None, date_to: str | None
) -> tuple[datetime | None, datetime | None]:
- """Validate and parse date_from and date_to.
-
- Args:
- date_from: Optional ISO timestamp for start date with timezone info
- date_to: Optional ISO timestamp for end date with timezone info
-
- Returns:
- Tuple of (parsed_date_from, parsed_date_to) in UTC
-
- Raises:
- ValidationError: If dates are invalid or if date_from is after date_to
- """
- parsed_from = None
- parsed_to = None
-
try:
- if date_from:
- parsed_from = datetime.fromisoformat(date_from).astimezone(UTC)
-
- if date_to:
- parsed_to = datetime.fromisoformat(date_to).astimezone(UTC)
-
- if parsed_from and parsed_to and parsed_from > parsed_to:
- raise exceptions.ValidationError("date_from must be before date_to")
-
- return parsed_from, parsed_to
-
- except ValueError:
- raise exceptions.ValidationError(
- "Invalid date format. Please use ISO 8601 format with timezone info (e.g. 2024-01-01T00:00:00Z or 2024-01-01T00:00:00+00:00)"
- )
+ return validate_and_parse_dates(date_from, date_to)
+ except ValueError as exc:
+ raise exceptions.ValidationError(str(exc)) from exc
def _process_survey_results(
self, results: builtins.list[tuple[str, int, int, datetime | None, datetime | None]]
) -> SurveyStats:
- """Process raw survey event results into stats format.
-
- Args:
- results: Raw results from ClickHouse query containing event stats
-
- Returns:
- Dictionary containing processed stats for each event type
- """
- # Initialize stats with zero values for all event types
- stats: SurveyStats = {
- SurveyEventName.SHOWN.value: {
- "total_count": 0,
- "unique_persons": 0,
- "first_seen": None,
- "last_seen": None,
- "unique_persons_only_seen": 0, # Calculated later in _get_survey_stats
- "total_count_only_seen": 0, # Calculated later in _get_survey_stats
- },
- SurveyEventName.DISMISSED.value: {
- "total_count": 0,
- "unique_persons": 0,
- "first_seen": None,
- "last_seen": None,
- # These fields are not applicable/calculated for dismissed/sent
- "unique_persons_only_seen": 0,
- "total_count_only_seen": 0,
- },
- SurveyEventName.SENT.value: {
- "total_count": 0,
- "unique_persons": 0,
- "first_seen": None,
- "last_seen": None,
- # These fields are not applicable/calculated for dismissed/sent
- "unique_persons_only_seen": 0,
- "total_count_only_seen": 0,
- },
- }
-
- # Update stats with actual results
- for event_name, total_count, unique_persons, first_seen, last_seen in results:
- event_stats: EventStats = {
- "total_count": total_count,
- "unique_persons": unique_persons,
- "first_seen": first_seen.isoformat() + "Z" if first_seen else None,
- "last_seen": last_seen.isoformat() + "Z" if last_seen else None,
- # Ensure these are initialized to 0
- "unique_persons_only_seen": 0,
- "total_count_only_seen": 0,
- }
-
- if event_name == SurveyEventName.SHOWN.value:
- stats[SurveyEventName.SHOWN.value] = event_stats
- elif event_name == SurveyEventName.DISMISSED.value:
- stats[SurveyEventName.DISMISSED.value] = event_stats
- elif event_name == SurveyEventName.SENT.value:
- stats[SurveyEventName.SENT.value] = event_stats
-
- # REMOVED calculation block for _only_seen fields from here.
- return stats
+ return process_survey_results(results)
def _calculate_rates(self, stats: SurveyStats) -> SurveyRates:
- """Calculate response and dismissal rates from stats.
-
- Args:
- stats: Dictionary containing event stats
-
- Returns:
- Dictionary containing calculated rates
- """
- rates: SurveyRates = {
- "response_rate": 0.0,
- "dismissal_rate": 0.0,
- "unique_users_response_rate": 0.0,
- "unique_users_dismissal_rate": 0.0,
- }
-
- shown_count = stats[SurveyEventName.SHOWN.value]["total_count"]
- if shown_count > 0:
- sent_count = stats[SurveyEventName.SENT.value]["total_count"]
- dismissed_count = stats[SurveyEventName.DISMISSED.value]["total_count"]
- unique_users_shown_count = stats[SurveyEventName.SHOWN.value]["unique_persons"]
- unique_users_sent_count = stats[SurveyEventName.SENT.value]["unique_persons"]
- unique_users_dismissed_count = stats[SurveyEventName.DISMISSED.value]["unique_persons"]
- rates = {
- "response_rate": round(sent_count / shown_count * 100, 2),
- "dismissal_rate": round(dismissed_count / shown_count * 100, 2),
- "unique_users_response_rate": round(unique_users_sent_count / unique_users_shown_count * 100, 2),
- "unique_users_dismissal_rate": round(unique_users_dismissed_count / unique_users_shown_count * 100, 2),
- }
- return rates
+ return calculate_rates(stats)
def _get_survey_stats(
self, date_from: str | None, date_to: str | None, survey_id: str | None = None, exclude_archived: bool = False
@@ -2473,189 +2341,17 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.
Returns:
Dictionary containing survey statistics and rates
"""
- parsed_from, parsed_to = self._validate_and_parse_dates(date_from, date_to)
-
- # Build query parameters
- params: dict[str, Any] = {"team_id": str(self.team_id)}
- date_filter = ""
- survey_id_expr = get_survey_property_string_expr(SurveyEventProperties.SURVEY_ID)
- survey_partially_completed_expr = get_survey_property_bool_expr(
- SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED
- )
- effective_from = parsed_from
- effective_to = parsed_to
-
- if survey_id:
- survey_dates = (
- Survey.objects.filter(team_id=self.team_id, id=survey_id)
- .values("start_date", "created_at", "end_date")
- .first()
- )
-
- if survey_dates:
- survey_start = survey_dates["start_date"] or survey_dates["created_at"]
- survey_end = survey_dates["end_date"]
-
- if survey_start:
- effective_from = max(filter(None, [parsed_from, survey_start]), default=survey_start)
-
- if survey_end:
- effective_to = min(filter(None, [parsed_to, survey_end]), default=survey_end)
-
- if effective_from:
- date_filter += " AND timestamp >= %(date_from)s"
- params["date_from"] = effective_from
- if effective_to:
- date_filter += " AND timestamp <= %(date_to)s"
- params["date_to"] = effective_to
-
- # Add archive filter if needed
- archive_filter = ""
- if survey_id and exclude_archived:
- archive_filter_sql, archive_params = self._get_archived_responses_filter(survey_id)
- if archive_filter_sql:
- archive_filter = f"AND {archive_filter_sql}"
- params.update(archive_params)
-
- # Add survey filter if specific survey
- survey_filter = ""
- if survey_id:
- survey_filter = f"AND {survey_id_expr} = %(survey_id)s"
- params["survey_id"] = str(survey_id)
- else:
- # For global stats, only include non-archived surveys
- active_survey_ids = list(
- Survey.objects.filter(team_id=self.team_id, archived=False).values_list("id", flat=True)
- )
- if not active_survey_ids:
- return {
- "stats": {},
- "rates": {
- "response_rate": 0.0,
- "dismissal_rate": 0.0,
- "unique_users_response_rate": 0.0,
- "unique_users_dismissal_rate": 0.0,
- },
- }
- survey_filter = f"AND {survey_id_expr} IN %(survey_ids)s"
- params["survey_ids"] = [str(id) for id in active_survey_ids]
-
- partial_responses_base_conditions = ["team_id = %(team_id)s"]
- if effective_from:
- partial_responses_base_conditions.append("timestamp >= %(date_from)s")
- if effective_to:
- partial_responses_base_conditions.append("timestamp <= %(date_to)s")
-
- partial_responses_filter = self._get_partial_responses_filter(
- base_conditions_sql=partial_responses_base_conditions,
- )
-
- # Query 1: Base Stats (Similar to original query)
- base_stats_query = f"""
- SELECT
- event as event_name,
- count() as total_count,
- count(DISTINCT person_id) as unique_persons,
- if(count() > 0, min(timestamp), null) as first_seen,
- if(count() > 0, max(timestamp), null) as last_seen
- FROM events
- WHERE team_id = %(team_id)s
- AND event IN (%(shown)s, %(dismissed)s, %(sent)s)
- {survey_filter}
- {date_filter}
- {archive_filter}
- AND (
- event != %(dismissed)s
- OR
- COALESCE({survey_partially_completed_expr}, False) = False
- )
- AND (
- event != %(sent)s
- OR
- {partial_responses_filter}
- )
- GROUP BY event
- """
- query_params = {
- **params,
- "shown": SurveyEventName.SHOWN.value,
- "dismissed": SurveyEventName.DISMISSED.value,
- "sent": SurveyEventName.SENT.value,
- }
- tag_queries(product=ProductKey.SURVEYS, feature=Feature.QUERY)
- results_base = sync_execute(base_stats_query, query_params)
-
- # Query 2: Count of unique persons who both dismissed AND sent
- dismissed_and_sent_query = f"""
- SELECT count()
- FROM (
- SELECT person_id
- FROM events
- WHERE team_id = %(team_id)s
- AND event IN (%(dismissed)s, %(sent)s)
- {survey_filter}
- {date_filter}
- {archive_filter}
- AND (
- event != %(dismissed)s
- OR
- COALESCE({survey_partially_completed_expr}, False) = False
- )
- GROUP BY person_id
- HAVING sum(if(event = %(dismissed)s, 1, 0)) > 0
- AND sum(if(event = %(sent)s, 1, 0)) > 0
- ) AS PersonsWithBothEvents
- """
- dismissed_and_sent_count_result = sync_execute(dismissed_and_sent_query, query_params)
- dismissed_and_sent_count = dismissed_and_sent_count_result[0][0] if dismissed_and_sent_count_result else 0
-
- # Process initial stats
- stats = self._process_survey_results(results_base)
-
- # Adjust dismissed unique count
- if SurveyEventName.DISMISSED.value in stats:
- stats[SurveyEventName.DISMISSED.value]["unique_persons"] -= dismissed_and_sent_count
- # Ensure it doesn't go below zero, although logically it shouldn't
- stats[SurveyEventName.DISMISSED.value]["unique_persons"] = max(
- 0, stats[SurveyEventName.DISMISSED.value]["unique_persons"]
- )
-
- # Recalculate derived 'only_seen' counts based on final counts
- if SurveyEventName.SHOWN.value in stats:
- # Get final counts, defaulting to 0 if a category has no events
- unique_shown = stats.get(SurveyEventName.SHOWN.value, {}).get("unique_persons", 0)
- unique_dismissed = stats.get(SurveyEventName.DISMISSED.value, {}).get(
- "unique_persons", 0
- ) # Use adjusted count
- unique_sent = stats.get(SurveyEventName.SENT.value, {}).get("unique_persons", 0)
-
- total_shown = stats.get(SurveyEventName.SHOWN.value, {}).get("total_count", 0)
- total_dismissed = stats.get(SurveyEventName.DISMISSED.value, {}).get("total_count", 0)
- total_sent = stats.get(SurveyEventName.SENT.value, {}).get("total_count", 0)
-
- # Calculate unique persons who only saw the survey
- stats[SurveyEventName.SHOWN.value]["unique_persons_only_seen"] = (
- unique_shown - unique_dismissed - unique_sent
- )
- stats[SurveyEventName.SHOWN.value]["unique_persons_only_seen"] = max(
- 0, stats[SurveyEventName.SHOWN.value]["unique_persons_only_seen"]
- )
-
- # Calculate total count for those who only saw the survey
- stats[SurveyEventName.SHOWN.value]["total_count_only_seen"] = total_shown - total_dismissed - total_sent
- stats[SurveyEventName.SHOWN.value]["total_count_only_seen"] = max(
- 0, stats[SurveyEventName.SHOWN.value]["total_count_only_seen"]
+ # Shared helper raises ValueError for bad dates; surface it as a REST 400 here.
+ try:
+ return get_survey_stats(
+ team_id=self.team_id,
+ date_from=date_from,
+ date_to=date_to,
+ survey_id=survey_id,
+ exclude_archived=exclude_archived,
)
-
- # Calculate rates using the adjusted stats
- rates = self._calculate_rates(stats)
-
- response_data = {
- "stats": stats,
- "rates": rates,
- }
-
- return response_data
+ except ValueError as exc:
+ raise exceptions.ValidationError(str(exc)) from exc
@extend_schema(
parameters=[
diff --git a/products/surveys/backend/responses/__init__.py b/products/surveys/backend/responses/__init__.py
index 3d18d9212179..dedd79d03c81 100644
--- a/products/surveys/backend/responses/__init__.py
+++ b/products/surveys/backend/responses/__init__.py
@@ -4,11 +4,31 @@ from products.surveys.backend.responses.fetch_rows import (
resolve_question_metadata,
)
from products.surveys.backend.responses.per_question_stats import PerQuestionStats, fetch_per_question_stats
+from products.surveys.backend.responses.stats import (
+ EventStats,
+ SurveyRates,
+ SurveyStats,
+ archived_responses_filter,
+ calculate_rates,
+ get_survey_stats,
+ partial_responses_filter,
+ process_survey_results,
+ validate_and_parse_dates,
+)
__all__ = [
+ "EventStats",
"PerQuestionStats",
+ "SurveyRates",
"SurveyResponseRow",
+ "SurveyStats",
+ "archived_responses_filter",
+ "calculate_rates",
"fetch_per_question_stats",
"fetch_response_rows",
+ "get_survey_stats",
+ "partial_responses_filter",
+ "process_survey_results",
"resolve_question_metadata",
+ "validate_and_parse_dates",
]
diff --git a/products/surveys/backend/responses/stats.py b/products/surveys/backend/responses/stats.py
new file mode 100644
index 000000000000..59c7c6878bf0
--- /dev/null
+++ b/products/surveys/backend/responses/stats.py
@@ -0,0 +1,372 @@
+"""Shared survey summary-stats computation.
+
+Single source of truth for the "survey performance" numbers (shown / dismissed / sent
+counts, unique persons, and derived response/dismissal rates). Both the surveys REST
+viewset and the dashboard survey widget call `get_survey_stats` so there is exactly one
+query path for these stats.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from typing import Any, TypedDict
+
+from posthog.schema import ProductKey
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, tag_queries
+
+from products.surveys.backend.models import Survey
+from products.surveys.backend.util import (
+ SurveyEventName,
+ SurveyEventProperties,
+ get_archived_response_uuids,
+ get_survey_property_bool_expr,
+ get_survey_property_string_expr,
+ get_unique_survey_event_uuids_sql_subquery,
+)
+
+
+class EventStats(TypedDict):
+ total_count: int
+ total_count_only_seen: int
+ unique_persons: int
+ unique_persons_only_seen: int # unique_persons - dismissed - sent
+ first_seen: str | None
+ last_seen: str | None
+
+
+class SurveyRates(TypedDict):
+ response_rate: float
+ dismissal_rate: float
+ unique_users_response_rate: float
+ unique_users_dismissal_rate: float
+
+
+# Ideally we'd use SurveyEventName here, but enum values are not valid as keys in TypedDicts
+SurveyStats = TypedDict(
+ "SurveyStats",
+ {
+ "survey shown": EventStats,
+ "survey dismissed": EventStats,
+ "survey sent": EventStats,
+ },
+)
+
+
+class _InvertedDateRangeError(ValueError):
+ """date_from is after date_to — kept distinct so its message survives the parse-error rewrite."""
+
+
+def validate_and_parse_dates(date_from: str | None, date_to: str | None) -> tuple[datetime | None, datetime | None]:
+ """Parse ISO timestamps to UTC datetimes, raising on malformed input or inverted range.
+
+ Raises ``ValueError`` on parse failures and inverted ranges so callers in non-REST contexts
+ (e.g. the dashboard widget) receive a standard Python exception. The REST viewset re-raises
+ it as ``rest_framework.exceptions.ValidationError``.
+ """
+ parsed_from = None
+ parsed_to = None
+
+ try:
+ if date_from:
+ parsed_from = datetime.fromisoformat(date_from).astimezone(UTC)
+
+ if date_to:
+ parsed_to = datetime.fromisoformat(date_to).astimezone(UTC)
+
+ if parsed_from and parsed_to and parsed_from > parsed_to:
+ raise _InvertedDateRangeError("date_from must be before date_to")
+
+ return parsed_from, parsed_to
+
+ except _InvertedDateRangeError:
+ raise
+ except ValueError as exc:
+ raise ValueError(
+ "Invalid date format. Please use ISO 8601 format with timezone info (e.g. 2024-01-01T00:00:00Z or 2024-01-01T00:00:00+00:00)"
+ ) from exc
+
+
+def partial_responses_filter(base_conditions_sql: list[str]) -> str:
+ unique_uuids_subquery = get_unique_survey_event_uuids_sql_subquery(
+ base_conditions_sql=base_conditions_sql,
+ )
+
+ return f"uuid IN {unique_uuids_subquery}"
+
+
+def archived_responses_filter(survey_id: str | None, team_id: int) -> tuple[str, dict]:
+ archived_uuids = get_archived_response_uuids(survey_id, team_id)
+
+ if not archived_uuids:
+ return "", {}
+
+ params = {"archived_uuids": list(archived_uuids)}
+ return "uuid NOT IN %(archived_uuids)s", params
+
+
+def process_survey_results(
+ results: list[tuple[str, int, int, datetime | None, datetime | None]],
+) -> SurveyStats:
+ """Process raw survey event results into stats format."""
+ # Initialize stats with zero values for all event types
+ stats: SurveyStats = {
+ SurveyEventName.SHOWN.value: {
+ "total_count": 0,
+ "unique_persons": 0,
+ "first_seen": None,
+ "last_seen": None,
+ "unique_persons_only_seen": 0, # Calculated later in get_survey_stats
+ "total_count_only_seen": 0, # Calculated later in get_survey_stats
+ },
+ SurveyEventName.DISMISSED.value: {
+ "total_count": 0,
+ "unique_persons": 0,
+ "first_seen": None,
+ "last_seen": None,
+ # These fields are not applicable/calculated for dismissed/sent
+ "unique_persons_only_seen": 0,
+ "total_count_only_seen": 0,
+ },
+ SurveyEventName.SENT.value: {
+ "total_count": 0,
+ "unique_persons": 0,
+ "first_seen": None,
+ "last_seen": None,
+ # These fields are not applicable/calculated for dismissed/sent
+ "unique_persons_only_seen": 0,
+ "total_count_only_seen": 0,
+ },
+ }
+
+ # Update stats with actual results
+ for event_name, total_count, unique_persons, first_seen, last_seen in results:
+ event_stats: EventStats = {
+ "total_count": total_count,
+ "unique_persons": unique_persons,
+ "first_seen": first_seen.isoformat() + "Z" if first_seen else None,
+ "last_seen": last_seen.isoformat() + "Z" if last_seen else None,
+ # Ensure these are initialized to 0
+ "unique_persons_only_seen": 0,
+ "total_count_only_seen": 0,
+ }
+
+ if event_name == SurveyEventName.SHOWN.value:
+ stats[SurveyEventName.SHOWN.value] = event_stats
+ elif event_name == SurveyEventName.DISMISSED.value:
+ stats[SurveyEventName.DISMISSED.value] = event_stats
+ elif event_name == SurveyEventName.SENT.value:
+ stats[SurveyEventName.SENT.value] = event_stats
+
+ return stats
+
+
+def calculate_rates(stats: SurveyStats) -> SurveyRates:
+ """Calculate response and dismissal rates from stats."""
+ rates: SurveyRates = {
+ "response_rate": 0.0,
+ "dismissal_rate": 0.0,
+ "unique_users_response_rate": 0.0,
+ "unique_users_dismissal_rate": 0.0,
+ }
+
+ shown_count = stats[SurveyEventName.SHOWN.value]["total_count"]
+ if shown_count > 0:
+ sent_count = stats[SurveyEventName.SENT.value]["total_count"]
+ dismissed_count = stats[SurveyEventName.DISMISSED.value]["total_count"]
+ unique_users_shown_count = stats[SurveyEventName.SHOWN.value]["unique_persons"]
+ unique_users_sent_count = stats[SurveyEventName.SENT.value]["unique_persons"]
+ unique_users_dismissed_count = stats[SurveyEventName.DISMISSED.value]["unique_persons"]
+ rates = {
+ "response_rate": round(sent_count / shown_count * 100, 2),
+ "dismissal_rate": round(dismissed_count / shown_count * 100, 2),
+ "unique_users_response_rate": round(unique_users_sent_count / unique_users_shown_count * 100, 2),
+ "unique_users_dismissal_rate": round(unique_users_dismissed_count / unique_users_shown_count * 100, 2),
+ }
+ return rates
+
+
+def get_survey_stats(
+ *,
+ team_id: int,
+ date_from: str | None,
+ date_to: str | None,
+ survey_id: str | None = None,
+ exclude_archived: bool = False,
+) -> dict[str, Any]:
+ """Get survey statistics from ClickHouse.
+
+ When `survey_id` is None, computes stats across all non-archived surveys for the team.
+ `date_from`/`date_to` are optional ISO timestamps; for a single survey they are clamped
+ to the survey's own start/end window.
+ """
+ parsed_from, parsed_to = validate_and_parse_dates(date_from, date_to)
+
+ params: dict[str, Any] = {"team_id": str(team_id)}
+ date_filter = ""
+ survey_id_expr = get_survey_property_string_expr(SurveyEventProperties.SURVEY_ID)
+ survey_partially_completed_expr = get_survey_property_bool_expr(SurveyEventProperties.SURVEY_PARTIALLY_COMPLETED)
+ effective_from = parsed_from
+ effective_to = parsed_to
+
+ if survey_id:
+ survey_dates = (
+ Survey.objects.filter(team_id=team_id, id=survey_id).values("start_date", "created_at", "end_date").first()
+ )
+
+ if survey_dates:
+ survey_start = survey_dates["start_date"] or survey_dates["created_at"]
+ survey_end = survey_dates["end_date"]
+
+ if survey_start:
+ effective_from = max(filter(None, [parsed_from, survey_start]), default=survey_start)
+
+ if survey_end:
+ effective_to = min(filter(None, [parsed_to, survey_end]), default=survey_end)
+
+ if effective_from:
+ date_filter += " AND timestamp >= %(date_from)s"
+ params["date_from"] = effective_from
+ if effective_to:
+ date_filter += " AND timestamp <= %(date_to)s"
+ params["date_to"] = effective_to
+
+ # Add archive filter if needed
+ archive_filter = ""
+ if survey_id and exclude_archived:
+ archive_filter_sql, archive_params = archived_responses_filter(survey_id, team_id)
+ if archive_filter_sql:
+ archive_filter = f"AND {archive_filter_sql}"
+ params.update(archive_params)
+
+ # Add survey filter if specific survey
+ survey_filter = ""
+ if survey_id:
+ survey_filter = f"AND {survey_id_expr} = %(survey_id)s"
+ params["survey_id"] = str(survey_id)
+ else:
+ # For global stats, only include non-archived surveys
+ active_survey_ids = list(Survey.objects.filter(team_id=team_id, archived=False).values_list("id", flat=True))
+ if not active_survey_ids:
+ return {
+ "stats": {},
+ "rates": {
+ "response_rate": 0.0,
+ "dismissal_rate": 0.0,
+ "unique_users_response_rate": 0.0,
+ "unique_users_dismissal_rate": 0.0,
+ },
+ }
+ survey_filter = f"AND {survey_id_expr} IN %(survey_ids)s"
+ params["survey_ids"] = [str(id) for id in active_survey_ids]
+
+ partial_responses_base_conditions = ["team_id = %(team_id)s"]
+ if effective_from:
+ partial_responses_base_conditions.append("timestamp >= %(date_from)s")
+ if effective_to:
+ partial_responses_base_conditions.append("timestamp <= %(date_to)s")
+
+ partial_filter = partial_responses_filter(
+ base_conditions_sql=partial_responses_base_conditions,
+ )
+
+ # Query 1: Base Stats
+ base_stats_query = f"""
+ SELECT
+ event as event_name,
+ count() as total_count,
+ count(DISTINCT person_id) as unique_persons,
+ if(count() > 0, min(timestamp), null) as first_seen,
+ if(count() > 0, max(timestamp), null) as last_seen
+ FROM events
+ WHERE team_id = %(team_id)s
+ AND event IN (%(shown)s, %(dismissed)s, %(sent)s)
+ {survey_filter}
+ {date_filter}
+ {archive_filter}
+ AND (
+ event != %(dismissed)s
+ OR
+ COALESCE({survey_partially_completed_expr}, False) = False
+ )
+ AND (
+ event != %(sent)s
+ OR
+ {partial_filter}
+ )
+ GROUP BY event
+ """
+ query_params = {
+ **params,
+ "shown": SurveyEventName.SHOWN.value,
+ "dismissed": SurveyEventName.DISMISSED.value,
+ "sent": SurveyEventName.SENT.value,
+ }
+ tag_queries(product=ProductKey.SURVEYS, feature=Feature.QUERY)
+ results_base = sync_execute(base_stats_query, query_params)
+
+ # Query 2: Count of unique persons who both dismissed AND sent
+ dismissed_and_sent_query = f"""
+ SELECT count()
+ FROM (
+ SELECT person_id
+ FROM events
+ WHERE team_id = %(team_id)s
+ AND event IN (%(dismissed)s, %(sent)s)
+ {survey_filter}
+ {date_filter}
+ {archive_filter}
+ AND (
+ event != %(dismissed)s
+ OR
+ COALESCE({survey_partially_completed_expr}, False) = False
+ )
+ GROUP BY person_id
+ HAVING sum(if(event = %(dismissed)s, 1, 0)) > 0
+ AND sum(if(event = %(sent)s, 1, 0)) > 0
+ ) AS PersonsWithBothEvents
+ """
+ dismissed_and_sent_count_result = sync_execute(dismissed_and_sent_query, query_params)
+ dismissed_and_sent_count = dismissed_and_sent_count_result[0][0] if dismissed_and_sent_count_result else 0
+
+ # Process initial stats
+ stats = process_survey_results(results_base)
+
+ # Adjust dismissed unique count
+ if SurveyEventName.DISMISSED.value in stats:
+ stats[SurveyEventName.DISMISSED.value]["unique_persons"] -= dismissed_and_sent_count
+ # Ensure it doesn't go below zero, although logically it shouldn't
+ stats[SurveyEventName.DISMISSED.value]["unique_persons"] = max(
+ 0, stats[SurveyEventName.DISMISSED.value]["unique_persons"]
+ )
+
+ # Recalculate derived 'only_seen' counts based on final counts
+ if SurveyEventName.SHOWN.value in stats:
+ unique_shown = stats.get(SurveyEventName.SHOWN.value, {}).get("unique_persons", 0)
+ unique_dismissed = stats.get(SurveyEventName.DISMISSED.value, {}).get("unique_persons", 0) # Use adjusted count
+ unique_sent = stats.get(SurveyEventName.SENT.value, {}).get("unique_persons", 0)
+
+ total_shown = stats.get(SurveyEventName.SHOWN.value, {}).get("total_count", 0)
+ total_dismissed = stats.get(SurveyEventName.DISMISSED.value, {}).get("total_count", 0)
+ total_sent = stats.get(SurveyEventName.SENT.value, {}).get("total_count", 0)
+
+ # Calculate unique persons who only saw the survey
+ stats[SurveyEventName.SHOWN.value]["unique_persons_only_seen"] = unique_shown - unique_dismissed - unique_sent
+ stats[SurveyEventName.SHOWN.value]["unique_persons_only_seen"] = max(
+ 0, stats[SurveyEventName.SHOWN.value]["unique_persons_only_seen"]
+ )
+
+ # Calculate total count for those who only saw the survey
+ stats[SurveyEventName.SHOWN.value]["total_count_only_seen"] = total_shown - total_dismissed - total_sent
+ stats[SurveyEventName.SHOWN.value]["total_count_only_seen"] = max(
+ 0, stats[SurveyEventName.SHOWN.value]["total_count_only_seen"]
+ )
+
+ # Calculate rates using the adjusted stats
+ rates = calculate_rates(stats)
+
+ return {
+ "stats": stats,
+ "rates": rates,
+ }
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 18428b8617f6..49e769dfdb04 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4444,6 +4444,44 @@ export namespace Schemas {
config: ExperimentResultsWidgetConfig;
}
+ export type SurveyResultsWidgetAddRequestOpenApiWidgetType = typeof SurveyResultsWidgetAddRequestOpenApiWidgetType[keyof typeof SurveyResultsWidgetAddRequestOpenApiWidgetType];
+
+
+ export const SurveyResultsWidgetAddRequestOpenApiWidgetType = {
+ SurveyResults: 'survey_results',
+ } as const;
+
+ export interface SurveyResultsWidgetConfig {
+ /** Null or omitted means all time (the survey's full lifetime). */
+ dateRange?: WidgetDateRange | null;
+ /** Survey to show performance stats and recent responses for. Null until the user picks one. */
+ surveyId?: string | null;
+ /**
+ * Maximum number of recent responses to return.
+ * @minimum 1
+ * @maximum 25
+ */
+ limit?: number;
+ }
+
+ export interface SurveyResultsWidgetAddRequestOpenApi {
+ /**
+ * 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: SurveyResultsWidgetAddRequestOpenApiWidgetType;
+ /** Configuration for the survey results widget. */
+ config: SurveyResultsWidgetConfig;
+ }
+
export type LogsListWidgetAddRequestOpenApiWidgetType = typeof LogsListWidgetAddRequestOpenApiWidgetType[keyof typeof LogsListWidgetAddRequestOpenApiWidgetType];
@@ -4525,14 +4563,14 @@ export namespace Schemas {
config: LogsListWidgetConfig;
}
- export type AddDashboardWidgetRequest = ActivityEventsListWidgetAddRequestOpenApi | ErrorTrackingListWidgetAddRequestOpenApi | SessionReplayListWidgetAddRequestOpenApi | ExperimentsListWidgetAddRequestOpenApi | ExperimentResultsWidgetAddRequestOpenApi | LogsListWidgetAddRequestOpenApi;
+ export type AddDashboardWidgetRequest = ActivityEventsListWidgetAddRequestOpenApi | ErrorTrackingListWidgetAddRequestOpenApi | SessionReplayListWidgetAddRequestOpenApi | ExperimentsListWidgetAddRequestOpenApi | ExperimentResultsWidgetAddRequestOpenApi | SurveyResultsWidgetAddRequestOpenApi | LogsListWidgetAddRequestOpenApi;
/**
* 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, experiment_results, experiments_list, logs_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, logs_list, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).
* @minItems 1
* @maxItems 10
*/
@@ -7565,7 +7603,7 @@ export namespace Schemas {
team: number;
}
- export type DashboardWidgetConfig = ActivityEventsListWidgetConfig | ErrorTrackingListWidgetConfig | SessionReplayListWidgetConfig | ExperimentsListWidgetConfig | ExperimentResultsWidgetConfig | LogsListWidgetConfig;
+ export type DashboardWidgetConfig = ActivityEventsListWidgetConfig | ErrorTrackingListWidgetConfig | SessionReplayListWidgetConfig | ExperimentsListWidgetConfig | ExperimentResultsWidgetConfig | SurveyResultsWidgetConfig | LogsListWidgetConfig;
export interface DashboardWidget {
readonly id: string;
@@ -14543,6 +14581,7 @@ export namespace Schemas {
* * `experiments_list` - experiments_list
* * `logs_list` - logs_list
* * `session_replay_list` - session_replay_list
+ * * `survey_results` - survey_results
*/
export type DashboardPatchWidgetOpenApiWidgetTypeEnum = typeof DashboardPatchWidgetOpenApiWidgetTypeEnum[keyof typeof DashboardPatchWidgetOpenApiWidgetTypeEnum];
@@ -14554,6 +14593,7 @@ export namespace Schemas {
ExperimentsList: 'experiments_list',
LogsList: 'logs_list',
SessionReplayList: 'session_replay_list',
+ SurveyResults: 'survey_results',
} as const;
export interface DashboardPatchWidgetOpenApi {
@@ -14566,7 +14606,8 @@ export namespace Schemas {
* * `experiment_results` - experiment_results
* * `experiments_list` - experiments_list
* * `logs_list` - logs_list
- * * `session_replay_list` - session_replay_list */
+ * * `session_replay_list` - session_replay_list
+ * * `survey_results` - survey_results */
widget_type?: DashboardPatchWidgetOpenApiWidgetTypeEnum;
/** Widget-specific configuration. Shape depends on the tile's widget_type. */
config?: DashboardWidgetConfig;
@@ -42374,7 +42415,30 @@ export namespace Schemas {
config?: SessionReplayListWidgetConfig;
}
- export type UpdateDashboardWidgetRequest = ActivityEventsListWidgetUpdateRequestOpenApi | ErrorTrackingListWidgetUpdateRequestOpenApi | SessionReplayListWidgetUpdateRequestOpenApi | ExperimentsListWidgetUpdateRequestOpenApi | ExperimentResultsWidgetUpdateRequestOpenApi | LogsListWidgetUpdateRequestOpenApi;
+ export type SurveyResultsWidgetUpdateRequestOpenApiWidgetType = typeof SurveyResultsWidgetUpdateRequestOpenApiWidgetType[keyof typeof SurveyResultsWidgetUpdateRequestOpenApiWidgetType];
+
+
+ export const SurveyResultsWidgetUpdateRequestOpenApiWidgetType = {
+ SurveyResults: 'survey_results',
+ } as const;
+
+ export interface SurveyResultsWidgetUpdateRequestOpenApi {
+ /** ID of the widget tile to update. Use dashboard-get to look up widget tile IDs. */
+ tile_id: number;
+ /**
+ * New display name for the widget. Empty string or null clears it; omit to leave unchanged.
+ * @maxLength 400
+ * @nullable
+ */
+ name?: string | null;
+ /** New markdown description for the widget. Omit to leave unchanged. */
+ description?: string;
+ widget_type: SurveyResultsWidgetUpdateRequestOpenApiWidgetType;
+ /** New configuration for the survey results widget. Omit to leave unchanged. */
+ config?: SurveyResultsWidgetConfig;
+ }
+
+ export type UpdateDashboardWidgetRequest = ActivityEventsListWidgetUpdateRequestOpenApi | ErrorTrackingListWidgetUpdateRequestOpenApi | SessionReplayListWidgetUpdateRequestOpenApi | ExperimentsListWidgetUpdateRequestOpenApi | ExperimentResultsWidgetUpdateRequestOpenApi | SurveyResultsWidgetUpdateRequestOpenApi | LogsListWidgetUpdateRequestOpenApi;
/**
* OpenAPI-only batch-update schema with widget_type-discriminated config shapes for agents.
@@ -51567,6 +51631,35 @@ export namespace Schemas {
offset: number;
}
+ export type SurveyResultsWidgetCatalogEntryOpenApiWidgetType = typeof SurveyResultsWidgetCatalogEntryOpenApiWidgetType[keyof typeof SurveyResultsWidgetCatalogEntryOpenApiWidgetType];
+
+
+ export const SurveyResultsWidgetCatalogEntryOpenApiWidgetType = {
+ SurveyResults: 'survey_results',
+ } as const;
+
+ export interface SurveyResultsWidgetCatalogEntryOpenApi {
+ widget_type: SurveyResultsWidgetCatalogEntryOpenApiWidgetType;
+ 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: SurveyResultsWidgetConfig;
+ /** @nullable */
+ required_product_access?: string | null;
+ }
+
+ /**
+ * * `survey_results` - survey_results
+ */
+ export type SurveyResultsWidgetTypeEnum = typeof SurveyResultsWidgetTypeEnum[keyof typeof SurveyResultsWidgetTypeEnum];
+
+
+ export const SurveyResultsWidgetTypeEnum = {
+ SurveyResults: 'survey_results',
+ } as const;
+
export interface SurveySerializerCreateUpdateOnly {
readonly id: string;
/** @maxLength 400 */
@@ -53907,7 +54000,7 @@ export namespace Schemas {
is_organization_first_user: boolean;
}
- export type WidgetCatalogEntry = ActivityEventsListWidgetCatalogEntryOpenApi | ErrorTrackingListWidgetCatalogEntryOpenApi | SessionReplayListWidgetCatalogEntryOpenApi | ExperimentsListWidgetCatalogEntryOpenApi | ExperimentResultsWidgetCatalogEntryOpenApi | LogsListWidgetCatalogEntryOpenApi;
+ export type WidgetCatalogEntry = ActivityEventsListWidgetCatalogEntryOpenApi | ErrorTrackingListWidgetCatalogEntryOpenApi | SessionReplayListWidgetCatalogEntryOpenApi | ExperimentsListWidgetCatalogEntryOpenApi | ExperimentResultsWidgetCatalogEntryOpenApi | SurveyResultsWidgetCatalogEntryOpenApi | LogsListWidgetCatalogEntryOpenApi;
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.ts
index 50afdcdf5566..34403deb5fdc 100644
--- a/services/mcp/src/generated/dashboards/api.ts
+++ b/services/mcp/src/generated/dashboards/api.ts
@@ -141,12 +141,15 @@ export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourLimitMax
export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderByDefault = `created_at`
export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourOrderDirectionDefault = `DESC`
export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneFourStatusDefault = `all`
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitDefault = 50
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitMax = 100
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitDefault = 10
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitMax = 25
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixOrderByDefault = `latest`
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixWrapLinesDefault = false
-export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixTimezoneDefault = `UTC`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitDefault = 50
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitMax = 100
+
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenOrderByDefault = `latest`
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenWrapLinesDefault = false
+export const dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenTimezoneDefault = `UTC`
export const dashboardsPartialUpdateBodyTilesItemWidgetOneNameMax = 400
export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
@@ -208,13 +211,14 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
'experiments_list',
'logs_list',
'session_replay_list',
+ 'survey_results',
])
.describe(
- '* `activity_events_list` - activity_events_list\n* `error_tracking_list` - error_tracking_list\n* `experiment_results` - experiment_results\n* `experiments_list` - experiments_list\n* `logs_list` - logs_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* `logs_list` - logs_list\n* `session_replay_list` - session_replay_list\n* `survey_results` - survey_results'
)
.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* `experiment_results` - experiment_results\n* `experiments_list` - experiments_list\n* `logs_list` - logs_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* `logs_list` - logs_list\n* `session_replay_list` - session_replay_list\n* `survey_results` - survey_results'
),
config: zod
.union([
@@ -613,7 +617,14 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe("Null or omitted means all time (the survey's full lifetime)."),
+ surveyId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Survey to show performance stats and recent responses for. Null until the user picks one.'
+ ),
limit: zod
.number()
.min(1)
@@ -621,11 +632,44 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
.default(
dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixLimitDefault
)
+ .describe('Maximum number of recent responses to return.'),
+ }),
+ zod.object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitMax)
+ .default(
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenLimitDefault
+ )
.describe('Maximum number of log lines to return.'),
orderBy: zod
.enum(['latest', 'earliest'])
.default(
- dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixOrderByDefault
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenOrderByDefault
)
.describe('Sort by newest (latest) or oldest (earliest) first.'),
severityLevels: zod
@@ -641,7 +685,7 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
wrapLines: zod
.boolean()
.default(
- dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixWrapLinesDefault
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenWrapLinesDefault
)
.describe(
'Wrap long log lines instead of truncating them to a single row.'
@@ -649,7 +693,7 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
timezone: zod
.enum(['UTC', 'local'])
.default(
- dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSixTimezoneDefault
+ dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneSevenTimezoneDefault
)
.describe(
"Render log timestamps in UTC or in each viewer's local timezone."
@@ -1030,12 +1074,17 @@ export const dashboardsWidgetsBatchCreateBodyWidgetsItemFiveNameMax = 400
export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixNameMax = 400
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitDefault = 50
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitMax = 100
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitDefault = 10
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitMax = 25
+
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenNameMax = 400
+
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneLimitDefault = 50
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneLimitMax = 100
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneOrderByDefault = `latest`
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneWrapLinesDefault = false
-export const dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneTimezoneDefault = `UTC`
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneOrderByDefault = `latest`
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneWrapLinesDefault = false
+export const dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneTimezoneDefault = `UTC`
export const dashboardsWidgetsBatchCreateBodyWidgetsMax = 10
export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
@@ -1748,7 +1797,7 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
.boolean()
.optional()
.describe('Whether to show the description on the dashboard tile.'),
- widget_type: zod.enum(['logs_list']),
+ widget_type: zod.enum(['survey_results']),
config: zod
.object({
dateRange: zod
@@ -1773,16 +1822,115 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe("Null or omitted means all time (the survey's full lifetime)."),
+ surveyId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Survey to show performance stats and recent responses for. Null until the user picks one.'
+ ),
limit: zod
.number()
.min(1)
.max(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitMax)
.default(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneLimitDefault)
+ .describe('Maximum number of recent responses to return.'),
+ })
+ .describe('Configuration for the survey results widget.'),
+ }),
+ zod.object({
+ name: zod
+ .string()
+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenNameMax)
+ .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(['logs_list']),
+ config: zod
+ .object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneLimitMax)
+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneLimitDefault)
.describe('Maximum number of log lines to return.'),
orderBy: zod
.enum(['latest', 'earliest'])
- .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneOrderByDefault)
+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneOrderByDefault)
.describe('Sort by newest (latest) or oldest (earliest) first.'),
severityLevels: zod
.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal']))
@@ -1794,11 +1942,11 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
.describe('Only show logs from these services. Empty shows all services.'),
wrapLines: zod
.boolean()
- .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneWrapLinesDefault)
+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneWrapLinesDefault)
.describe('Wrap long log lines instead of truncating them to a single row.'),
timezone: zod
.enum(['UTC', 'local'])
- .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSixConfigOneTimezoneDefault)
+ .default(dashboardsWidgetsBatchCreateBodyWidgetsItemSevenConfigOneTimezoneDefault)
.describe("Render log timestamps in UTC or in each viewer's local timezone."),
savedViewId: zod
.union([zod.string(), zod.null()])
@@ -1814,7 +1962,7 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
.min(1)
.max(dashboardsWidgetsBatchCreateBodyWidgetsMax)
.describe(
- 'Widget tiles to add atomically. Supported widget_type values: activity_events_list, error_tracking_list, experiment_results, experiments_list, logs_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, logs_list, session_replay_list, survey_results. 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.')
@@ -1873,12 +2021,17 @@ export const dashboardsUpdateWidgetsBatchBodyWidgetsItemFiveNameMax = 400
export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixNameMax = 400
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitDefault = 50
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitMax = 100
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitDefault = 10
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitMax = 25
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneOrderByDefault = `latest`
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneWrapLinesDefault = false
-export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneTimezoneDefault = `UTC`
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenNameMax = 400
+
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneLimitDefault = 50
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneLimitMax = 100
+
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneOrderByDefault = `latest`
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneWrapLinesDefault = false
+export const dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneTimezoneDefault = `UTC`
export const dashboardsUpdateWidgetsBatchBodyWidgetsMax = 10
export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
@@ -2344,7 +2497,7 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
.string()
.optional()
.describe('New markdown description for the widget. Omit to leave unchanged.'),
- widget_type: zod.enum(['logs_list']),
+ widget_type: zod.enum(['survey_results']),
config: zod
.object({
dateRange: zod
@@ -2369,16 +2522,74 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
}),
zod.null(),
])
- .optional(),
+ .optional()
+ .describe("Null or omitted means all time (the survey's full lifetime)."),
+ surveyId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'Survey to show performance stats and recent responses for. Null until the user picks one.'
+ ),
limit: zod
.number()
.min(1)
.max(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitMax)
.default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneLimitDefault)
+ .describe('Maximum number of recent responses to return.'),
+ })
+ .optional()
+ .describe('New configuration for the survey results widget. Omit to leave unchanged.'),
+ }),
+ zod.object({
+ tile_id: zod
+ .number()
+ .describe('ID of the widget tile to update. Use dashboard-get to look up widget tile IDs.'),
+ name: zod
+ .string()
+ .max(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenNameMax)
+ .nullish()
+ .describe(
+ 'New display name for the widget. Empty string or null clears it; omit to leave unchanged.'
+ ),
+ description: zod
+ .string()
+ .optional()
+ .describe('New markdown description for the widget. Omit to leave unchanged.'),
+ widget_type: zod.enum(['logs_list']),
+ config: zod
+ .object({
+ dateRange: zod
+ .union([
+ zod.object({
+ date_from: zod
+ .union([
+ zod.enum([
+ '-1M',
+ '-30M',
+ '-1h',
+ '-3h',
+ '-24h',
+ '-7d',
+ '-14d',
+ '-30d',
+ '-90d',
+ ]),
+ zod.null(),
+ ])
+ .optional(),
+ }),
+ zod.null(),
+ ])
+ .optional(),
+ limit: zod
+ .number()
+ .min(1)
+ .max(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneLimitMax)
+ .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneLimitDefault)
.describe('Maximum number of log lines to return.'),
orderBy: zod
.enum(['latest', 'earliest'])
- .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneOrderByDefault)
+ .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneOrderByDefault)
.describe('Sort by newest (latest) or oldest (earliest) first.'),
severityLevels: zod
.array(zod.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal']))
@@ -2390,11 +2601,11 @@ export const DashboardsUpdateWidgetsBatchBody = /* @__PURE__ */ zod
.describe('Only show logs from these services. Empty shows all services.'),
wrapLines: zod
.boolean()
- .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneWrapLinesDefault)
+ .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneWrapLinesDefault)
.describe('Wrap long log lines instead of truncating them to a single row.'),
timezone: zod
.enum(['UTC', 'local'])
- .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSixConfigOneTimezoneDefault)
+ .default(dashboardsUpdateWidgetsBatchBodyWidgetsItemSevenConfigOneTimezoneDefault)
.describe("Render log timestamps in UTC or in each viewer's local timezone."),
savedViewId: zod
.union([zod.string(), zod.null()])
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
index f10c2cc2e333..08bef1168056 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
@@ -717,6 +717,63 @@
},
"type": "object"
},
+ {
+ "properties": {
+ "dateRange": {
+ "anyOf": [
+ {
+ "properties": {
+ "date_from": {
+ "anyOf": [
+ {
+ "enum": [
+ "-1M",
+ "-30M",
+ "-1h",
+ "-3h",
+ "-24h",
+ "-7d",
+ "-14d",
+ "-30d",
+ "-90d"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Null or omitted means all time (the survey's full lifetime)."
+ },
+ "limit": {
+ "default": 10,
+ "description": "Maximum number of recent responses to return.",
+ "maximum": 25,
+ "minimum": 1,
+ "type": "number"
+ },
+ "surveyId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Survey to show performance stats and recent responses for. Null until the user picks one."
+ }
+ },
+ "type": "object"
+ },
{
"properties": {
"dateRange": {
@@ -829,14 +886,15 @@
"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* `experiment_results` - experiment_results\n* `experiments_list` - experiments_list\n* `logs_list` - logs_list\n* `session_replay_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* `logs_list` - logs_list\n* `session_replay_list` - session_replay_list\n* `survey_results` - survey_results",
"enum": [
"activity_events_list",
"error_tracking_list",
"experiment_results",
"experiments_list",
"logs_list",
- "session_replay_list"
+ "session_replay_list",
+ "survey_results"
],
"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.json
index 40f690f777bf..eac72a91a8fa 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, experiment_results, experiments_list, logs_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, logs_list, session_replay_list, survey_results. Use dashboard-widget-catalog-list for per-type config_schema documentation. (1–10 per request).",
"items": {
"anyOf": [
{
@@ -1000,6 +1000,144 @@
"required": ["widget_type", "config"],
"type": "object"
},
+ {
+ "properties": {
+ "config": {
+ "description": "Configuration for the survey results widget.",
+ "properties": {
+ "dateRange": {
+ "anyOf": [
+ {
+ "properties": {
+ "date_from": {
+ "anyOf": [
+ {
+ "enum": [
+ "-1M",
+ "-30M",
+ "-1h",
+ "-3h",
+ "-24h",
+ "-7d",
+ "-14d",
+ "-30d",
+ "-90d"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Null or omitted means all time (the survey's full lifetime)."
+ },
+ "limit": {
+ "default": 10,
+ "description": "Maximum number of recent responses to return.",
+ "maximum": 25,
+ "minimum": 1,
+ "type": "number"
+ },
+ "surveyId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Survey to show performance stats and recent responses for. Null until the user picks one."
+ }
+ },
+ "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": ["survey_results"],
+ "type": "string"
+ }
+ },
+ "required": ["widget_type", "config"],
+ "type": "object"
+ },
{
"properties": {
"config": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json
index 140186efbb19..a6d8c57375e3 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-update.json
@@ -750,6 +750,94 @@
"required": ["tile_id", "widget_type"],
"type": "object"
},
+ {
+ "properties": {
+ "config": {
+ "description": "New configuration for the survey results widget. Omit to leave unchanged.",
+ "properties": {
+ "dateRange": {
+ "anyOf": [
+ {
+ "properties": {
+ "date_from": {
+ "anyOf": [
+ {
+ "enum": [
+ "-1M",
+ "-30M",
+ "-1h",
+ "-3h",
+ "-24h",
+ "-7d",
+ "-14d",
+ "-30d",
+ "-90d"
+ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Null or omitted means all time (the survey's full lifetime)."
+ },
+ "limit": {
+ "default": 10,
+ "description": "Maximum number of recent responses to return.",
+ "maximum": 25,
+ "minimum": 1,
+ "type": "number"
+ },
+ "surveyId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Survey to show performance stats and recent responses for. Null until the user picks one."
+ }
+ },
+ "type": "object"
+ },
+ "description": {
+ "description": "New markdown description for the widget. Omit to leave unchanged.",
+ "type": "string"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "maxLength": 400,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "New display name for the widget. Empty string or null clears it; omit to leave unchanged."
+ },
+ "tile_id": {
+ "description": "ID of the widget tile to update. Use dashboard-get to look up widget tile IDs.",
+ "type": "number"
+ },
+ "widget_type": {
+ "enum": ["survey_results"],
+ "type": "string"
+ }
+ },
+ "required": ["tile_id", "widget_type"],
+ "type": "object"
+ },
{
"properties": {
"config": {
diff --git a/tach.toml b/tach.toml
index c2556fd0a663..ada41209e211 100644
--- a/tach.toml
+++ b/tach.toml
@@ -222,6 +222,7 @@ depends_on = [
"products.logs",
"products.mcp_analytics",
"products.product_analytics",
+ "products.surveys",
]
layer = "modules"