: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): add AI report context contract (#91428)
Vasco de Krijger0d8ec36bc225
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex dce2ba547b81..12b927d3a139 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -358,6 +358,7 @@ rules:|SourceGroupLease|StreamlitApp|Subscription+ |SubscriptionContext|SubscriptionDelivery|Survey|SurveyResponseArchive@@ -762,6 +763,7 @@ rules:|SourceGroupLease|StreamlitApp|Subscription+ |SubscriptionContext|SubscriptionDelivery|Survey|SurveyResponseArchivediff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex dd11ebfb193f..fd65a440e828 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -1,11 +1,14 @@import uuidimport asyncio-from collections.abc import Callable+from collections.abc import Callable, Iterablefrom typing import Any, ClassVar, Optionalfrom django.conf import settings+from django.contrib.postgres.expressions import ArraySubqueryfrom django.core.cache import cache-from django.db.models import Manager, Q, QuerySet+from django.db import transaction+from django.db.models import CharField, Manager, Prefetch, Q, QuerySet, Value+from django.db.models.functions import Cast, Concatfrom django.http import HttpRequest, JsonResponsefrom django.shortcuts import get_object_or_404@@ -14,6 +17,7 @@ import posthoganalyticsfrom drf_spectacular.utils import (OpenApiParameter,OpenApiResponse,+ PolymorphicProxySerializer,extend_schema,extend_schema_field,extend_schema_view,@@ -25,13 +29,15 @@ from rest_framework.pagination import CursorPaginationfrom rest_framework.response import Responsefrom temporalio.exceptions import WorkflowAlreadyStartedError+from posthog.schema import SubscriptionAIContextLimit+from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.cloud_utils import is_cloudfrom posthog.constants import SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEYfrom posthog.dataclasses import frozen-from posthog.event_usage import get_request_analytics_properties, groups+from posthog.event_usage import AnalyticsProps, get_request_analytics_properties, groupsfrom posthog.exceptions import QuotaLimitExceededfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.integration import Integration, SlackIntegration@@ -54,6 +60,7 @@ from products.exports.backend.models.subscription import (attribute_subscription_saves,unsubscribe_using_token,)+from products.exports.backend.models.subscription_context import SubscriptionContextfrom products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (PROMPT_MAX_LENGTH as AI_PROMPT_MAX_LENGTH,PromptRejectedError,@@ -70,6 +77,7 @@ from products.exports.backend.temporal.subscriptions.types import (ProcessSubscriptionWorkflowInputs,SubscriptionTriggerType,)+from products.product_analytics.backend.facade.api import insights_including_soft_deleted_for_teamfrom products.product_analytics.backend.facade.models import Insightfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limited@@ -79,6 +87,7 @@ from ee.tasks.subscriptions.teams_subscriptions import TEAMS_WEBHOOK_URL_ERROR,SUMMARY_QUOTA_CACHE_TTL_SECONDS = 60SUMMARY_CAP_HIT_DEDUPE_TTL_SECONDS = 600+MAX_AI_SUBSCRIPTION_CONTEXTS: int = int(SubscriptionAIContextLimit.model_fields["root"].default)AI_DELIVERY_DISPLAY_FIELDS = frozenset({"include_images", "include_feedback", "include_manage_link", "include_posthog_hint"})@@ -111,6 +120,9 @@ def _invalidate_summary_quota_cache(organization_id) -> None:class _TargetLookups:insight: strdashboard: str+ live_context_insight_lookup: str+ live_context_dashboard_lookup: str+ snapshot_context_ref_overlap: str | Noneexported_insights: strno_selection: strinsights: Manager@@ -121,6 +133,9 @@ class _TargetLookups:_SUBSCRIPTION_TARGETS = _TargetLookups(insight="insight_id__in",dashboard="dashboard_id__in",+ live_context_insight_lookup="contexts__insight_id__in",+ live_context_dashboard_lookup="contexts__dashboard_id__in",+ snapshot_context_ref_overlap=None,exported_insights="dashboard_export_insights__id__in",no_selection="dashboard_export_insights__isnull",insights=Insight.objects,@@ -132,6 +147,9 @@ _SUBSCRIPTION_TARGETS = _TargetLookups(_DELIVERY_TARGETS = _TargetLookups(insight="subscription__insight_id__in",dashboard="subscription__dashboard_id__in",+ 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",exported_insights="subscription__dashboard_export_insights__id__in",no_selection="subscription__dashboard_export_insights__isnull",insights=Insight.objects_including_soft_deleted,@@ -293,7 +311,70 @@ class DeliveryConfigSerializer(serializers.Serializer):)-class SubscriptionSerializer(serializers.ModelSerializer):+class SubscriptionContextWriteSerializer(serializers.Serializer):+ dashboard_id = serializers.IntegerField(+ required=False,+ min_value=1,+ help_text="Dashboard ID to use as AI report context. Set either dashboard_id or insight_id, not both.",+ )+ insight_id = serializers.IntegerField(+ required=False,+ min_value=1,+ help_text="Insight ID to use as AI report context. Set either insight_id or dashboard_id, not both.",+ )++ def validate(self, attrs: dict) -> dict:+ if ("dashboard_id" in attrs) == ("insight_id" in attrs):+ raise ValidationError("Set exactly one of dashboard_id or insight_id.")+ return attrs+++@extend_schema_field(+ {+ "type": "array",+ "maxItems": MAX_AI_SUBSCRIPTION_CONTEXTS,+ "items": {+ "oneOf": [+ {+ "type": "object",+ "additionalProperties": False,+ "required": ["dashboard_id"],+ "properties": {"dashboard_id": {"type": "integer", "minimum": 1}},+ },+ {+ "type": "object",+ "additionalProperties": False,+ "required": ["insight_id"],+ "properties": {"insight_id": {"type": "integer", "minimum": 1}},+ },+ ]+ },+ }+)+class SubscriptionContextsWriteField(serializers.ListField):+ pass+++class SubscriptionDashboardContextSerializer(serializers.Serializer):+ dashboard_id = serializers.IntegerField(help_text="Dashboard ID used to open the context dashboard.")+ dashboard_name = serializers.CharField(help_text="Current display name of the context dashboard.")+++class SubscriptionInsightContextSerializer(serializers.Serializer):+ insight_id = serializers.IntegerField(help_text="Database ID of the context insight.")+ insight_short_id = serializers.CharField(help_text="Stable insight identifier used to open the context insight.")+ insight_name = serializers.CharField(help_text="Current display name of the context insight.")+++SUBSCRIPTION_CONTEXT_READ_SCHEMA = PolymorphicProxySerializer(+ component_name="SubscriptionContext",+ serializers=[SubscriptionDashboardContextSerializer, SubscriptionInsightContextSerializer],+ resource_type_field_name=None,+ many=True,+)+++class SubscriptionWriteSerializer(serializers.ModelSerializer):"""Standard Subscription serializer."""FIELDS_THAT_TRIGGER_REDELIVERY: ClassVar[tuple[str, ...]] = (@@ -340,6 +421,15 @@ class SubscriptionSerializer(serializers.ModelSerializer):"when resource_type is 'ai_prompt'. Replaced wholesale on writes."),)+ contexts: serializers.Field = SubscriptionContextsWriteField(+ child=SubscriptionContextWriteSerializer(),+ required=False,+ write_only=True,+ help_text=(+ "Complete dashboard and insight context for an AI report. Omit on PATCH to preserve, pass an empty "+ f"list to clear, or pass up to {MAX_AI_SUBSCRIPTION_CONTEXTS} items to replace all contexts."+ ),+ )ai_query_plan_status = serializers.SerializerMethodField(help_text=("Query plan reuse state for AI prompt subscriptions: frozen, not_frozen, or planner_updated. "@@ -375,6 +465,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):"dashboard_export_insights","prompt","ai_prompt_config",+ "contexts","ai_query_plan_status","target_type","target_value",@@ -481,6 +572,52 @@ class SubscriptionSerializer(serializers.ModelSerializer):info = obj.resource_inforeturn info.name if info else None+ @staticmethod+ def _context_rows(obj: Subscription) -> Iterable[SubscriptionContext]:+ cached_contexts = getattr(obj, "_prefetched_objects_cache", {}).get("contexts")+ if cached_contexts is not None:+ return cached_contexts+ return (+ SubscriptionContext.objects.for_team(obj.team_id)+ .filter(subscription=obj)+ .select_related("dashboard", "insight")+ )++ @classmethod+ def _context_representation(cls, obj: Subscription) -> list[dict[str, str | int]]:+ if obj.resource_type != Subscription.ResourceType.AI_PROMPT:+ return []++ contexts: list[dict[str, str | int]] = []+ for context in cls._context_rows(obj):+ if not context.has_live_target_for_team(context.team_id):+ continue++ if context.dashboard_id is not None and context.dashboard is not None:+ contexts.append(+ {+ "dashboard_id": context.dashboard_id,+ "dashboard_name": context.dashboard.name or "Untitled dashboard",+ }+ )+ elif context.insight_id is not None and context.insight is not None:+ contexts.append(+ {+ "insight_id": context.insight_id,+ "insight_short_id": context.insight.short_id,+ "insight_name": str(context.insight),+ }+ )+ return contexts++ def to_representation(self, instance: Subscription) -> dict:+ representation = super().to_representation(instance)+ if instance.target_type == Subscription.SubscriptionTarget.TEAMS:+ representation["target_value"] = instance.recipient_label+ if "contexts" not in representation:+ representation["contexts"] = self._context_representation(instance)+ return representation+@extend_schema_field(serializers.ChoiceField(choices=AIQueryPlanStatus.choices,@@ -529,6 +666,49 @@ class SubscriptionSerializer(serializers.ModelSerializer):if gate_reason is not None:raise ValidationError(gate_reason)+ def _validate_contexts(self, contexts: list[dict[str, int]]) -> list[dict[str, Insight | Dashboard]]:+ if len(contexts) > MAX_AI_SUBSCRIPTION_CONTEXTS:+ raise ValidationError(+ {"contexts": [f"Select no more than {MAX_AI_SUBSCRIPTION_CONTEXTS} dashboards and insights."]}+ )++ identifiers = [+ ("dashboard", context["dashboard_id"]) if "dashboard_id" in context else ("insight", context["insight_id"])+ for context in contexts+ ]+ if len(set(identifiers)) != len(identifiers):+ raise ValidationError({"contexts": ["Select each dashboard or insight only once."]})++ dashboard_ids = {identifier for kind, identifier in identifiers if kind == "dashboard"}+ insight_ids = {identifier for kind, identifier in identifiers if kind == "insight"}+ team_id = self.context["get_team"]().id+ dashboards = {+ dashboard.id: dashboard+ for dashboard in Dashboard.objects_including_soft_deleted.filter(team_id=team_id, id__in=dashboard_ids)+ }+ insights = {+ insight.id: insight+ for insight in insights_including_soft_deleted_for_team(team_id=team_id, insight_ids=insight_ids)+ }+ user_access_control = self.context["view"].user_access_control+ validated_contexts: list[dict[str, Insight | Dashboard]] = []++ for kind, identifier in identifiers:+ target = dashboards.get(identifier) if kind == "dashboard" else insights.get(identifier)+ if target is None:+ raise ValidationError({"contexts": [f"This {kind} is not in your team, or no longer exists."]})+ if target.deleted:+ raise ValidationError({"contexts": [f"This {kind} has been deleted."]})+ if not user_access_control.check_access_level_for_object(target, "viewer"):+ raise ValidationError(+ {"contexts": [f"Viewer access to this {kind} is required. Ask an admin to grant you access."]}+ )+ if isinstance(target, Dashboard):+ self._require_viewer_access_to_every_live_tile(target, error_field="contexts")+ validated_contexts.append({kind: target})++ return validated_contexts+def validate(self, attrs):request = self.context.get("request")# Re-run the free-tier cap on create AND on restore (deleted: true → false) —@@ -594,6 +774,10 @@ class SubscriptionSerializer(serializers.ModelSerializer):raise ValidationError({"resource_type": [f"Unsupported resource_type: {resource_type}."]})if resource_type != Subscription.ResourceType.AI_PROMPT and attrs.get("ai_prompt_config"):raise ValidationError({"ai_prompt_config": ["AI report settings only apply to AI subscriptions."]})+ if "contexts" in attrs:+ if resource_type != Subscription.ResourceType.AI_PROMPT:+ raise ValidationError({"contexts": ["Context only applies to AI subscriptions."]})+ attrs["contexts"] = self._validate_contexts(attrs["contexts"])validate_for_resource_type(attrs, existing)self._validate_dashboard_export_subscription(attrs)@@ -879,7 +1063,9 @@ class SubscriptionSerializer(serializers.ModelSerializer):def _keeps_its_own_selection(self) -> bool:return self.instance is not None and self.instance.dashboard_export_insights.exists()- def _require_viewer_access_to_every_live_tile(self, dashboard: Dashboard) -> None:+ def _require_viewer_access_to_every_live_tile(+ self, dashboard: Dashboard, *, error_field: str = "dashboard"+ ) -> None:live_tile_insights = Insight.objects.filter(team_id=self.context["team_id"],id__in=dashboard.tiles.filter(insight__isnull=False, insight__deleted=False).values("insight_id"),@@ -888,18 +1074,82 @@ class SubscriptionSerializer(serializers.ModelSerializer):if _blocked_target_ids(user_access_control, live_tile_insights, "insight").exists():raise ValidationError({- "dashboard": [+ error_field: ["Viewer access to every insight on this dashboard is required. ""Ask an admin for access, or select only the insights you can view."]})- def to_representation(self, instance: Subscription) -> dict:- data = super().to_representation(instance)- if instance.target_type == Subscription.SubscriptionTarget.TEAMS:- data["target_value"] = instance.recipient_label- return data+ @staticmethod+ def _context_identifiers(contexts: list[dict[str, Insight | Dashboard]]) -> set[tuple[str, int]]:+ return {(kind, target.id) for context in contexts for kind, target in context.items()}++ @classmethod+ def _stored_context_identifiers(cls, instance: Subscription) -> set[tuple[str, int]]:+ identifiers: set[tuple[str, int]] = set()+ for context in cls._context_rows(instance):+ if context.dashboard_id is not None:+ identifiers.add(("dashboard", context.dashboard_id))+ elif context.insight_id is not None:+ identifiers.add(("insight", context.insight_id))+ return identifiers++ @classmethod+ def _replaceable_context_identifiers(cls, instance: Subscription) -> set[tuple[str, int]]:+ identifiers: set[tuple[str, int]] = set()+ for context in cls._context_rows(instance):+ if not context.has_target_for_team(context.team_id, include_deleted=True):+ continue++ if context.dashboard_id is not None:+ identifiers.add(("dashboard", context.dashboard_id))+ elif context.insight_id is not None:+ identifiers.add(("insight", context.insight_id))+ return identifiers++ @staticmethod+ def _context_refs(identifiers: set[tuple[str, int]]) -> list[str]:+ return sorted(f"{kind}:{identifier}" for kind, identifier in identifiers)++ @staticmethod+ def _replace_contexts(instance: Subscription, contexts: list[dict[str, Insight | Dashboard]]) -> None:+ context_team_id = instance.team.parent_team_id or instance.team_id+ scoped_contexts = SubscriptionContext.objects.for_team(context_team_id, canonical=True)+ scoped_contexts.filter(subscription=instance).filter(+ Q(dashboard__team_id=context_team_id) | Q(insight__team_id=context_team_id)+ ).delete()+ for context in contexts:+ scoped_contexts.create(team_id=context_team_id, subscription=instance, **context)+ getattr(instance, "_prefetched_objects_cache", {}).pop("contexts", None)++ def _update_with_contexts(+ self,+ instance: Subscription,+ validated_data: dict,+ contexts: list[dict[str, Insight | Dashboard]],+ contexts_in_payload: bool,+ analytics_props: AnalyticsProps,+ ) -> tuple[Subscription, bool]:+ contexts_changed = False+ context_change: tuple[list[str], list[str]] | None = None+ with transaction.atomic():+ if contexts_in_payload:+ instance = Subscription.objects.select_for_update().get(pk=instance.pk)+ stored_identifiers = self._stored_context_identifiers(instance)+ preserved_identifiers = stored_identifiers - self._replaceable_context_identifiers(instance)+ updated_identifiers = preserved_identifiers | self._context_identifiers(contexts)+ contexts_changed = stored_identifiers != updated_identifiers+ if contexts_changed:+ context_change = (+ self._context_refs(stored_identifiers),+ self._context_refs(updated_identifiers),+ )+ with attribute_subscription_saves(analytics_props, context_change=context_change):+ instance = super().update(instance, validated_data)+ if contexts_changed:+ self._replace_contexts(instance, contexts)+ return instance, contexts_changeddef create(self, validated_data: dict, *args: Any, **kwargs: Any) -> Subscription:request = self.context["request"]@@ -920,8 +1170,15 @@ class SubscriptionSerializer(serializers.ModelSerializer):# 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)+ contexts = validated_data.pop("contexts", [])+ with transaction.atomic():+ context_identifiers = self._context_identifiers(contexts)+ context_change: tuple[list[str], list[str]] | None = (+ ([], self._context_refs(context_identifiers)) if context_identifiers else None+ )+ with attribute_subscription_saves(get_request_analytics_properties(request), context_change=context_change):+ instance: Subscription = super().create(validated_data)+ self._replace_contexts(instance, contexts)# Bust the org-wide active-summary count cache so the next quota# fetch reflects this row, regardless of summary_enabled — over-busting@@ -995,6 +1252,9 @@ class SubscriptionSerializer(serializers.ModelSerializer):# 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", [])+ contexts_in_payload = "contexts" in validated_data+ contexts = validated_data.pop("contexts", [])+ contexts_changed = Falseanalytics_props = get_request_analytics_properties(request)# Snapshot delivery-relevant values before the write so the inferred path can tell,@@ -1022,13 +1282,15 @@ class SubscriptionSerializer(serializers.ModelSerializer):"resource_type": instance.resource_type,},):- with attribute_subscription_saves(analytics_props):- instance = super().update(instance, validated_data)+ instance, contexts_changed = self._update_with_contexts(+ instance, validated_data, contexts, contexts_in_payload, analytics_props+ )_invalidate_summary_quota_cache(instance.team.organization_id)return instance- with attribute_subscription_saves(analytics_props):- instance = super().update(instance, validated_data)+ instance, contexts_changed = self._update_with_contexts(+ instance, validated_data, contexts, contexts_in_payload, analytics_props+ )_invalidate_summary_quota_cache(instance.team.organization_id)# Apply the M2M whenever the field is in the payload — including an empty list, which clears it.@@ -1048,6 +1310,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):delivery_content_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)+ delivery_content_changed = delivery_content_changed or contexts_changed# 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@@ -1115,6 +1378,16 @@ class SubscriptionSerializer(serializers.ModelSerializer):return instance+class SubscriptionSerializer(SubscriptionWriteSerializer):+ contexts: serializers.Field = serializers.SerializerMethodField(+ help_text="Dashboards and insights that ground this AI report. Deleted resources are omitted."+ )++ @extend_schema_field(SUBSCRIPTION_CONTEXT_READ_SCHEMA)+ def get_contexts(self, obj: Subscription) -> list[dict[str, str | int]]:+ return self._context_representation(obj)++def _blocked_target_ids(user_access_control: UserAccessControl, queryset: QuerySet, resource: APIScopeObject) -> QuerySet:@@ -1126,6 +1399,13 @@ def _blocked_target_ids()+def _context_ref_subquery(kind: str, blocked_ids: QuerySet, *, id_field: str = "id") -> ArraySubquery:+ references = blocked_ids.annotate(+ context_ref=Concat(Value(f"{kind}:"), Cast(id_field, output_field=CharField()))+ ).values("context_ref")+ return ArraySubquery(references)++def _viewable_subscription_filter(user_access_control: UserAccessControl, team_id: int) -> Q:return _target_filter(user_access_control, team_id, _SUBSCRIPTION_TARGETS)@@ -1148,17 +1428,43 @@ def _target_filter(user_access_control: UserAccessControl, team_id: int, targetsteam_dashboards = targets.dashboards.filter(team_id=team_id)blocked_insights = _blocked_target_ids(user_access_control, targets.insights.filter(team_id=team_id), "insight")blocked_dashboards = _blocked_target_ids(user_access_control, team_dashboards, "dashboard")- dashboards_with_blocked_tiles = targets.tiles.filter(- dashboard__in=team_dashboards, insight_id__in=blocked_insights- ).values("dashboard_id")+ # Distinct so the context-ref array below holds one entry per dashboard, not one per blocked tile.+ dashboards_with_blocked_tiles = (+ targets.tiles.filter(dashboard__in=team_dashboards, insight_id__in=blocked_insights)+ .values("dashboard_id")+ .distinct()+ )targets_a_blocked_insight = Q(**{targets.insight: blocked_insights})targets_a_blocked_dashboard = Q(**{targets.dashboard: blocked_dashboards})exports_a_blocked_insight = Q(**{targets.exported_insights: blocked_insights})renders_a_blocked_tile = Q(**{targets.no_selection: True}) & Q(**{targets.dashboard: dashboards_with_blocked_tiles})+ references_a_blocked_context = (+ Q(**{targets.live_context_insight_lookup: blocked_insights})+ | Q(**{targets.live_context_dashboard_lookup: blocked_dashboards})+ | Q(**{targets.live_context_dashboard_lookup: dashboards_with_blocked_tiles})+ )+ if targets.snapshot_context_ref_overlap is not None:+ references_a_blocked_context |= Q(+ **{targets.snapshot_context_ref_overlap: _context_ref_subquery("insight", blocked_insights)}+ )+ references_a_blocked_context |= Q(+ **{targets.snapshot_context_ref_overlap: _context_ref_subquery("dashboard", blocked_dashboards)}+ )+ references_a_blocked_context |= Q(+ **{+ targets.snapshot_context_ref_overlap: _context_ref_subquery(+ "dashboard", dashboards_with_blocked_tiles, id_field="dashboard_id"+ )+ }+ )return ~(- targets_a_blocked_insight | targets_a_blocked_dashboard | exports_a_blocked_insight | renders_a_blocked_tile+ targets_a_blocked_insight+ | targets_a_blocked_dashboard+ | exports_a_blocked_insight+ | renders_a_blocked_tile+ | references_a_blocked_context)@@ -1249,9 +1555,22 @@ def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> bool),],),- create=extend_schema(extensions={"x-product": "subscriptions"}),+ create=extend_schema(+ request=SubscriptionWriteSerializer,+ responses={201: SubscriptionSerializer},+ extensions={"x-product": "subscriptions"},+ ),retrieve=extend_schema(extensions={"x-product": "subscriptions"}),- partial_update=extend_schema(extensions={"x-product": "subscriptions"}),+ update=extend_schema(+ request=SubscriptionWriteSerializer,+ responses={200: SubscriptionSerializer},+ extensions={"x-product": "subscriptions"},+ ),+ partial_update=extend_schema(+ request=SubscriptionWriteSerializer,+ responses={200: SubscriptionSerializer},+ extensions={"x-product": "subscriptions"},+ ),destroy=extend_schema(extensions={"x-product": "subscriptions"}),)@extend_schema(tags=["subscriptions"], extensions={"x-product": "subscriptions"})@@ -1278,6 +1597,11 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.M]ordering = ["-created_at"]+ def get_serializer_class(self) -> type[serializers.Serializer]:+ if self.action in ("create", "update", "partial_update"):+ return SubscriptionWriteSerializer+ return SubscriptionSerializer+# Writing an AI prompt subscription also requires query-read access: it runs LLM-generated# HogQL and delivers the results, so subscription:write alone could exfiltrate analytics.# Two layers gate this off _write_touches_ai_subscription: a required query:read scope keeps a@@ -1323,10 +1647,12 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mdef safely_get_queryset(self, queryset) -> QuerySet:request_params = self.request.GET.dict()- # Prefetch dashboard_export_insights to avoid N+1 queries in list/detail views- queryset = queryset.prefetch_related("dashboard_export_insights")-if self.action == "list":+ context_queryset = SubscriptionContext.objects.for_team(self.team_id).select_related("dashboard", "insight")+ queryset = queryset.prefetch_related(+ "dashboard_export_insights",+ Prefetch("contexts", queryset=context_queryset),+ )queryset = queryset.select_related("insight", "dashboard", "created_by")if "deleted" not in request_params:@@ -1391,7 +1717,7 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.Mqueryset = queryset.filter(deleted=str_to_bool(request_params["deleted"]))if self.action == "list":- return queryset.filter(_viewable_subscription_filter(self.user_access_control, self.team_id))+ return queryset.filter(_viewable_subscription_filter(self.user_access_control, self.team_id)).distinct()return querysetdef safely_get_object(self, queryset: QuerySet) -> Subscription:@@ -1802,7 +2128,7 @@ class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModel{"status": [f"Must be one of: {', '.join(sorted(valid))}."]},)queryset = queryset.filter(status=status_param)- return queryset.filter(_viewable_delivery_filter(self.user_access_control, self.team_id))+ return queryset.filter(_viewable_delivery_filter(self.user_access_control, self.team_id)).distinct()def unsubscribe(request: HttpRequest):diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex eb1f8e72a86a..3a415b60686c 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -9,6 +9,8 @@ import time_machinefrom unittest.mock import AsyncMock, MagicMock, patchfrom django.core.cache import cache+from django.db import connection+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom parameterized import parameterized@@ -33,6 +35,7 @@ from products.exports.backend.models.subscription import (Subscription,SubscriptionDelivery,)+from products.exports.backend.models.subscription_context import SubscriptionContextfrom products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import AI_QUERY_PLAN_VERSIONfrom products.exports.backend.temporal.subscriptions.types import (AI_REPORT_CHARTS_KEY,@@ -144,6 +147,7 @@ class TestSubscriptionTemporal(APILicensedTest):"dashboard_export_insights": [],"prompt": None,"ai_prompt_config": {},+ "contexts": [],"ai_query_plan_status": None,"target_type": "email","target_value": "[email protected]",@@ -3158,6 +3162,427 @@ class TestAISubscriptionAPI(APILicensedTest):assert data["insight"] is Noneassert data["dashboard"] is None+ @parameterized.expand([("project", False), ("legacy_environment", True)])+ def test_create_and_read_mixed_contexts(self, mock_is_cloud, mock_flag, mock_sync, _name, through_environment):+ self._enable_ai()+ self._mock_temporal(mock_sync)+ request_team = (+ Team.objects.create(organization=self.organization, parent_team=self.team, name="Environment")+ if through_environment+ else self.team+ )+ route = "environments" if through_environment else "projects"+ dashboard = Dashboard.objects.create(team=request_team, name="Growth overview", created_by=self.user)+ insight = Insight.objects.create(+ team=request_team,+ created_by=self.user,+ name="Weekly signups",+ short_id="signup12",+ )++ created = self.client.post(+ f"/api/{route}/{request_team.id}/subscriptions",+ self._make_ai_payload(contexts=[{"dashboard_id": dashboard.id}, {"insight_id": insight.id}]),+ )++ assert created.status_code == status.HTTP_201_CREATED, created.json()+ assert created.json()["contexts"] == [+ {"dashboard_id": dashboard.id, "dashboard_name": "Growth overview"},+ {"insight_id": insight.id, "insight_short_id": "signup12", "insight_name": "Weekly signups"},+ ]+ retrieved = self.client.get(f"/api/{route}/{request_team.id}/subscriptions/{created.json()['id']}")+ assert retrieved.status_code == status.HTTP_200_OK, retrieved.json()+ assert retrieved.json()["contexts"] == created.json()["contexts"]+ assert set(+ SubscriptionContext.objects.for_team(request_team.id)+ .filter(subscription_id=created.json()["id"])+ .values_list("team_id", flat=True)+ ) == {self.team.id}++ @parameterized.expand(+ [+ (+ "dashboard",+ lambda self, team: (+ {+ "dashboard_id": Dashboard.objects.create(+ team=team, name="Foreign dashboard", created_by=self.user+ ).id+ },+ "Foreign dashboard",+ ),+ ),+ (+ "insight",+ lambda self, team: (+ {"insight_id": Insight.objects.create(team=team, name="Foreign insight", created_by=self.user).id},+ "Foreign insight",+ ),+ ),+ ]+ )+ def test_read_omits_a_malformed_cross_team_context(+ self, mock_is_cloud, mock_flag, mock_sync, _name, context_factory+ ):+ self._enable_ai()+ self._mock_temporal(mock_sync)+ created = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(send_test_now=False),+ )+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ context_fields, foreign_name = context_factory(self, other_team)+ SubscriptionContext.objects.for_team(self.team.id).bulk_create(+ [+ SubscriptionContext(+ team_id=self.team.id,+ subscription_id=created.json()["id"],+ **context_fields,+ )+ ]+ )++ retrieved = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}")++ assert retrieved.status_code == status.HTTP_200_OK, retrieved.json()+ assert retrieved.json()["contexts"] == []+ assert foreign_name not in retrieved.content.decode()++ updated = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}",+ {"contexts": [], "send_test_now": False},+ )++ assert updated.status_code == status.HTTP_200_OK, updated.json()+ assert (+ SubscriptionContext.objects.for_team(self.team.id)+ .filter(subscription_id=created.json()["id"], **context_fields)+ .exists()+ )++ @parameterized.expand(+ [+ ("dashboard", lambda self: self._context_dashboard()),+ (+ "insight",+ lambda self: Insight.objects.create(team=self.team, created_by=self.user, name="Deleted insight"),+ ),+ ]+ )+ def test_patch_empty_contexts_clears_a_soft_deleted_context(+ self, mock_is_cloud, mock_flag, mock_sync, _name, target_factory+ ):+ self._enable_ai()+ self._mock_temporal(mock_sync)+ target = target_factory(self)+ identifier = "dashboard_id" if isinstance(target, Dashboard) else "insight_id"+ created = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(contexts=[{identifier: target.id}], send_test_now=False),+ )+ target.deleted = True+ target.save(update_fields=["deleted"])++ updated = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}",+ {"contexts": [], "send_test_now": False},+ )++ assert updated.status_code == status.HTTP_200_OK, updated.json()+ assert updated.json()["contexts"] == []+ assert (+ not SubscriptionContext.objects.for_team(self.team.id).filter(subscription_id=created.json()["id"]).exists()+ )++ target.deleted = False+ target.save(update_fields=["deleted"])+ retrieved = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}")+ assert retrieved.status_code == status.HTTP_200_OK, retrieved.json()+ assert retrieved.json()["contexts"] == []++ def test_patch_omitting_contexts_preserves_them(self, mock_is_cloud, mock_flag, mock_sync):+ self._enable_ai()+ self._mock_temporal(mock_sync)+ dashboard = Dashboard.objects.create(team=self.team, name="Growth", created_by=self.user)+ created = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(contexts=[{"dashboard_id": dashboard.id}], send_test_now=False),+ )+ dashboard.deleted = True+ dashboard.save(update_fields=["deleted"])++ updated = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}",+ {"title": "Renamed", "send_test_now": False},+ )++ assert updated.status_code == status.HTTP_200_OK, updated.json()+ assert updated.json()["contexts"] == []++ dashboard.deleted = False+ dashboard.save(update_fields=["deleted"])+ retrieved = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}")+ assert retrieved.status_code == status.HTTP_200_OK, retrieved.json()+ assert retrieved.json()["contexts"] == [{"dashboard_id": dashboard.id, "dashboard_name": "Growth"}]++ def test_patch_empty_contexts_clears_them(self, mock_is_cloud, mock_flag, mock_sync):+ self._enable_ai()+ self._mock_temporal(mock_sync)+ dashboard = Dashboard.objects.create(team=self.team, name="Growth", created_by=self.user)+ created = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(contexts=[{"dashboard_id": dashboard.id}], send_test_now=False),+ )++ updated = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}",+ {"contexts": [], "send_test_now": False},+ )++ assert updated.status_code == status.HTTP_200_OK, updated.json()+ assert updated.json()["contexts"] == []+ assert (+ not SubscriptionContext.objects.for_team(self.team.id).filter(subscription_id=created.json()["id"]).exists()+ )++ def test_patch_contexts_replaces_the_complete_collection(self, mock_is_cloud, mock_flag, mock_sync):+ self._enable_ai()+ self._mock_temporal(mock_sync)+ old_dashboard = Dashboard.objects.create(team=self.team, name="Old", created_by=self.user)+ new_insight = Insight.objects.create(team=self.team, created_by=self.user, name="New", short_id="new12345")+ created = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(contexts=[{"dashboard_id": old_dashboard.id}], send_test_now=False),+ )+ old_dashboard.deleted = True+ old_dashboard.save(update_fields=["deleted"])++ updated = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}",+ {"contexts": [{"insight_id": new_insight.id}], "send_test_now": False},+ )++ old_dashboard.deleted = False+ old_dashboard.save(update_fields=["deleted"])+ retrieved = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{created.json()['id']}")++ assert updated.status_code == status.HTTP_200_OK, updated.json()+ assert retrieved.status_code == status.HTTP_200_OK, retrieved.json()+ assert retrieved.json()["contexts"] == [+ {"insight_id": new_insight.id, "insight_short_id": "new12345", "insight_name": "New"}+ ]+ assert (+ SubscriptionContext.objects.for_team(self.team.id).filter(subscription_id=created.json()["id"]).count() == 1+ )++ @parameterized.expand(+ [+ (+ "more_than_three",+ lambda self: [+ {"dashboard_id": Dashboard.objects.create(team=self.team, name=str(index)).id} for index in range(4)+ ],+ ),+ ("duplicate", lambda self: [{"dashboard_id": self._context_dashboard().id}] * 2),+ ("both_identifiers", lambda self: [{"dashboard_id": 1, "insight_id": 1}]),+ ("neither_identifier", lambda self: [{}]),+ (+ "cross_team",+ lambda self: [+ {+ "dashboard_id": Dashboard.objects.create(+ team=Team.objects.create(organization=self.organization, name="Other"), name="Foreign"+ ).id+ }+ ],+ ),+ ("deleted", lambda self: [{"dashboard_id": self._context_dashboard(deleted=True).id}]),+ ]+ )+ def test_rejects_invalid_contexts(self, mock_is_cloud, mock_flag, mock_sync, _name, contexts_factory):+ self._enable_ai()+ self._mock_temporal(mock_sync)++ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(contexts=contexts_factory(self)),+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"].split("__", 1)[0] == "contexts"++ def _context_dashboard(self, **kwargs) -> Dashboard:+ return Dashboard.objects.create(team=self.team, name="Context dashboard", created_by=self.user, **kwargs)++ def test_rejects_contexts_on_traditional_subscriptions(self, mock_is_cloud, mock_flag, mock_sync):+ self._mock_temporal(mock_sync)+ context = self._context_dashboard()+ insight = Insight.objects.create(team=self.team, created_by=self.user)++ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ {+ **self._insight_payload(),+ "insight": insight.id,+ "contexts": [{"dashboard_id": context.id}],+ },+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "contexts"++ def test_context_replacement_rolls_back_subscription_and_rows(self, mock_is_cloud, mock_flag, mock_sync):+ self._enable_ai()+ self._mock_temporal(mock_sync)+ old_dashboard = self._context_dashboard()+ first_new = Insight.objects.create(team=self.team, created_by=self.user, name="First")+ second_new = Insight.objects.create(team=self.team, created_by=self.user, name="Second")+ created = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(contexts=[{"dashboard_id": old_dashboard.id}], send_test_now=False),+ )+ subscription = Subscription.objects.get(id=created.json()["id"])+ Subscription.objects.filter(id=subscription.id).update(ai_query_plan={"version": 1, "plan": {}})+ original_save = SubscriptionContext.save+ saves = 0++ def fail_second_save(context: SubscriptionContext, *args, **kwargs):+ nonlocal saves+ saves += 1+ if saves == 2:+ raise RuntimeError("forced context write failure")+ return original_save(context, *args, **kwargs)++ with (+ patch.object(SubscriptionContext, "save", autospec=True, side_effect=fail_second_save),+ patch("posthog.event_usage.posthoganalytics.capture") as mock_capture,+ ):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}",+ {+ "title": "Must roll back",+ "contexts": [{"insight_id": first_new.id}, {"insight_id": second_new.id}],+ },+ )++ assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR+ subscription.refresh_from_db()+ assert subscription.title == "Weekly AI report"+ assert subscription.ai_query_plan == {"version": 1, "plan": {}}+ restored_context = SubscriptionContext.objects.for_team(self.team.id).get(subscription=subscription)+ assert restored_context.dashboard_id == old_dashboard.id+ assert restored_context.insight_id is None+ mock_capture.assert_not_called()++ @parameterized.expand(+ [+ ("changed_set", False, True),+ ("same_set_reordered", True, False),+ ]+ )+ def test_context_set_change_drives_redelivery_without_touching_the_stored_plan(+ self, mock_is_cloud, mock_flag, mock_sync, _name, same_set, expects_delivery+ ):+ self._enable_ai()+ mock_client = self._mock_temporal(mock_sync)+ first = self._context_dashboard()+ second = Insight.objects.create(team=self.team, created_by=self.user, name="Second")+ third = Insight.objects.create(team=self.team, created_by=self.user, name="Third")+ created = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._make_ai_payload(+ contexts=[{"dashboard_id": first.id}, {"insight_id": second.id}], send_test_now=False+ ),+ )+ subscription = Subscription.objects.get(id=created.json()["id"])+ frozen_plan = {"version": 1, "plan": {}}+ Subscription.objects.filter(id=subscription.id).update(ai_query_plan=frozen_plan)+ mock_client.start_workflow.reset_mock()+ contexts = (+ [{"insight_id": second.id}, {"dashboard_id": first.id}]+ if same_set+ else [{"dashboard_id": first.id}, {"insight_id": third.id}]+ )++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}", {"contexts": contexts}+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ subscription.refresh_from_db()+ assert subscription.ai_query_plan == frozen_plan+ assert mock_client.start_workflow.call_count == int(expects_delivery)++ def test_traditional_resource_type_ignores_context_rows(self, mock_is_cloud, mock_flag, mock_sync):+ self._mock_temporal(mock_sync)+ root_insight = Insight.objects.create(team=self.team, created_by=self.user)+ root_dashboard = Dashboard.objects.create(team=self.team, name="Root", created_by=self.user)+ context = self._context_dashboard()+ subscriptions = [+ Subscription.objects.create(+ team=self.team,+ created_by=self.user,+ insight=root_insight,+ target_type="email",+ target_value="[email protected]",+ frequency="weekly",+ start_date=timezone.now(),+ ),+ Subscription.objects.create(+ team=self.team,+ created_by=self.user,+ dashboard=root_dashboard,+ target_type="email",+ target_value="[email protected]",+ frequency="weekly",+ start_date=timezone.now(),+ ),+ ]+ for subscription in subscriptions:+ SubscriptionContext.objects.for_team(self.team.id).create(+ team_id=subscription.team_id, subscription=subscription, dashboard=context+ )++ responses = [+ self.client.get(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}").json()+ for subscription in subscriptions+ ]++ assert [response["resource_type"] for response in responses] == ["insight", "dashboard"]+ assert [response["contexts"] for response in responses] == [[], []]++ def test_context_serialization_prefetches_targets(self, mock_is_cloud, mock_flag, mock_sync):+ self._mock_temporal(mock_sync)+ dashboard = self._context_dashboard()+ insight = Insight.objects.create(team=self.team, created_by=self.user, name="Context insight")+ for index, target in enumerate((dashboard, insight)):+ subscription = Subscription.objects.create(+ team=self.team,+ created_by=self.user,+ prompt=f"Prompt {index}",+ target_type="email",+ target_value="[email protected]",+ frequency="weekly",+ start_date=timezone.now(),+ )+ context_kwargs = {"dashboard": target} if isinstance(target, Dashboard) else {"insight": target}+ SubscriptionContext.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ subscription=subscription,+ **context_kwargs,+ )++ with CaptureQueriesContext(connection) as queries:+ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions")++ assert response.status_code == status.HTTP_200_OK, response.json()+ context_queries = [query["sql"] for query in queries if 'FROM "posthog_subscription_context"' in query["sql"]]+ assert len(context_queries) == 1+ dashboard_target_queries = [query["sql"] for query in queries if 'FROM "posthog_dashboard"' in query["sql"]]+ insight_target_queries = [query["sql"] for query in queries if 'FROM "posthog_insight"' in query["sql"]]+ assert dashboard_target_queries == []+ assert insight_target_queries == []+def test_create_ai_subscription_persists_trimmed_prompt(self, mock_is_cloud, mock_flag, mock_sync):self._enable_ai()self._mock_temporal(mock_sync)@@ -3638,6 +4063,28 @@ class TestSubscriptionObjectAccessControl(APILicensedTest):DashboardTile.objects.create(dashboard=dashboard, insight=insight)return dashboard+ def test_rejects_context_dashboard_with_an_unreadable_tile(self):+ self.organization.is_ai_data_processing_approved = True+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ dashboard = self._dashboard_with_tiles(self.open_insight, self.restricted_insight)++ with (+ patch("ee.api.subscription.is_cloud", return_value=True),+ patch("ee.api.subscription.posthoganalytics.feature_enabled", return_value=True),+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions",+ self._payload(+ prompt="Summarize the dashboard",+ contexts=[{"dashboard_id": dashboard.id}],+ send_test_now=False,+ ),+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "contexts"+ assert not Subscription.objects.filter(team_id=self.team.id, prompt="Summarize the dashboard").exists()+def _sub_on_an_open_insight(self) -> Subscription:return self._subscription_for(insight=self.open_insight)@@ -3650,6 +4097,25 @@ class TestSubscriptionObjectAccessControl(APILicensedTest):def _sub_on_an_ai_prompt(self) -> Subscription:return self._subscription_for(prompt="How did signups do last week?")+ def _ai_sub_with_contexts(self, *targets: Insight | Dashboard) -> Subscription:+ subscription = self._sub_on_an_ai_prompt()+ for target in targets:+ context_kwargs = {"insight": target} if isinstance(target, Insight) else {"dashboard": target}+ SubscriptionContext.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ subscription=subscription,+ **context_kwargs,+ )+ return subscription++ @staticmethod+ def _rename_context_target(target: Insight | Dashboard, name: str) -> None:+ if isinstance(target, Insight):+ Insight.objects.filter(pk=target.pk).update(name=name)+ else:+ Dashboard.objects.filter(pk=target.pk).update(name=name)+ target.name = name+def _sub_exporting_an_insight_restricted_afterwards(self) -> Subscription:exported = Insight.objects.create(team=self.team, filters={"events": [{"id": "$pageview"}]})subscription = self._subscription_for(dashboard=self._dashboard_with_tiles(exported))@@ -3748,6 +4214,116 @@ class TestSubscriptionObjectAccessControl(APILicensedTest):self._assert_visibility(subscription, sees_subscription=sees_subscription, sees_deliveries=sees_deliveries)+ @parameterized.expand(+ [+ ("restricted insight", "restricted_insight"),+ ("restricted dashboard", "restricted_dashboard"),+ ]+ )+ def test_ai_subscription_with_any_unreadable_live_context_is_hidden(self, _name, target_attribute):+ subscription = self._ai_sub_with_contexts(self.open_insight, getattr(self, target_attribute))++ listed = self.client.get(f"/api/projects/{self.team.id}/subscriptions")+ retrieved = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{subscription.id}")++ assert listed.status_code == status.HTTP_200_OK, listed.json()+ assert subscription.id not in [row["id"] for row in listed.json()["results"]]+ assert retrieved.status_code == status.HTTP_403_FORBIDDEN, retrieved.json()++ def test_ai_subscription_with_a_context_dashboard_containing_an_unreadable_tile_is_hidden(self):+ dashboard = self._dashboard_with_tiles(self.open_insight, self.restricted_insight)+ subscription = self._ai_sub_with_contexts(dashboard)+ self._delivery_for(subscription)++ self._assert_visibility(subscription, sees_subscription=False, sees_deliveries=False)++ @parameterized.expand(+ [+ ("restricted insight", lambda self: self.restricted_insight),+ ("restricted dashboard", lambda self: self.restricted_dashboard),+ (+ "dashboard with a restricted tile",+ lambda self: self._dashboard_with_tiles(self.open_insight, self.restricted_insight),+ ),+ ]+ )+ def test_historical_delivery_keeps_context_authorization_after_contexts_are_cleared(self, _name, target_factory):+ target = target_factory(self)+ kind = "insight" if isinstance(target, Insight) else "dashboard"+ subscription = self._ai_sub_with_contexts(target)+ self._delivery_for(subscription, context_refs=[f"{kind}:{target.id}"])+ SubscriptionContext.objects.for_team(self.team.id).filter(subscription=subscription).delete()++ self._assert_visibility(subscription, sees_subscription=True, sees_deliveries=False)++ @parameterized.expand(+ [+ ("restricted insight", "restricted_insight"),+ ("restricted dashboard", "restricted_dashboard"),+ ]+ )+ def test_unsnapshotted_delivery_falls_back_to_unreadable_live_context(self, _name, target_attribute):+ target = getattr(self, target_attribute)+ secret_name = f"Private context {uuid4()}"+ self._rename_context_target(target, secret_name)+ subscription = self._sub_on_an_ai_prompt()+ delivery = self._delivery_for(subscription)+ context_kwargs = {"insight": target} if isinstance(target, Insight) else {"dashboard": target}+ SubscriptionContext.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ subscription=subscription,+ **context_kwargs,+ )++ response = self.client.get(f"/api/environments/{self.team.id}/subscriptions/{subscription.id}/deliveries/")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["results"] == []+ assert str(delivery.id) not in response.content.decode()+ assert str(target.id) not in response.content.decode()+ assert secret_name not in response.content.decode()++ @parameterized.expand(+ [+ ("restricted insight", "restricted_insight"),+ ("restricted dashboard", "restricted_dashboard"),+ ]+ )+ def test_delivery_detail_forbids_ai_subscription_with_unreadable_context(self, _name, target_attribute):+ target = getattr(self, target_attribute)+ secret_name = f"Private context {uuid4()}"+ self._rename_context_target(target, secret_name)+ subscription = self._ai_sub_with_contexts(target)+ delivery = self._delivery_for(subscription)++ response = self.client.get(+ f"/api/environments/{self.team.id}/subscriptions/{subscription.id}/deliveries/{delivery.id}/"+ )++ assert response.status_code == status.HTTP_404_NOT_FOUND, response.json()+ assert str(delivery.id) not in response.content.decode()+ assert str(target.id) not in response.content.decode()+ assert secret_name not in response.content.decode()++ @parameterized.expand(+ [+ ("restricted insight", "restricted_insight", "insight_id"),+ ("restricted dashboard", "restricted_dashboard", "dashboard_id"),+ ]+ )+ def test_cannot_add_an_unreadable_context(self, _name, target_attribute, identifier):+ subscription = self._sub_on_an_ai_prompt()+ target = getattr(self, target_attribute)++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription.id}",+ {"contexts": [{identifier: target.id}], "send_test_now": False},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert response.json()["attr"] == "contexts"+ assert "Viewer access" in response.json()["detail"]+def _create_on_a_restricted_insight(self):return self.client.post(f"/api/projects/{self.team.id}/subscriptions", self._payload(insight=self.restricted_insight.id)diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex d669cb9598c1..21871078c05a 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -52690,6 +52690,11 @@"required": ["id", "tool_call_id", "content"],"type": "object"},+ "SubscriptionAIContextLimit": {+ "const": 3,+ "description": "Maximum number of dashboards and insights an AI subscription may use as context.",+ "type": "number"+ },"SubscriptionAIPromptMaxLength": {"const": 4000,"description": "Maximum length, in characters, of an AI subscription prompt.",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 6b79d2eeb4be..8359a6fdf5f3 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -9851,6 +9851,11 @@ export enum SubscriptionAIPromptMaxLength {CHARACTERS = 4000,}+/** Maximum number of dashboards and insights an AI subscription may use as context. */+export enum SubscriptionAIContextLimit {+ COUNT = 3,+}+export type UsageMetricFormat = 'numeric' | 'currency'export type UsageMetricDisplay = 'number' | 'sparkline'diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex b5bdecdd8a95..5eb827afa1ee 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -586,6 +586,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {# Scheduler-derived field; keep it out of user-facing change diffs even when another# field changes in the same save (signal_exclusions only governs whether the signal fires)."next_delivery_date",+ # Context rows use a fail-closed team manager that has no scope during signal handling.+ "contexts",# FK to a connected Slack integration. The generic field-diff captures the related object,# which isn't JSON-serializable for the change detail (same reason FeatureFlag/Experiment# exclude their FK relations) — without this, editing a subscription's integration 500s the save.diff --git a/posthog/models/test/test_subscription_activity_log.py b/posthog/models/test/test_subscription_activity_log.pyindex 2bedf1e35abd..976cdf21a332 100644--- a/posthog/models/test/test_subscription_activity_log.py+++ b/posthog/models/test/test_subscription_activity_log.py@@ -7,10 +7,11 @@ from posthog.test.base import BaseTestfrom parameterized import parameterized+from posthog.event_usage import EventSourcefrom posthog.models.activity_logging.activity_log import ActivityLogfrom products.dashboards.backend.models.dashboard import Dashboard-from products.exports.backend.models.subscription import Subscription+from products.exports.backend.models.subscription import Subscription, attribute_subscription_savesfrom products.product_analytics.backend.facade.models import Insight@@ -85,6 +86,25 @@ class TestSubscriptionActivityLog(BaseTest):assert prompt_change["before"] == "Summarize last week's signups"assert prompt_change["after"] == "Summarize last week's churn instead"+ def test_updating_subscription_records_context_changes(self):+ subscription = self._create_subscription()++ with attribute_subscription_saves(+ {"source": EventSource.WEB}, context_change=(["dashboard:1"], ["dashboard:2", "insight:3"])+ ):+ subscription.save()++ context_change = next(+ change for change in self._subscription_logs()[1].detail["changes"] if change["field"] == "contexts"+ )+ assert context_change == {+ "type": "Subscription",+ "field": "contexts",+ "action": "changed",+ "before": ["dashboard:1"],+ "after": ["dashboard:2", "insight:3"],+ }+@parameterized.expand([("adding_a_prompt", None, "Now summarize signups", "created"),diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.pyindex 8d7a8b4cc19d..fe388f22e8b0 100644--- a/posthog/models/test/test_subscription_model.py+++ b/posthog/models/test/test_subscription_model.py@@ -8,13 +8,14 @@ from posthog.test.base import BaseTestfrom unittest.mock import patchfrom django.conf import settings-from django.db import IntegrityError+from django.db import IntegrityError, transactionfrom django.utils import timezoneimport jwtfrom parameterized import parameterizedfrom posthog.constants import AvailableFeature+from posthog.event_usage import EventSourcefrom posthog.jwt import PosthogJwtAudiencefrom products.dashboards.backend.models.dashboard import Dashboard@@ -23,6 +24,7 @@ from products.exports.backend.models.subscription import (UNSUBSCRIBE_TOKEN_EXP_DAYS,Subscription,SubscriptionDelivery,+ attribute_subscription_saves,get_unsubscribe_token,unsubscribe_using_token,)@@ -152,6 +154,23 @@ class TestSubscription(BaseTest):**kwargs,)+ def test_analytics_event_runs_after_the_subscription_transaction_commits(self) -> None:+ with (+ patch("posthog.event_usage.posthoganalytics.capture") as mock_capture,+ self.captureOnCommitCallbacks(execute=True),+ attribute_subscription_saves({"source": EventSource.WEB}),+ ):+ with transaction.atomic():+ self._create_subscription(+ prompt="Summarize signups",+ title="Weekly AI digest",+ created_by=self.user,+ )+ mock_capture.assert_not_called()++ mock_capture.assert_called_once()+ assert mock_capture.call_args.kwargs["properties"]["source"] == EventSource.WEB+@parameterized.expand([(diff --git a/posthog/schema.py b/posthog/schema.pyindex 16f82968b701..ca751256b325 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -2974,6 +2974,13 @@ class SubagentUpdateEvent(BaseModel):tool_call_id: str+class SubscriptionAIContextLimit(RootModel[Literal[3]]):+ root: Literal[3] = Field(+ 3,+ description=("Maximum number of dashboards and insights an AI subscription may use as context."),+ )++class SubscriptionAIPromptMaxLength(RootModel[Literal[4000]]):root: Literal[4000] = Field(4000, description="Maximum length, in characters, of an AI subscription prompt.")diff --git a/products/exports/backend/migrations/0013_subscription_context.py b/products/exports/backend/migrations/0013_subscription_context.pynew file mode 100644index 000000000000..2340aae5f9b7--- /dev/null+++ b/products/exports/backend/migrations/0013_subscription_context.py@@ -0,0 +1,104 @@+# Generated by Django 5.2.17 on 2026-08-28 10:17++import django.db.models.deletion+import django.contrib.postgres.fields+from django.db import migrations, models++import posthog.uuidt+from posthog.migration_helpers import AddForeignKeyNotValid+++class Migration(migrations.Migration):+ dependencies = [+ ("exports", "0012_alter_subscription_created_by_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="subscriptiondelivery",+ name="context_refs",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=64), db_default=[], default=list, size=None+ ),+ ),+ migrations.CreateModel(+ name="SubscriptionContext",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "subscription",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="contexts",+ to="exports.subscription",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "dashboard",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="dashboards.dashboard",+ ),+ ),+ (+ "insight",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="product_analytics.insight",+ ),+ ),+ ],+ options={+ "db_table": "posthog_subscription_context",+ "constraints": [+ models.CheckConstraint(+ condition=models.Q(+ models.Q(("dashboard__isnull", False), ("insight__isnull", True)),+ models.Q(("dashboard__isnull", True), ("insight__isnull", False)),+ _connector="OR",+ ),+ name="subscription_context_exactly_one_target",+ ),+ models.UniqueConstraint(+ condition=models.Q(("dashboard__isnull", False)),+ fields=("subscription", "dashboard"),+ name="subscription_context_unique_dashboard",+ ),+ models.UniqueConstraint(+ condition=models.Q(("insight__isnull", False)),+ fields=("subscription", "insight"),+ name="subscription_context_unique_insight",+ ),+ ],+ },+ ),+ AddForeignKeyNotValid(+ model_name="subscriptioncontext",+ name="subscriptioncontext_team_id_fk",+ column="team_id",+ to_table="posthog_team",+ to_column="id",+ ),+ ]diff --git a/products/exports/backend/migrations/0014_validate_subscription_context_team_fk.py b/products/exports/backend/migrations/0014_validate_subscription_context_team_fk.pynew file mode 100644index 000000000000..61ebf7e203ab--- /dev/null+++ b/products/exports/backend/migrations/0014_validate_subscription_context_team_fk.py@@ -0,0 +1,15 @@+from django.db import migrations++from posthog.migration_helpers import ValidateForeignKey+++class Migration(migrations.Migration):+ """Validate the team FK separately so creating the context table stays non-blocking."""++ dependencies = [+ ("exports", "0013_subscription_context"),+ ]++ operations = [+ ValidateForeignKey(model_name="subscriptioncontext", name="subscriptioncontext_team_id_fk"),+ ]diff --git a/products/exports/backend/migrations/max_migration.txt b/products/exports/backend/migrations/max_migration.txtindex 904a1c727c4e..9ad17dfac883 100644--- a/products/exports/backend/migrations/max_migration.txt+++ b/products/exports/backend/migrations/max_migration.txt@@ -1 +1 @@-0012_alter_subscription_created_by_and_more+0014_validate_subscription_context_team_fkdiff --git a/products/exports/backend/models/__init__.py b/products/exports/backend/models/__init__.pyindex d2467a688e0f..6f1bcccd06fc 100644--- a/products/exports/backend/models/__init__.py+++ b/products/exports/backend/models/__init__.py@@ -1,8 +1,10 @@from .exported_asset import ExportedAssetfrom .subscription import Subscription, SubscriptionDelivery+from .subscription_context import SubscriptionContext__all__ = ["ExportedAsset","Subscription",+ "SubscriptionContext","SubscriptionDelivery",]diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.pyindex 483077da45e1..29a3ef55cdf3 100644--- a/products/exports/backend/models/subscription.py+++ b/products/exports/backend/models/subscription.py@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Any, Literal, Optional, castfrom urllib.parse import urlparsefrom django.contrib.postgres.fields import ArrayField-from django.db import models+from django.db import models, transactionfrom django.db.models.signals import post_savefrom django.dispatch import receiverfrom django.utils import timezone@@ -18,7 +18,7 @@ from dateutil.rrule import DAILY, FR, MO, MONTHLY, SA, SU, TH, TU, WE, WEEKLY, Yfrom posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exceptionfrom posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt-from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity+from posthog.models.activity_logging.activity_log import Change, ChangeAction, Detail, changes_between, log_activityfrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.signals import model_activity_signal, mutable_receiverfrom posthog.models.utils import UUIDModel@@ -40,15 +40,22 @@ UNSUBSCRIBE_TOKEN_EXP_DAYS = 30subscription_request_analytics_props: ContextVar[Optional["AnalyticsProps"]] = ContextVar("subscription_request_analytics_props", default=None)+subscription_context_activity_change: ContextVar[tuple[list[str], list[str]] | None] = ContextVar(+ "subscription_context_activity_change", default=None+)@contextmanager-def attribute_subscription_saves(analytics_props: "AnalyticsProps") -> Iterator[None]:- token = subscription_request_analytics_props.set(analytics_props)+def attribute_subscription_saves(+ analytics_props: "AnalyticsProps", *, context_change: tuple[list[str], list[str]] | None = None+) -> Iterator[None]:+ analytics_token = subscription_request_analytics_props.set(analytics_props)+ context_token = subscription_context_activity_change.set(context_change)try:yieldfinally:- subscription_request_analytics_props.reset(token)+ subscription_context_activity_change.reset(context_token)+ subscription_request_analytics_props.reset(analytics_token)# Single source of truth shared with the frontend create gate via generated schema@@ -273,6 +280,10 @@ class Subscription(ModelActivityMixin, models.Model):def includes_delivery_part(self, option: str) -> bool:return self._delivery_config_includes(self.delivery_config, option)+ def _should_log_activity_for_update(self, **kwargs: Any) -> tuple[bool, Any]:+ should_log, before_update = super()._should_log_activity_for_update(**kwargs)+ return should_log or subscription_context_activity_change.get() is not None, before_update+@classmethoddef derive_resource_type(cls, insight_id: int | None, dashboard_id: int | None, prompt: str | None) -> str:# Shared by the `resource_type` property and the scheduler's `.values()` fan-out@@ -564,15 +575,24 @@ def subscription_saved(sender, instance, created, raw, using, **kwargs):if kwargs.get("update_fields"):return- if instance.created_by and instance.resource_info:- event_name: str = f"{instance.resource_info.kind.lower()} subscription {'created' if created else 'updated'}"- report_user_action(- instance.created_by,- event_name,- instance.get_analytics_metadata(),- team=instance.team,- analytics_props=subscription_request_analytics_props.get(),- )+ resource_info = instance.resource_info+ if instance.created_by and resource_info:+ event_name: str = f"{resource_info.kind.lower()} subscription {'created' if created else 'updated'}"+ user = instance.created_by+ metadata = instance.get_analytics_metadata()+ team = instance.team+ analytics_props = subscription_request_analytics_props.get()++ def capture_subscription_event() -> None:+ report_user_action(+ user,+ event_name,+ metadata,+ team=team,+ analytics_props=analytics_props,+ )++ transaction.on_commit(capture_subscription_event, using=using)@mutable_receiver(model_activity_signal, sender=Subscription)@@ -584,6 +604,25 @@ def log_subscription_activity(returnchanges = changes_between("Subscription", previous=before_update, current=after_update)+ context_change = subscription_context_activity_change.get()+ if context_change is not None:+ before_contexts, after_contexts = context_change+ action: ChangeAction+ if not before_contexts:+ action = "created"+ elif not after_contexts:+ action = "deleted"+ else:+ action = "changed"+ changes.append(+ Change(+ type="Subscription",+ field="contexts",+ action=action,+ before=before_contexts or None,+ after=after_contexts or None,+ )+ )try:log_activity(organization_id=instance.team.organization_id,@@ -642,6 +681,9 @@ class SubscriptionDelivery(UUIDModel):exported_asset_ids: ArrayField = ArrayField(models.IntegerField(), default=list)content_snapshot = models.JSONField(default=dict)+ # db_default so workers on the previous image can INSERT without naming this column during a rolling deploy.+ context_refs = ArrayField(models.CharField(max_length=64), default=list, db_default=[])+# AI-generated summary sent in the delivery, when summary_enabled is on for the subscription.# None when no summary is attached.change_summary = models.TextField(null=True, blank=True)diff --git a/products/exports/backend/models/subscription_context.py b/products/exports/backend/models/subscription_context.pynew file mode 100644index 000000000000..cf023b26e017--- /dev/null+++ b/products/exports/backend/models/subscription_context.py@@ -0,0 +1,81 @@+from typing import Any++from django.core.exceptions import ValidationError+from django.db import models+from django.db.models import Q++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++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")+ dashboard = models.ForeignKey(+ "dashboards.Dashboard",+ on_delete=models.CASCADE,+ null=True,+ related_name="+",+ )+ insight = models.ForeignKey(+ "product_analytics.Insight",+ on_delete=models.CASCADE,+ null=True,+ related_name="+",+ )+ created_at = models.DateTimeField(auto_now_add=True)++ def has_target_for_team(self, team_id: int, *, include_deleted: bool) -> bool:+ if self.dashboard_id is not None:+ return (+ self.dashboard is not None+ and self.dashboard.team_id == team_id+ and (include_deleted or not self.dashboard.deleted)+ )+ if self.insight_id is not None:+ return (+ self.insight is not None+ and self.insight.team_id == team_id+ and (include_deleted or not self.insight.deleted)+ )+ return False++ def has_live_target_for_team(self, team_id: int) -> bool:+ return self.has_target_for_team(team_id, include_deleted=False)++ def clean(self) -> None:+ super().clean()+ context_team_id = self.team.parent_team_id or self.team_id+ if self.subscription_id:+ subscription_team = self.subscription.team+ subscription_team_id = subscription_team.parent_team_id or subscription_team.id+ if subscription_team_id != context_team_id:+ raise ValidationError("Subscription context must belong to the subscription team.")+ target = self.dashboard if self.dashboard_id is not None else self.insight+ if target is not None and target.team_id != context_team_id:+ raise ValidationError("Subscription context target must belong to the context team.")++ def save(self, *args: Any, **kwargs: Any) -> None:+ self.clean()+ super().save(*args, **kwargs)++ class Meta:+ db_table = "posthog_subscription_context"+ constraints = [+ models.CheckConstraint(+ condition=(+ Q(dashboard__isnull=False, insight__isnull=True) | Q(dashboard__isnull=True, insight__isnull=False)+ ),+ name="subscription_context_exactly_one_target",+ ),+ models.UniqueConstraint(+ fields=["subscription", "dashboard"],+ condition=Q(dashboard__isnull=False),+ name="subscription_context_unique_dashboard",+ ),+ models.UniqueConstraint(+ fields=["subscription", "insight"],+ condition=Q(insight__isnull=False),+ name="subscription_context_unique_insight",+ ),+ ]diff --git a/products/exports/backend/tests/test_subscription_context_model.py b/products/exports/backend/tests/test_subscription_context_model.pynew file mode 100644index 000000000000..496b8df8af34--- /dev/null+++ b/products/exports/backend/tests/test_subscription_context_model.py@@ -0,0 +1,112 @@+from posthog.test.base import BaseTest++from django.core.exceptions import ValidationError+from django.db import IntegrityError, transaction+from django.db.models import Model+from django.utils import timezone++from parameterized import parameterized++from posthog.models.scoping.manager import TeamScopeError++from products.dashboards.backend.models.dashboard import Dashboard+from products.exports.backend.models import Subscription, SubscriptionContext+from products.product_analytics.backend.facade.models import Insight+++class TestSubscriptionContextModel(BaseTest):+ def _subscription(self) -> Subscription:+ return Subscription.objects.create(+ team=self.team,+ prompt="Summarize this report",+ target_type=Subscription.SubscriptionTarget.EMAIL,+ target_value="[email protected]",+ frequency=Subscription.SubscriptionFrequency.WEEKLY,+ start_date=timezone.now(),+ )++ def _dashboard(self) -> Dashboard:+ return Dashboard.objects.create(team=self.team, name="Context dashboard", created_by=self.user)++ def _insight(self) -> Insight:+ return Insight.objects.create(team=self.team, name="Context insight", created_by=self.user)++ def _create_context(self, **kwargs: object) -> SubscriptionContext:+ defaults: dict[str, object] = {+ "team": self.team,+ "subscription": self._subscription(),+ "dashboard": self._dashboard(),+ }+ defaults.update(kwargs)+ return SubscriptionContext.objects.for_team(self.team.id).create(**defaults)++ def test_exactly_one_target_is_required(self) -> None:+ subscription = self._subscription()++ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create_context(subscription=subscription, dashboard=None)++ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create_context(subscription=subscription, insight=self._insight())++ @parameterized.expand([("dashboard",), ("insight",)])+ def test_duplicate_target_for_subscription_is_rejected(self, target_kind: str) -> None:+ subscription = self._subscription()+ target = self._dashboard() if target_kind == "dashboard" else self._insight()+ target_kwargs: dict[str, Dashboard | Insight | None] = {target_kind: target}+ if target_kind == "insight":+ target_kwargs["dashboard"] = None+ self._create_context(subscription=subscription, **target_kwargs)++ with self.assertRaises(IntegrityError), transaction.atomic():+ self._create_context(subscription=subscription, **target_kwargs)++ def test_for_team_returns_only_its_contexts(self) -> None:+ other_team = self.organization.teams.create(name="other")+ mine = self._create_context()+ other_subscription = Subscription.objects.create(+ team=other_team,+ prompt="Summarize another report",+ target_type=Subscription.SubscriptionTarget.EMAIL,+ target_value="[email protected]",+ frequency=Subscription.SubscriptionFrequency.WEEKLY,+ start_date=timezone.now(),+ )+ other_dashboard = Dashboard.objects.create(team=other_team, name="Other dashboard", created_by=self.user)+ SubscriptionContext.objects.for_team(other_team.id).create(+ team=other_team,+ subscription=other_subscription,+ dashboard=other_dashboard,+ )++ self.assertEqual(list(SubscriptionContext.objects.for_team(self.team.id)), [mine])++ def test_rejects_a_target_from_another_team(self) -> None:+ other_team = self.organization.teams.create(name="other")+ other_dashboard = Dashboard.objects.create(team=other_team, name="Other dashboard", created_by=self.user)++ with self.assertRaisesRegex(ValidationError, "target must belong"):+ self._create_context(dashboard=other_dashboard)++ def test_unscoped_read_fails_closed(self) -> None:+ self._create_context()++ with self.assertRaises(TeamScopeError):+ list(SubscriptionContext.objects.all())++ @parameterized.expand([("subscription",), ("dashboard",), ("insight",)])+ def test_target_delete_cascades_to_context(self, target_kind: str) -> None:+ target: Model+ if target_kind == "subscription":+ target = self._subscription()+ context = self._create_context(subscription=target)+ elif target_kind == "dashboard":+ target = self._dashboard()+ context = self._create_context(dashboard=target)+ else:+ target = self._insight()+ context = self._create_context(dashboard=None, insight=target)++ target.delete()++ self.assertFalse(SubscriptionContext.objects.unscoped().filter(pk=context.pk).exists())diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.pyindex 4ba51c3fb3a6..b907845a0177 100644--- a/products/product_analytics/backend/facade/api.py+++ b/products/product_analytics/backend/facade/api.py@@ -108,6 +108,10 @@ def recently_viewed_insights(*, team_id: int, user_id: int, limit: int) -> list[return logic.recently_viewed_insights(team_id=team_id, user_id=user_id, limit=limit)+def insights_including_soft_deleted_for_team(*, team_id: int, insight_ids: Collection[int]) -> list[Insight]:+ return logic.insights_including_soft_deleted_for_team(team_id=team_id, insight_ids=insight_ids)++def recent_viewers_by_insight(*, team_id: int, insight_ids: Collection[int], since: datetime, max_per_insight: int) -> dict[int, list["User"]]:diff --git a/products/product_analytics/backend/logic.py b/products/product_analytics/backend/logic.pyindex 62cdeecf97e8..5a5181302cda 100644--- a/products/product_analytics/backend/logic.py+++ b/products/product_analytics/backend/logic.py@@ -79,6 +79,10 @@ def recently_viewed_insights(*, team_id: int, user_id: int, limit: int) -> list[return recently_viewed+def insights_including_soft_deleted_for_team(*, team_id: int, insight_ids: Collection[int]) -> list[Insight]:+ return list(Insight.objects_including_soft_deleted.filter(team_id=team_id, id__in=insight_ids))++def recent_viewers_by_insight(*, team_id: int, insight_ids: Collection[int], since: datetime, max_per_insight: int) -> dict[int, list["User"]]:diff --git a/products/product_analytics/backend/tests/test_facade.py b/products/product_analytics/backend/tests/test_facade.pyindex 2fad8d4e5320..e353381ac8c6 100644--- a/products/product_analytics/backend/tests/test_facade.py+++ b/products/product_analytics/backend/tests/test_facade.py@@ -14,7 +14,11 @@ from posthog.schema import TrendsQueryResponsefrom posthog.clickhouse.query_tagging import reset_query_tags, tag_queriesfrom posthog.models.team import Team-from products.product_analytics.backend.facade.api import insight_variables_for_team, record_insight_view+from products.product_analytics.backend.facade.api import (+ insight_variables_for_team,+ insights_including_soft_deleted_for_team,+ record_insight_view,+)from products.product_analytics.backend.facade.queries import run_cached_trends_queryfrom products.product_analytics.backend.models.insight import Insight, InsightViewedfrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -65,6 +69,21 @@ class TestRecordInsightView(BaseTest):assert InsightViewed.objects.filter(insight_id=self.insight.pk).count() == 2+class TestInsightReads(BaseTest):+ def test_including_soft_deleted_insights_stays_scoped_to_the_team(self) -> None:+ deleted_insight = Insight.objects.create(team=self.team, name="Deleted", deleted=True)+ live_insight = Insight.objects.create(team=self.team, name="Live")+ other_team = Team.objects.create(organization=self.organization)+ other_team_insight = Insight.objects.create(team=other_team, name="Other team")++ insights = insights_including_soft_deleted_for_team(+ team_id=self.team.pk,+ insight_ids={deleted_insight.pk, live_insight.pk, other_team_insight.pk},+ )++ assert {insight.pk for insight in insights} == {deleted_insight.pk, live_insight.pk}++class TestRunCachedTrendsQuery(BaseTest):def tearDown(self) -> None:reset_query_tags()diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex 0aaf62ea37c4..73a510df474a 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -66,6 +66,24 @@ export interface AIPromptConfigApi {window?: AIWindowConfigApi}+export interface SubscriptionDashboardContextApi {+ /** Dashboard ID used to open the context dashboard. */+ dashboard_id: number+ /** Current display name of the context dashboard. */+ dashboard_name: string+}++export interface SubscriptionInsightContextApi {+ /** Database ID of the context insight. */+ insight_id: number+ /** Stable insight identifier used to open the context insight. */+ insight_short_id: string+ /** Current display name of the context insight. */+ insight_name: string+}++export type SubscriptionContextApi = SubscriptionDashboardContextApi | SubscriptionInsightContextApi+export type AIQueryPlanStatusEnumApi = (typeof AIQueryPlanStatusEnumApi)[keyof typeof AIQueryPlanStatusEnumApi]export const AIQueryPlanStatusEnumApi = {@@ -231,6 +249,8 @@ export interface SubscriptionApi {prompt?: string | null/** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */ai_prompt_config?: AIPromptConfigApi+ /** Dashboards and insights that ground this AI report. Deleted resources are omitted. */+ readonly contexts: readonly SubscriptionContextApi[]/** Query plan reuse state for AI prompt subscriptions: frozen, not_frozen, or planner_updated. Null for other subscription types. */readonly ai_query_plan_status: AIQueryPlanStatusEnumApi | null/** Delivery channel: email, slack, or teams.@@ -328,6 +348,175 @@ export interface PaginatedSubscriptionListApi {results: SubscriptionApi[]}+export type SubscriptionWriteApiContextsItem =+ | {+ /** @minimum 1 */+ dashboard_id: number+ }+ | {+ /** @minimum 1 */+ insight_id: number+ }++/**+ * * `monday` - Monday+ * * `tuesday` - Tuesday+ * * `wednesday` - Wednesday+ * * `thursday` - Thursday+ * * `friday` - Friday+ * * `saturday` - Saturday+ * * `sunday` - Sunday+ */+export type SubscriptionWriteApiByweekdayItem =+ (typeof SubscriptionWriteApiByweekdayItem)[keyof typeof SubscriptionWriteApiByweekdayItem]++export const SubscriptionWriteApiByweekdayItem = {+ Monday: 'monday',+ Tuesday: 'tuesday',+ Wednesday: 'wednesday',+ Thursday: 'thursday',+ Friday: 'friday',+ Saturday: 'saturday',+ Sunday: 'sunday',+} as const++/**+ * Standard Subscription serializer.+ */+export interface SubscriptionWriteApi {+ readonly id: number+ /** What the subscription delivers: 'insight' (snapshot of one insight), 'dashboard' (snapshot of one dashboard), or 'ai_prompt' (LLM-generated report). Read-only — derived from the populated target (insight → insight, dashboard → dashboard, prompt → ai_prompt).+ *+ * * `insight` - Insight+ * * `dashboard` - Dashboard+ * * `ai_prompt` - AI prompt */+ readonly resource_type: SubscriptionResourceTypeEnumApi+ /**+ * Dashboard ID to subscribe to (mutually exclusive with insight on create).+ * @nullable+ */+ dashboard?: number | null+ /**+ * Insight ID to subscribe to (mutually exclusive with dashboard on create).+ * @nullable+ */+ insight?: number | null+ /** @nullable */+ readonly insight_short_id: string | null+ /** @nullable */+ readonly resource_name: string | null+ /** List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 10. */+ dashboard_export_insights?: number[]+ /**+ * Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters.+ * @nullable+ */+ prompt?: string | null+ /** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */+ ai_prompt_config?: AIPromptConfigApi+ /**+ * Complete dashboard and insight context for an AI report. Omit on PATCH to preserve, pass an empty list to clear, or pass up to 3 items to replace all contexts.+ * @maxItems 3+ */+ contexts?: SubscriptionWriteApiContextsItem[]+ /** Query plan reuse state for AI prompt subscriptions: frozen, not_frozen, or planner_updated. Null for other subscription types. */+ readonly ai_query_plan_status: AIQueryPlanStatusEnumApi | null+ /** Delivery channel: email, slack, or teams.+ *+ * * `email` - Email+ * * `slack` - Slack+ * * `teams` - Microsoft Teams */+ target_type: SubscriptionTargetEnumApi+ /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it. */+ target_value: string+ /** How often to deliver: daily, weekly, monthly, or yearly.+ *+ * * `daily` - Daily+ * * `weekly` - Weekly+ * * `monthly` - Monthly+ * * `yearly` - Yearly */+ frequency: RecurrenceIntervalEnumApi+ /**+ * Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.+ * @minimum 1+ * @maximum 2147483647+ */+ interval: number+ /**+ * Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.+ * @nullable+ */+ byweekday?: SubscriptionWriteApiByweekdayItem[] | null+ /**+ * Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).+ * @minimum -2147483648+ * @maximum 2147483647+ * @nullable+ */+ bysetpos?: number | null+ /**+ * Total number of deliveries before the subscription stops. Null for unlimited.+ * @minimum -2147483648+ * @maximum 2147483647+ * @nullable+ */+ count?: number | null+ /** When to start delivering (ISO 8601 datetime). The date anchors the recurrence and may be in the past. Deliveries run on half-hour cycles at :00 and :30. Other minute values are accepted for backward compatibility, but delivery happens during the next cycle instead of at that exact minute. */+ start_date: string+ /**+ * When to stop delivering (ISO 8601 datetime). Null for indefinite.+ * @nullable+ */+ until_date?: string | null+ readonly created_at: string+ readonly created_by: UserBasicApi+ /** Set to true to soft-delete. Subscriptions cannot be hard-deleted. */+ deleted?: boolean+ /** Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid. */+ enabled?: boolean+ /**+ * Human-readable name for this subscription.+ * @maxLength 100+ * @nullable+ */+ title?: string | null+ /** Human-readable schedule summary, e.g. 'sent daily'. */+ readonly summary: string+ /** @nullable */+ readonly next_delivery_date: string | null+ /**+ * ID of a connected Slack integration. Required when target_type is slack.+ * @nullable+ */+ integration_id?: number | null+ /**+ * Optional message included in the invitation email when adding new recipients.+ * @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+ /**+ * Optional free-text guidance (max 500 chars) steering the AI summary, e.g. which metrics to emphasize. Only settable when AI summary context is enabled for the organization; clearing it (empty string) is always allowed.+ * @maxLength 500+ */+ summary_prompt_guide?: string+ /** Per-delivery rendering options. Each option documents which delivery targets it applies to. */+ delivery_config?: DeliveryConfigApi+}++export type PatchedSubscriptionWriteApiContextsItem =+ | {+ /** @minimum 1 */+ dashboard_id: number+ }+ | {+ /** @minimum 1 */+ insight_id: number+ }+/*** * `monday` - Monday* * `tuesday` - Tuesday@@ -337,10 +526,10 @@ export interface PaginatedSubscriptionListApi {* * `saturday` - Saturday* * `sunday` - Sunday*/-export type PatchedSubscriptionApiByweekdayItem =- (typeof PatchedSubscriptionApiByweekdayItem)[keyof typeof PatchedSubscriptionApiByweekdayItem]+export type PatchedSubscriptionWriteApiByweekdayItem =+ (typeof PatchedSubscriptionWriteApiByweekdayItem)[keyof typeof PatchedSubscriptionWriteApiByweekdayItem]-export const PatchedSubscriptionApiByweekdayItem = {+export const PatchedSubscriptionWriteApiByweekdayItem = {Monday: 'monday',Tuesday: 'tuesday',Wednesday: 'wednesday',@@ -353,7 +542,7 @@ export const PatchedSubscriptionApiByweekdayItem = {/*** Standard Subscription serializer.*/-export interface PatchedSubscriptionApi {+export interface PatchedSubscriptionWriteApi {readonly id?: number/** What the subscription delivers: 'insight' (snapshot of one insight), 'dashboard' (snapshot of one dashboard), or 'ai_prompt' (LLM-generated report). Read-only — derived from the populated target (insight → insight, dashboard → dashboard, prompt → ai_prompt).*@@ -384,6 +573,11 @@ export interface PatchedSubscriptionApi {prompt?: string | null/** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */ai_prompt_config?: AIPromptConfigApi+ /**+ * Complete dashboard and insight context for an AI report. Omit on PATCH to preserve, pass an empty list to clear, or pass up to 3 items to replace all contexts.+ * @maxItems 3+ */+ contexts?: PatchedSubscriptionWriteApiContextsItem[]/** Query plan reuse state for AI prompt subscriptions: frozen, not_frozen, or planner_updated. Null for other subscription types. */readonly ai_query_plan_status?: AIQueryPlanStatusEnumApi | null/** Delivery channel: email, slack, or teams.@@ -411,7 +605,7 @@ export interface PatchedSubscriptionApi {* Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.* @nullable*/- byweekday?: PatchedSubscriptionApiByweekdayItem[] | null+ byweekday?: PatchedSubscriptionWriteApiByweekdayItem[] | null/*** Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).* @minimum -2147483648diff --git a/products/subscriptions/frontend/generated/api.ts b/products/subscriptions/frontend/generated/api.tsindex 88382323191d..f932b49b56ce 100644--- a/products/subscriptions/frontend/generated/api.ts+++ b/products/subscriptions/frontend/generated/api.ts@@ -11,9 +11,10 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'import type {PaginatedSubscriptionDeliveryListApi,PaginatedSubscriptionListApi,- PatchedSubscriptionApi,+ PatchedSubscriptionWriteApi,SubscriptionApi,SubscriptionDeliveryApi,+ SubscriptionWriteApi,SubscriptionsDeliveriesListParams,SubscriptionsListParams,SubscriptionsSummaryQuotaRetrieve200,@@ -69,14 +70,14 @@ export const getSubscriptionsCreateUrl = (projectId: string) => {export const subscriptionsCreate = async (projectId: string,- subscriptionApi: NonReadonly<SubscriptionApi>,+ subscriptionWriteApi: NonReadonly<SubscriptionWriteApi>,options?: RequestInit): Promise<SubscriptionApi> => {return apiMutator<SubscriptionApi>(getSubscriptionsCreateUrl(projectId), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(subscriptionApi),+ body: JSON.stringify(subscriptionWriteApi),})}@@ -102,14 +103,14 @@ export const getSubscriptionsUpdateUrl = (projectId: string, id: number) => {export const subscriptionsUpdate = async (projectId: string,id: number,- subscriptionApi: NonReadonly<SubscriptionApi>,+ subscriptionWriteApi: NonReadonly<SubscriptionWriteApi>,options?: RequestInit): Promise<SubscriptionApi> => {return apiMutator<SubscriptionApi>(getSubscriptionsUpdateUrl(projectId, id), {...options,method: 'PUT',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(subscriptionApi),+ body: JSON.stringify(subscriptionWriteApi),})}@@ -120,14 +121,14 @@ export const getSubscriptionsPartialUpdateUrl = (projectId: string, id: number)export const subscriptionsPartialUpdate = async (projectId: string,id: number,- patchedSubscriptionApi?: NonReadonly<PatchedSubscriptionApi>,+ patchedSubscriptionWriteApi?: NonReadonly<PatchedSubscriptionWriteApi>,options?: RequestInit): Promise<SubscriptionApi> => {return apiMutator<SubscriptionApi>(getSubscriptionsPartialUpdateUrl(projectId, id), {...options,method: 'PATCH',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchedSubscriptionApi),+ body: JSON.stringify(patchedSubscriptionWriteApi),})}diff --git a/products/subscriptions/frontend/generated/api.zod.ts b/products/subscriptions/frontend/generated/api.zod.tsindex 55275080a4b8..a6208697c67f 100644--- a/products/subscriptions/frontend/generated/api.zod.ts+++ b/products/subscriptions/frontend/generated/api.zod.ts@@ -15,6 +15,8 @@ export const subscriptionsCreateBodyAiPromptConfigOneWindowOneStartDaysAgoMax =export const subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMin = 0export const subscriptionsCreateBodyAiPromptConfigOneWindowOneEndDaysAgoMax = 365+export const subscriptionsCreateBodyContextsMax = 3+export const subscriptionsCreateBodyIntervalMax = 2147483647export const subscriptionsCreateBodyBysetposMin = -2147483648@@ -90,6 +92,22 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.describe("Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."),+ contexts: zod+ .array(+ zod.union([+ zod.object({+ dashboard_id: zod.number().min(1),+ }),+ zod.object({+ insight_id: zod.number().min(1),+ }),+ ])+ )+ .max(subscriptionsCreateBodyContextsMax)+ .optional()+ .describe(+ 'Complete dashboard and insight context for an AI report. Omit on PATCH to preserve, pass an empty list to clear, or pass up to 3 items to replace all contexts.'+ ),target_type: zod.enum(['email', 'slack', 'teams']).describe('\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams')@@ -231,6 +249,8 @@ export const subscriptionsUpdateBodyAiPromptConfigOneWindowOneStartDaysAgoMax =export const subscriptionsUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMin = 0export const subscriptionsUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMax = 365+export const subscriptionsUpdateBodyContextsMax = 3+export const subscriptionsUpdateBodyIntervalMax = 2147483647export const subscriptionsUpdateBodyBysetposMin = -2147483648@@ -306,6 +326,22 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod.describe("Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."),+ contexts: zod+ .array(+ zod.union([+ zod.object({+ dashboard_id: zod.number().min(1),+ }),+ zod.object({+ insight_id: zod.number().min(1),+ }),+ ])+ )+ .max(subscriptionsUpdateBodyContextsMax)+ .optional()+ .describe(+ 'Complete dashboard and insight context for an AI report. Omit on PATCH to preserve, pass an empty list to clear, or pass up to 3 items to replace all contexts.'+ ),target_type: zod.enum(['email', 'slack', 'teams']).describe('\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams')@@ -447,6 +483,8 @@ export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneStartDaysAgexport const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMin = 0export const subscriptionsPartialUpdateBodyAiPromptConfigOneWindowOneEndDaysAgoMax = 365+export const subscriptionsPartialUpdateBodyContextsMax = 3+export const subscriptionsPartialUpdateBodyIntervalMax = 2147483647export const subscriptionsPartialUpdateBodyBysetposMin = -2147483648@@ -522,6 +560,22 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.describe("Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."),+ contexts: zod+ .array(+ zod.union([+ zod.object({+ dashboard_id: zod.number().min(1),+ }),+ zod.object({+ insight_id: zod.number().min(1),+ }),+ ])+ )+ .max(subscriptionsPartialUpdateBodyContextsMax)+ .optional()+ .describe(+ 'Complete dashboard and insight context for an AI report. Omit on PATCH to preserve, pass an empty list to clear, or pass up to 3 items to replace all contexts.'+ ),target_type: zod.enum(['email', 'slack', 'teams']).describe('\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams')diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionsTable.stories.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionsTable.stories.tsxindex b9a0dd1d065a..d094507491e2 100644--- a/products/subscriptions/frontend/scenes/components/SubscriptionsTable.stories.tsx+++ b/products/subscriptions/frontend/scenes/components/SubscriptionsTable.stories.tsx@@ -31,6 +31,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard: null,insight_short_id: 'abc123',resource_name: 'North star metric',+ contexts: [],title: 'This is a really long subscription name that does something important for the team every week',dashboard_export_insights: [],target_type: SubscriptionTargetEnumApi.Email,@@ -54,6 +55,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard: 501,insight_short_id: null,resource_name: 'Company overview',+ contexts: [],title: 'Some slack notification that does something',dashboard_export_insights: [101, 102],target_type: SubscriptionTargetEnumApi.Slack,@@ -77,6 +79,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard: null,insight_short_id: 'ghi789',resource_name: 'Weekly KPIs',+ contexts: [],title: 'Some test on an insight',dashboard_export_insights: [],target_type: SubscriptionTargetEnumApi.Email,@@ -99,6 +102,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard: null,insight_short_id: 'activation-insight',resource_name: 'Activation funnel',+ contexts: [],title: 'Slack delivery to internal automation',dashboard_export_insights: [],target_type: SubscriptionTargetEnumApi.Slack,@@ -121,6 +125,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard: null,insight_short_id: 'disabled-insight',resource_name: 'Activation funnel',+ contexts: [],title: 'Auto-paused after integration broke',dashboard_export_insights: [],target_type: SubscriptionTargetEnumApi.Slack,@@ -144,6 +149,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [dashboard: null,insight_short_id: null,resource_name: null,+ contexts: [],prompt: 'Summarize weekly signups and flag any anomalies worth a closer look',title: 'AI weekly digest',dashboard_export_insights: [],@@ -188,6 +194,7 @@ function buildMockSubscriptions(total: number): SubscriptionApi[] {dashboard: isInsight ? null : 2000 + n,insight_short_id: isInsight ? `short${n}` : null,resource_name: `Quarterly metrics ${n}`,+ contexts: [],title: `Digest ${n}`,dashboard_export_insights: [],target_type: isSlack ? SubscriptionTargetEnumApi.Slack : SubscriptionTargetEnumApi.Email,diff --git a/products/subscriptions/frontend/scenes/components/subscriptionStoryFixtures.ts b/products/subscriptions/frontend/scenes/components/subscriptionStoryFixtures.tsindex 383d9f09ff15..22fd59514406 100644--- a/products/subscriptions/frontend/scenes/components/subscriptionStoryFixtures.ts+++ b/products/subscriptions/frontend/scenes/components/subscriptionStoryFixtures.ts@@ -24,6 +24,7 @@ export const MOCK_SUBSCRIPTION_INSIGHT: SubscriptionApi = {dashboard: null,insight_short_id: 'abc123',resource_name: 'North star metric',+ contexts: [],title: 'Weekly rollup',dashboard_export_insights: [],target_type: SubscriptionTargetEnumApi.Email,@@ -56,6 +57,7 @@ export const MOCK_SUBSCRIPTION_DASHBOARD: SubscriptionApi = {dashboard: 501,insight_short_id: null,resource_name: 'Company overview',+ contexts: [],title: 'Dashboard digest',dashboard_export_insights: [101],target_type: SubscriptionTargetEnumApi.Slack,diff --git a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.tsindex 3d5b709190b0..bb5dbe78946a 100644--- a/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts+++ b/products/subscriptions/frontend/scenes/subscriptionSceneLogic.test.ts@@ -33,6 +33,7 @@ const MOCK_SUBSCRIPTION: SubscriptionApi = {dashboard: null,insight_short_id: 'abc123',resource_name: 'North star metric',+ contexts: [],title: 'Weekly rollup',dashboard_export_insights: [],target_type: SubscriptionTargetEnumApi.Email,@@ -55,6 +56,7 @@ const MOCK_AI_SUBSCRIPTION: SubscriptionApi = {dashboard: null,insight_short_id: null,resource_name: null,+ contexts: [],prompt: 'Summarize weekly signups and flag any anomalies',title: 'Weekly AI digest',dashboard_export_insights: [],diff --git a/products/subscriptions/mcp/tools.yaml b/products/subscriptions/mcp/tools.yamlindex 422d14b286e7..d878ce5b4ff4 100644--- a/products/subscriptions/mcp/tools.yaml+++ b/products/subscriptions/mcp/tools.yaml@@ -57,6 +57,7 @@ tools:summary (`summary_prompt_guide`). Do not enable the summary on your own without asking. (Promptsubscriptions are themselves AI-generated, so this does not apply to them.)exclude_params:+ - contexts- deleted- next_delivery_date- resource_name@@ -182,6 +183,7 @@ tools:it with `summary_prompt_guide`. Enabling a summary requires the organization to have approved AI dataprocessing and to be within its active-summary cap and AI credit budget; otherwise the update is rejected.exclude_params:+ - contexts- deleted- next_delivery_date- resource_namediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d5e7a9a50213..fef0deed92ec 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -60241,6 +60241,24 @@ export namespace Schemas {AiPrompt: 'ai_prompt',} as const;+ export interface SubscriptionDashboardContext {+ /** Dashboard ID used to open the context dashboard. */+ dashboard_id: number;+ /** Current display name of the context dashboard. */+ dashboard_name: string;+ }++ export interface SubscriptionInsightContext {+ /** Database ID of the context insight. */+ insight_id: number;+ /** Stable insight identifier used to open the context insight. */+ insight_short_id: string;+ /** Current display name of the context insight. */+ insight_name: string;+ }++ export type SubscriptionContext = SubscriptionDashboardContext | SubscriptionInsightContext;+/*** * `email` - Email* * `slack` - Slack@@ -60311,6 +60329,8 @@ export namespace Schemas {prompt?: string | null;/** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */ai_prompt_config?: AIPromptConfig;+ /** Dashboards and insights that ground this AI report. Deleted resources are omitted. */+ readonly contexts: readonly SubscriptionContext[];/** Query plan reuse state for AI prompt subscriptions: frozen, not_frozen, or planner_updated. Null for other subscription types. */readonly ai_query_plan_status: AIQueryPlanStatusEnum | null;/** Delivery channel: email, slack, or teams.@@ -69706,6 +69726,14 @@ export namespace Schemas {trigger_label?: string;}+ export type PatchedSubscriptionWriteContextsItem = {+ /** @minimum 1 */+ dashboard_id: number;+ } | {+ /** @minimum 1 */+ insight_id: number;+ };+/*** * `monday` - Monday* * `tuesday` - Tuesday@@ -69715,10 +69743,10 @@ export namespace Schemas {* * `saturday` - Saturday* * `sunday` - Sunday*/- export type PatchedSubscriptionByweekdayItem = typeof PatchedSubscriptionByweekdayItem[keyof typeof PatchedSubscriptionByweekdayItem];+ export type PatchedSubscriptionWriteByweekdayItem = typeof PatchedSubscriptionWriteByweekdayItem[keyof typeof PatchedSubscriptionWriteByweekdayItem];- export const PatchedSubscriptionByweekdayItem = {+ export const PatchedSubscriptionWriteByweekdayItem = {Monday: 'monday',Tuesday: 'tuesday',Wednesday: 'wednesday',@@ -69731,7 +69759,7 @@ export namespace Schemas {/*** Standard Subscription serializer.*/- export interface PatchedSubscription {+ export interface PatchedSubscriptionWrite {readonly id?: number;/** What the subscription delivers: 'insight' (snapshot of one insight), 'dashboard' (snapshot of one dashboard), or 'ai_prompt' (LLM-generated report). Read-only — derived from the populated target (insight → insight, dashboard → dashboard, prompt → ai_prompt).*@@ -69762,6 +69790,11 @@ export namespace Schemas {prompt?: string | null;/** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */ai_prompt_config?: AIPromptConfig;+ /**+ * Complete dashboard and insight context for an AI report. Omit on PATCH to preserve, pass an empty list to clear, or pass up to 3 items to replace all contexts.+ * @maxItems 3+ */+ contexts?: PatchedSubscriptionWriteContextsItem[];/** Query plan reuse state for AI prompt subscriptions: frozen, not_frozen, or planner_updated. Null for other subscription types. */readonly ai_query_plan_status?: AIQueryPlanStatusEnum | null;/** Delivery channel: email, slack, or teams.@@ -69789,7 +69822,7 @@ export namespace Schemas {* Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.* @nullable*/- byweekday?: PatchedSubscriptionByweekdayItem[] | null;+ byweekday?: PatchedSubscriptionWriteByweekdayItem[] | null;/*** Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).* @minimum -2147483648@@ -86520,6 +86553,163 @@ export namespace Schemas {interesting_notes: InterestingNote[];}+ export type SubscriptionWriteContextsItem = {+ /** @minimum 1 */+ dashboard_id: number;+ } | {+ /** @minimum 1 */+ insight_id: number;+ };++ /**+ * * `monday` - Monday+ * * `tuesday` - Tuesday+ * * `wednesday` - Wednesday+ * * `thursday` - Thursday+ * * `friday` - Friday+ * * `saturday` - Saturday+ * * `sunday` - Sunday+ */+ export type SubscriptionWriteByweekdayItem = typeof SubscriptionWriteByweekdayItem[keyof typeof SubscriptionWriteByweekdayItem];+++ export const SubscriptionWriteByweekdayItem = {+ Monday: 'monday',+ Tuesday: 'tuesday',+ Wednesday: 'wednesday',+ Thursday: 'thursday',+ Friday: 'friday',+ Saturday: 'saturday',+ Sunday: 'sunday',+ } as const;++ /**+ * Standard Subscription serializer.+ */+ export interface SubscriptionWrite {+ readonly id: number;+ /** What the subscription delivers: 'insight' (snapshot of one insight), 'dashboard' (snapshot of one dashboard), or 'ai_prompt' (LLM-generated report). Read-only — derived from the populated target (insight → insight, dashboard → dashboard, prompt → ai_prompt).+ *+ * * `insight` - Insight+ * * `dashboard` - Dashboard+ * * `ai_prompt` - AI prompt */+ readonly resource_type: SubscriptionResourceTypeEnum;+ /**+ * Dashboard ID to subscribe to (mutually exclusive with insight on create).+ * @nullable+ */+ dashboard?: number | null;+ /**+ * Insight ID to subscribe to (mutually exclusive with dashboard on create).+ * @nullable+ */+ insight?: number | null;+ /** @nullable */+ readonly insight_short_id: string | null;+ /** @nullable */+ readonly resource_name: string | null;+ /** List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 10. */+ dashboard_export_insights?: number[];+ /**+ * Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters.+ * @nullable+ */+ prompt?: string | null;+ /** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */+ ai_prompt_config?: AIPromptConfig;+ /**+ * Complete dashboard and insight context for an AI report. Omit on PATCH to preserve, pass an empty list to clear, or pass up to 3 items to replace all contexts.+ * @maxItems 3+ */+ contexts?: SubscriptionWriteContextsItem[];+ /** Query plan reuse state for AI prompt subscriptions: frozen, not_frozen, or planner_updated. Null for other subscription types. */+ readonly ai_query_plan_status: AIQueryPlanStatusEnum | null;+ /** Delivery channel: email, slack, or teams.+ *+ * * `email` - Email+ * * `slack` - Slack+ * * `teams` - Microsoft Teams */+ target_type: SubscriptionTargetEnum;+ /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it. */+ target_value: string;+ /** How often to deliver: daily, weekly, monthly, or yearly.+ *+ * * `daily` - Daily+ * * `weekly` - Weekly+ * * `monthly` - Monthly+ * * `yearly` - Yearly */+ frequency: RecurrenceIntervalEnum;+ /**+ * Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.+ * @minimum 1+ * @maximum 2147483647+ */+ interval: number;+ /**+ * Days of week for daily or weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.+ * @nullable+ */+ byweekday?: SubscriptionWriteByweekdayItem[] | null;+ /**+ * Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).+ * @minimum -2147483648+ * @maximum 2147483647+ * @nullable+ */+ bysetpos?: number | null;+ /**+ * Total number of deliveries before the subscription stops. Null for unlimited.+ * @minimum -2147483648+ * @maximum 2147483647+ * @nullable+ */+ count?: number | null;+ /** When to start delivering (ISO 8601 datetime). The date anchors the recurrence and may be in the past. Deliveries run on half-hour cycles at :00 and :30. Other minute values are accepted for backward compatibility, but delivery happens during the next cycle instead of at that exact minute. */+ start_date: string;+ /**+ * When to stop delivering (ISO 8601 datetime). Null for indefinite.+ * @nullable+ */+ until_date?: string | null;+ readonly created_at: string;+ readonly created_by: UserBasic;+ /** Set to true to soft-delete. Subscriptions cannot be hard-deleted. */+ deleted?: boolean;+ /** Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid. */+ enabled?: boolean;+ /**+ * Human-readable name for this subscription.+ * @maxLength 100+ * @nullable+ */+ title?: string | null;+ /** Human-readable schedule summary, e.g. 'sent daily'. */+ readonly summary: string;+ /** @nullable */+ readonly next_delivery_date: string | null;+ /**+ * ID of a connected Slack integration. Required when target_type is slack.+ * @nullable+ */+ integration_id?: number | null;+ /**+ * Optional message included in the invitation email when adding new recipients.+ * @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;+ /**+ * Optional free-text guidance (max 500 chars) steering the AI summary, e.g. which metrics to emphasize. Only settable when AI summary context is enabled for the organization; clearing it (empty string) is always allowed.+ * @maxLength 500+ */+ summary_prompt_guide?: string;+ /** Per-delivery rendering options. Each option documents which delivery targets it applies to. */+ delivery_config?: DeliveryConfig;+ }+/*** Body of POST /vision/scanners/suggest_tags/ — the classifier config currently being edited.*/