:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(subscriptions): tabbed overview and optional first send (#69205)
Vasco de Krijger121127314c32
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 8edd18cf813d..92555eb9cfd7 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -43,6 +43,8 @@ from posthog.slo.types import SloArea, SloOperationfrom posthog.temporal.common.client import sync_connectfrom posthog.utils import str_to_bool+from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.exports.backend.models.subscription import (Subscription,SubscriptionDelivery,@@ -215,6 +217,16 @@ class SubscriptionSerializer(serializers.ModelSerializer):allow_null=True,help_text="Optional message included in the invitation email when adding new recipients.",)+ send_test_now = serializers.BooleanField(+ required=False,+ write_only=True,+ help_text=(+ "Whether to immediately deliver the subscription once on save so the editor can confirm "+ "it looks right. Defaults to true on create. When omitted on update, a delivery is sent "+ "only if the edit changed what gets delivered (recipient, channel, source) or re-enabled "+ "the subscription. The recurring schedule is unaffected."+ ),+ )integration_id = serializers.IntegerField(required=False,allow_null=True,@@ -274,6 +286,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):"next_delivery_date","integration_id","invite_message",+ "send_test_now","summary_enabled","summary_prompt_guide",]@@ -604,29 +617,6 @@ class SubscriptionSerializer(serializers.ModelSerializer):# Telemetry must never poison the validation path.pass- def _capture_update_delivery_decision(- self, instance: Subscription, *, delivery_triggered: bool, re_enabled: bool- ) -> None:- try:- posthoganalytics.capture(- distinct_id=self._caller_distinct_id(),- event="subscription_update_delivery_decision",- properties={- "subscription_id": instance.id,- "team_id": instance.team_id,- "resource_type": instance.resource_type,- "target_type": instance.target_type,- "delivery_triggered": delivery_triggered,- "reason": "re_enabled"- if re_enabled- else ("delivery_field_changed" if delivery_triggered else "no_delivery_relevant_change"),- },- groups=groups(None, instance.team),- )- except Exception as e:- # Telemetry must never block the update.- capture_exception(e)-def _evaluate_feature_flag(self, flag_key: str) -> bool:"""Evaluate a feature flag for the caller's organization.@@ -721,6 +711,10 @@ class SubscriptionSerializer(serializers.ModelSerializer):)invite_message = validated_data.pop("invite_message", "")+ # The immediate confirmation delivery (TARGET_CHANGE below) is separate from the+ # recurring schedule, which the scheduler drives off next_delivery_date. Creators+ # can opt out of that first send via send_test_now; the schedule is unaffected.+ send_test_now = validated_data.pop("send_test_now", True)dashboard_export_insight_ids = validated_data.pop("dashboard_export_insights", [])with attribute_subscription_saves(get_request_analytics_properties(request)):instance: Subscription = super().create(validated_data)@@ -733,10 +727,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):if dashboard_export_insight_ids:instance.dashboard_export_insights.set(dashboard_export_insight_ids)- # Skip the workflow trigger when the new subscription is created in a disabled- # state — mirrors the equivalent guard in `update()`. Avoids firing a delivery- # for a subscription that won't fire on its schedule either.- if not instance.enabled:+ if not instance.enabled or not send_test_now:return instancewith slo_operation(@@ -792,14 +783,17 @@ class SubscriptionSerializer(serializers.ModelSerializer):was_disabled = instance.enabled is Falseis_delete = not instance.deleted and validated_data.get("deleted") is Trueinvite_message = validated_data.pop("invite_message", "")+ # None means "not provided" — the delivery decision then falls back to inferring from+ # what the edit changed, matching the long-standing default behavior.+ send_test_now: bool | None = validated_data.pop("send_test_now", None)# Track payload PRESENCE, not truthiness: an empty list (clearing all exports) is delivery-relevant# too, so `bool(ids)` would miss it. Pop loses presence, so capture it first.export_insights_in_payload = "dashboard_export_insights" in validated_datadashboard_export_insight_ids = validated_data.pop("dashboard_export_insights", [])analytics_props = get_request_analytics_properties(request)- # Snapshot delivery-relevant scalar values before the write so we can tell, after,- # whether the edit actually changed what gets delivered. Only snapshot the+ # Snapshot delivery-relevant values before the write so the inferred path can tell,+ # after, whether the edit actually changed what gets delivered. Only snapshot the# dashboard_export_insights M2M when the payload carries it — that's the only case# `.set()` can mutate the relation, so a schedule/meta-only edit pays no M2M query.old_delivery_values = {field: getattr(instance, field) for field in self.FIELDS_THAT_TRIGGER_REDELIVERY}@@ -846,53 +840,95 @@ class SubscriptionSerializer(serializers.ModelSerializer):instance.set_next_delivery_date()instance.save(update_fields=["next_delivery_date"])- # Skip the workflow trigger when the resulting state is disabled. No delivery- # should fire for a disabled subscription regardless of whether it was just- # disabled or already disabled.- if not instance.enabled:- return instance-- # Only fire the immediate confirmation delivery when the edit changed *what*- # gets delivered, or when re-enabling (`enabled: false → true`) — the user- # expects a confirmation delivery in both cases. A schedule/meta-only edit- # (frequency, interval, title, summary_*, …) re-saves next_delivery_date via- # the model's save() but must not push a fresh delivery.delivery_target_changed = any(getattr(instance, field) != old_value for field, old_value in old_delivery_values.items()) or (old_export_insight_ids is not None and set(dashboard_export_insight_ids) != old_export_insight_ids)- # The "<kind> subscription updated" event fires from the post_save signal before this decision is- # made, so it can't tell an edit that fired a confirmation from one that intentionally skipped.- # Emit the decision explicitly so a regression that silently suppressed deliveries stays observable.- delivery_triggered = is_re_enabling or delivery_target_changed- self._capture_update_delivery_decision(- instance, delivery_triggered=delivery_triggered, re_enabled=is_re_enabling+ # Explicit send_test_now wins. When omitted, infer: send when the edit changed what+ # gets delivered, or on re-enable — a schedule/meta-only edit must not push a fresh+ # delivery. Disabled subscriptions never fire regardless.+ wants_delivery = send_test_now if send_test_now is not None else (is_re_enabling or delivery_target_changed)+ delivery_triggered = wants_delivery and instance.enabled++ # Explicit observability for the delivery decision on edits — the canonical+ # "subscription updated" event fires from the post_save signal before this decision+ # exists, so a regression that silently suppressed deliveries would be invisible there.+ posthoganalytics.capture(+ distinct_id=str(request.user.distinct_id),+ event="subscription_update_delivery_intent",+ properties={+ **analytics_props,+ "subscription_id": instance.id,+ "team_id": instance.team_id,+ "resource_type": instance.resource_type,+ "send_test_now": send_test_now,+ "delivery_triggered": delivery_triggered,+ "re_enabled": is_re_enabling,+ "subscription_enabled": instance.enabled,+ },+ groups=groups(None, instance.team),)+if not delivery_triggered:return instancetemporal = sync_connect()- workflow_id = f"handle-subscription-value-change-{instance.id}-{uuid.uuid4()}"- asyncio.run(- temporal.start_workflow(- "handle-subscription-value-change",- ProcessSubscriptionWorkflowInputs(- subscription_id=instance.id,- team_id=instance.team_id,- distinct_id=str(instance.created_by.distinct_id) if instance.created_by else str(instance.team_id),- previous_value=previous_value,- invite_message=invite_message,- trigger_type=SubscriptionTriggerType.TARGET_CHANGE,- resource_type=instance.resource_type,- ),- id=workflow_id,- task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,+ if send_test_now:+ # Explicit ask: deterministic ID so a caller spamming send_test_now dedupes to one+ # in-flight delivery per subscription instead of fanning out real sends. Kept distinct+ # from the test-delivery action's ID family so the two flows stay tellable apart.+ workflow_id = f"send-test-now-subscription-{instance.id}"+ else:+ # Inferred delivery (recipient/target change, re-enable): unique ID so two legitimate+ # consecutive edits both deliver instead of the second silently deduping.+ workflow_id = f"handle-subscription-value-change-{instance.id}-{uuid.uuid4()}"+ try:+ asyncio.run(+ temporal.start_workflow(+ "handle-subscription-value-change",+ ProcessSubscriptionWorkflowInputs(+ subscription_id=instance.id,+ team_id=instance.team_id,+ distinct_id=str(instance.created_by.distinct_id)+ if instance.created_by+ else str(instance.team_id),+ previous_value=previous_value,+ invite_message=invite_message,+ trigger_type=SubscriptionTriggerType.TARGET_CHANGE,+ resource_type=instance.resource_type,+ ),+ id=workflow_id,+ task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,+ ))- )+ except WorkflowAlreadyStartedError:+ # A delivery for this subscription is already in flight; the update itself+ # succeeded, so skip the duplicate send rather than failing the request.+ passreturn instance+def _parse_int_param(value: str, param: str) -> int:+ try:+ return int(value.strip())+ except ValueError:+ raise ValidationError({param: ["Must be an integer ID."]}) from None+++def _parse_int_list_param(value: str, param: str) -> list[int]:+ # int() (not str.isdigit) so exotic digits like "²" fail as a 400 here instead of a 500,+ # and invalid tokens reject the request instead of being silently dropped.+ tokens = [token.strip() for token in value.split(",") if token.strip()]+ try:+ ids = [int(token) for token in tokens]+ except ValueError:+ ids = []+ if not ids:+ raise ValidationError({param: ["Must be a comma-separated list of integer insight IDs."]})+ return ids++def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> bool:"""An AI subscription is one backed by a non-empty prompt (team-scoped)."""return (@@ -936,6 +972,13 @@ def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> boolrequired=False,description="Filter by insight ID.",),+ OpenApiParameter(+ name="insights",+ type=str,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter by a comma-separated list of insight IDs.",+ ),OpenApiParameter(name="dashboard",type=int,@@ -943,6 +986,13 @@ def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> boolrequired=False,description="Filter by dashboard ID.",),+ OpenApiParameter(+ name="dashboard_tiles",+ type=int,+ location=OpenApiParameter.QUERY,+ required=False,+ description="Filter to subscriptions on insights that are tiles of the given dashboard ID.",+ ),],),)@@ -999,6 +1049,15 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mpk = view.kwargs.get("pk")return bool(pk) and _subscription_is_ai_prompt(pk, self.team_id)+ def get_throttles(self):+ throttles = super().get_throttles()+ # An update that requests send_test_now enqueues a real email/Slack delivery — the same+ # blast radius as the test-delivery action — so it shares that team-wide throttle.+ data = self.request.data+ if self.action in ("update", "partial_update") and isinstance(data, dict) and data.get("send_test_now"):+ throttles.append(SubscriptionTestDeliveryThrottle())+ return throttles+def safely_get_queryset(self, queryset) -> QuerySet:request_params = self.request.GET.dict()@@ -1040,10 +1099,33 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mqueryset = queryset.filter(target_type=target_type_filter)for key in request_params:- if key == "insight":- queryset = queryset.filter(insight_id=request_params["insight"])+ if key in ("insight", "insights"):+ # `insight` (single ID) and `insights` (comma-separated IDs) share one filter:+ # both are parsed as an ID list so behavior and validation stay identical.+ queryset = queryset.filter(insight_id__in=_parse_int_list_param(request_params[key], key))+ elif key == "dashboard_tiles":+ # Subscriptions on insights that are live tiles of the given dashboard, resolved server-side+ # so the overview's "Insights" tab never depends on which tiles the client happens to have+ # loaded into memory. The default DashboardTile manager skips deleted tiles/dashboards; we+ # also drop soft-deleted insights and scope to the team, matching the tile set the sibling+ # dashboard-export validation resolves.+ dashboard_id = _parse_int_param(request_params["dashboard_tiles"], "dashboard_tiles")+ # Require view access to the dashboard itself: without it a project member could pass any+ # dashboard ID and enumerate which subscribed insights are tiles on a dashboard they can't see.+ dashboard = Dashboard.objects.filter(id=dashboard_id, team_id=self.team_id).first()+ if dashboard is None:+ raise ValidationError({"dashboard_tiles": ["Dashboard not found."]})+ if not self.user_access_control.check_access_level_for_object(dashboard, "viewer"):+ raise exceptions.PermissionDenied("You do not have access to this dashboard.")+ tile_insight_ids = DashboardTile.objects.filter(+ dashboard_id=dashboard_id,+ dashboard__team_id=self.team_id,+ insight_id__isnull=False,+ insight__deleted=False,+ ).values_list("insight_id", flat=True)+ queryset = queryset.filter(insight_id__in=tile_insight_ids)elif key == "dashboard":- queryset = queryset.filter(dashboard_id=request_params["dashboard"])+ queryset = queryset.filter(dashboard_id=_parse_int_param(request_params["dashboard"], "dashboard"))elif key == "deleted":queryset = queryset.filter(deleted=str_to_bool(request_params["deleted"]))diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex b1492c79f9ec..032b5b6c83e5 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -140,6 +140,95 @@ class TestSubscriptionTemporal(APILicensedTest):assert activity_inputs.subscription_id == data["id"]assert activity_inputs.invite_message == "hey there!"+ @parameterized.expand(+ [+ ("default_fires", None, True),+ ("explicit_true_fires", True, True),+ ("opt_out_skips", False, False),+ ]+ )+ def test_create_send_test_now_controls_immediate_delivery(self, _name, send_test_now, should_fire):+ kwargs = {} if send_test_now is None else {"send_test_now": send_test_now}+ response = self._create_subscription(**kwargs)+ assert response.status_code == status.HTTP_201_CREATED, response.content+ assert "send_test_now" not in response.json()+ if should_fire:+ self.mock_temporal_client.start_workflow.assert_called_once()+ else:+ self.mock_temporal_client.start_workflow.assert_not_called()+ # Opting out of the first send must not touch the recurring schedule+ assert Subscription.objects.get(id=response.json()["id"]).next_delivery_date is not None++ @parameterized.expand(+ [+ ("opt_in_fires", True, True),+ ("opt_out_skips", False, False),+ ]+ )+ def test_update_honors_explicit_send_test_now(self, _name, send_test_now, should_fire):+ sub_id = self._create_subscription().json()["id"]+ self.mock_temporal_client.start_workflow.reset_mock()++ # target_value would infer a send on its own — explicit send_test_now must override either way+ payload: dict = {"target_value": "[email protected]", "send_test_now": send_test_now}+ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", payload)+ assert response.status_code == status.HTTP_200_OK, response.content+ assert "send_test_now" not in response.json()+ if should_fire:+ self.mock_temporal_client.start_workflow.assert_called_once()+ else:+ self.mock_temporal_client.start_workflow.assert_not_called()++ def test_update_send_test_now_skips_duplicate_in_flight_delivery(self):+ sub_id = self._create_subscription().json()["id"]+ self.mock_temporal_client.start_workflow.reset_mock()+ self.mock_temporal_client.start_workflow.side_effect = WorkflowAlreadyStartedError(+ f"send-test-now-subscription-{sub_id}", "handle-subscription-value-change"+ )++ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", {"send_test_now": True})+ # A delivery already in flight must not fail the update or fan out a second send+ assert response.status_code == status.HTTP_200_OK, response.content++ def test_update_inferred_deliveries_get_unique_workflow_ids(self):+ # Only explicit send_test_now dedupes: two legitimate consecutive recipient edits must+ # both deliver, each under a fresh workflow ID, instead of the second silently deduping.+ sub_id = self._create_subscription().json()["id"]+ self.mock_temporal_client.start_workflow.reset_mock()++ for recipient in ("[email protected]", "[email protected]"):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}", {"target_value": recipient}+ )+ assert response.status_code == status.HTTP_200_OK, response.content++ assert self.mock_temporal_client.start_workflow.call_count == 2+ workflow_ids = [call.kwargs["id"] for call in self.mock_temporal_client.start_workflow.call_args_list]+ assert all(wf_id.startswith(f"handle-subscription-value-change-{sub_id}-") for wf_id in workflow_ids)+ assert len(set(workflow_ids)) == 2++ @patch("posthog.rate_limit.SubscriptionTestDeliveryThrottle.rate", new="2/minute")+ @patch("posthog.rate_limit.is_rate_limit_enabled", return_value=True)+ def test_update_send_test_now_shares_test_delivery_throttle(self, _rate_limit_enabled_mock):+ throttle_key = f"throttle_subscription_test_delivery_team_{self.team.id}"+ cache.delete(throttle_key)+ self.addCleanup(cache.delete, throttle_key)++ sub_id = self._create_subscription().json()["id"]++ for _ in range(2):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}", {"send_test_now": True}+ )+ assert response.status_code == status.HTTP_200_OK, response.content++ throttled = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", {"send_test_now": True})+ assert throttled.status_code == status.HTTP_429_TOO_MANY_REQUESTS++ # Plain edits without send_test_now must not be throttled+ plain = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", {"title": "Still editable"})+ assert plain.status_code == status.HTTP_200_OK, plain.content+def test_cannot_create_subscription_without_insight_or_dashboard(self):response = self.client.post(f"/api/projects/{self.team.id}/subscriptions",@@ -201,6 +290,7 @@ class TestSubscriptionTemporal(APILicensedTest):{"target_value": "[email protected],[email protected]","invite_message": "hi new user",+ "send_test_now": True,},)updated_data = response.json()@@ -250,110 +340,57 @@ class TestSubscriptionTemporal(APILicensedTest):},).json()["id"]- # Each case is (name, build, should_fire, expected_reason); build(test) -> (sub_id, patch_payload).- # The inline factory keeps each case's setup next to its expected outcome.+ # Each case is (name, build, should_fire); build(test) -> (sub_id, patch_payload). Explicit+ # send_test_now always wins; when omitted, the send is inferred from whether the edit changed+ # what gets delivered (or re-enabled the subscription) — schedule/meta-only edits stay quiet.@parameterized.expand([- # Schedule/meta-only edits must NOT re-fire a delivery.- ("frequency", lambda t: (t._basic_sub(), {"frequency": "daily"}), False, "no_delivery_relevant_change"),- ("interval", lambda t: (t._basic_sub(), {"interval": 3}), False, "no_delivery_relevant_change"),- ("title", lambda t: (t._basic_sub(), {"title": "Renamed"}), False, "no_delivery_relevant_change"),- # Delivery-relevant edits MUST fire a confirmation — what (or where) gets delivered changed,- # or the subscription was re-enabled.+ ("schedule_only_inferred_no_send", lambda t: (t._basic_sub(), {"frequency": "daily"}), False),(- "target_value",- lambda t: (t._basic_sub(), {"target_value": "[email protected],[email protected]"}),+ "schedule_only_with_send",+ lambda t: (t._basic_sub(), {"frequency": "daily", "send_test_now": True}),True,- "delivery_field_changed",),(- "target_type", # switching channel routes delivery elsewhere — needs a Slack integration- lambda t: (- t._basic_sub(),- {- "target_type": "slack",- "target_value": "#general",- "integration_id": Integration.objects.create(team=t.team, kind="slack", config={}).id,- },- ),- True,- "delivery_field_changed",- ),- ("re_enable", lambda t: (t._disabled_email_sub(), {"enabled": True}), True, "re_enabled"),- (- "integration_swap", # Slack routing depends on the workspace, not just target_value- lambda t: (- Subscription.objects.create(- team=t.team,- target_type="slack",- target_value="#general",- integration=Integration.objects.create(team=t.team, kind="slack", config={}),- frequency="daily",- start_date=timezone.now(),- insight=t.insight,- title="t",- ).id,- {"integration_id": Integration.objects.create(team=t.team, kind="slack", config={}).id},- ),+ "recipient_inferred_send",+ lambda t: (t._basic_sub(), {"target_value": "[email protected],[email protected]"}),True,- "delivery_field_changed",),(- "dashboard_export_change", # changing the exported insight set hits the M2M branch+ "recipient_with_opt_out",lambda t: (- t._dashboard_sub(- [t.insight, (other := Insight.objects.create(team=t.team, name="other"))],- [t.insight],- ),- {"dashboard_export_insights": [t.insight.id, other.id]},+ t._basic_sub(),+ {"target_value": "[email protected],[email protected]", "send_test_now": False},),- True,- "delivery_field_changed",+ False,),- # ...except re-submitting the identical export set, which changes nothing.+ ("re_enable_inferred_send", lambda t: (t._disabled_email_sub(), {"enabled": True}), True),(- "dashboard_export_resubmit_same",- lambda t: (- t._dashboard_sub([t.insight], [t.insight]),- {"dashboard_export_insights": [t.insight.id], "title": "Renamed"},- ),+ "re_enable_with_opt_out",+ lambda t: (t._disabled_email_sub(), {"enabled": True, "send_test_now": False}),False,- "no_delivery_relevant_change",),+ # send_test_now on an edit that leaves the sub disabled must not deliver.+ ("send_but_left_disabled", lambda t: (t._disabled_email_sub(), {"send_test_now": True}), False),])- def test_update_fires_delivery_only_when_delivery_relevant_field_changes(+ def test_update_fires_delivery_only_when_send_test_now(self,_name: str,build: Callable[["TestSubscriptionTemporal"], tuple[int, dict]],should_fire: bool,- expected_reason: str,):sub_id, patch_payload = build(self)self.mock_temporal_client.start_workflow.reset_mock()- with patch("ee.api.subscription.posthoganalytics.capture") as mock_capture:- response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", patch_payload)- assert response.status_code == status.HTTP_200_OK, response.content+ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", patch_payload)+ assert response.status_code == status.HTTP_200_OK, response.content- # The workflow fires only when the edit warrants a confirmation delivery...if should_fire:self.mock_temporal_client.start_workflow.assert_called_once()else:self.mock_temporal_client.start_workflow.assert_not_called()- # ...and the decision is always emitted so a silent suppression is observable — the post_save- # "<kind> subscription updated" event fires pre-decision and can't carry this signal.- decision_calls = [- call- for call in mock_capture.call_args_list- if call.kwargs.get("event") == "subscription_update_delivery_decision"- ]- assert len(decision_calls) == 1- properties = decision_calls[0].kwargs["properties"]- assert properties["delivery_triggered"] is should_fire- assert properties["reason"] == expected_reason-@freeze_time("2026-06-15T10:00:00Z") # Monday — weekly (Sat) is 5 days away, daily is 1 daydef test_schedule_only_update_still_recomputes_next_delivery_date(self):# A schedule edit must not fire a delivery but MUST still reschedule — the model@@ -1454,10 +1491,103 @@ class TestSubscriptionTemporal(APILicensedTest):assert len(results) == 1assert results[0]["title"] == "Mine"+ def test_list_subscriptions_filter_by_insights(self):+ other_insight = Insight.objects.create(+ filters=Filter(data=self.insight_filter_dict).to_dict(), team=self.team, created_by=self.user+ )+ first_id = self._create_subscription(title="First").json()["id"]+ second_id = self._create_subscription(title="Second", insight=other_insight.id).json()["id"]++ both = self.client.get(+ f"/api/projects/{self.team.id}/subscriptions/",+ {"insights": f"{self.insight.id},{other_insight.id}"},+ )+ assert both.status_code == status.HTTP_200_OK+ assert {r["id"] for r in both.json()["results"]} == {first_id, second_id}++ # The legacy single-ID `insight` param routes through the same filter+ single = self.client.get(+ f"/api/projects/{self.team.id}/subscriptions/",+ {"insight": str(other_insight.id)},+ )+ assert single.status_code == status.HTTP_200_OK+ assert {r["id"] for r in single.json()["results"]} == {second_id}++ @parameterized.expand(+ [+ ("insights_non_numeric_token", "insights", "abc,1"),+ ("insights_superscript_digit", "insights", "²"),+ ("insights_empty", "insights", ","),+ ("insight_non_numeric", "insight", "abc"),+ ("dashboard_tiles_non_numeric", "dashboard_tiles", "abc"),+ ("dashboard_non_numeric", "dashboard", "abc"),+ ]+ )+ def test_list_subscriptions_rejects_invalid_id_filters(self, _name, param, value):+ # Invalid tokens must 400 rather than being silently dropped (a typo would+ # otherwise quietly narrow results) or raising an unhandled 500.+ res = self.client.get(f"/api/projects/{self.team.id}/subscriptions/", {param: value})+ assert res.status_code == status.HTTP_400_BAD_REQUEST+ assert res.json()["attr"] == param++ def _insight(self, **kwargs) -> Insight:+ return Insight.objects.create(+ filters=Filter(data=self.insight_filter_dict).to_dict(), team=self.team, created_by=self.user, **kwargs+ )++ def test_list_subscriptions_filter_by_dashboard_tiles(self):+ # The filter resolves the dashboard's tile insights server-side, so it returns subscriptions on+ # tiled insights without the client passing any insight IDs (fixes the overview's flaky Insights tab).+ tiled_insight = self._insight()+ self.dashboard.tiles.create(insight=tiled_insight)+ on_tile_id = self._create_subscription(title="On tile", insight=tiled_insight.id).json()["id"]++ # A tiled insight that has since been soft-deleted must drop out (mirrors the old client-side guard).+ deleted_insight = self._insight()+ self.dashboard.tiles.create(insight=deleted_insight)+ self._create_subscription(title="On deleted insight", insight=deleted_insight.id)+ deleted_insight.deleted = True+ deleted_insight.save()++ # A subscription on an insight that is not a tile of this dashboard must be excluded.+ self._create_subscription(title="Off dashboard", insight=self._insight().id)++ res = self.client.get(f"/api/projects/{self.team.id}/subscriptions/", {"dashboard_tiles": self.dashboard.id})+ assert res.status_code == status.HTTP_200_OK+ assert {r["id"] for r in res.json()["results"]} == {on_tile_id}++ def test_list_subscriptions_filter_by_dashboard_tiles_empty_dashboard(self):+ # A dashboard with no insight tiles resolves to an empty set rather than erroring.+ self._create_subscription(title="Unrelated", insight=self._insight().id)+ res = self.client.get(f"/api/projects/{self.team.id}/subscriptions/", {"dashboard_tiles": self.dashboard.id})+ assert res.status_code == status.HTTP_200_OK+ assert res.json()["results"] == []++ def test_dashboard_tiles_filter_requires_dashboard_view_access(self):+ # Without a view-access check a member could pass any dashboard ID and enumerate its tiles'+ # subscriptions. Denying object access must 403, not leak the tile set.+ self._create_subscription(title="On tile", insight=self._insight().id)+ with patch(+ "posthog.rbac.user_access_control.UserAccessControl.check_access_level_for_object", return_value=False+ ):+ res = self.client.get(+ f"/api/projects/{self.team.id}/subscriptions/", {"dashboard_tiles": self.dashboard.id}+ )+ assert res.status_code == status.HTTP_403_FORBIDDEN, res.content++ def test_dashboard_tiles_filter_rejects_other_teams_dashboard(self):+ # A dashboard from another team must 404-style reject (team scoping), never resolve its tiles.+ other_team = Team.objects.create(organization=self.organization, name="Other")+ other_dashboard = Dashboard.objects.create(team=other_team, name="Theirs")+ res = self.client.get(f"/api/projects/{self.team.id}/subscriptions/", {"dashboard_tiles": other_dashboard.id})+ assert res.status_code == status.HTTP_400_BAD_REQUEST+ assert res.json().get("attr") == "dashboard_tiles"+@parameterized.expand([("invalid_created_by", "created_by", "not-a-uuid", "created_by"),("invalid_target_type", "target_type", "not_a_channel", "target_type"),+ ("invalid_insights", "insights", "abc,def", "insights"),],name_func=lambda f, _n, p: f"{f.__name__}__{p.args[0]}",)@@ -1561,8 +1691,8 @@ class TestSubscriptionTemporal(APILicensedTest):assert subscription.enabled is Trueassert subscription.next_delivery_date is not Noneassert subscription.next_delivery_date > timezone.now()- # Re-enable also fires the immediate TARGET_CHANGE confirmation delivery —- # the date reset prevents the *scheduler* from firing a second one moments later.+ # Re-enabling infers a confirmation delivery; the date reset must still run so the+ # scheduler doesn't fire a second, stale-dated delivery right after it.temporal_mock.return_value.start_workflow.assert_called_once()@parameterized.expand(@@ -1684,14 +1814,14 @@ class TestSubscriptionTemporal(APILicensedTest):@parameterized.expand([- # The confirmation-delivery workflow fires only on a re-enable or a delivery-relevant change —- # not on a meta-only edit (title) or a redundant enable that changes nothing. (This narrows the- # previous "every edit to an enabled sub fires" matrix; see FIELDS_THAT_TRIGGER_REDELIVERY.)- ("enabled_to_enabled_field_edit", True, {"title": "renamed"}, False),+ # No edit fires a confirmation delivery unless send_test_now is set — not a meta-only edit,+ # not a redundant toggle, and (unlike before) not a bare re-enable either.+ ("enabled_field_edit_no_send", True, {"title": "renamed"}, False),("redundant_enable", True, {"enabled": True}, False),("disable_enabled", True, {"enabled": False}, False),("redundant_disable", False, {"enabled": False}, False),- ("enable_disabled", False, {"enabled": True}, True),+ ("enable_disabled_inferred_send", False, {"enabled": True}, True),+ ("enable_disabled_with_opt_out", False, {"enabled": True, "send_test_now": False}, False),])def test_patch_workflow_trigger_for_enabled_field(@@ -2782,12 +2912,11 @@ class TestAISubscriptionAPI(APILicensedTest):update_resp = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}",- {"prompt": "Show me new error events"},+ {"prompt": "Show me new error events", "send_test_now": True},)assert update_resp.status_code == status.HTTP_200_OK, update_resp.json()assert update_resp.json()["prompt"] == "Show me new error events"- # prompt is delivery-relevant for AI subscriptions; editing it must re-fire the- # confirmation delivery so recipients see the updated report.+ # send_test_now on the edit fires the confirmation delivery so recipients see the updated report.mock_client.start_workflow.assert_called_once()def test_resource_type_is_derived_and_read_only(self, mock_is_cloud, mock_flag, mock_sync):diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 8b7655a4eb1b..0b826a784550 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -541,9 +541,9 @@ snapshots:components-hogcharts-barchart--horizontal-grouped--light:hash: v1.k794b7964.dfb7762f979f93d3cd458dc83d73057930a46faeec8044f756c2b25365f8a71c.sIavxCz1HLhwvVO6D0Y4RqO4Y48Otohk7tB-q2ut9QYcomponents-hogcharts-barchart--horizontal-wide-value-labels--dark:- hash: v1.k794b7964.de748c4ee5a5eefdd95047814f7116148c8f460de13decb3bdc023a4e5252f4c.ZZKmFWvCjv_YANsXJ5UHe7d3ny1Cfpi0X_n4UT5Jrlg+ hash: v1.k794b7964.939b83d3aaadd40cd06189abc0f661a5e9c7942639b3fd19db4d751227aacb54.vFYOTHz4Cz9XaFywZ7FmxIerUdX8bLkzTAVuMfLT_lYcomponents-hogcharts-barchart--horizontal-wide-value-labels--light:- hash: v1.k794b7964.a5c6fd8f9d7fbbc9753e5fc9174ed32c0cc9be8f3413987743f5f757b4c22429.mCdlAsg4goJO4WlH2efiupI0b5igP3z2k9roDJtHNbY+ hash: v1.k794b7964.61e9303ff7d7121575678a23b9eb3350aa88aced790dd345031343bba1aeba55.H21Q2Ehq3KPbduhdD4s9a4v9Ymtuyu7j9rsHcP9c3iwcomponents-hogcharts-barchart--incomplete-period--dark:hash: v1.k794b7964.a89e7cf2b28d2040ea81adaff44f51826c868a6657cf20d31214a23a46bcb4c1.VN2mXXnL05V77ddvqYAwo3w6gvv7_4b6AkowkiP7e24components-hogcharts-barchart--incomplete-period--light:@@ -1689,37 +1689,41 @@ snapshots:components-sso-select--sso-select--light:hash: v1.k794b7964.a53e97cb122fd5f1c1ebeafc7f3711094334bedbfc57d3a5edb61305fa9b7fd5.sWZP2Xf1ZHvG-3zB-I5poEQvHnqMjEVOBVEbYzNYLfccomponents-subscriptions--subscription-at-ai-summary-limit--dark:- hash: v1.k794b7964.5c9ef0b731313ae038c8cbdeb98a2e25f662094ab7944845a2fa5c24ee7918fc.pC1cRU2ZrsNGx0z3PzW6Ux6xHN1s_NikTLIfy87aUVQ+ hash: v1.k794b7964.f311eeee76a344bb3e5d6f821bfc39eaed7084676ed8303b75f72bc7a1b07850.OG5oagYOX-YdE_uuALBpZ0XnpKUWBxR0tg5t-QkSHIYcomponents-subscriptions--subscription-at-ai-summary-limit--light:- hash: v1.k794b7964.d0ee72dfd20ccbfbd8d31e63381052b354f7d838da71781244cb328938e93843.h1y7XF2TSwVezFKixPIfoJD63GN_puTIhswzWrvBwVE+ hash: v1.k794b7964.5811e86e8e76821927d62745628b48be1c326808cdcb74a9df4391cbbd699267.1g0Ui2rQZi3A5BTK587dS2Ub5cmJodiiHnHlryX4Ypccomponents-subscriptions--subscription-no-integrations--dark:- hash: v1.k794b7964.2eb6dcdf4e8c3e76561de5335a0871a76f152394e34886173c59fe96758d062c.5aRbdpHzXybGMeJwmsmXgFBuMU9lDHxUXqGvJAfiLTc+ hash: v1.k794b7964.e6331066f5581a9fb274858fc8b1d680bc830856000c5f7313baa857e4d80cf7.UoMnvRaSYrBFiWRG0yXh1ON8kgc5dFLiakUr57kWFRccomponents-subscriptions--subscription-no-integrations--light:- hash: v1.k794b7964.ae8706fd6101c48c7b56b1e3cb2628ab15594a8d21c5c70ef0a8e1c5fcecdc7d.T3YljPu11srtsHN3YE5medDFDwUhcs3RFDYnWWZfGHY+ hash: v1.k794b7964.1d81095d9f3e559c7e0c9888e5e5633c7ea78d61b156983c4b8dcdf86e590522.1wlbv02BG2FOCiRP9tcYU5tiZbNMl_K2gMY3uFuKupscomponents-subscriptions--subscriptions--dark:hash: v1.k794b7964.29bdf80867c8ea5ac4cd22db82f1de2a85b6abc668c54549a7c5796e2a0d88fb.JhmMnIpOHOLA-rZUHKlFL3o9BZaa076RRs819fS5J_0components-subscriptions--subscriptions--light:hash: v1.k794b7964.190dae50134f9c6e97cbaa89bc1ef20af0b0fa1906c265f64f06fbca1e2bf3a7.BR5ZMkdkYEF89q5H-5VEEjWAq3wbTD0Jq7HUqoG1CIYcomponents-subscriptions--subscriptions-edit--dark:- hash: v1.k794b7964.e7ade5e3e88fa41a14c263c7e7b3b4a247768062e6b911f541a9a6be7b55fdc8.cFAwmmpC0V6vYPSwM3rN7s-9mX0vJPFse1d0O-Zn1r0+ hash: v1.k794b7964.6400968f5984a0e590c6da9c375a74e29b21a1b8412904757f12b5c8b81c93d8.Kl2_HZbKUxV0wFUpKub7d3fp_2vMvc9MeSgFer_KpPUcomponents-subscriptions--subscriptions-edit--light:- hash: v1.k794b7964.8d1baf90050be9a728116a18fa57198391ea719a87ea99f0784b21ccf709f047.hU3QQb3F-14YfveO2vg-H9lq1BHSmkZeUNuHbBJGP6c+ hash: v1.k794b7964.cda28c1f47746476c6d4d226f55fb21dc032c49a04917ee738178d4214b390fd.4gLWUZ9IhlqKOns_wtGrT4N71RqOa7kqyWF4QDMF1Aocomponents-subscriptions--subscriptions-empty--dark:hash: v1.k794b7964.d8851cce11bb043fb1826b75e58a625dc42c485634fd03cbc015d90c00ef0867.jMy7Y347ZmcIyPvSHFIH8LGxLVa7ebjVBFWL_c8tHJocomponents-subscriptions--subscriptions-empty--light:hash: v1.k794b7964.4741de4c6e53cadf340e18e25b7363fa8b19834165e224f00ebfc35f69bd36e3.VdR976zptd0BsK_uJxEdTGsnF0tu4r8tLNNbxgL23Tocomponents-subscriptions--subscriptions-new--dark:- hash: v1.k794b7964.5c9ef0b731313ae038c8cbdeb98a2e25f662094ab7944845a2fa5c24ee7918fc.prePw0LoiSzPW4axb7WdAVbdM0ee3Hx9na92RrSxdDk+ hash: v1.k794b7964.f311eeee76a344bb3e5d6f821bfc39eaed7084676ed8303b75f72bc7a1b07850.wrgev2PJ3oA6tjAy87wPNrzBWZ5zZ6t1VzbGM0MHQvIcomponents-subscriptions--subscriptions-new--light:- hash: v1.k794b7964.d0ee72dfd20ccbfbd8d31e63381052b354f7d838da71781244cb328938e93843.xX7uOp6lDavMkx6a-7_HEfRWvF8ISEZzklBg9dvnwbU+ hash: v1.k794b7964.5811e86e8e76821927d62745628b48be1c326808cdcb74a9df4391cbbd699267.N5AxNAkXbCKwfxtrF1yDtD_NZ2SQ_G9Pr1WIPWJxYmocomponents-subscriptions--subscriptions-new-free-at-limit--dark:hash: v1.k794b7964.9f3333111f3d966404dda85a5b31ec40ab38e817bb61506144a5a13850d5714f.zm_fwavL51Xt_v932vmSHzXu2Zky7BrDCfn76ejB1oscomponents-subscriptions--subscriptions-new-free-at-limit--light:hash: v1.k794b7964.73777e7f5b880d59e78d99675e3c235da1e5c171e4c732c5b80ce732e23a9505.abF-3QCC4joptEiOpAPa-5Fl5bNmMKygoIExYM169Tkcomponents-subscriptions--subscriptions-new-free-under-limit--dark:- hash: v1.k794b7964.5c9ef0b731313ae038c8cbdeb98a2e25f662094ab7944845a2fa5c24ee7918fc.pO6-wBQ3UnD3izp-IyWQcBw8jfBJMtUffBTAWdJnffA+ hash: v1.k794b7964.f311eeee76a344bb3e5d6f821bfc39eaed7084676ed8303b75f72bc7a1b07850.tZL-FFNFMJcqKgxtVQ426AUs7kPn-eIBWFBFmU6eA9Mcomponents-subscriptions--subscriptions-new-free-under-limit--light:- hash: v1.k794b7964.d0ee72dfd20ccbfbd8d31e63381052b354f7d838da71781244cb328938e93843.jB5EvM11B7Ho34avA2tTuleE4gsKJjUCkVilDz4fI8w+ hash: v1.k794b7964.5811e86e8e76821927d62745628b48be1c326808cdcb74a9df4391cbbd699267.O-3UjKNxThBJf5B1xg7HxN4_1E3Sb-rQ5vI6ko0BO_E+ components-subscriptions--subscriptions-tabbed--dark:+ hash: v1.k794b7964.5ab4848e98d0e3782b8e08d03e947319bf3e0d733056a29ef9179c3e37e6facd.jg95MiA7A-g8IH1--HCt1ABLUFBbnODt_bGiy0Hbj58+ components-subscriptions--subscriptions-tabbed--light:+ hash: v1.k794b7964.151d3a1c18a9631558afc699790debe6d5c39401edff2d3170bf91169a2c2adb.7jhan5AEplszZtWpR4LyHLMNyFMD5Bpow9VKGY2cj1Icomponents-table-preview--default--dark:hash: v1.k794b7964.874fae2dfa767a71abbd43aff3ee6197c9ae1934601bfbe911d564c2ad6f8ac2.hsTFVeAPvG-h0bVqGrZ15OciFEfhyHIahDYpyxyxyWwcomponents-table-preview--default--light:@@ -4827,9 +4831,9 @@ snapshots:replay-tabs-home-failure--not-found--light:hash: v1.k794b7964.63f4edcf1afa31941d7fd4fe1cf6b2233335e5396691f5abfbeb5f32a5e77079.fT5YLbBCAptU85nyVbgAYp7DeiCCV6_bPb894JVNQFUreplay-tabs-home-filters-banner--product-analytics-over-limit--dark:- hash: v1.k794b7964.9ee25b6594b07076cff0c2d285096a7e2d2031e3d30e58d4d043c8e3e0d44447.0wsqTslGRLqaidPoW0-teojry4FMwKSiOqo9E6i6AG8+ hash: v1.k794b7964.e43831aab10f34ebb833d39856c8285ca3ec054b018c07a8eea2dc6551d12119.w0JYkgk5ujwBybY8356Xe93bi6ky_z7Skt5wuoRPX1greplay-tabs-home-filters-banner--product-analytics-over-limit--light:- hash: v1.k794b7964.9e6e0a6b500bea8a289281eaadb397a36a19381074a6d72291d186c7dbc89837.O2Q9Dv4VQBJqT5IlxRTwoYrGw7cXNkhGd2ikmDmIrZc+ hash: v1.k794b7964.3455a8a462eb913f7d478672c16b5fa56fd4591efcc09b5ad1119707842f80b3.FMUgEs84D1HWKB2fVtRZP_Dsk6HYgaz604k3bLZqwFIreplay-tabs-home-filters-banner--product-analytics-under-limit--dark:hash: v1.k794b7964.c4cc11f519896f1493409b60c0a04da6023d71a83374094c29c2666c65c205cf.aabEMRgGPdgSlwx4q2x34yULwzqiBwz2CI6LUyV5eakreplay-tabs-home-filters-banner--product-analytics-under-limit--light:diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 5116ebd9e3d2..41c086f01a26 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -6157,17 +6157,20 @@ const api = {return await new ApiRequest().subscription(subscriptionId).update({ data })},async list({- insightId,+ insights,dashboardId,+ dashboardTiles,resourceType,}: {- insightId?: number+ insights?: number[]dashboardId?: number+ dashboardTiles?: numberresourceType?: SubscriptionType['resource_type']}): Promise<PaginatedResponse<SubscriptionType>> {const params = [- insightId ? `insight=${insightId}` : null,+ insights?.length ? `insights=${insights.join(',')}` : null,dashboardId ? `dashboard=${dashboardId}` : null,+ dashboardTiles ? `dashboard_tiles=${dashboardTiles}` : null,resourceType ? `resource_type=${resourceType}` : null,].filter(Boolean)return await new ApiRequest().subscriptions().withQueryString(params.join('&')).get()diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 4a29c8fff6b4..cd0574661242 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -485,6 +485,7 @@ export const FEATURE_FLAGS = {SSE_DASHBOARDS: 'sse-dashboards', // owner: @aspicer #team-analytics-platformSUBSCRIPTION_AI_PROMPT: 'ai-subscriptions', // owner: #team-analytics-platform, gates AI prompt-based subscriptionsSUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE: 'subscription-ai-summary-prompt-guide', // owner: #team-analytics-platform, gates the per-subscription prompt guide textarea+ SUBSCRIPTION_TABBED_OVERVIEW: 'subscription-tabbed-overview', // owner: #team-analytics-platform, gates the tabbed subscriptions overview modalSURVEY_HEADLINE_SUMMARY: 'survey-headline-summary', // owner: @adboio #team-surveysSURVEYS_ERROR_TRACKING_CROSS_SELL: 'surveys-in-error-tracking', // owner: @adboio #team-surveysSURVEYS_FORM_BUILDER: 'surveys-form-builder', // owner: @adboio #team-surveysdiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex d1c39a59417f..54a0c4f1f4cf 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5365,6 +5365,8 @@ export interface SubscriptionType {enabled?: booleansummary_enabled?: booleansummary_prompt_guide?: string+ /** Write-only. When false, creating the subscription skips the immediate confirmation send (the schedule is unaffected). */+ send_test_now?: boolean}export type SmallTimeUnit = 'hours' | 'minutes' | 'seconds'diff --git a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsxindex 3fe12198d6e7..7e06e7c66db9 100644--- a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.stories.tsx@@ -3,13 +3,14 @@ import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'import { Meta, StoryObj } from '@storybook/react'import { useRef, useState } from 'react'+import { FEATURE_FLAGS } from 'lib/constants'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { uuid } from 'lib/utils/dom'import { useStorybookMocks } from '~/mocks/browser'import preflightJson from '~/mocks/fixtures/_preflight.json'import { createMockSubscription, mockIntegration, mockSlackChannels } from '~/test/mocks'-import { InsightShortId, Realm } from '~/types'+import { DashboardType, InsightShortId, Realm } from '~/types'import { SubscriptionsModal, SubscriptionsModalProps } from './SubscriptionsModal'@@ -31,6 +32,8 @@ const meta: Meta<StoryArgs> = {render: (args) => {const { noIntegrations = false, aiSummaryAtLimit = false, freeTierSubscriptionCount, ...props } = argsconst insightShortIdRef = useRef(props.insightShortId || (uuid() as InsightShortId))+ // Dashboard-context stories must not also pass an insight, or the modal renders the insight flow.+ const insightShortId = props.dashboard ? undefined : insightShortIdRef.currentconst [modalOpen, setModalOpen] = useState(false)useStorybookMocks({@@ -94,7 +97,7 @@ const meta: Meta<StoryArgs> = {// eslint-disable-next-line no-consoleconsole.log('close')}}- insightShortId={insightShortIdRef.current}+ insightShortId={insightShortId}isOpen={true}inline/>@@ -109,7 +112,7 @@ const meta: Meta<StoryArgs> = {<SubscriptionsModal{...(props as SubscriptionsModalProps)}closeModal={() => setModalOpen(false)}- insightShortId={insightShortIdRef.current}+ insightShortId={insightShortId}isOpen={modalOpen}/></div>@@ -151,3 +154,23 @@ export const SubscriptionsNewFreeUnderLimit: Story = {export const SubscriptionsNewFreeAtLimit: Story = {args: { subscriptionId: 'new', freeTierSubscriptionCount: 5 },}++// Tabbed overview (feature flag on), dashboard context: This dashboard / Insights / AI prompt reports tabs.+export const SubscriptionsTabbed: Story = {+ parameters: {+ featureFlags: {+ [FEATURE_FLAGS.SUBSCRIPTION_TABBED_OVERVIEW]: 'test',+ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: true,+ },+ },+ args: {+ dashboard: {+ id: 1,+ name: 'Weekly metrics',+ tiles: [+ { id: 1, insight: { id: 11, short_id: 'ins11' as InsightShortId } },+ { id: 2, insight: { id: 12, short_id: 'ins12' as InsightShortId } },+ ],+ } as unknown as DashboardType,+ },+}diff --git a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.tsx b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.tsxindex f281010e373d..ab7a2034b4b5 100644--- a/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal.tsx@@ -1,6 +1,10 @@import { useActions, useValues } from 'kea'import { router } from 'kea-router'+import posthog from 'posthog-js'+import { useEffect, useState } from 'react'+import { FEATURE_FLAGS } from 'lib/constants'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { LemonModal } from 'lib/lemon-ui/LemonModal'import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'import { userLogic } from 'scenes/userLogic'@@ -10,6 +14,7 @@ import { DashboardType, InsightShortId } from '~/types'import { SubscriptionBaseProps, urlForSubscription, urlForSubscriptions } from './utils'import { EditSubscription } from './views/EditSubscription'import { ManageSubscriptions } from './views/ManageSubscriptions'+import { SubscriptionTabKey, TabbedManageSubscriptions } from './views/TabbedManageSubscriptions'export interface SubscriptionsModalProps {isOpen: boolean@@ -28,6 +33,20 @@ export function SubscriptionsModal(props: SubscriptionsModalProps): JSX.Elementconst dashboardId = dashboard?.idconst baseProps: SubscriptionBaseProps = { insightShortId, dashboardId }+ // Experiment-gated: the flag resolves to a variant string, so only the test variant gets the new UI.+ const useTabbedOverview = useFeatureFlag('SUBSCRIPTION_TABBED_OVERVIEW', 'test')+ // Owned here (not in the tabbed view) so the selected tab survives the edit round-trip,+ // during which the tabbed view unmounts.+ const [activeTab, setActiveTab] = useState<SubscriptionTabKey>('resource')++ useEffect(() => {+ if (isOpen) {+ // Records which overview variant the user saw, so the tabbed-overview experiment is measurable.+ posthog.capture('subscription_modal_opened', {+ tabbed_overview_variant: posthog.getFeatureFlag(FEATURE_FLAGS.SUBSCRIPTION_TABBED_OVERVIEW) ?? null,+ })+ }+ }, [isOpen])if (userLoading) {return <Spinner className="text-2xl" />@@ -43,11 +62,21 @@ export function SubscriptionsModal(props: SubscriptionsModalProps): JSX.Elementdata-attr={dataAttr}>{!subscriptionId ? (- <ManageSubscriptions- {...baseProps}- onCancel={closeModal}- onSelect={(id) => push(urlForSubscription(id, baseProps))}- />+ useTabbedOverview ? (+ <TabbedManageSubscriptions+ {...baseProps}+ activeTab={activeTab}+ onChangeTab={setActiveTab}+ onCancel={closeModal}+ onSelect={(id) => push(urlForSubscription(id, baseProps))}+ />+ ) : (+ <ManageSubscriptions+ {...baseProps}+ onCancel={closeModal}+ onSelect={(id) => push(urlForSubscription(id, baseProps))}+ />+ )) : (<EditSubscriptionid={subscriptionId}diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.tsindex 5238a21812b9..a503bd011a8a 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts@@ -88,6 +88,8 @@ describe('subscriptionLogic', () => {start_date: '2022-01-01T00:09:00',byweekday: ['wednesday'],bysetpos: 1,+ // write-only on the API, so the edit form defaults it on to match the create flow+ send_test_now: true,})})diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.tsindex cbbb6a139c74..e8187d1f059c 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts@@ -121,6 +121,7 @@ const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {summary_enabled: false,summary_prompt_guide: '',ai_prompt_config: { window: { mode: 'since_last_sent' } },+ send_test_now: true,}export interface SubscriptionLogicProps extends SubscriptionBaseProps {@@ -181,6 +182,9 @@ export const subscriptionLogic = kea<subscriptionLogicType>([// so the analysis window select renders the effective default instead of empty.return {...subscription,+ // Write-only, so never present on the API response: default the edit form's+ // "Send a test run now" toggle to on, matching the create flow.+ send_test_now: true,ai_prompt_config: {...subscription.ai_prompt_config,window: {@@ -257,8 +261,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([// If a subscriptionsLogic for this insight/dashboard is mounted already, refresh both// its resource-scoped list and the AI subscriptions section so new entries show upconst mountedSubscriptionsLogic = subscriptionsLogic.findMounted(props)- mountedSubscriptionsLogic?.actions.loadSubscriptions()- mountedSubscriptionsLogic?.actions.loadAiSubscriptions()+ mountedSubscriptionsLogic?.actions.loadAllSubscriptions()actions.loadSubscriptionSuccess(updatedSub)actions.loadSummaryQuota()lemonToast.success(`Subscription saved.`)diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.test.tsindex 0500b98a43a9..1e01e34fc415 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.test.ts@@ -54,9 +54,11 @@ describe('subscriptionsLogic', () => {let logic: ReturnType<typeof subscriptionsLogic.build>let subscriptions: SubscriptionType[] = []let aiSubscriptions: SubscriptionType[] = []+ let tileSubscriptions: SubscriptionType[] = []beforeEach(async () => {subscriptions = [fixtureSubscriptionResponse(1), fixtureSubscriptionResponse(2)]aiSubscriptions = [fixtureSubscriptionResponse(10, { resource_type: 'ai_prompt', prompt: 'Weekly report' })]+ tileSubscriptions = [fixtureSubscriptionResponse(20)]useMocks({get: {'/api/environments/:team_id/insights/1': fixtureInsightResponse(1),@@ -69,13 +71,16 @@ describe('subscriptionsLogic', () => {'/api/environments/:team_id/subscriptions': ({ request }) => {const url = new URL(request.url)- const insightId = url.searchParams.get('insight')+ const insightIds = url.searchParams.get('insights')?.split(',') ?? []+ const dashboardTiles = url.searchParams.get('dashboard_tiles')const resourceType = url.searchParams.get('resource_type')let results: SubscriptionType[] = []if (resourceType === 'ai_prompt') {results = aiSubscriptions- } else if (insightId === Insight2) {+ } else if (dashboardTiles === '9') {+ results = tileSubscriptions+ } else if (insightIds.includes(Insight2)) {results = subscriptions}@@ -113,6 +118,23 @@ describe('subscriptionsLogic', () => {})})+ it('loads subscriptions on dashboard tiles via the server-side dashboard_tiles filter', async () => {+ logic = subscriptionsLogic({ dashboardId: 9 })+ logic.mount()++ await expectLogic(logic).toFinishListeners().toMatchValues({+ insightSubscriptions: tileSubscriptions,+ insightSubscriptionsLoading: false,+ })+ })++ it('does not load tile subscriptions outside a dashboard context', async () => {+ await expectLogic(logic).toFinishListeners().toMatchValues({+ insightSubscriptions: [],+ insightSubscriptionsLoading: false,+ })+ })+it('does not load AI subscriptions when the flag is off', async () => {await expectLogic(logic).toFinishListeners().toMatchValues({aiSubscriptions: [],diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.tsindex 372240234aef..58afb7d8cbb5 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionsLogic.ts@@ -12,16 +12,17 @@ import { SubscriptionResourceTypes, SubscriptionType } from '~/types'import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'import type { subscriptionsLogicType } from './subscriptionsLogicType'import { toggleSubscriptionEnabled } from './toggleSubscriptionEnabled'-import { SubscriptionBaseProps } from './utils'+import { SubscriptionsLogicProps } from './utils'export const subscriptionsLogic = kea<subscriptionsLogicType>([path(['lib', 'components', 'Subscriptions', 'subscriptionsLogic']),- props({} as SubscriptionBaseProps),+ props({} as SubscriptionsLogicProps),key(({ insightShortId, dashboardId }) =>insightShortId ? `insight-${insightShortId}` : dashboardId ? `dashboard-${dashboardId}` : 'subscriptions'),connect({ values: [featureFlagLogic, ['featureFlags']] }),actions({+ loadAllSubscriptions: true,deleteSubscription: (id: number) => ({ id }),deliverSubscription: (id: number) => ({ id }),deliverSubscriptionSuccess: true,@@ -44,7 +45,7 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([const insightId = props.insightShortId ? await getInsightId(props.insightShortId) : undefinedconst response = await api.subscriptions.list({dashboardId: props.dashboardId,- insightId: insightId,+ insights: insightId ? [insightId] : undefined,})breakpoint?.()return response.results@@ -65,6 +66,20 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([return response.results},},+ // Subscriptions on the dashboard's insight tiles. The backend resolves the tile set from+ // dashboardId, so the count doesn't depend on the dashboard's tiles being loaded client-side.+ insightSubscriptions: {+ __default: [] as SubscriptionType[],+ loadInsightSubscriptions: async (_?: any, breakpoint?: BreakPointFunction) => {+ if (!props.dashboardId) {+ return []+ }+ breakpoint?.()+ const response = await api.subscriptions.list({ dashboardTiles: props.dashboardId })+ breakpoint?.()+ return response.results+ },+ },})),reducers({@@ -74,6 +89,9 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([aiSubscriptions: {deleteSubscription: (state, { id }) => state.filter((a) => a.id !== id),},+ insightSubscriptions: {+ deleteSubscription: (state, { id }) => state.filter((a) => a.id !== id),+ },deliveringSubscriptionId: [null as number | null,{@@ -93,13 +111,17 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([}),listeners(({ actions }) => ({+ loadAllSubscriptions: () => {+ actions.loadSubscriptions()+ actions.loadAiSubscriptions()+ actions.loadInsightSubscriptions()+ },deleteSubscription: async ({ id }) => {await deleteWithUndo({endpoint: api.subscriptions.determineDeleteEndpoint(),object: { name: 'Subscription', id },callback: () => {- actions.loadSubscriptions()- actions.loadAiSubscriptions()+ actions.loadAllSubscriptions()},})},@@ -120,13 +142,11 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([}},setSubscriptionEnabledSuccess: () => {- actions.loadSubscriptions()- actions.loadAiSubscriptions()+ actions.loadAllSubscriptions()},})),afterMount(({ actions }) => {- actions.loadSubscriptions()- actions.loadAiSubscriptions()+ actions.loadAllSubscriptions()}),])diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsxindex b9e76af1dbd8..1a63cd47c506 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx@@ -3,6 +3,7 @@ import { RRule } from 'rrule'import { IconLetter } from '@posthog/icons'import { LemonSelectOption, LemonSelectOptionLeaf, LemonSelectOptions } from '@posthog/lemon-ui'+import { dayjs } from 'lib/dayjs'import { IconSlack } from 'lib/lemon-ui/icons'import { range } from 'lib/utils/arrays'import { urls } from 'scenes/urls'@@ -17,6 +18,12 @@ export interface SubscriptionBaseProps {insightShortId?: InsightShortId}+export type SubscriptionsLogicProps = SubscriptionBaseProps++export function formatNextDeliveryDate(date: string | Date): string {+ return dayjs(date).format('ddd, MMM D [at] HH:mm')+}+export const urlForSubscriptions = ({ dashboardId, insightShortId }: SubscriptionBaseProps): string => {if (insightShortId) {return urls.insightSubcriptions(insightShortId)diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsxindex 84d7d4509967..31db80da5b2c 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx@@ -46,6 +46,7 @@ import {bysetposOptions,frequencyOptionsPlural,frequencyOptionsSingular,+ formatNextDeliveryDate,getAiSubscriptionGate,getNextDeliveryDate,intervalOptions,@@ -741,67 +742,94 @@ function EditSubscriptionForm({</div>{nextDeliveryDate && (<div className="text-xs text-secondary mt-1">- Next delivery: {dayjs(nextDeliveryDate).format('ddd, MMM D [at] HH:mm')}+ Next delivery: {formatNextDeliveryDate(nextDeliveryDate)}</div>)}</div>{/*- * AI-prompt subscriptions are themselves an LLM-generated report —- * appending an insight-style "automatic AI summary" on top would be- * a summary of a summary. Hide the toggle entirely for AI subs.+ * Delivery options: the AI-summary toggle is hidden for AI-prompt subs, which are+ * themselves an LLM report — a summary of a summary. The test-run toggle always+ * renders; it is disabled (with a reason) while the subscription is disabled.*/}- {!isAiPrompt && (- <>- <LemonField name="summary_enabled">- {({ value, onChange }) => (- <AIConsentPopoverWrapper>- <LemonSwitch- checked={value}- onChange={onChange}- bordered- label="Include an automatic AI summary"- fullWidth- disabledReason={- !dataProcessingAccepted && !value- ? 'Your organization needs to approve AI data processing before enabling AI summaries'- : summaryQuota?.at_limit && !value- ? `Plan limit reached (${summaryQuota.limit} active AI summaries). See details below.`- : undefined- }+ <div className="flex flex-col gap-2">+ <LemonLabel className="mb-2">Settings</LemonLabel>+ {!isAiPrompt && (+ <>+ <LemonField name="summary_enabled">+ {({ value, onChange }) => (+ <AIConsentPopoverWrapper>+ <LemonSwitch+ checked={value}+ onChange={onChange}+ bordered+ label="Include an automatic AI summary"+ fullWidth+ disabledReason={+ !dataProcessingAccepted && !value+ ? 'Your organization needs to approve AI data processing before enabling AI summaries'+ : summaryQuota?.at_limit && !value+ ? `Plan limit reached (${summaryQuota.limit} active AI summaries). See details below.`+ : undefined+ }+ />+ </AIConsentPopoverWrapper>+ )}+ </LemonField>++ {summaryQuota?.at_limit &&+ !subscription.summary_enabled &&+ summaryQuota.limit !== null && (+ <UsageLimitPaywall+ title="AI summary limit reached"+ description="Disable an existing AI summary or upgrade your plan to add more."+ limit={summaryQuota.limit}+ currentUsage={summaryQuota.active_count}+ unit="active AI summaries on your plan"/>- </AIConsentPopoverWrapper>+ )}++ {subscription.summary_enabled && (+ <FlaggedFeature flag={FEATURE_FLAGS.SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE}>+ <LemonField+ name="summary_prompt_guide"+ label="Context for the AI summary"+ showOptional+ >+ <LemonTextArea+ placeholder="e.g. This is a daily revenue health check - focus on revenue drop-off and churn signals"+ maxLength={500}+ />+ </LemonField>+ </FlaggedFeature>)}- </LemonField>+ </>+ )}- {summaryQuota?.at_limit &&- !subscription.summary_enabled &&- summaryQuota.limit !== null && (- <UsageLimitPaywall- title="AI summary limit reached"- description="Disable an existing AI summary or upgrade your plan to add more."- limit={summaryQuota.limit}- currentUsage={summaryQuota.active_count}- unit="active AI summaries on your plan"+ <div>+ <LemonField name="send_test_now">+ {({ value, onChange }) => (+ <LemonSwitch+ checked={subscription?.enabled === false ? false : value}+ onChange={onChange}+ bordered+ fullWidth+ label="Send a test run now"+ disabledReason={+ subscription?.enabled === false+ ? 'This subscription is disabled — re-enable it to send a test run'+ : undefined+ }/>)}-- {subscription.summary_enabled && (- <FlaggedFeature flag={FEATURE_FLAGS.SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE}>- <LemonField- name="summary_prompt_guide"- label="Context for the AI summary"- showOptional- >- <LemonTextArea- placeholder="e.g. This is a daily revenue health check - focus on revenue drop-off and churn signals"- maxLength={500}- />- </LemonField>- </FlaggedFeature>- )}- </>- )}+ </LemonField>+ <p className="text-xs text-secondary mt-1 mb-0">+ On save we send this report once to the destination above, so you can confirm it+ looks right. Turn this off to wait for the next scheduled delivery+ {nextDeliveryDate ? ` (${formatNextDeliveryDate(nextDeliveryDate)})` : ''}.+ </p>+ </div>+ </div>{insightShortId && !isAiPrompt && (<div>diff --git a/products/subscriptions/frontend/components/Subscriptions/views/ManageSubscriptions.tsx b/products/subscriptions/frontend/components/Subscriptions/views/ManageSubscriptions.tsxindex f3f8119bf85c..12149a07824e 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/ManageSubscriptions.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/ManageSubscriptions.tsx@@ -3,7 +3,6 @@ import { useActions, useValues } from 'kea'import { IconEllipsis } from '@posthog/icons'import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'-import { dayjs } from 'lib/dayjs'import { IconSlack } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonModal } from 'lib/lemon-ui/LemonModal'@@ -17,7 +16,7 @@ import { SubscriptionResourceTypes, SubscriptionType } from '~/types'import { isSubscriptionEnabled } from '../../../scenes/components/SubscriptionsTable'import { subscriptionsLogic } from '../subscriptionsLogic'-import { SubscriptionBaseProps } from '../utils'+import { SubscriptionBaseProps, formatNextDeliveryDate } from '../utils'const PROMPT_PREVIEW_MAX_CHARS = 80// AI subscriptions are supplementary context in this modal, so only a few are shown inline —@@ -106,6 +105,9 @@ export function SubscriptionListItem({<div className="text-sm text-muted italic">{`"${aiPromptPreview}"`}</div></Tooltip>) : null}+ {subscription.resource_type === SubscriptionResourceTypes.Insight && subscription.resource_name ? (+ <div className="text-sm text-muted">{subscription.resource_name}</div>+ ) : null}<div className="text-sm text-text-3000">{capitalizeFirstLetter(subscription.summary)}{selectedInsightsCount@@ -118,7 +120,7 @@ export function SubscriptionListItem({</LemonTag>) : subscription.next_delivery_date ? (<div className="text-xs text-secondary">- Next delivery: {dayjs(subscription.next_delivery_date).format('ddd, MMM D [at] HH:mm')}+ Next delivery: {formatNextDeliveryDate(subscription.next_delivery_date)}</div>) : null}</div>diff --git a/products/subscriptions/frontend/components/Subscriptions/views/TabbedManageSubscriptions.tsx b/products/subscriptions/frontend/components/Subscriptions/views/TabbedManageSubscriptions.tsxnew file mode 100644index 000000000000..5340f8276562--- /dev/null+++ b/products/subscriptions/frontend/components/Subscriptions/views/TabbedManageSubscriptions.tsx@@ -0,0 +1,194 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { LemonModal } from 'lib/lemon-ui/LemonModal'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'+import { PaginationControl, usePagination } from 'lib/lemon-ui/PaginationControl'+import { urls } from 'scenes/urls'++import { SubscriptionType } from '~/types'++import { isSubscriptionEnabled } from '../../../scenes/components/SubscriptionsTable'+import { subscriptionsLogic } from '../subscriptionsLogic'+import { SubscriptionsLogicProps } from '../utils'+import { SubscriptionListItem } from './ManageSubscriptions'++const PAGE_SIZE = 10++export type SubscriptionTabKey = 'resource' | 'insights' | 'ai'++interface SubscriptionTabConfig {+ key: SubscriptionTabKey+ label: string+ subscriptions: SubscriptionType[]+ loading: boolean+ emptyMessage: string+}++interface TabbedManageSubscriptionsProps extends SubscriptionsLogicProps {+ onCancel: () => void+ onSelect: (value: number | 'new') => void+ // Tab state is owned by the parent modal: this component unmounts while a subscription+ // is being edited, so local state would snap back to the first tab on return.+ activeTab: SubscriptionTabKey+ onChangeTab: (tab: SubscriptionTabKey) => void+}++interface SubscriptionTabListProps {+ logicProps: SubscriptionsLogicProps+ paginationId: string+ subscriptions: SubscriptionType[]+ loading: boolean+ emptyMessage: string+ onSelect: (id: number) => void+}++// Scrollable, paginated list of subscriptions for a single tab. Pagination keeps the modal+// usable when a project accumulates a large number of subscriptions.+function SubscriptionTabList({+ logicProps,+ paginationId,+ subscriptions,+ loading,+ emptyMessage,+ onSelect,+}: SubscriptionTabListProps): JSX.Element {+ const logic = subscriptionsLogic(logicProps)+ const { deliveringSubscriptionId, togglingEnabledId } = useValues(logic)+ const { deleteSubscription, deliverSubscription, setSubscriptionEnabled } = useActions(logic)+ // Disabled subscriptions sort to the bottom so active ones stay visible first.+ const orderedSubscriptions = useMemo(+ () => [...subscriptions].sort((a, b) => Number(isSubscriptionEnabled(b)) - Number(isSubscriptionEnabled(a))),+ [subscriptions]+ )+ const pagination = usePagination(orderedSubscriptions, { pageSize: PAGE_SIZE }, paginationId)++ if (loading && subscriptions.length === 0) {+ return (+ <div className="deprecated-space-y-2 py-2">+ <LemonSkeleton.Row repeat={3} />+ </div>+ )+ }++ if (subscriptions.length === 0) {+ return <div className="text-secondary py-6 text-center">{emptyMessage}</div>+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="max-h-[50vh] overflow-y-auto flex flex-col gap-2">+ {pagination.dataSourcePage.map((sub) => (+ <SubscriptionListItem+ key={sub.id}+ subscription={sub}+ onClick={() => onSelect(sub.id)}+ onDelete={() => deleteSubscription(sub.id)}+ onDeliver={() => deliverSubscription(sub.id)}+ onToggleEnabled={(enabled) => setSubscriptionEnabled(sub.id, enabled)}+ isDelivering={deliveringSubscriptionId === sub.id}+ isToggling={togglingEnabledId === sub.id}+ />+ ))}+ </div>+ <PaginationControl {...pagination} nouns={['subscription', 'subscriptions']} />+ </div>+ )+}++export function TabbedManageSubscriptions({+ insightShortId,+ dashboardId,+ onCancel,+ onSelect,+ activeTab,+ onChangeTab,+}: TabbedManageSubscriptionsProps): JSX.Element {+ const logicProps: SubscriptionsLogicProps = { insightShortId, dashboardId }+ const {+ subscriptions,+ subscriptionsLoading,+ insightSubscriptions,+ insightSubscriptionsLoading,+ aiSubscriptions,+ aiSubscriptionsLoading,+ } = useValues(subscriptionsLogic(logicProps))++ const isInsightContext = !!insightShortId++ // Tabs always render (including at count 0) so the available scopes stay discoverable.+ const tabConfigs: (SubscriptionTabConfig | false)[] = [+ {+ key: 'resource',+ label: isInsightContext ? 'This insight' : 'This dashboard',+ subscriptions,+ loading: subscriptionsLoading,+ emptyMessage: `No subscriptions for this ${isInsightContext ? 'insight' : 'dashboard'} yet.`,+ },+ !isInsightContext && {+ key: 'insights',+ label: 'Insights',+ subscriptions: insightSubscriptions,+ loading: insightSubscriptionsLoading,+ emptyMessage: "No subscriptions on this dashboard's insights yet.",+ },+ {+ key: 'ai',+ label: 'AI prompt reports',+ subscriptions: aiSubscriptions,+ loading: aiSubscriptionsLoading,+ emptyMessage: 'No AI prompt reports yet.',+ },+ ]+ const tabs: LemonTab<SubscriptionTabKey>[] = tabConfigs+ .filter((tab): tab is SubscriptionTabConfig => !!tab)+ .map(({ key, label, subscriptions, loading, emptyMessage }) => ({+ key,+ // No count during the initial fetch — "(0)" would read as empty rather than loading.+ label: loading && subscriptions.length === 0 ? label : `${label} (${subscriptions.length})`,+ content: (+ <SubscriptionTabList+ logicProps={logicProps}+ paginationId={key}+ subscriptions={subscriptions}+ loading={loading}+ emptyMessage={emptyMessage}+ onSelect={onSelect}+ />+ ),+ }))++ return (+ <>+ <LemonModal.Header>+ <h3>Subscriptions</h3>+ </LemonModal.Header>+ <LemonModal.Content>+ <LemonTabs+ activeKey={activeTab}+ onChange={onChangeTab}+ tabs={tabs}+ data-attr="manage-subscriptions-tabs"+ rightSlotClassName="bg-transparent"+ rightSlot={+ <LemonButton type="primary" onClick={() => onSelect('new')} data-attr="add-subscription">+ Add subscription+ </LemonButton>+ }+ />+ </LemonModal.Content>+ <LemonModal.Footer>+ <div className="flex-1">+ <LemonButton type="tertiary" to={urls.subscriptions()}>+ View all subscriptions+ </LemonButton>+ </div>+ <LemonButton type="secondary" onClick={onCancel}>+ Close+ </LemonButton>+ </LemonModal.Footer>+ </>+ )+}diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex fe14bc25b021..636acd6b642b 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -273,6 +273,8 @@ export interface SubscriptionApi {* @nullable*/invite_message?: string | null+ /** Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected. */+ send_test_now?: boolean/** Whether to attach an AI-generated summary to each delivery (insight and dashboard subscriptions only). Requires the organization to have approved AI data processing, and is subject to the org's active-summary cap and AI credit budget; otherwise the write is rejected. Not applicable to prompt subscriptions, which are themselves AI-generated. */summary_enabled?: boolean/**@@ -419,6 +421,8 @@ export interface PatchedSubscriptionApi {* @nullable*/invite_message?: string | null+ /** Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected. */+ send_test_now?: boolean/** Whether to attach an AI-generated summary to each delivery (insight and dashboard subscriptions only). Requires the organization to have approved AI data processing, and is subject to the org's active-summary cap and AI credit budget; otherwise the write is rejected. Not applicable to prompt subscriptions, which are themselves AI-generated. */summary_enabled?: boolean/**@@ -550,10 +554,18 @@ export type SubscriptionsListParams = {* Filter by dashboard ID.*/dashboard?: number+ /**+ * Filter to subscriptions on insights that are tiles of the given dashboard ID.+ */+ dashboard_tiles?: number/*** Filter by insight ID.*/insight?: number+ /**+ * Filter by a comma-separated list of insight IDs.+ */+ insights?: string/*** Number of results to return per page.*/diff --git a/products/subscriptions/frontend/generated/api.zod.ts b/products/subscriptions/frontend/generated/api.zod.tsindex c3835fe7bab8..42e77f65e40b 100644--- a/products/subscriptions/frontend/generated/api.zod.ts+++ b/products/subscriptions/frontend/generated/api.zod.ts@@ -157,6 +157,12 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.string().nullish().describe('Optional message included in the invitation email when adding new recipients.'),+ send_test_now: zod+ .boolean()+ .optional()+ .describe(+ 'Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected.'+ ),summary_enabled: zod.boolean().optional()@@ -321,6 +327,12 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod.string().nullish().describe('Optional message included in the invitation email when adding new recipients.'),+ send_test_now: zod+ .boolean()+ .optional()+ .describe(+ 'Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected.'+ ),summary_enabled: zod.boolean().optional()@@ -492,6 +504,12 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.string().nullish().describe('Optional message included in the invitation email when adding new recipients.'),+ send_test_now: zod+ .boolean()+ .optional()+ .describe(+ 'Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected.'+ ),summary_enabled: zod.boolean().optional()diff --git a/products/subscriptions/mcp/tools.yaml b/products/subscriptions/mcp/tools.yamlindex 859da64b1d9c..cf47a45f0d4c 100644--- a/products/subscriptions/mcp/tools.yaml+++ b/products/subscriptions/mcp/tools.yaml@@ -174,6 +174,7 @@ tools:- resource_name- insight_short_id- invite_message+ - send_test_nowsubscriptions-retrieve:operation: subscriptions_retrieveenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f646451262b2..d37fb4e2cd90 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -36369,6 +36369,8 @@ export namespace Schemas {* @nullable*/invite_message?: string | null;+ /** Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected. */+ send_test_now?: boolean;/** Whether to attach an AI-generated summary to each delivery (insight and dashboard subscriptions only). Requires the organization to have approved AI data processing, and is subject to the org's active-summary cap and AI credit budget; otherwise the write is rejected. Not applicable to prompt subscriptions, which are themselves AI-generated. */summary_enabled?: boolean;/**@@ -43562,6 +43564,8 @@ export namespace Schemas {* @nullable*/invite_message?: string | null;+ /** Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected. */+ send_test_now?: boolean;/** Whether to attach an AI-generated summary to each delivery (insight and dashboard subscriptions only). Requires the organization to have approved AI data processing, and is subject to the org's active-summary cap and AI credit budget; otherwise the write is rejected. Not applicable to prompt subscriptions, which are themselves AI-generated. */summary_enabled?: boolean;/**@@ -63795,10 +63799,18 @@ export namespace Schemas {* Filter by dashboard ID.*/dashboard?: number;+ /**+ * Filter to subscriptions on insights that are tiles of the given dashboard ID.+ */+ dashboard_tiles?: number;/*** Filter by insight ID.*/insight?: number;+ /**+ * Filter by a comma-separated list of insight IDs.+ */+ insights?: string;/*** Number of results to return per page.*/@@ -71658,10 +71670,18 @@ export namespace Schemas {* Filter by dashboard ID.*/dashboard?: number;+ /**+ * Filter to subscriptions on insights that are tiles of the given dashboard ID.+ */+ dashboard_tiles?: number;/*** Filter by insight ID.*/insight?: number;+ /**+ * Filter by a comma-separated list of insight IDs.+ */+ insights?: string;/*** Number of results to return per page.*/diff --git a/services/mcp/src/generated/subscriptions/api.ts b/services/mcp/src/generated/subscriptions/api.tsindex 98640e6b148f..3e7aa5eaaddc 100644--- a/services/mcp/src/generated/subscriptions/api.ts+++ b/services/mcp/src/generated/subscriptions/api.ts@@ -19,7 +19,12 @@ export const SubscriptionsListParams = /* @__PURE__ */ zod.object({export const SubscriptionsListQueryParams = /* @__PURE__ */ zod.object({created_by: zod.string().optional().describe('Filter by creator user UUID.'),dashboard: zod.number().optional().describe('Filter by dashboard ID.'),+ dashboard_tiles: zod+ .number()+ .optional()+ .describe('Filter to subscriptions on insights that are tiles of the given dashboard ID.'),insight: zod.number().optional().describe('Filter by insight ID.'),+ insights: zod.string().optional().describe('Filter by a comma-separated list of insight IDs.'),limit: zod.number().optional().describe('Number of results to return per page.'),offset: zod.number().optional().describe('The initial index from which to return the results.'),ordering: zod.string().optional().describe('Which field to use when ordering the results.'),@@ -182,6 +187,12 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.number().nullish().describe('ID of a connected Slack integration. Required when target_type is slack.'),+ send_test_now: zod+ .boolean()+ .optional()+ .describe(+ 'Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected.'+ ),summary_enabled: zod.boolean().optional()diff --git a/services/mcp/src/tools/generated/subscriptions.ts b/services/mcp/src/tools/generated/subscriptions.tsindex 360ed7971c07..9d59de4c48c6 100644--- a/services/mcp/src/tools/generated/subscriptions.ts+++ b/services/mcp/src/tools/generated/subscriptions.ts@@ -77,6 +77,9 @@ const subscriptionsCreate = (): ToolBase<typeof SubscriptionsCreateSchema, Schemif (params.integration_id !== undefined) {body['integration_id'] = params.integration_id}+ if (params.send_test_now !== undefined) {+ body['send_test_now'] = params.send_test_now+ }if (params.summary_enabled !== undefined) {body['summary_enabled'] = params.summary_enabled}@@ -187,7 +190,9 @@ const subscriptionsList = (): ToolBase<query: {created_by: params.created_by,dashboard: params.dashboard,+ dashboard_tiles: params.dashboard_tiles,insight: params.insight,+ insights: params.insights,limit: params.limit,offset: params.offset,ordering: params.ordering,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.jsonindex 5f98195113a6..4e2bfd746b98 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json@@ -154,6 +154,10 @@],"description": "Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."},+ "send_test_now": {+ "description": "Whether to immediately deliver the subscription once on save so the editor can confirm it looks right. Defaults to true on create. When omitted on update, a delivery is sent only if the edit changed what gets delivered (recipient, channel, source) or re-enabled the subscription. The recurring schedule is unaffected.",+ "type": "boolean"+ },"start_date": {"description": "When to start delivering (ISO 8601 datetime).","format": "date-time",diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.jsonindex 46516e156cfd..c7c00e863a71 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json@@ -9,10 +9,18 @@"description": "Filter by dashboard ID.","type": "number"},+ "dashboard_tiles": {+ "description": "Filter to subscriptions on insights that are tiles of the given dashboard ID.",+ "type": "number"+ },"insight": {"description": "Filter by insight ID.","type": "number"},+ "insights": {+ "description": "Filter by a comma-separated list of insight IDs.",+ "type": "string"+ },"limit": {"description": "Number of results to return per page.","type": "number"