: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): show ai summaries on their dashboard or insight (#114495)
posthog[bot]789d8ccd5648
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex d9e5abefa67d..3f5a7edbc8f5 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -5,9 +5,25 @@ from typing import Any, ClassVar, Optionalfrom django.conf import settingsfrom django.contrib.postgres.expressions import ArraySubquery+from django.contrib.postgres.fields import ArrayFieldfrom django.core.cache import cachefrom django.db import transaction-from django.db.models import CharField, Manager, Prefetch, Q, QuerySet, Value+from django.db.models import (+ BigIntegerField,+ BooleanField,+ CharField,+ F,+ Func,+ JSONField,+ Manager,+ OuterRef,+ Prefetch,+ Q,+ QuerySet,+ Subquery,+ TextField,+ Value,+)from django.db.models.functions import Cast, Concatfrom django.http import HttpRequest, JsonResponsefrom django.shortcuts import get_object_or_404@@ -61,7 +77,7 @@ from products.exports.backend.models.subscription import (attribute_subscription_saves,unsubscribe_using_token,)-from products.exports.backend.models.subscription_context import SubscriptionContext+from products.exports.backend.models.subscription_context import SubscriptionContext, context_reffrom products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (PROMPT_MAX_LENGTH as AI_PROMPT_MAX_LENGTH,PromptRejectedError,@@ -142,6 +158,7 @@ class _TargetLookups:live_context_insight_lookup: strlive_context_dashboard_lookup: strsnapshot_context_ref_overlap: str | None+ rendered_snapshot: str | Noneexported_insights: strno_selection: strinsights: Manager@@ -155,6 +172,7 @@ _SUBSCRIPTION_TARGETS = _TargetLookups(live_context_insight_lookup="contexts__insight_id__in",live_context_dashboard_lookup="contexts__dashboard_id__in",snapshot_context_ref_overlap=None,+ rendered_snapshot=None,exported_insights="dashboard_export_insights__id__in",no_selection="dashboard_export_insights__isnull",insights=Insight.objects,@@ -169,6 +187,7 @@ _DELIVERY_TARGETS = _TargetLookups(live_context_insight_lookup="subscription__contexts__insight_id__in",live_context_dashboard_lookup="subscription__contexts__dashboard_id__in",snapshot_context_ref_overlap="context_refs__overlap",+ rendered_snapshot="content_snapshot",exported_insights="subscription__dashboard_export_insights__id__in",no_selection="subscription__dashboard_export_insights__isnull",insights=Insight.objects_including_soft_deleted,@@ -1184,7 +1203,7 @@ class SubscriptionWriteSerializer(serializers.ModelSerializer):@staticmethoddef _context_refs(identifiers: set[tuple[str, int]]) -> list[str]:- return sorted(f"{kind}:{identifier}" for kind, identifier in identifiers)+ return sorted(context_ref(kind, identifier) for kind, identifier in identifiers)@staticmethoddef _replace_contexts(instance: Subscription, contexts: list[dict[str, Insight | Dashboard]]) -> None:@@ -1487,6 +1506,26 @@ def _context_ref_subquery(kind: str, blocked_ids: QuerySet, *, id_field: str = "return ArraySubquery(references)+def _snapshot_renders_any_of(snapshot_field: str, json_path: str, target_ids: QuerySet) -> Func:+ return Func(+ F(snapshot_field),+ Func(Value(json_path), template="%(expressions)s::jsonpath", output_field=CharField()),+ Func(+ Cast(Value("ids"), output_field=TextField()),+ # An empty target set compiles to a bare NULL, which Postgres cannot type without the cast.+ Func(+ Cast(ArraySubquery(target_ids), output_field=ArrayField(BigIntegerField())),+ function="to_jsonb",+ output_field=JSONField(),+ ),+ function="jsonb_build_object",+ output_field=JSONField(),+ ),+ function="jsonb_path_exists",+ output_field=BooleanField(),+ )++def _viewable_subscription_filter(user_access_control: UserAccessControl, team_id: int) -> Q:return _target_filter(user_access_control, team_id, _SUBSCRIPTION_TARGETS)@@ -1540,12 +1579,20 @@ def _target_filter(user_access_control: UserAccessControl, team_id: int, targets})+ # The subscription can point somewhere else now, so also check what the delivery rendered.+ rendered_a_blocked_target = Q()+ if targets.rendered_snapshot is not None:+ rendered_a_blocked_target = _snapshot_renders_any_of(+ targets.rendered_snapshot, "$.insights[*] ? (@.id == $ids[*])", blocked_insights+ ) | _snapshot_renders_any_of(targets.rendered_snapshot, "$.dashboard ? (@.id == $ids[*])", blocked_dashboards)+return ~(targets_a_blocked_insight| targets_a_blocked_dashboard| exports_a_blocked_insight| renders_a_blocked_tile| references_a_blocked_context+ | rendered_a_blocked_target)@@ -1579,6 +1626,66 @@ def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> bool)+class SubscriptionSummariesQuerySerializer(serializers.Serializer):+ insight = serializers.IntegerField(+ required=False,+ min_value=1,+ help_text="Insight ID. Returns summaries from the subscriptions on this insight. Set either insight or dashboard.",+ )+ dashboard = serializers.IntegerField(+ required=False,+ min_value=1,+ help_text="Dashboard ID. Returns summaries from the subscriptions on this dashboard. Set either dashboard or insight.",+ )++ def validate(self, attrs: dict) -> dict:+ if ("insight" in attrs) == ("dashboard" in attrs):+ raise ValidationError("Set exactly one of insight or dashboard.")+ return attrs+++class SubscriptionSummarySerializer(serializers.ModelSerializer):+ subscription_title = serializers.CharField(+ source="subscription.title",+ allow_null=True,+ read_only=True,+ help_text="Title of the subscription that generated this summary. Null when the subscription has no title.",+ )+ period_start = serializers.DateTimeField(+ allow_null=True,+ read_only=True,+ help_text=(+ "Start of the period this summary covers: the time of the previous completed delivery of the same "+ "subscription. Null for the first delivery, which has no earlier data to compare with."+ ),+ )++ class Meta:+ model = SubscriptionDelivery+ fields = [+ "id",+ "subscription",+ "subscription_title",+ "target_type",+ "change_summary",+ "period_start",+ "created_at",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "id": {"help_text": "ID of the delivery that included this summary."},+ "subscription": {"help_text": "ID of the subscription that generated this summary."},+ "target_type": {"help_text": "Channel the summary was sent to: email, slack, or teams."},+ "change_summary": {"help_text": "AI-generated summary text included in the delivery."},+ "created_at": {"help_text": "When the delivery started. This is also the end of the covered period."},+ }+++class SubscriptionSummaryCursorPagination(CursorPagination):+ page_size = 20+ ordering = "-created_at"++@extend_schema_view(list=extend_schema(extensions={"x-product": "subscriptions"},@@ -1861,6 +1968,81 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mcache.set(cache_key, payload, SUMMARY_QUOTA_CACHE_TTL_SECONDS)return Response(payload)+ @extend_schema(+ extensions={"x-product": "subscriptions"},+ summary="List AI summaries for an insight or dashboard",+ description=(+ "Completed deliveries that include an AI summary, across every active subscription on one insight or "+ "dashboard, newest first. Requires viewer access to the insight or dashboard."+ ),+ parameters=[SubscriptionSummariesQuerySerializer],+ responses={200: SubscriptionSummarySerializer(many=True)},+ )+ @action(+ methods=["GET"],+ detail=False,+ url_path="summaries",+ required_scopes=["subscription:read"],+ pagination_class=SubscriptionSummaryCursorPagination,+ filter_backends=[],+ )+ def summaries(self, request, **kwargs):+ query = SubscriptionSummariesQuerySerializer(data=request.query_params)+ query.is_valid(raise_exception=True)+ if "insight" in query.validated_data:+ live_insights = [+ insight+ for insight in insights_including_soft_deleted_for_team(+ team_id=self.team_id, insight_ids=[query.validated_data["insight"]]+ )+ if not insight.deleted+ ]+ if not live_insights:+ raise exceptions.NotFound()+ source: Insight | Dashboard = live_insights[0]+ # A subscription can change its source, so also match the source in the delivery snapshot.+ source_filter = Q(subscription__insight_id=source.pk, content_snapshot__insights__0__id=source.pk)+ else:+ source = get_object_or_404(+ Dashboard.objects.filter(team_id=self.team_id), pk=query.validated_data["dashboard"]+ )+ source_filter = Q(subscription__dashboard_id=source.pk, content_snapshot__dashboard__id=source.pk)+ if not self.user_access_control.check_access_level_for_object(source, "viewer"):+ raise exceptions.PermissionDenied("You do not have access to this resource.")++ previous_delivery_at = (+ SubscriptionDelivery.objects.filter(+ subscription_id=OuterRef("subscription_id"),+ status=SubscriptionDelivery.Status.COMPLETED,+ content_snapshot__isnull=False,+ created_at__lt=OuterRef("created_at"),+ )+ .order_by("-created_at")+ .values("created_at")[:1]+ )+ visible_ids = (+ SubscriptionDelivery.objects.filter(+ source_filter,+ team_id=self.team_id,+ subscription__deleted=False,+ status=SubscriptionDelivery.Status.COMPLETED,+ change_summary__isnull=False,+ )+ .exclude(change_summary="")+ .filter(_viewable_delivery_filter(self.user_access_control, self.team_id))+ .values("id")+ )+ # An id subquery instead of DISTINCT lets Postgres compute period_start only for the rows on the page.+ deliveries = (+ SubscriptionDelivery.objects.filter(team_id=self.team_id, id__in=visible_ids)+ .select_related("subscription")+ # content_snapshot holds full query results, so load only the fields the serializer returns.+ .only("id", "subscription_id", "subscription__title", "target_type", "change_summary", "created_at")+ .annotate(period_start=Subquery(previous_delivery_at))+ )+ page = self.paginate_queryset(deliveries)+ return self.get_paginated_response(SubscriptionSummarySerializer(page, many=True).data)+@extend_schema(extensions={"x-product": "subscriptions"},request=None,diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex ba091c3ad97b..4bbe24d4b96f 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -2780,6 +2780,111 @@ class TestSubscriptionDeliveryAPI(APILicensedTest):str(d.id) for d in SubscriptionDelivery.objects.filter(subscription=self.subscription)}+ def test_summaries_list_completed_summaries_across_subscriptions_on_the_source(self):+ second_subscription = Subscription.objects.create(+ team=self.team,+ insight=self.insight,+ created_by=self.user,+ target_type="slack",+ target_value="C123|#general",+ frequency="daily",+ interval=1,+ start_date=datetime(2022, 1, 1, 0, 0, 0, tzinfo=UTC),+ title="Second Sub",+ )+ deleted_subscription = Subscription.objects.create(+ team=self.team,+ insight=self.insight,+ created_by=self.user,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ interval=1,+ start_date=datetime(2022, 1, 1, 0, 0, 0, tzinfo=UTC),+ deleted=True,+ )+ other_insight = Insight.objects.create(query=default_pageview_query(), team=self.team, created_by=self.user)+ other_subscription = Subscription.objects.create(+ team=self.team,+ insight=other_insight,+ created_by=self.user,+ target_type="email",+ target_value="[email protected]",+ frequency="daily",+ interval=1,+ start_date=datetime(2022, 1, 1, 0, 0, 0, tzinfo=UTC),+ )+ start = datetime(2026, 1, 1, tzinfo=UTC)++ def delivery(+ key: str, days: int, subscription: Subscription | None = None, insight: Insight | None = None, **kwargs+ ) -> SubscriptionDelivery:+ subscription = subscription or self.subscription+ sent_for_id = insight.id if insight else subscription.insight_id+ row = self._create_delivery(+ idempotency_key=key,+ subscription=subscription,+ content_snapshot={"insights": [{"id": sent_for_id}]},+ **kwargs,+ )+ SubscriptionDelivery.objects.filter(pk=row.pk).update(created_at=start + timedelta(days=days))+ return row++ first = delivery("first", 0, change_summary="First summary")+ delivery("failed", 1, status=SubscriptionDelivery.Status.FAILED, change_summary="Failed summary")+ delivery("no-summary", 2)+ delivery("empty-summary", 3, change_summary="")+ latest = delivery("latest", 7, change_summary="Latest summary")+ other_channel = delivery("second-sub", 5, subscription=second_subscription, change_summary="Slack summary")+ delivery("deleted-sub", 6, subscription=deleted_subscription, change_summary="Deleted summary")+ delivery("other-insight", 6, subscription=other_subscription, change_summary="Other summary")+ delivery("sent-before-source-change", 1, insight=other_insight, change_summary="Previous source summary")++ response = self.client.get(+ f"/api/projects/{self.team.id}/subscriptions/summaries/", {"insight": self.insight.id}+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ results = response.json()["results"]+ assert [row["id"] for row in results] == [str(latest.id), str(other_channel.id), str(first.id)]+ assert results[0]["change_summary"] == "Latest summary"+ assert results[0]["subscription_title"] == "Test Sub"+ assert results[0]["period_start"] == "2026-01-04T00:00:00Z"+ assert results[1]["subscription"] == second_subscription.id+ assert results[2]["period_start"] is None++ @parameterized.expand(+ [+ ("neither source", {}),+ ("both sources", {"insight": 1, "dashboard": 1}),+ ("non integer", {"insight": "abc"}),+ ]+ )+ def test_summaries_reject_an_invalid_source(self, _name, params):+ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/summaries/", params)++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()++ @parameterized.expand(+ [+ ("another team's dashboard", "dashboard", True, False),+ ("another team's insight", "insight", True, False),+ ("deleted insight", "insight", False, True),+ ]+ )+ def test_summaries_for_a_source_out_of_reach_are_not_found(self, _name, source_type, other_team, deleted):+ team = Team.objects.create(organization=self.organization, name="Other") if other_team else self.team+ if source_type == "dashboard":+ source_id = Dashboard.objects.create(team=team, name="Unreachable dashboard").id+ else:+ source_id = Insight.objects.create(+ query=default_pageview_query(), team=team, created_by=self.user, deleted=deleted+ ).id++ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/summaries/", {source_type: source_id})++ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()+class TestSubscriptionFreeTierAccess(APILicensedTest):# free-tier orgs can retrieve subscriptions and read deliveries without a premium gate.@@ -4173,8 +4278,12 @@ class TestSubscriptionObjectAccessControl(APILicensedTest):target_type="email",target_value="[email protected]",status=SubscriptionDelivery.Status.COMPLETED,- content_snapshot={"insights": [{"id": 1, "name": "Secret", "query_results": [[1, 2, 3]]}]},- **overrides,+ **{+ "content_snapshot": {+ "insights": [{"id": self.open_insight.id, "name": "Secret", "query_results": [[1, 2, 3]]}]+ },+ **overrides,+ },)def _rule(self, resource: str, *, obj=None, level: str = "none", for_member: bool = True, team=None) -> None:@@ -4344,6 +4453,30 @@ class TestSubscriptionObjectAccessControl(APILicensedTest):self._assert_visibility(subscription, sees_subscription=sees_subscription, sees_deliveries=sees_deliveries)+ def test_summaries_require_viewer_access_to_the_source(self):+ self._delivery_for(self._sub_on_a_restricted_dashboard(), change_summary="Private summary")++ response = self.client.get(+ f"/api/projects/{self.team.id}/subscriptions/summaries/", {"dashboard": self.restricted_dashboard.id}+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN, response.json()++ def test_summaries_hide_a_dashboard_delivery_that_renders_a_restricted_tile(self):+ dashboard = self._dashboard_with_tiles(self.open_insight, self.restricted_insight)+ self._delivery_for(+ self._subscription_for(dashboard=dashboard),+ change_summary="Covers a private tile",+ content_snapshot={"dashboard": {"id": dashboard.id}, "insights": []},+ )++ response = self.client.get(+ f"/api/projects/{self.team.id}/subscriptions/summaries/", {"dashboard": dashboard.id}+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["results"] == []+@parameterized.expand([("restricted insight", "restricted_insight"),@@ -4386,6 +4519,33 @@ class TestSubscriptionObjectAccessControl(APILicensedTest):self._assert_visibility(subscription, sees_subscription=True, sees_deliveries=False)+ @parameterized.expand(+ [+ ("a restricted insight", lambda self: {"insights": [{"id": self.restricted_insight.id}]}),+ (+ "a restricted dashboard",+ lambda self: {+ "dashboard": {"id": self.restricted_dashboard.id},+ "insights": [{"id": self.open_insight.id}],+ },+ ),+ (+ "a restricted tile on an open dashboard",+ lambda self: {+ "dashboard": {"id": self._dashboard_with_tiles(self.open_insight).id},+ "insights": [{"id": self.open_insight.id}, {"id": self.restricted_insight.id}],+ },+ ),+ ]+ )+ def test_historical_delivery_keeps_the_authorization_of_what_it_rendered_after_the_target_changes(+ self, _name, rendered_snapshot+ ):+ subscription = self._sub_on_an_open_insight()+ self._delivery_for(subscription, content_snapshot=rendered_snapshot(self))++ self._assert_visibility(subscription, sees_subscription=True, sees_deliveries=False)+@parameterized.expand([("restricted insight", "restricted_insight"),diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex faf9348b41ab..77f573c6b531 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7662,6 +7662,10 @@ snapshots:hash: v1.k794b7964.9d825454b80602e3cca17fa872553832e01b929728eb3b554b98a7f0d63b01be.Amp7jiLWQltIcWNKpEimC7DjTEsQ4cc1mtxoGU_hEFsproducts-subscriptions-subscription-delivery-history--with-expanded-summary--light:hash: v1.k794b7964.e8ea5acdf82c72e927990f4672e1615f9b8269abc31a3feb639fa9b993babad0.5j1v9u_2-7CyIDaD0INwHMOAarvZot8UsqYDMVc0UAE+ products-subscriptions-subscription-summaries--latest--dark:+ hash: v1.k794b7964.5bb39a9f65b10116e99b886107fc7c9a099063d5e50b734cad2fbf303b24a579.whmd0Wn5AbO58YH-a4mwp9WhnHStQP_JvjfWGSy_yVo+ products-subscriptions-subscription-summaries--latest--light:+ hash: v1.k794b7964.7ed4c1c38b2c94eb88b830211f11c1c2295583aef2637d82d3ac0a75ddd84fb8.JIQJzOL48ohEv_Z9rgLrAUVO5soYMewTOoMbm-pLAMEproducts-subscriptions-subscriptions-modal--dashboard-with-subscriptions--dark:hash: v1.k794b7964.c40534e6ed4ad299ed4b0317035ef2867ce1fa1dd9400dc05f63b58fafa2f3a8.uhuetA6HfBqWc8E72Mnwihnwg71M7zKnXlzl9FEAJmYproducts-subscriptions-subscriptions-modal--dashboard-with-subscriptions--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex bcdcc15a7824..4b4793440234 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -560,6 +560,7 @@ export const FEATURE_FLAGS = {STREAMLIT_APPS: 'streamlit-apps', // owner: @sakceSUBSCRIPTION_AI_PROMPT: 'ai-subscriptions', // owner: #team-analytics-platform, gates AI prompt-based subscriptionsSUBSCRIPTION_SLACK_GALLERY: 'subscription-slack-gallery', // owner: #team-analytics-platform, enables gallery delivery after the worker rollout completes+ SUBSCRIPTION_SOURCE_SUMMARIES: 'subscription-source-summaries', // owner: #team-analytics-platform, shows subscription AI summaries on their dashboard or insightSUBSCRIPTION_SUMMARY_COPY_EXPERIMENT: 'subscription-summary-copy-experiment',SURVEY_HEADLINE_SUMMARY: 'survey-headline-summary', // owner: @adboio #team-surveysSURVEYS_ERROR_TRACKING_CROSS_SELL: 'surveys-in-error-tracking', // owner: @adboio #team-surveysdiff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsxindex b54bdff98d4b..a1507c2f86ac 100644--- a/frontend/src/scenes/dashboard/Dashboard.tsx+++ b/frontend/src/scenes/dashboard/Dashboard.tsx@@ -28,6 +28,7 @@ import { ProductKey } from '~/queries/schema/schema-general'import { DashboardPlacement, DashboardType, DataColorThemeModel } from '~/types'import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'+import { SubscriptionSummaries } from 'products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaries'import { teamLogic } from '../teamLogic'import { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'@@ -202,6 +203,10 @@ function DashboardScene({<ScreenShotEditor screenshotKey={dashboardTileScreenshotKey(dashboard?.id)} />)}<DashboardEmbeddedShareButton dashboard={dashboard} placement={placement} />+ {/* Outside the tile-count branches: a dashboard can keep subscriptions and delivery history after its tiles are removed. */}+ {placement === DashboardPlacement.Dashboard && !!dashboard?.id && (+ <SubscriptionSummaries dashboardId={dashboard.id} className="mt-2 mb-2" />+ )}{dashboardFailedToLoad && !tiles?.length ? (<InsightErrorStatediff --git a/frontend/src/scenes/insights/InsightAsScene.tsx b/frontend/src/scenes/insights/InsightAsScene.tsxindex 76c96691a254..3ee441530ac1 100644--- a/frontend/src/scenes/insights/InsightAsScene.tsx+++ b/frontend/src/scenes/insights/InsightAsScene.tsx@@ -15,6 +15,7 @@ import { containsHogQLQuery, isBIVisualizationNode, isDataVisualizationNode, isIimport { InsightShortId, ItemMode } from '~/types'import { InsightHomeGuide } from 'products/product_analytics/frontend/insights/home/InsightHomeGuide'+import { SubscriptionSummaries } from 'products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaries'import { teamLogic } from '../teamLogic'import { InsightRetentionBanner } from './dataRetention/InsightRetentionBanner'@@ -102,6 +103,8 @@ export function InsightAsScene({ insightId, attachTo }: InsightAsSceneProps): JS{!isBIVisualizationNode(query) && <InsightQueryScanBanner insightProps={insightProps} />}+ {!isEditing && !!insight.id && <SubscriptionSummaries insightId={insight.id} />}+<SqlInsightFilters query={query} setQuery={setQuery}>{isDataVisualizationNode(query) && insightLoading ? (// Avoid painting the stale chart type during a reload (the query re-syncs in insightDataLogic).diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex dc7fb5a0bcd2..5cf9b446119c 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -39,6 +39,7 @@ from products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.models.subscription import Subscription, SubscriptionDelivery+from products.exports.backend.models.subscription_context import SubscriptionContextfrom products.exports.backend.tasks.failure_handler import ExcelColumnLimitExceededfrom products.exports.backend.temporal.subscriptions.activities import (_resolve_exportable_insights,@@ -1203,6 +1204,10 @@ async def test_create_export_assets_persists_insight_snapshots_to_delivery_conteasync def test_create_delivery_record_persists_row_and_idempotency_key_dedupes(team, user):insight = await sync_to_async(Insight.objects.create)(team=team, short_id="delrec01", name="Delivery record")subscription = await sync_to_async(create_subscription)(team=team, insight=insight, created_by=user)+ context_dashboard = await sync_to_async(Dashboard.objects.create)(team=team, name="Context dashboard")+ await sync_to_async(SubscriptionContext.objects.for_team(team.id).create)(+ team_id=team.id, subscription=subscription, dashboard=context_dashboard+ )env = ActivityEnvironment()inputs = CreateDeliveryRecordInputs(@@ -1226,6 +1231,7 @@ async def test_create_delivery_record_persists_row_and_idempotency_key_dedupes(tassert row.content_snapshot["total_insight_count"] == 0assert len(row.content_snapshot["insights"]) == 1assert row.content_snapshot["insights"][0]["short_id"] == "delrec01"+ assert row.context_refs == [f"dashboard:{context_dashboard.id}"]inputs_retry = CreateDeliveryRecordInputs(subscription_id=subscription.id,diff --git a/products/exports/backend/models/subscription_context.py b/products/exports/backend/models/subscription_context.pyindex cf023b26e017..bba803f61c92 100644--- a/products/exports/backend/models/subscription_context.py+++ b/products/exports/backend/models/subscription_context.py@@ -8,6 +8,10 @@ from posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDModel+def context_ref(kind: str, target_id: int) -> str:+ return f"{kind}:{target_id}"++class SubscriptionContext(TeamScopedRootMixin, UUIDModel):team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")subscription = models.ForeignKey("Subscription", on_delete=models.CASCADE, related_name="contexts")@@ -25,6 +29,14 @@ class SubscriptionContext(TeamScopedRootMixin, UUIDModel):)created_at = models.DateTimeField(auto_now_add=True)+ @property+ def ref(self) -> str:+ if self.dashboard_id is not None:+ return context_ref("dashboard", self.dashboard_id)+ if self.insight_id is not None:+ return context_ref("insight", self.insight_id)+ raise ValueError("A subscription context needs a dashboard or an insight.")+def has_target_for_team(self, team_id: int, *, include_deleted: bool) -> bool:if self.dashboard_id is not None:return (diff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.pyindex e0771f52e12c..79cd09e88582 100644--- a/products/exports/backend/temporal/subscriptions/activities.py+++ b/products/exports/backend/temporal/subscriptions/activities.py@@ -17,6 +17,7 @@ from posthog.sync import database_sync_to_asyncfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.models.subscription import Subscription, SubscriptionDelivery+from products.exports.backend.models.subscription_context import SubscriptionContextfrom products.exports.backend.temporal.subscriptions.ai_subscription.activities import _deliver_ai_subscriptionfrom products.exports.backend.temporal.subscriptions.delivery_common import (auto_disable_and_return,@@ -573,6 +574,10 @@ async def create_delivery_record(inputs: CreateDeliveryRecordInputs) -> uuid.UUI)content_snapshot = build_initial_content_snapshot(subscription)+ context_refs = sorted(+ context.ref+ for context in SubscriptionContext.objects.for_team(subscription.team_id).filter(subscription=subscription)+ )delivery, _created = SubscriptionDelivery.objects.get_or_create(idempotency_key=inputs.idempotency_key,@@ -585,6 +590,7 @@ async def create_delivery_record(inputs: CreateDeliveryRecordInputs) -> uuid.UUI"target_type": subscription.target_type,"target_value": subscription.recipient_label,"content_snapshot": content_snapshot,+ "context_refs": context_refs,"status": SubscriptionDelivery.Status.STARTING,},)diff --git a/products/exports/backend/temporal/subscriptions/llm_change_summary.py b/products/exports/backend/temporal/subscriptions/llm_change_summary.pyindex bc11bcb8716c..d00fc2dc9f54 100644--- a/products/exports/backend/temporal/subscriptions/llm_change_summary.py+++ b/products/exports/backend/temporal/subscriptions/llm_change_summary.py@@ -369,6 +369,18 @@ def _get_openai_client() -> OpenAI:return OpenAI(posthog_client=posthoganalytics.setup(), base_url=settings.OPENAI_BASE_URL, max_retries=3)+def _previous_states_rendered_in_current_delivery(+ previous_states: list[dict] | None,+ current_states: list[dict],+) -> list[dict] | None:+ # A summary must describe only what this delivery rendered, so the delivery access+ # check (which covers only the current snapshot's insights) also covers the summary.+ if not previous_states:+ return previous_states+ current_insight_ids = {state["insight_id"] for state in current_states}+ return [state for state in previous_states if state["insight_id"] in current_insight_ids]++def generate_change_summary(previous_states: list[dict] | None,current_states: list[dict],@@ -382,6 +394,8 @@ def generate_change_summary() -> str:team_id = team.id if team else 0+ previous_states = _previous_states_rendered_in_current_delivery(previous_states, current_states)+if previous_states:messages = build_prompt_messages(previous_states,diff --git a/products/exports/backend/temporal/subscriptions/snapshot_activities.py b/products/exports/backend/temporal/subscriptions/snapshot_activities.pyindex 54b6708b12d8..a76fc9e4bc53 100644--- a/products/exports/backend/temporal/subscriptions/snapshot_activities.py+++ b/products/exports/backend/temporal/subscriptions/snapshot_activities.py@@ -1,4 +1,5 @@import uuid+from datetime import datetimefrom typing import Anyimport temporalio.activity@@ -230,18 +231,17 @@ def _get_delivery_by_id(delivery_id: str) -> SubscriptionDelivery | None:return None-def _get_previous_delivery(subscription_id: int, exclude_delivery_id: str | None = None) -> SubscriptionDelivery | None:- qs = SubscriptionDelivery.objects.filter(- subscription_id=subscription_id,- status=SubscriptionDelivery.Status.COMPLETED,- content_snapshot__isnull=False,- ).order_by("-created_at")- if exclude_delivery_id:- try:- qs = qs.exclude(pk=uuid.UUID(exclude_delivery_id))- except ValueError:- pass- return qs.first()+def _get_previous_delivery(subscription_id: int, before: datetime) -> SubscriptionDelivery | None:+ return (+ SubscriptionDelivery.objects.filter(+ subscription_id=subscription_id,+ status=SubscriptionDelivery.Status.COMPLETED,+ content_snapshot__isnull=False,+ created_at__lt=before,+ )+ .order_by("-created_at")+ .first()+ )def _get_insight_query_kinds(insight_ids: list[int]) -> dict[int, str]:@@ -483,7 +483,7 @@ async def _run_snapshot_subscription_insights(inputs: SnapshotInsightsInputs) ->temporalio.activity.heartbeat("loading previous delivery")previous_delivery = await database_sync_to_async(_get_previous_delivery, thread_sensitive=False)(- inputs.subscription_id, exclude_delivery_id=inputs.delivery_id+ inputs.subscription_id, before=current_delivery.created_at)previous_states: list[dict] | None = Nonediff --git a/products/exports/backend/temporal/subscriptions/test_llm_change_summary.py b/products/exports/backend/temporal/subscriptions/test_llm_change_summary.pyindex 8469a1f20b4b..495d0f9864a2 100644--- a/products/exports/backend/temporal/subscriptions/test_llm_change_summary.py+++ b/products/exports/backend/temporal/subscriptions/test_llm_change_summary.py@@ -3,6 +3,8 @@ from types import SimpleNamespaceimport pytestfrom unittest.mock import MagicMock, patch+from parameterized import parameterized+from products.exports.backend.temporal.subscriptions.llm_change_summary import (_attach_images_to_user_message,build_initial_prompt_messages,@@ -730,6 +732,48 @@ class TestGenerateChangeSummary:assert captured["properties"]["ai_product"] == "subscriptions"assert captured["groups"] == {"project": "42", "instance": "https://us.posthog.com"}+ @parameterized.expand(+ [+ (+ "overlapping_insight_survives_the_filter",+ [+ _make_state(99, "Revenue", "total $999"),+ _make_state(1, "Pageviews", "avg 100/day"),+ ],+ [_make_state(1, "Pageviews", "avg 150/day", timestamp="2025-04-15T10:00:00Z")],+ ),+ (+ "no_overlap_falls_back_to_the_initial_prompt",+ [_make_state(99, "Revenue", "total $999")],+ [_make_state(1, "Pageviews", "avg 150/day", timestamp="2025-04-15T10:00:00Z")],+ ),+ ]+ )+ def test_previous_only_insights_stay_out_of_the_prompt(self, name, previous_states, current_states):+ with patch(+ "products.exports.backend.temporal.subscriptions.llm_change_summary._get_openai_client"+ ) as mock_get_client:+ mock_client = mock_get_client.return_value+ mock_client.chat.completions.create.return_value = _mock_openai_response("- ok")++ generate_change_summary(previous_states, current_states, team=None)++ messages = mock_client.chat.completions.create.call_args.kwargs["messages"]++ system_content = messages[0]["content"]+ user_content = messages[1]["content"]++ assert "Revenue" not in system_content+ assert "Revenue" not in user_content+ assert "$999" not in user_content++ if name == "overlapping_insight_survives_the_filter":+ assert "avg 100/day" in user_content+ assert "avg 150/day" in user_content+ else:+ assert "current state" in system_content+ assert "No previous data" not in user_content+class TestAnnotationsSection:def test_change_prompt_omits_annotations_block_when_empty(self):diff --git a/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py b/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.pyindex 3336fe464407..7cb14575e05c 100644--- a/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py+++ b/products/exports/backend/temporal/subscriptions/test_snapshot_ai_consent.py@@ -1,5 +1,5 @@import uuid-from datetime import datetime+from datetime import datetime, timedeltafrom zoneinfo import ZoneInfoimport pytest@@ -50,9 +50,17 @@ def _create_delivery(subscription: Subscription, content_snapshot: dict) -> Substeam=subscription.team,status=SubscriptionDelivery.Status.STARTING,content_snapshot=content_snapshot,+ # idempotency_key is unique; production sets it from the workflow id, tests need their own per row.+ idempotency_key=str(uuid.uuid4()),)+@sync_to_async+def _set_delivery_timing(delivery: SubscriptionDelivery, *, created_at: datetime, status: str) -> None:+ # created_at has auto_now_add=True, so it can only be backdated through an update(), not create().+ SubscriptionDelivery.objects.filter(pk=delivery.pk).update(created_at=created_at, status=status)++class _FakePhClient:"""In-memory stand-in for the real PostHog client used by `ph_scoped_capture`.@@ -139,6 +147,59 @@ async def test_runs_summary_when_org_has_approved_ai(team, user, monkeypatch):assert result.summary_text == "- Pageviews is trending up"+async def test_summary_compares_against_the_last_delivery_created_before_it(team, user, monkeypatch):+ subscription = await _create_subscription(team, user)+ await _set_ai_consent(subscription, approved=True)+ base_time = datetime(2024, 1, 1, tzinfo=ZoneInfo("UTC"))++ def _snapshot(insight_name: str) -> dict:+ return {+ "insights": [+ {+ "id": subscription.insight_id,+ "name": insight_name,+ "query_results": {"result": [{"label": insight_name, "data": [1, 2, 3]}]},+ }+ ]+ }++ d0 = await _create_delivery(subscription, _snapshot("D0 Insight"))+ d1 = await _create_delivery(subscription, _snapshot("Current Insight"))+ d2 = await _create_delivery(subscription, _snapshot("D2 Insight"))+ await _set_delivery_timing(d0, created_at=base_time, status=SubscriptionDelivery.Status.COMPLETED)+ await _set_delivery_timing(+ d1, created_at=base_time + timedelta(days=1), status=SubscriptionDelivery.Status.STARTING+ )+ # D2 is created after D1, so it must not be picked as "previous" even though it sorts+ # later than D0 by created_at.+ await _set_delivery_timing(+ d2, created_at=base_time + timedelta(days=2), status=SubscriptionDelivery.Status.COMPLETED+ )++ captured: dict = {}++ def fake_generate(previous_states, current_states, **kwargs):+ captured["previous_states"] = previous_states+ return "- summary"++ monkeypatch.setattr(+ "products.exports.backend.temporal.subscriptions.snapshot_activities.generate_change_summary",+ fake_generate,+ )++ await _run(+ SnapshotInsightsInputs(+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ delivery_id=str(d1.id),+ )+ )++ previous_states = captured.get("previous_states")+ assert previous_states is not None+ assert previous_states[0]["insight_name"] == "D0 Insight"++# A named function rather than a lambda because the fail-open param case needs to raise.def _raise_quota_lookup_error(*args, **kwargs):raise RuntimeError("quota cache unavailable")diff --git a/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaries.stories.tsx b/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaries.stories.tsxnew file mode 100644index 000000000000..0391ddf523d8--- /dev/null+++ b/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaries.stories.tsx@@ -0,0 +1,72 @@+import { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'++import { mswDecorator } from '~/mocks/browser'++import type { PaginatedSubscriptionSummaryListApi } from 'products/subscriptions/frontend/generated/api.schemas'++import { SubscriptionSummaries } from './SubscriptionSummaries'++const SUMMARIES: PaginatedSubscriptionSummaryListApi = {+ next: null,+ previous: null,+ results: [+ {+ id: 'summary-3',+ subscription: 11,+ subscription_title: 'Weekly growth review',+ target_type: 'slack',+ change_summary:+ 'Weekly signups rose from 1,204 to 1,388 (+15%). Activation held steady at 41%.\nPaid conversions fell from 92 to 81, mostly on the annual plan.',+ period_start: '2026-03-30T09:00:00Z',+ created_at: '2026-04-06T09:00:00Z',+ },+ {+ id: 'summary-2',+ subscription: 12,+ subscription_title: 'Daily metrics email',+ target_type: 'email',+ change_summary: 'Daily active users fell from 3,410 to 3,120 (-9%) after the weekend.',+ period_start: '2026-04-04T08:00:00Z',+ created_at: '2026-04-05T08:00:00Z',+ },+ {+ id: 'summary-1',+ subscription: 11,+ subscription_title: 'Weekly growth review',+ target_type: 'slack',+ change_summary: 'First summary for this dashboard. Weekly signups were 1,204.',+ period_start: null,+ created_at: '2026-03-30T09:00:00Z',+ },+ ],+}++const meta: Meta<typeof SubscriptionSummaries> = {+ component: SubscriptionSummaries,+ title: 'Products/Subscriptions/Subscription summaries',+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team_id/subscriptions/summaries/': SUMMARIES,+ },+ }),+ ],+ parameters: {+ mockDate: '2026-04-07',+ featureFlags: [FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES],+ },+}++export default meta++type Story = StoryObj<typeof SubscriptionSummaries>++export const Latest: Story = {+ render: () => (+ <div className="max-w-200">+ <SubscriptionSummaries dashboardId={1} />+ </div>+ ),+}diff --git a/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaries.tsx b/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaries.tsxnew file mode 100644index 000000000000..dad3d643ba55--- /dev/null+++ b/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaries.tsx@@ -0,0 +1,45 @@+import { useValues } from 'kea'++import { IconSparkles } from '@posthog/icons'+import { Link } from '@posthog/lemon-ui'++import { cn } from 'lib/utils/css-classes'+import { urls } from 'scenes/urls'++import { subscriptionSummariesLogic, type SubscriptionSummariesLogicProps } from './subscriptionSummariesLogic'+import { SubscriptionSummaryEntry } from './SubscriptionSummaryEntry'++interface SubscriptionSummariesProps extends SubscriptionSummariesLogicProps {+ className?: string+}++export function SubscriptionSummaries({ className, ...props }: SubscriptionSummariesProps): JSX.Element | null {+ const { latestSummary } = useValues(subscriptionSummariesLogic(props))++ // Most dashboards and insights have no summaries, so nothing renders until summaries exist.+ if (!latestSummary) {+ return null+ }++ return (+ <div+ className={cn('border rounded bg-surface-primary p-3 flex flex-col gap-2', className)}+ data-attr="subscription-summaries"+ >+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="flex items-center gap-2 font-semibold">+ <IconSparkles className="text-accent" />+ Latest AI summary+ </div>+ <Link+ to={urls.subscription(latestSummary.subscription)}+ className="text-xs"+ data-attr="subscription-summaries-delivery-history-link"+ >+ View delivery history+ </Link>+ </div>+ <SubscriptionSummaryEntry summary={latestSummary} />+ </div>+ )+}diff --git a/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaryEntry.tsx b/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaryEntry.tsxnew file mode 100644index 000000000000..5f965a86c367--- /dev/null+++ b/products/subscriptions/frontend/components/SubscriptionSummaries/SubscriptionSummaryEntry.tsx@@ -0,0 +1,41 @@+import { Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'++import type { SubscriptionApi, SubscriptionSummaryApi } from 'products/subscriptions/frontend/generated/api.schemas'++import { TARGET_TYPE_LABEL } from '../../scenes/components/subscriptionLabels'++const TIME_FORMAT = { formatDate: 'MMM D, YYYY', formatTime: 'h:mm A', timestampStyle: 'absolute' } as const++export function SubscriptionSummaryEntry({ summary }: { summary: SubscriptionSummaryApi }): JSX.Element {+ const channel = TARGET_TYPE_LABEL[summary.target_type as SubscriptionApi['target_type']] ?? summary.target_type+ return (+ <div className="flex flex-col gap-1 min-w-0">+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-secondary">+ <Link+ to={urls.subscription(summary.subscription)}+ className="truncate"+ data-attr="subscription-summary-subscription-link"+ >+ {summary.subscription_title || 'Untitled subscription'}+ </Link>+ <span>·</span>+ <span>{channel}</span>+ <span>·</span>+ {summary.period_start ? (+ <span>+ Changes from <TZLabel time={summary.period_start} {...TIME_FORMAT} /> to{' '}+ <TZLabel time={summary.created_at} {...TIME_FORMAT} />+ </span>+ ) : (+ <span>+ Sent <TZLabel time={summary.created_at} {...TIME_FORMAT} />+ </span>+ )}+ </div>+ <div className="whitespace-pre-wrap text-sm">{summary.change_summary}</div>+ </div>+ )+}diff --git a/products/subscriptions/frontend/components/SubscriptionSummaries/subscriptionSummariesLogic.test.ts b/products/subscriptions/frontend/components/SubscriptionSummaries/subscriptionSummariesLogic.test.tsnew file mode 100644index 000000000000..7b064badf672--- /dev/null+++ b/products/subscriptions/frontend/components/SubscriptionSummaries/subscriptionSummariesLogic.test.ts@@ -0,0 +1,93 @@+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { subscriptionsSummariesList } from 'products/subscriptions/frontend/generated/api'++import { subscriptionSummariesLogic } from './subscriptionSummariesLogic'++jest.mock('products/subscriptions/frontend/generated/api', () => ({+ subscriptionsSummariesList: jest.fn(),+}))++const mockSummariesList = subscriptionsSummariesList as jest.Mock++const summary = (id: string): Record<string, unknown> => ({+ id,+ subscription: 1,+ subscription_title: 'Weekly',+ target_type: 'email',+ change_summary: `Summary ${id}`,+ period_start: null,+ created_at: '2026-01-01T00:00:00Z',+})++describe('subscriptionSummariesLogic', () => {+ let logic: ReturnType<typeof subscriptionSummariesLogic.build>++ beforeEach(() => {+ initKeaTests()+ mockSummariesList.mockReset()+ mockSummariesList.mockResolvedValue({ next: null, previous: null, results: [summary('b'), summary('a')] })+ })++ afterEach(() => {+ logic?.unmount()+ })++ it.each([+ { flagEnabled: false, expectedSummaries: null, expectedLatest: null, expectedCalls: [] },+ {+ flagEnabled: true,+ expectedSummaries: [summary('b'), summary('a')],+ expectedLatest: summary('b'),+ expectedCalls: [[expect.any(String), { dashboard: 7 }]],+ },+ ])(+ 'loads summaries for the source only when the flag is enabled ($flagEnabled)',+ async ({ flagEnabled, expectedSummaries, expectedLatest, expectedCalls }) => {+ featureFlagLogic.actions.setFeatureFlags([], {+ [FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES]: flagEnabled,+ })+ logic = subscriptionSummariesLogic({ dashboardId: 7 })+ logic.mount()++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ summaries: expectedSummaries, latestSummary: expectedLatest })+ expect(mockSummariesList.mock.calls).toEqual(expectedCalls)+ }+ )++ it('loads summaries when the flag turns on after the component is already mounted', async () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES]: false })+ logic = subscriptionSummariesLogic({ dashboardId: 7 })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(mockSummariesList).not.toHaveBeenCalled()++ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES]: true })++ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ latestSummary: summary('b') })+ expect(mockSummariesList).toHaveBeenCalledTimes(1)+ })++ it('hides the latest summary once the flag turns off, so it also acts as a kill switch', async () => {+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES]: true })+ logic = subscriptionSummariesLogic({ dashboardId: 7 })+ logic.mount()+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ latestSummary: summary('b') })++ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES]: false })++ expectLogic(logic).toMatchValues({ latestSummary: null })+ expect(mockSummariesList).toHaveBeenCalledTimes(1)+ })+})diff --git a/products/subscriptions/frontend/components/SubscriptionSummaries/subscriptionSummariesLogic.ts b/products/subscriptions/frontend/components/SubscriptionSummaries/subscriptionSummariesLogic.tsnew file mode 100644index 000000000000..5899edae816c--- /dev/null+++ b/products/subscriptions/frontend/components/SubscriptionSummaries/subscriptionSummariesLogic.ts@@ -0,0 +1,138 @@+import { MakeLogicType, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'+import { getCurrentTeamId } from 'lib/utils/getAppContext'++import { subscriptionsSummariesList } from 'products/subscriptions/frontend/generated/api'+import type { SubscriptionSummaryApi } from 'products/subscriptions/frontend/generated/api.schemas'++export interface SubscriptionSummariesLogicProps {+ insightId?: number+ dashboardId?: number+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface subscriptionSummariesLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ latestSummary: SubscriptionSummaryApi | null+ summaries: SubscriptionSummaryApi[] | null+ summariesLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface subscriptionSummariesLogicActions {+ loadSummaries: () => any+ loadSummariesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSummariesSuccess: (+ summaries: SubscriptionSummaryApi[] | null,+ payload?: any+ ) => {+ summaries: SubscriptionSummaryApi[] | null+ payload?: any+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface subscriptionSummariesLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ latestSummary: (+ summaries: SubscriptionSummaryApi[] | null,+ featureFlags: FeatureFlagsSet+ ) => SubscriptionSummaryApi | null+ }+}++export type subscriptionSummariesLogicType = MakeLogicType<+ subscriptionSummariesLogicValues,+ subscriptionSummariesLogicActions,+ SubscriptionSummariesLogicProps,+ subscriptionSummariesLogicMeta+>++function sourceType(props: SubscriptionSummariesLogicProps): 'dashboard' | 'insight' {+ return props.dashboardId ? 'dashboard' : 'insight'+}++export const subscriptionSummariesLogic = kea<subscriptionSummariesLogicType>([+ path((key) => [+ 'products',+ 'subscriptions',+ 'components',+ 'SubscriptionSummaries',+ 'subscriptionSummariesLogic',+ key,+ ]),+ props({} as SubscriptionSummariesLogicProps),+ key((props) => `${sourceType(props)}-${props.dashboardId ?? props.insightId}`),+ connect(() => ({+ values: [featureFlagLogic, ['featureFlags']],+ })),+ loaders(({ props }) => ({+ // null = not loaded yet+ summaries: [+ null as SubscriptionSummaryApi[] | null,+ {+ loadSummaries: async (): Promise<SubscriptionSummaryApi[] | null> => {+ const params = props.dashboardId ? { dashboard: props.dashboardId } : { insight: props.insightId }+ const response = await subscriptionsSummariesList(String(getCurrentTeamId()), params)+ return response.results+ },+ },+ ],+ })),+ selectors({+ // Depends on the flag too, so disabling it mid-session hides the panel immediately instead of+ // waiting for a remount.+ latestSummary: [+ (s) => [s.summaries, s.featureFlags],+ (summaries: SubscriptionSummaryApi[] | null, featureFlags: FeatureFlagsSet) =>+ featureFlags[FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES] ? (summaries?.[0] ?? null) : null,+ ],+ }),+ listeners(({ actions, props, values }) => ({+ loadSummariesSuccess: ({ summaries }) => {+ if (!summaries?.length) {+ return+ }+ // pinned: analytics event name — renaming breaks dashboards+ posthog.capture('subscription summaries viewed', {+ source_type: sourceType(props),+ summary_count: summaries.length,+ subscription_count: new Set(summaries.map((summary) => summary.subscription)).size,+ })+ },+ // The rollout can flip after mount, so a late assignment still loads summaries instead of+ // waiting for the component to remount.+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ if (!props.dashboardId && !props.insightId) {+ return+ }+ if (+ values.featureFlags[FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES] &&+ values.summaries === null &&+ !values.summariesLoading+ ) {+ actions.loadSummaries()+ }+ },+ })),+ afterMount(({ actions, props, values }) => {+ if (!values.featureFlags[FEATURE_FLAGS.SUBSCRIPTION_SOURCE_SUMMARIES]) {+ return+ }+ if (!props.dashboardId && !props.insightId) {+ return+ }+ actions.loadSummaries()+ }),+])diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex b0e10b840830..8d064936b10a 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -800,6 +800,40 @@ export interface PaginatedSubscriptionDeliveryListApi {results: SubscriptionDeliveryApi[]}+export interface SubscriptionSummaryApi {+ /** ID of the delivery that included this summary. */+ readonly id: string+ /** ID of the subscription that generated this summary. */+ readonly subscription: number+ /**+ * Title of the subscription that generated this summary. Null when the subscription has no title.+ * @nullable+ */+ readonly subscription_title: string | null+ /** Channel the summary was sent to: email, slack, or teams. */+ readonly target_type: string+ /**+ * AI-generated summary text included in the delivery.+ * @nullable+ */+ readonly change_summary: string | null+ /**+ * Start of the period this summary covers: the time of the previous completed delivery of the same subscription. Null for the first delivery, which has no earlier data to compare with.+ * @nullable+ */+ readonly period_start: string | null+ /** When the delivery started. This is also the end of the covered period. */+ readonly created_at: string+}++export interface PaginatedSubscriptionSummaryListApi {+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: SubscriptionSummaryApi[]+}+export type SubscriptionsListParams = {/*** Filter by creator user UUID.@@ -885,6 +919,23 @@ export const SubscriptionsDeliveriesListStatus = {Starting: 'starting',} as const+export type SubscriptionsSummariesListParams = {+ /**+ * The pagination cursor value.+ */+ cursor?: string+ /**+ * Dashboard ID. Returns summaries from the subscriptions on this dashboard. Set either dashboard or insight.+ * @minimum 1+ */+ dashboard?: number+ /**+ * Insight ID. Returns summaries from the subscriptions on this insight. Set either insight or dashboard.+ * @minimum 1+ */+ insight?: number+}+export type SubscriptionsSummaryQuotaRetrieve200 = {active_count: number/** @nullable */diff --git a/products/subscriptions/frontend/generated/api.ts b/products/subscriptions/frontend/generated/api.tsindex f932b49b56ce..1afb43cb3883 100644--- a/products/subscriptions/frontend/generated/api.ts+++ b/products/subscriptions/frontend/generated/api.ts@@ -11,12 +11,14 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'import type {PaginatedSubscriptionDeliveryListApi,PaginatedSubscriptionListApi,+ PaginatedSubscriptionSummaryListApi,PatchedSubscriptionWriteApi,SubscriptionApi,SubscriptionDeliveryApi,SubscriptionWriteApi,SubscriptionsDeliveriesListParams,SubscriptionsListParams,+ SubscriptionsSummariesListParams,SubscriptionsSummaryQuotaRetrieve200,} from './api.schemas'@@ -220,6 +222,37 @@ export const subscriptionsDeliveriesRetrieve = async (})}+export const getSubscriptionsSummariesListUrl = (projectId: string, params?: SubscriptionsSummariesListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/subscriptions/summaries/?${stringifiedParams}`+ : `/api/projects/${projectId}/subscriptions/summaries/`+}++/**+ * Completed deliveries that include an AI summary, across every active subscription on one insight or dashboard, newest first. Requires viewer access to the insight or dashboard.+ * @summary List AI summaries for an insight or dashboard+ */+export const subscriptionsSummariesList = async (+ projectId: string,+ params?: SubscriptionsSummariesListParams,+ options?: RequestInit+): Promise<PaginatedSubscriptionSummaryListApi> => {+ return apiMutator<PaginatedSubscriptionSummaryListApi>(getSubscriptionsSummariesListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}+export const getSubscriptionsSummaryQuotaRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/subscriptions/summary_quota/`}diff --git a/products/subscriptions/mcp/tools.yaml b/products/subscriptions/mcp/tools.yamlindex 3f21951d0fd9..9a24ba3ea7ae 100644--- a/products/subscriptions/mcp/tools.yaml+++ b/products/subscriptions/mcp/tools.yaml@@ -219,6 +219,25 @@ tools:response:exclude:- invite_message+ subscriptions-summaries-list:+ operation: subscriptions_summaries_list+ enabled: true+ scopes:+ - subscription:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ list: true+ title: List AI summaries for an insight or dashboard+ description: >+ List the AI summaries that subscriptions sent for one insight or dashboard, newest first. Set exactly one of+ `insight` or `dashboard` (numeric ID). Each row comes from a completed delivery and includes the summary+ text, the subscription ID and title, the channel, and the covered period from `period_start` to+ `created_at`. `period_start` is null for the first delivery of a subscription. Summaries from deleted+ subscriptions are not returned. Use subscriptions-partial-update with `summary_prompt_guide` to change how+ future summaries of one subscription are written. Results are cursor-paginated.+ feature_flag: subscription-source-summariessubscriptions-test-delivery-create:operation: subscriptions_test_delivery_createenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 79701d627b6e..5883da7e9018 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -12774,6 +12774,21 @@"readOnlyHint": true}},+ "subscriptions-summaries-list": {+ "description": "List the AI summaries that subscriptions sent for one insight or dashboard, newest first. Set exactly one of `insight` or `dashboard` (numeric ID). Each row comes from a completed delivery and includes the summary text, the subscription ID and title, the channel, and the covered period from `period_start` to `created_at`. `period_start` is null for the first delivery of a subscription. Summaries from deleted subscriptions are not returned. Use subscriptions-partial-update with `summary_prompt_guide` to change how future summaries of one subscription are written. Results are cursor-paginated.",+ "category": "Subscriptions",+ "feature": "subscriptions",+ "summary": "List AI summaries for an insight or dashboard",+ "title": "List AI summaries for an insight or dashboard",+ "required_scopes": ["subscription:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "subscription-source-summaries"+ },"subscriptions-test-delivery-create": {"description": "Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or Microsoft Teams). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription is already in flight, or if the subscription is disabled (re-enable it first); 404 if it has been deleted. Test-delivering a prompt subscription additionally requires the `query:read` scope (it runs the AI HogQL pipeline).","category": "Subscriptions",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex f390637f35d6..a859006e3546 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -13379,6 +13379,21 @@"readOnlyHint": true}},+ "subscriptions-summaries-list": {+ "description": "List the AI summaries that subscriptions sent for one insight or dashboard, newest first. Set exactly one of `insight` or `dashboard` (numeric ID). Each row comes from a completed delivery and includes the summary text, the subscription ID and title, the channel, and the covered period from `period_start` to `created_at`. `period_start` is null for the first delivery of a subscription. Summaries from deleted subscriptions are not returned. Use subscriptions-partial-update with `summary_prompt_guide` to change how future summaries of one subscription are written. Results are cursor-paginated.",+ "category": "Subscriptions",+ "feature": "subscriptions",+ "summary": "List AI summaries for an insight or dashboard",+ "title": "List AI summaries for an insight or dashboard",+ "required_scopes": ["subscription:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ },+ "feature_flag": "subscription-source-summaries"+ },"subscriptions-test-delivery-create": {"description": "Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or Microsoft Teams). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription is already in flight, or if the subscription is disabled (re-enable it first); 404 if it has been deleted. Test-delivering a prompt subscription additionally requires the `query:read` scope (it runs the AI HogQL pipeline).","category": "Subscriptions",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex aa962e7c0d1c..40cc8aa6fa88 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -73606,6 +73606,40 @@ export namespace Schemas {results: Subscription[];}+ export interface SubscriptionSummary {+ /** ID of the delivery that included this summary. */+ readonly id: string;+ /** ID of the subscription that generated this summary. */+ readonly subscription: number;+ /**+ * Title of the subscription that generated this summary. Null when the subscription has no title.+ * @nullable+ */+ readonly subscription_title: string | null;+ /** Channel the summary was sent to: email, slack, or teams. */+ readonly target_type: string;+ /**+ * AI-generated summary text included in the delivery.+ * @nullable+ */+ readonly change_summary: string | null;+ /**+ * Start of the period this summary covers: the time of the previous completed delivery of the same subscription. Null for the first delivery, which has no earlier data to compare with.+ * @nullable+ */+ readonly period_start: string | null;+ /** When the delivery started. This is also the end of the covered period. */+ readonly created_at: string;+ }++ export interface PaginatedSubscriptionSummaryList {+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: SubscriptionSummary[];+ }+/*** * `popover` - popover* * `widget` - widget@@ -128059,6 +128093,23 @@ export namespace Schemas {Starting: 'starting',} as const;+ export type SubscriptionsSummariesListParams = {+ /**+ * The pagination cursor value.+ */+ cursor?: string;+ /**+ * Dashboard ID. Returns summaries from the subscriptions on this dashboard. Set either dashboard or insight.+ * @minimum 1+ */+ dashboard?: number;+ /**+ * Insight ID. Returns summaries from the subscriptions on this insight. Set either insight or dashboard.+ * @minimum 1+ */+ insight?: number;+ };+export type SubscriptionsSummaryQuotaRetrieve200 = {active_count: number;/** @nullable */diff --git a/services/mcp/src/generated/subscriptions/api.ts b/services/mcp/src/generated/subscriptions/api.tsindex 2ca495180c27..a3b607ad778d 100644--- a/services/mcp/src/generated/subscriptions/api.ts+++ b/services/mcp/src/generated/subscriptions/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 8 enabled ops+ * PostHog API - MCP 9 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -545,3 +545,33 @@ export const SubscriptionsDeliveriesRetrieveParams = () => zod.object({),subscription_id: zod.number(),})++/**+ * Completed deliveries that include an AI summary, across every active subscription on one insight or dashboard, newest first. Requires viewer access to the insight or dashboard.+ * @summary List AI summaries for an insight or dashboard+ */+export const SubscriptionsSummariesListParams = () => zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to \/api\/projects\/."+ ),+})++export const SubscriptionsSummariesListQueryParams = () => zod.object({+ cursor: zod.string().optional().describe('The pagination cursor value.'),+ dashboard: zod+ .number()+ .min(1)+ .optional()+ .describe(+ 'Dashboard ID. Returns summaries from the subscriptions on this dashboard. Set either dashboard or insight.'+ ),+ insight: zod+ .number()+ .min(1)+ .optional()+ .describe(+ 'Insight ID. Returns summaries from the subscriptions on this insight. Set either insight or dashboard.'+ ),+})diff --git a/services/mcp/src/tools/generated/subscriptions.ts b/services/mcp/src/tools/generated/subscriptions.tsindex 8c07054357fa..36ee475b9635 100644--- a/services/mcp/src/tools/generated/subscriptions.ts+++ b/services/mcp/src/tools/generated/subscriptions.ts@@ -330,6 +330,32 @@ const subscriptionsRetrieve = (): ToolBase<ReturnType<typeof SubscriptionsRetrie},})+const SubscriptionsSummariesListSchema = () => {+ const SubscriptionsSummariesListQueryParams = orvalSchemas.SubscriptionsSummariesListQueryParams()+ return SubscriptionsSummariesListQueryParams+}++const subscriptionsSummariesList = (): ToolBase<+ ReturnType<typeof SubscriptionsSummariesListSchema>,+ WithPostHogUrl<Schemas.PaginatedSubscriptionSummaryList>+> => ({+ name: 'subscriptions-summaries-list',+ schema: SubscriptionsSummariesListSchema(),+ handler: async (context: Context, params: z.infer<ReturnType<typeof SubscriptionsSummariesListSchema>>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.PaginatedSubscriptionSummaryList>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/summaries/`,+ query: {+ cursor: params.cursor,+ dashboard: params.dashboard,+ insight: params.insight,+ },+ })+ return await withPostHogUrl(context, result, '/subscriptions')+ },+})+const SubscriptionsTestDeliveryCreateSchema = () => {const SubscriptionsTestDeliveryCreateParams = orvalSchemas.SubscriptionsTestDeliveryCreateParams()return SubscriptionsTestDeliveryCreateParams.omit({ project_id: true })@@ -359,5 +385,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'subscriptions-list': subscriptionsList,'subscriptions-partial-update': subscriptionsPartialUpdate,'subscriptions-retrieve': subscriptionsRetrieve,+ 'subscriptions-summaries-list': subscriptionsSummariesList,'subscriptions-test-delivery-create': subscriptionsTestDeliveryCreate,}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-summaries-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-summaries-list.jsonnew file mode 100644index 000000000000..f4339d8ea3bf--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-summaries-list.json@@ -0,0 +1,20 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "cursor": {+ "description": "The pagination cursor value.",+ "type": "string"+ },+ "dashboard": {+ "description": "Dashboard ID. Returns summaries from the subscriptions on this dashboard. Set either dashboard or insight.",+ "minimum": 1,+ "type": "number"+ },+ "insight": {+ "description": "Insight ID. Returns summaries from the subscriptions on this insight. Set either insight or dashboard.",+ "minimum": 1,+ "type": "number"+ }+ },+ "type": "object"+}diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.tsindex 5d1fc34e2337..96de197a2ec3 100644--- a/services/mcp/tests/unit/tool-filtering.test.ts+++ b/services/mcp/tests/unit/tool-filtering.test.ts@@ -1114,10 +1114,11 @@ describe('Tool Filtering - Feature Flags', () => {'autoresearch','today-rail-nav','marketing-analytics-setup-plan-mcp',+ 'subscription-source-summaries',]))expect(flags).toContain('ai-observability-offline-evaluations')- expect(flags).toHaveLength(39)+ expect(flags).toHaveLength(40)})it('every loops tool is gated on the loops flag', () => {diff --git a/services/mcp/tests/unit/tool-schema-snapshots.test.ts b/services/mcp/tests/unit/tool-schema-snapshots.test.tsindex affd908e5722..13f124d18d86 100644--- a/services/mcp/tests/unit/tool-schema-snapshots.test.ts+++ b/services/mcp/tests/unit/tool-schema-snapshots.test.ts@@ -102,6 +102,7 @@ async function loadSnapshotTools(): Promise<Tool<ZodObjectAny>[]> {'ai-observability-offline-evaluations': true,'warehouse-suggestions': true,'scouts-tool-access': true,+ 'subscription-source-summaries': true,}return [...(await getToolsFromContext(createMockContext(), { featureFlags }))].sort((a, b) =>a.name.localeCompare(b.name)