Skip to content

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

feat(subscriptions): AI subscription API, validation, telemetry, and UI (#59632)

Vasco de Krijgerc0eb99e7962a
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index 205efb436a58..64f4f8574aa5 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -1,5 +1,6 @@
import uuid
import asyncio
+from collections.abc import Callable
from typing import Any, Optional
from django.conf import settings
@@ -26,7 +27,11 @@ from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
-from posthog.constants import SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY
+from posthog.cloud_utils import is_cloud
+from posthog.constants import (
+ SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY,
+ SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY,
+)
from posthog.event_usage import groups
from posthog.exceptions import QuotaLimitExceeded
from posthog.exceptions_capture import capture_exception
@@ -40,6 +45,11 @@ from posthog.temporal.common.client import sync_connect
from posthog.utils import str_to_bool
from products.exports.backend.models.subscription import Subscription, SubscriptionDelivery, unsubscribe_using_token
+from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import (
+ PROMPT_MAX_LENGTH as AI_PROMPT_MAX_LENGTH,
+ PromptRejectedError,
+ sanitize_prompt,
+)
from products.exports.backend.temporal.subscriptions.types import (
ProcessSubscriptionWorkflowInputs,
SubscriptionTriggerType,
@@ -77,6 +87,22 @@ def _invalidate_summary_quota_cache(organization_id) -> None:
cache.delete(_summary_quota_cache_key(organization_id))
+def _ai_create_gate_reason(organization) -> Optional[str]:
+ if not settings.DEBUG and not is_cloud():
+ return "AI subscriptions are only available in PostHog Cloud."
+ if not organization.is_ai_data_processing_approved:
+ return "Your organization must approve AI data processing before creating AI subscriptions."
+ if not posthoganalytics.feature_enabled(
+ SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY,
+ str(organization.id),
+ groups={"organization": str(organization.id)},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ ):
+ return "AI subscriptions are not enabled for your organization."
+ return None
+
+
@extend_schema_field({"type": "array", "items": {"type": "integer"}})
class DashboardExportInsightsField(serializers.Field):
"""Custom field to handle ManyToMany dashboard_export_insights as a list of IDs."""
@@ -115,16 +141,28 @@ class SubscriptionSerializer(serializers.ModelSerializer):
)
insight_short_id = serializers.SerializerMethodField()
resource_name = serializers.SerializerMethodField()
+ resource_type = serializers.ChoiceField(
+ choices=Subscription.ResourceType.choices,
+ read_only=True,
+ help_text=(
+ "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)."
+ ),
+ )
class Meta:
model = Subscription
fields = [
"id",
+ "resource_type",
"dashboard",
"insight",
"insight_short_id",
"resource_name",
"dashboard_export_insights",
+ "prompt",
"target_type",
"target_value",
"frequency",
@@ -156,6 +194,12 @@ class SubscriptionSerializer(serializers.ModelSerializer):
"resource_name",
]
extra_kwargs = {
+ "prompt": {
+ "help_text": (
+ "Free-text prompt that drives the AI-generated report. Required when "
+ "resource_type is 'ai_prompt'. Max 4000 characters."
+ ),
+ },
"dashboard": {"help_text": "Dashboard ID to subscribe to (mutually exclusive with insight on create)."},
"insight": {"help_text": "Insight ID to subscribe to (mutually exclusive with dashboard on create)."},
"target_type": {"help_text": "Delivery channel: email, slack, or webhook."},
@@ -196,6 +240,42 @@ class SubscriptionSerializer(serializers.ModelSerializer):
info = obj.resource_info
return info.name if info else None
+ def _validate_insight_content(self, attrs: dict, existing: Optional[Subscription]) -> None:
+ if not (attrs.get("insight") or (existing and existing.insight_id)):
+ raise ValidationError({"insight": ["Insight is required for insight subscriptions."]})
+ if attrs.get("dashboard") or attrs.get("prompt"):
+ raise ValidationError({"insight": ["Insight subscriptions cannot also set dashboard or prompt."]})
+
+ def _validate_dashboard_content(self, attrs: dict, existing: Optional[Subscription]) -> None:
+ if not (attrs.get("dashboard") or (existing and existing.dashboard_id)):
+ raise ValidationError({"dashboard": ["Dashboard is required for dashboard subscriptions."]})
+ if attrs.get("insight") or attrs.get("prompt"):
+ raise ValidationError({"dashboard": ["Dashboard subscriptions cannot also set insight or prompt."]})
+
+ def _validate_ai_content(self, attrs: dict, existing: Optional[Subscription]) -> None:
+ if attrs.get("insight") or attrs.get("dashboard"):
+ raise ValidationError({"prompt": ["AI subscriptions cannot also set insight or dashboard."]})
+ # Explicit-key check so a PATCH sending prompt="" doesn't fall through to the stale value.
+ prompt = (attrs["prompt"] if "prompt" in attrs else (existing.prompt if existing else None)) or ""
+ prompt = prompt.strip()
+ if not prompt:
+ raise ValidationError({"prompt": ["Prompt is required for AI subscriptions."]})
+ if len(prompt) > AI_PROMPT_MAX_LENGTH:
+ raise ValidationError({"prompt": [f"Prompt cannot exceed {AI_PROMPT_MAX_LENGTH} characters."]})
+ if "prompt" in attrs:
+ attrs["prompt"] = prompt
+ target_type = attrs.get("target_type") or (existing.target_type if existing else None)
+ if target_type and target_type not in (
+ Subscription.SubscriptionTarget.EMAIL,
+ Subscription.SubscriptionTarget.SLACK,
+ ):
+ raise ValidationError({"target_type": ["AI subscriptions only support email or slack delivery."]})
+ # Gates fire on create only; existing AI subs stay editable.
+ if existing is None:
+ gate_reason = _ai_create_gate_reason(self.context["get_organization"]())
+ if gate_reason is not None:
+ raise ValidationError(gate_reason)
+
def validate(self, attrs):
request = self.context.get("request")
# Re-run the free-tier cap on create AND on restore (deleted: true → false) —
@@ -209,10 +289,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):
if msg:
raise ValidationError({"subscription": [msg]})
- if self.instance is None:
- # Create: a subscription must export an insight, a dashboard, or an AI prompt.
- if not attrs.get("dashboard") and not attrs.get("insight") and not attrs.get("prompt"):
- raise ValidationError("A subscription must have an insight, a dashboard, or a prompt.")
+ existing = self.instance
if attrs.get("dashboard") and attrs["dashboard"].team.id != self.context["team_id"]:
raise ValidationError({"dashboard": ["This dashboard does not belong to your team."]})
@@ -220,6 +297,35 @@ class SubscriptionSerializer(serializers.ModelSerializer):
if attrs.get("insight") and attrs["insight"].team.id != self.context["team_id"]:
raise ValidationError({"insight": ["This insight does not belong to your team."]})
+ if existing is None:
+ # Create: a subscription must export an insight, a dashboard, or an AI prompt.
+ if not attrs.get("dashboard") and not attrs.get("insight") and not attrs.get("prompt"):
+ raise ValidationError("A subscription must have an insight, a dashboard, or a prompt.")
+
+ try:
+ if existing is not None:
+ # `resource_type` derives from the row's content; a corrupt row (e.g. a prompt
+ # nulled directly in the DB) leaves nothing to derive from and raises.
+ resource_type = existing.resource_type
+ else:
+ insight, dashboard = attrs.get("insight"), attrs.get("dashboard")
+ resource_type = Subscription.derive_resource_type(
+ insight.id if insight else None, dashboard.id if dashboard else None, attrs.get("prompt")
+ )
+ except ValueError as exc:
+ raise ValidationError(str(exc))
+ content_validators: dict[str, Callable[[dict, Optional[Subscription]], None]] = {
+ Subscription.ResourceType.INSIGHT: self._validate_insight_content,
+ Subscription.ResourceType.DASHBOARD: self._validate_dashboard_content,
+ Subscription.ResourceType.AI_PROMPT: self._validate_ai_content,
+ }
+ validate_for_resource_type = content_validators.get(resource_type)
+ # Fail soft on an unexpected resource_type (e.g. a stale DB row) — a 400 is
+ # diagnosable, an unhandled KeyError surfaces as a 500.
+ if validate_for_resource_type is None:
+ raise ValidationError({"resource_type": [f"Unsupported resource_type: {resource_type}."]})
+ validate_for_resource_type(attrs, existing)
+
self._validate_dashboard_export_subscription(attrs)
target_type = attrs.get("target_type") or (self.instance.target_type if self.instance else None)
@@ -240,6 +346,22 @@ class SubscriptionSerializer(serializers.ModelSerializer):
error_message = validate_re_enable(target_type, integration_id)
if error_message:
raise ValidationError({"enabled": [error_message]})
+ # AI subs auto-disable on PromptRejectedError (deleted creator, prompt now
+ # fails sanitization). The delivery path will just re-disable on the next
+ # tick unless the underlying cause is fixed by this PATCH.
+ if resource_type == Subscription.ResourceType.AI_PROMPT:
+ prompt_after = attrs.get("prompt") if "prompt" in attrs else (existing.prompt if existing else None)
+ created_by_after = existing.created_by if existing else None
+ if created_by_after is None:
+ raise ValidationError(
+ {"enabled": ["Cannot re-enable AI subscription: the original creator is unavailable."]}
+ )
+ try:
+ sanitize_prompt(prompt_after)
+ except PromptRejectedError as exc:
+ raise ValidationError(
+ {"enabled": [f"Cannot re-enable AI subscription: prompt is invalid ({exc})."]}
+ )
# Reject mutations that would land `next_delivery_date=None` — `enabled=True`
# with a null next_delivery_date is invisible to the scheduler (the
@@ -347,6 +469,12 @@ class SubscriptionSerializer(serializers.ModelSerializer):
"Disable an existing summary or upgrade your plan to add more."
)
+ def _caller_distinct_id(self) -> str:
+ request = self.context.get("request")
+ if request and getattr(request, "user", None) and getattr(request.user, "distinct_id", None):
+ return str(request.user.distinct_id)
+ return f"team_{self.context.get('team_id')}"
+
def _capture_summary_cap_hit(self, organization, active_count: int, limit: int) -> None:
# Rate-limited to one event per org per 10 minutes so a misbehaving
# client retrying in a loop doesn't spam the analytics stream. Within
@@ -356,15 +484,9 @@ class SubscriptionSerializer(serializers.ModelSerializer):
return
cache.set(dedupe_key, True, SUMMARY_CAP_HIT_DEDUPE_TTL_SECONDS)
- request = self.context.get("request")
- distinct_id = (
- str(request.user.distinct_id)
- if request and getattr(request, "user", None) and getattr(request.user, "distinct_id", None)
- else f"team_{self.context.get('team_id')}"
- )
try:
posthoganalytics.capture(
- distinct_id=distinct_id,
+ distinct_id=self._caller_distinct_id(),
event="subscription_ai_summary_cap_hit",
properties={
"team_id": self.context.get("team_id"),
@@ -504,7 +626,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):
"byweekday": instance.byweekday,
"bysetpos": instance.bysetpos,
"count": instance.count,
- "resource_type": "dashboard" if instance.dashboard_id else "insight" if instance.insight_id else None,
+ "resource_type": instance.resource_type,
"dashboard_export_insights_count": len(dashboard_export_insight_ids),
"summary_enabled": instance.summary_enabled,
"has_summary_prompt_guide": bool(instance.summary_prompt_guide),
@@ -556,11 +678,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):
"subscription_id": instance.id,
"target_type": instance.target_type,
"frequency": instance.frequency,
- "resource_type": "dashboard"
- if instance.dashboard_id
- else "insight"
- if instance.insight_id
- else None,
+ "resource_type": instance.resource_type,
},
):
instance = super().update(instance, validated_data)
@@ -623,10 +741,10 @@ class SubscriptionSerializer(serializers.ModelSerializer):
OpenApiParameter(
name="resource_type",
type=str,
- enum=["insight", "dashboard"],
+ enum=["insight", "dashboard", "ai_prompt"],
location=OpenApiParameter.QUERY,
required=False,
- description="Filter by subscription resource: insight vs dashboard export.",
+ description="Filter by subscription resource: insight, dashboard export, or AI report.",
),
OpenApiParameter(
name="target_type",
@@ -653,7 +771,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):
],
),
)
-@extend_schema(extensions={"x-product": "core"})
+@extend_schema(tags=["subscriptions"])
class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet):
scope_object = "subscription"
queryset = Subscription.objects.all()
@@ -673,6 +791,44 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.M
]
ordering = ["-created_at"]
+ # 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
+ # token least-privileged, and the RBAC check in check_permissions enforces actual query access
+ # for every write — a scope is only a capability flag, not proof of RBAC (personal keys can
+ # carry query:read without it), and session auth has no scopes at all.
+ def dangerously_get_required_scopes(self, request, view) -> list[str] | None:
+ if request.method in ("GET", "HEAD", "OPTIONS"):
+ return None
+ scopes = [f"{self.scope_object}:write"]
+ if self._write_touches_ai_subscription(request, view):
+ scopes.append("query:read")
+ return scopes
+
+ def check_permissions(self, request) -> None:
+ super().check_permissions(request)
+ # Enforce query-viewer RBAC for every AI-prompt write, regardless of auth: the query:read
+ # scope above gates tokens but does not prove the owner has query access, and session auth
+ # bypasses scopes entirely.
+ if (
+ request.method not in ("GET", "HEAD", "OPTIONS")
+ and self._write_touches_ai_subscription(request, self)
+ and not self.user_access_control.check_access_level_for_resource("query", "viewer")
+ ):
+ raise exceptions.PermissionDenied("You need query access to create or deliver AI prompt subscriptions.")
+
+ def _write_touches_ai_subscription(self, request, view) -> bool:
+ if request.data.get("prompt"): # create (or a body that sets a prompt)
+ return True
+ # Existing subscription (update / test-delivery): resolve its kind by pk, team-scoped.
+ pk = view.kwargs.get("pk")
+ return bool(pk) and (
+ Subscription.objects.filter(pk=pk, team_id=self.team_id)
+ .exclude(prompt__isnull=True)
+ .exclude(prompt="")
+ .exists()
+ )
+
def safely_get_queryset(self, queryset) -> QuerySet:
request_params = self.request.GET.dict()
@@ -698,6 +854,8 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.M
queryset = queryset.filter(insight_id__isnull=False)
elif resource_type == "dashboard":
queryset = queryset.filter(dashboard_id__isnull=False)
+ elif resource_type == "ai_prompt":
+ queryset = queryset.filter(prompt__isnull=False).exclude(prompt="")
target_type_filter = request_params.get("target_type")
if target_type_filter:
@@ -776,7 +934,9 @@ class SubscriptionViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.M
detail=True,
url_path="test-delivery",
throttle_classes=[SubscriptionTestDeliveryThrottle],
- required_scopes=["subscription:write"],
+ # Scope is resolved dynamically in dangerously_get_required_scopes so AI subscriptions
+ # also require query:read (test-delivery runs the AI HogQL pipeline). A static
+ # required_scopes here would short-circuit that check.
)
def test_delivery(self, request, **kwargs):
subscription = self.get_object()
@@ -916,7 +1076,7 @@ class SubscriptionDeliveryCursorPagination(CursorPagination):
responses={200: SubscriptionDeliverySerializer},
),
)
-@extend_schema(extensions={"x-product": "core"})
+@extend_schema(tags=["subscriptions"])
class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.ReadOnlyModelViewSet):
scope_object = "subscription"
queryset = SubscriptionDelivery.objects.all()
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index 815ed50814f2..f510a85ecc44 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -12,11 +12,14 @@ from parameterized import parameterized
from rest_framework import status
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.constants import AvailableFeature
from posthog.models import Team
from posthog.models.filters.filter import Filter
from posthog.models.integration import Integration
+from posthog.models.organization import OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.slo.context import slo_operation
from products.dashboards.backend.models.dashboard import Dashboard
from products.exports.backend.models.subscription import (
@@ -31,6 +34,7 @@ from products.exports.backend.temporal.subscriptions.types import (
from products.product_analytics.backend.models.insight import Insight
from ee.api.test.base import APILicensedTest
+from ee.models.rbac.access_control import AccessControl
from ee.tasks.subscriptions.slack_subscriptions import get_slack_integration_for_team
@@ -92,12 +96,14 @@ class TestSubscriptionTemporal(APILicensedTest):
data = response.json()
assert data == {
"id": data["id"],
+ "resource_type": "insight",
"dashboard": None,
"insight": self.insight.id,
"insight_short_id": self.insight.short_id,
# Serializer uses f"{name or derived_name}"; when both are None that is the string "None", not null.
"resource_name": data["resource_name"],
"dashboard_export_insights": [],
+ "prompt": None,
"target_type": "email",
"target_value": "[email protected]",
"frequency": "weekly",
@@ -1998,3 +2004,436 @@ class TestSubscriptionFreeTierAccess(APILicensedTest):
)
response = self.client.get(f"/api/environments/{self.team.id}/subscriptions/{self.subscription.id}/deliveries/")
assert response.status_code == status.HTTP_200_OK
+
+
+@patch("ee.api.subscription.sync_connect")
+@patch("ee.api.subscription.posthoganalytics.feature_enabled", return_value=True)
+@patch("ee.api.subscription.is_cloud", return_value=True)
+class TestAISubscriptionAPI(APILicensedTest):
+ def _enable_ai(self):
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+
+ def _make_ai_payload(self, **overrides):
+ payload = {
+ "prompt": "What are the biggest event gains week-over-week?",
+ "target_type": "email",
+ "target_value": "[email protected]",
+ "frequency": "weekly",
+ "interval": 1,
+ "start_date": "2022-01-01T00:00:00",
+ "title": "Weekly AI report",
+ }
+ payload.update(overrides)
+ return payload
+
+ def _mock_temporal(self, mock_sync):
+ mock_client = MagicMock()
+ mock_client.start_workflow = AsyncMock()
+ mock_sync.return_value = mock_client
+ return mock_client
+
+ def _scoped_key_headers(self, scopes: list[str]) -> dict[str, str]:
+ raw_key = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label=f"scoped-{uuid4().hex[:8]}",
+ user=self.user,
+ secure_value=hash_key_value(raw_key),
+ scopes=scopes,
+ )
+ return {"authorization": f"Bearer {raw_key}"}
+
+ def _insight_payload(self) -> dict:
+ insight = Insight.objects.create(team=self.team, created_by=self.user)
+ return {
+ "insight": insight.id,
+ "target_type": "email",
+ "target_value": "[email protected]",
+ "frequency": "weekly",
+ "interval": 1,
+ "start_date": "2022-01-01T00:00:00",
+ "title": "Insight sub",
+ }
+
+ def _create_subscription_for(self, resource_kind: str) -> int:
+ if resource_kind == "ai_prompt":
+ self._enable_ai()
+ payload = self._make_ai_payload()
+ else:
+ payload = self._insight_payload()
+ created = self.client.post(f"/api/projects/{self.team.id}/subscriptions", payload)
+ assert created.status_code == status.HTTP_201_CREATED, created.json()
+ return created.json()["id"]
+
+ @parameterized.expand(
+ [
+ # AI prompt subscriptions run HogQL, so a scoped key needs query:read on top of
+ # subscription:write; insight subscriptions carry no prompt and are unaffected.
+ ("ai_without_query_read", "ai_prompt", ["subscription:write"], status.HTTP_403_FORBIDDEN),
+ ("ai_with_query_read", "ai_prompt", ["subscription:write", "query:read"], status.HTTP_201_CREATED),
+ ("insight_without_query_read", "insight", ["subscription:write"], status.HTTP_201_CREATED),
+ ]
+ )
+ def test_scoped_key_create_requires_query_read_only_for_ai(
+ self, mock_is_cloud, mock_flag, mock_sync, _name, resource_kind, scopes, expected_status
+ ):
+ self._mock_temporal(mock_sync)
+ if resource_kind == "ai_prompt":
+ self._enable_ai()
+ payload = self._make_ai_payload()
+ else:
+ payload = self._insight_payload()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ payload,
+ headers=self._scoped_key_headers(scopes),
+ )
+ assert response.status_code == expected_status, response.json()
+
+ @parameterized.expand(
+ [
+ # Mutating or test-delivering an existing AI subscription re-runs the HogQL pipeline,
+ # so it needs query:read too; the same actions on an insight subscription do not.
+ ("patch_ai_without", "ai_prompt", "patch", ["subscription:write"], status.HTTP_403_FORBIDDEN),
+ ("patch_ai_with", "ai_prompt", "patch", ["subscription:write", "query:read"], status.HTTP_200_OK),
+ ("deliver_ai_without", "ai_prompt", "test_delivery", ["subscription:write"], status.HTTP_403_FORBIDDEN),
+ (
+ "deliver_ai_with",
+ "ai_prompt",
+ "test_delivery",
+ ["subscription:write", "query:read"],
+ status.HTTP_202_ACCEPTED,
+ ),
+ ("deliver_insight", "insight", "test_delivery", ["subscription:write"], status.HTTP_202_ACCEPTED),
+ ]
+ )
+ def test_scoped_key_existing_subscription_requires_query_read_only_for_ai(
+ self, mock_is_cloud, mock_flag, mock_sync, _name, resource_kind, action, scopes, expected_status
+ ):
+ self._mock_temporal(mock_sync)
+ cache.clear() # avoid test-delivery throttle state leaking across parameterized cases
+ sub_id = self._create_subscription_for(resource_kind)
+ headers = self._scoped_key_headers(scopes)
+ if action == "patch":
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",
+ {"title": "Updated title"},
+ headers=headers,
+ )
+ else:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}/test-delivery/",
+ headers=headers,
+ )
+ assert response.status_code == expected_status, response.json()
+
+ def _enable_access_control_feature(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+
+ def _restrict_query_access(self) -> None:
+ # Demote the session user from owner (which bypasses AC) to member, enable the
+ # ACCESS_CONTROL feature, and write an explicit query "none" row so they fall below
+ # the read level required to run AI HogQL.
+ self._enable_access_control_feature()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save(update_fields=["level"])
+ AccessControl.objects.create(
+ team=self.team,
+ resource="query",
+ resource_id=None,
+ organization_member=self.organization_membership,
+ access_level="none",
+ )
+ # Drop any access-control state cached on a prior request in the same test.
+ cache.clear()
+
+ @parameterized.expand(
+ [
+ # The query-read gate fires only for AI prompt subscriptions (which run HogQL);
+ # insight subscriptions carry no prompt and stay unaffected for a restricted member.
+ ("create_ai", "ai_prompt", "create", status.HTTP_403_FORBIDDEN),
+ ("deliver_ai", "ai_prompt", "test_delivery", status.HTTP_403_FORBIDDEN),
+ ("create_insight", "insight", "create", status.HTTP_201_CREATED),
+ ("deliver_insight", "insight", "test_delivery", status.HTTP_202_ACCEPTED),
+ ]
+ )
+ def test_session_query_restricted_member(
+ self, mock_is_cloud, mock_flag, mock_sync, _name, resource_kind, flow, expected_status
+ ):
+ self._mock_temporal(mock_sync)
+ if flow == "create":
+ if resource_kind == "ai_prompt":
+ self._enable_ai()
+ payload = self._make_ai_payload()
+ else:
+ payload = self._insight_payload()
+ self._restrict_query_access()
+ response = self.client.post(f"/api/projects/{self.team.id}/subscriptions", payload)
+ else:
+ sub_id = self._create_subscription_for(resource_kind)
+ self._restrict_query_access()
+ response = self.client.post(f"/api/projects/{self.team.id}/subscriptions/{sub_id}/test-delivery/")
+ assert response.status_code == expected_status, response.json()
+
+ @parameterized.expand(
+ [
+ # A query:read SCOPE on a personal key is a capability flag, not proof of query RBAC — a
+ # restricted member can freely mint one. The RBAC gate must fire for token auth too, not
+ # just session auth, so AI writes are blocked; insight writes carry no prompt and stay allowed.
+ ("create_ai", "ai_prompt", "create", status.HTTP_403_FORBIDDEN),
+ ("deliver_ai", "ai_prompt", "test_delivery", status.HTTP_403_FORBIDDEN),
+ ("create_insight", "insight", "create", status.HTTP_201_CREATED),
+ ("deliver_insight", "insight", "test_delivery", status.HTTP_202_ACCEPTED),
+ ]
+ )
+ def test_scoped_key_query_restricted_member(
+ self, mock_is_cloud, mock_flag, mock_sync, _name, resource_kind, flow, expected_status
+ ):
+ self._mock_temporal(mock_sync)
+ cache.clear() # avoid test-delivery throttle state leaking across parameterized cases
+ headers = self._scoped_key_headers(["subscription:write", "query:read"])
+ if flow == "create":
+ if resource_kind == "ai_prompt":
+ self._enable_ai()
+ payload = self._make_ai_payload()
+ else:
+ payload = self._insight_payload()
+ self._restrict_query_access()
+ response = self.client.post(f"/api/projects/{self.team.id}/subscriptions", payload, headers=headers)
+ else:
+ sub_id = self._create_subscription_for(resource_kind)
+ self._restrict_query_access()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}/test-delivery/", headers=headers
+ )
+ assert response.status_code == expected_status, response.json()
+
+ @parameterized.expand(
+ [
+ # The owner bypasses access controls; a plain member with no explicit query row keeps
+ # the default "editor" level. Both clear the read gate, so the create path must not regress.
+ ("owner", False),
+ ("member_without_query_restriction", True),
+ ]
+ )
+ def test_session_unrestricted_user_can_create_ai(self, mock_is_cloud, mock_flag, mock_sync, _name, as_member):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ if as_member:
+ self._enable_access_control_feature()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save(update_fields=["level"])
+ cache.clear()
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ def test_creates_ai_subscription(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ data = response.json()
+ assert data["resource_type"] == "ai_prompt"
+ assert data["prompt"] == "What are the biggest event gains week-over-week?"
+ assert data["insight"] is None
+ assert data["dashboard"] is None
+
+ def test_create_ai_subscription_persists_trimmed_prompt(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(prompt=" Weekly growth recap "),
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert response.json()["prompt"] == "Weekly growth recap"
+
+ def test_create_includes_resource_type_in_slo_properties(self, mock_is_cloud, mock_flag, mock_sync):
+ # resource_type telemetry rides on the existing subscription-create SLO rather than
+ # a separate capture, so the content-kind split lives in one metric/dashboard.
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ with patch("ee.api.subscription.slo_operation", wraps=slo_operation) as mock_slo:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ assert mock_slo.call_args is not None, "slo_operation was not called on create"
+ properties = mock_slo.call_args.kwargs["properties"]
+ assert properties["resource_type"] == "ai_prompt"
+ assert properties["target_type"] == "email"
+ assert properties["subscription_id"] == response.json()["id"]
+
+ def test_list_filter_by_resource_type_ai_prompt(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ ai_res = self.client.post(f"/api/projects/{self.team.id}/subscriptions", self._make_ai_payload())
+ assert ai_res.status_code == status.HTTP_201_CREATED, ai_res.json()
+ ai_id = ai_res.json()["id"]
+
+ insight = Insight.objects.create(team=self.team, created_by=self.user)
+ insight_sub = Subscription.objects.create(
+ team=self.team,
+ insight=insight,
+ target_type="email",
+ target_value="[email protected]",
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2022, 1, 1, tzinfo=UTC),
+ title="Insight sub",
+ created_by=self.user,
+ )
+
+ only_ai = self.client.get(f"/api/projects/{self.team.id}/subscriptions/", {"resource_type": "ai_prompt"})
+ assert only_ai.status_code == status.HTTP_200_OK
+ ids = {r["id"] for r in only_ai.json()["results"]}
+ assert ai_id in ids
+ assert insight_sub.id not in ids
+
+ def test_rejects_without_ai_consent(self, mock_is_cloud, mock_flag, mock_sync):
+ self._mock_temporal(mock_sync)
+ # Orgs are AI-approved by default, so opt out explicitly to exercise the consent gate.
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save(update_fields=["is_ai_data_processing_approved"])
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "AI data processing" in str(response.json())
+
+ def test_rejects_when_not_cloud_or_debug(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ mock_is_cloud.return_value = False
+ self._mock_temporal(mock_sync)
+ with self.settings(DEBUG=False):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "PostHog Cloud" in str(response.json())
+
+ def test_rejects_when_flag_off(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ mock_flag.return_value = False
+ self._mock_temporal(mock_sync)
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "not enabled" in str(response.json())
+
+ @parameterized.expand(
+ [
+ # blank prompt → no derivable target → non-field "must target" error
+ ("empty_prompt", {"prompt": " "}, None),
+ ("oversize_prompt", {"prompt": "x" * 4001}, "prompt"),
+ ("insight_set_too", {"prompt": "ok", "insight": -1}, "insight"),
+ ("dashboard_set_too", {"prompt": "ok", "dashboard": -1}, "dashboard"),
+ ]
+ )
+ def test_rejects_invalid_ai_payloads(self, mock_is_cloud, mock_flag, mock_sync, name, overrides, expected_attr):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ if overrides.get("insight") == -1:
+ insight = Insight.objects.create(team=self.team, created_by=self.user)
+ overrides["insight"] = insight.id
+ if overrides.get("dashboard") == -1:
+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user, name="d")
+ overrides["dashboard"] = dashboard.id
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(**overrides),
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ # The kind is derived from the populated target, so a malformed payload reports against
+ # the target field that drove the derivation (insight over dashboard over prompt), or a
+ # non-field error (attr None) when nothing valid was provided.
+ assert response.json()["attr"] == expected_attr, response.json()
+
+ def test_can_update_ai_subscription_prompt(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ create_resp = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ sub_id = create_resp.json()["id"]
+
+ update_resp = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",
+ {"prompt": "Show me new error events"},
+ )
+ assert update_resp.status_code == status.HTTP_200_OK, update_resp.json()
+ assert update_resp.json()["prompt"] == "Show me new error events"
+
+ def test_resource_type_is_derived_and_read_only(self, mock_is_cloud, mock_flag, mock_sync):
+ # resource_type is derived from the populated target and read-only — a client can
+ # neither set it on create nor change it on update.
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ insight = Insight.objects.create(team=self.team, short_id="aiins", name="x")
+ create_resp = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ {
+ # resource_type omitted on purpose — derived from the insight target.
+ "insight": insight.id,
+ "target_type": "email",
+ "target_value": "[email protected]",
+ "frequency": "weekly",
+ "interval": 1,
+ "start_date": "2022-01-01T00:00:00",
+ "title": "ins",
+ },
+ )
+ assert create_resp.status_code == status.HTTP_201_CREATED, create_resp.json()
+ assert create_resp.json()["resource_type"] == "insight"
+ sub_id = create_resp.json()["id"]
+ # A read-only resource_type in the body is ignored.
+ patch_resp = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",
+ {"resource_type": "ai_prompt"},
+ )
+ assert patch_resp.status_code == status.HTTP_200_OK, patch_resp.json()
+ assert patch_resp.json()["resource_type"] == "insight"
+
+ @parameterized.expand(
+ [
+ ("whitespace_prompt", " "),
+ # A NULL prompt (e.g. a row patched directly in the DB) must surface as a 400,
+ # not an AttributeError/500: sanitize_prompt treats None as an empty prompt.
+ ("none_prompt", None),
+ ]
+ )
+ def test_re_enabling_ai_sub_with_invalid_prompt_is_rejected(
+ self, mock_is_cloud, mock_flag, mock_sync, _name, stored_prompt
+ ):
+ # An auto-disabled AI sub re-enabled via plain PATCH {enabled:true} would
+ # just re-disable on the next tick (burning LLM tokens).
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ create_resp = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ sub_id = create_resp.json()["id"]
+ Subscription.objects.filter(pk=sub_id).update(enabled=False, prompt=stored_prompt)
+ patch_resp = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",
+ {"enabled": True},
+ )
+ assert patch_resp.status_code == status.HTTP_400_BAD_REQUEST, patch_resp.json()
+ assert "prompt" in str(patch_resp.json()).lower(), patch_resp.json()
diff --git a/frontend/package.json b/frontend/package.json
index 4114711c29e3..9acfb31e4283 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -112,6 +112,7 @@
"@posthog/products-revenue-analytics": "workspace:*",
"@posthog/products-session-replay": "workspace:*",
"@posthog/products-session-summaries": "workspace:*",
+ "@posthog/products-subscriptions": "workspace:*",
"@posthog/products-surveys": "workspace:*",
"@posthog/products-tasks": "workspace:*",
"@posthog/products-tracing": "workspace:*",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index c3b69418990a..2c438a275556 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5975,13 +5975,13 @@ snapshots:
scenes-app-subscriptions-subscription-summary--insight-many-destinations--light:
hash: v1.k794b7964.7968690ed0c205c44a124a590d4378a488129c505f67436dbf3ccaa4b1127492.8bq6koR9lVBh_hOICo4GHZrNdYCDfasqz8VoDggeGsA
scenes-app-subscriptions-subscriptionstable--default--dark:
- hash: v1.k794b7964.90f2e62383083127824591d993cee4ea4e504c06c58c817a915855da8f9dbfcd.AUdcp8LfnQvA4t0K29T_3cYd_07Pn-JTg52khlAAFZQ
+ hash: v1.k794b7964.b3f3b2c01567c7d72eba23504db526930781bbe753a4b4f020ed51aae676cfbd.tPRkawUFWJVsNMD1uAKT-Zm7kKp0-o-UudlAMTMwJXk
scenes-app-subscriptions-subscriptionstable--default--light:
- hash: v1.k794b7964.024cc8a50da2c6659f3fded562bb951d03263b969317c30708bb5c29d8e8e4da.OCK4oPEo-HrE9EwTICKmKrMLW_pffQ2uwoAvioc-TkU
+ hash: v1.k794b7964.283b6f5441a9bb131568f8cc918a7fa1da1c52bd1f9945668439ecd32d0acf5e.7nxMCGUyAGRC9ggvUdXH-WUKTbuopflGU1tFI_AUUVQ
scenes-app-subscriptions-subscriptionstable--with-pagination--dark:
- hash: v1.k794b7964.759c8e8a9d24283d827034c494fa2fef7c6ed6ab238be90e7a281ed5968a693b.ZhjfE7xtKH9wEgfEpuT6dMx9rJsz2-tvb1dIfolmUUI
+ hash: v1.k794b7964.4620b970b0112abfa403d669108c4aaa5a441fbca38949603551a4fd80f4830f.gBSKjxx7cakZ6Plja9cr9m-RmX1ZMOr-xO80xSCaQEU
scenes-app-subscriptions-subscriptionstable--with-pagination--light:
- hash: v1.k794b7964.2ecda154ffcd640ee1a2c456c53fed9df6376ca1402b4a4ae883f3d2d4ec4361.G3m__wRYh5gaqLM56d-lUTwnan6iGGUxvaplIvum1I4
+ hash: v1.k794b7964.4a730a7c835a092b2f82bed826231eca38d8f72d817f41e4cfa2f884a3684fbc.5SMeMec8ZUX22Y_HNOBodyEAhJQzqiteFStvkNdO8Y8
scenes-app-surveys--new-multi-question-survey-section--dark:
hash: v1.k794b7964.80244fc6a3d8a3130f386c0d4edcef49215f42a03be7f3ab1be45e8ac882a26c.KVHHAxOkmAL6XM5tYddm5-X_Zr6PSekVz_3BPjJ809k
scenes-app-surveys--new-multi-question-survey-section--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 73ea66217849..ae7e2915c72f 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -7,81 +7,6 @@
* PostHog API - core
* OpenAPI spec version: 1.0.0
*/
-/**
- * * `starting` - Starting
- * `completed` - Completed
- * `failed` - Failed
- * `skipped` - Skipped
- */
-export type SubscriptionDeliveryStatusEnumApi =
- (typeof SubscriptionDeliveryStatusEnumApi)[keyof typeof SubscriptionDeliveryStatusEnumApi]
-
-export const SubscriptionDeliveryStatusEnumApi = {
- Starting: 'starting',
- Completed: 'completed',
- Failed: 'failed',
- Skipped: 'skipped',
-} as const
-
-export interface SubscriptionDeliveryApi {
- /** Primary key for this delivery row. */
- readonly id: string
- /** Parent subscription id. */
- readonly subscription: number
- /** Temporal workflow id for this delivery run. */
- readonly temporal_workflow_id: string
- /** Dedupes activity retries for the same logical run. */
- readonly idempotency_key: string
- /** Why the run started (e.g. scheduled, manual, target_change). */
- readonly trigger_type: string
- /**
- * Planned send time when applicable.
- * @nullable
- */
- readonly scheduled_at: string | null
- /** Channel snapshot at send time (email, slack, webhook). */
- readonly target_type: string
- /** Destination snapshot at send time (emails, channel id, URL). */
- readonly target_value: string
- /** ExportedAsset ids generated for this send. */
- readonly exported_asset_ids: readonly number[]
- /** Snapshot at send time: dashboard metadata, total_insight_count, and per-exported-insight entries (id, short_id, name, query_hash, cache_key, query_results, optional query_error). */
- readonly content_snapshot: unknown
- /** Per-destination outcomes; items use status success, failed, or partial. */
- readonly recipient_results: unknown
- /** Overall run status: starting, completed, failed, or skipped.
-
- * `starting` - Starting
- * `completed` - Completed
- * `failed` - Failed
- * `skipped` - Skipped */
- readonly status: SubscriptionDeliveryStatusEnumApi
- /** Top-level failure payload when status is failed, if any. */
- readonly error: unknown
- /** When the delivery row was created. */
- readonly created_at: string
- /** Last ORM update to this row. */
- readonly last_updated_at: string
- /**
- * When the run finished, if applicable.
- * @nullable
- */
- readonly finished_at: string | null
- /**
- * AI-generated summary included in this delivery, when one was produced.
- * @nullable
- */
- readonly change_summary: string | null
-}
-
-export interface PaginatedSubscriptionDeliveryListApi {
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: SubscriptionDeliveryApi[]
-}
-
/**
* * `engineering` - Engineering
* `data` - Data
@@ -2633,286 +2558,6 @@ export interface BulkUpdateTagsResponseApi {
skipped: BulkUpdateTagsErrorApi[]
}
-/**
- * * `email` - Email
- * `slack` - Slack
- * `webhook` - Webhook
- */
-export type TargetTypeEnumApi = (typeof TargetTypeEnumApi)[keyof typeof TargetTypeEnumApi]
-
-export const TargetTypeEnumApi = {
- Email: 'email',
- Slack: 'slack',
- Webhook: 'webhook',
-} as const
-
-/**
- * * `daily` - Daily
- * `weekly` - Weekly
- * `monthly` - Monthly
- * `yearly` - Yearly
- */
-export type SubscriptionFrequencyEnumApi =
- (typeof SubscriptionFrequencyEnumApi)[keyof typeof SubscriptionFrequencyEnumApi]
-
-export const SubscriptionFrequencyEnumApi = {
- Daily: 'daily',
- Weekly: 'weekly',
- Monthly: 'monthly',
- Yearly: 'yearly',
-} as const
-
-/**
- * * `monday` - Monday
- * `tuesday` - Tuesday
- * `wednesday` - Wednesday
- * `thursday` - Thursday
- * `friday` - Friday
- * `saturday` - Saturday
- * `sunday` - Sunday
- */
-export type SubscriptionApiByweekdayItem =
- (typeof SubscriptionApiByweekdayItem)[keyof typeof SubscriptionApiByweekdayItem]
-
-export const SubscriptionApiByweekdayItem = {
- Monday: 'monday',
- Tuesday: 'tuesday',
- Wednesday: 'wednesday',
- Thursday: 'thursday',
- Friday: 'friday',
- Saturday: 'saturday',
- Sunday: 'sunday',
-} as const
-
-/**
- * Standard Subscription serializer.
- */
-export interface SubscriptionApi {
- readonly id: number
- /**
- * 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 6. */
- dashboard_export_insights?: number[]
- /** Delivery channel: email, slack, or webhook.
-
- * `email` - Email
- * `slack` - Slack
- * `webhook` - Webhook */
- target_type: TargetTypeEnumApi
- /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or full URL for webhook. */
- target_value: string
- /** How often to deliver: daily, weekly, monthly, or yearly.
-
- * `daily` - Daily
- * `weekly` - Weekly
- * `monthly` - Monthly
- * `yearly` - Yearly */
- frequency: SubscriptionFrequencyEnumApi
- /**
- * 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 weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
- * @nullable
- */
- byweekday?: SubscriptionApiByweekdayItem[] | 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). */
- 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
- summary_enabled?: boolean
- /** @maxLength 500 */
- summary_prompt_guide?: string
-}
-
-export interface PaginatedSubscriptionListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: SubscriptionApi[]
-}
-
-/**
- * * `monday` - Monday
- * `tuesday` - Tuesday
- * `wednesday` - Wednesday
- * `thursday` - Thursday
- * `friday` - Friday
- * `saturday` - Saturday
- * `sunday` - Sunday
- */
-export type PatchedSubscriptionApiByweekdayItem =
- (typeof PatchedSubscriptionApiByweekdayItem)[keyof typeof PatchedSubscriptionApiByweekdayItem]
-
-export const PatchedSubscriptionApiByweekdayItem = {
- Monday: 'monday',
- Tuesday: 'tuesday',
- Wednesday: 'wednesday',
- Thursday: 'thursday',
- Friday: 'friday',
- Saturday: 'saturday',
- Sunday: 'sunday',
-} as const
-
-/**
- * Standard Subscription serializer.
- */
-export interface PatchedSubscriptionApi {
- readonly id?: number
- /**
- * 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 6. */
- dashboard_export_insights?: number[]
- /** Delivery channel: email, slack, or webhook.
-
- * `email` - Email
- * `slack` - Slack
- * `webhook` - Webhook */
- target_type?: TargetTypeEnumApi
- /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or full URL for webhook. */
- target_value?: string
- /** How often to deliver: daily, weekly, monthly, or yearly.
-
- * `daily` - Daily
- * `weekly` - Weekly
- * `monthly` - Monthly
- * `yearly` - Yearly */
- frequency?: SubscriptionFrequencyEnumApi
- /**
- * 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 weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
- * @nullable
- */
- byweekday?: PatchedSubscriptionApiByweekdayItem[] | 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). */
- 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
- summary_enabled?: boolean
- /** @maxLength 500 */
- summary_prompt_guide?: string
-}
-
/**
* * `disabled` - disabled
* `toolbar` - toolbar
@@ -3524,27 +3169,6 @@ export interface UserPushTokenUnregisterRequestApi {
token: string
}
-export type SubscriptionsDeliveriesListParams = {
- /**
- * The pagination cursor value.
- */
- cursor?: string
- /**
- * Return only deliveries in this run status (starting, completed, failed, or skipped).
- */
- status?: SubscriptionsDeliveriesListStatus
-}
-
-export type SubscriptionsDeliveriesListStatus =
- (typeof SubscriptionsDeliveriesListStatus)[keyof typeof SubscriptionsDeliveriesListStatus]
-
-export const SubscriptionsDeliveriesListStatus = {
- Completed: 'completed',
- Failed: 'failed',
- Skipped: 'skipped',
- Starting: 'starting',
-} as const
-
export type CimdVerificationTokensListParams = {
/**
* Number of results to return per page.
@@ -3800,68 +3424,6 @@ export const PropertyDefinitionsListType = {
Session: 'session',
} as const
-export type SubscriptionsListParams = {
- /**
- * Filter by creator user UUID.
- */
- created_by?: string
- /**
- * Filter by dashboard ID.
- */
- dashboard?: number
- /**
- * Filter by insight ID.
- */
- insight?: number
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
- /**
- * Which field to use when ordering the results.
- */
- ordering?: string
- /**
- * Filter by subscription resource: insight vs dashboard export.
- */
- resource_type?: SubscriptionsListResourceType
- /**
- * A search term.
- */
- search?: string
- /**
- * Filter by delivery channel (email, Slack, or webhook).
- */
- target_type?: SubscriptionsListTargetType
-}
-
-export type SubscriptionsListResourceType =
- (typeof SubscriptionsListResourceType)[keyof typeof SubscriptionsListResourceType]
-
-export const SubscriptionsListResourceType = {
- Dashboard: 'dashboard',
- Insight: 'insight',
-} as const
-
-export type SubscriptionsListTargetType = (typeof SubscriptionsListTargetType)[keyof typeof SubscriptionsListTargetType]
-
-export const SubscriptionsListTargetType = {
- Email: 'email',
- Slack: 'slack',
- Webhook: 'webhook',
-} as const
-
-export type SubscriptionsSummaryQuotaRetrieve200 = {
- active_count: number
- /** @nullable */
- limit: number | null
- at_limit: boolean
-}
-
export type UsersListParams = {
email?: string
is_staff?: boolean
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 3c49e61627e7..da98036226c3 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -51,8 +51,6 @@ import type {
PaginatedPersistedFolderListApi,
PaginatedProjectBackwardCompatBasicListApi,
PaginatedProjectSecretAPIKeyListApi,
- PaginatedSubscriptionDeliveryListApi,
- PaginatedSubscriptionListApi,
PaginatedUserGitHubIntegrationListResponseListApi,
PaginatedUserListApi,
PatchedEnterprisePropertyDefinitionApi,
@@ -63,7 +61,6 @@ import type {
PatchedPersistedFolderApi,
PatchedProjectBackwardCompatApi,
PatchedProjectSecretAPIKeyApi,
- PatchedSubscriptionApi,
PatchedUserApi,
PersistedFolderApi,
PersistedFolderListParams,
@@ -73,11 +70,6 @@ import type {
PromotedProductIntentApi,
PropertyDefinitionsListParams,
SharingConfigurationApi,
- SubscriptionApi,
- SubscriptionDeliveryApi,
- SubscriptionsDeliveriesListParams,
- SubscriptionsListParams,
- SubscriptionsSummaryQuotaRetrieve200,
UserApi,
UserGitHubLinkStartRequestApi,
UserGitHubLinkStartResponseApi,
@@ -107,65 +99,6 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
-export const getSubscriptionsDeliveriesListUrl = (
- projectId: string,
- subscriptionId: number,
- params?: SubscriptionsDeliveriesListParams
-) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString())
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/environments/${projectId}/subscriptions/${subscriptionId}/deliveries/?${stringifiedParams}`
- : `/api/environments/${projectId}/subscriptions/${subscriptionId}/deliveries/`
-}
-
-/**
- * Paginated delivery history for a subscription. Requires premium subscriptions.
- * @summary List subscription deliveries
- */
-export const subscriptionsDeliveriesList = async (
- projectId: string,
- subscriptionId: number,
- params?: SubscriptionsDeliveriesListParams,
- options?: RequestInit
-): Promise<PaginatedSubscriptionDeliveryListApi> => {
- return apiMutator<PaginatedSubscriptionDeliveryListApi>(
- getSubscriptionsDeliveriesListUrl(projectId, subscriptionId, params),
- {
- ...options,
- method: 'GET',
- }
- )
-}
-
-export const getSubscriptionsDeliveriesRetrieveUrl = (projectId: string, subscriptionId: number, id: string) => {
- return `/api/environments/${projectId}/subscriptions/${subscriptionId}/deliveries/${id}/`
-}
-
-/**
- * Fetch one delivery row by id.
- * @summary Retrieve subscription delivery
- */
-export const subscriptionsDeliveriesRetrieve = async (
- projectId: string,
- subscriptionId: number,
- id: string,
- options?: RequestInit
-): Promise<SubscriptionDeliveryApi> => {
- return apiMutator<SubscriptionDeliveryApi>(getSubscriptionsDeliveriesRetrieveUrl(projectId, subscriptionId, id), {
- ...options,
- method: 'GET',
- })
-}
-
export const getCimdVerificationTokensListUrl = (organizationId: string, params?: CimdVerificationTokensListParams) => {
const normalizedParams = new URLSearchParams()
@@ -2823,144 +2756,6 @@ export const sessionRecordingsSharingRefreshCreate = async (
})
}
-export const getSubscriptionsListUrl = (projectId: string, params?: SubscriptionsListParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : value.toString())
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/subscriptions/?${stringifiedParams}`
- : `/api/projects/${projectId}/subscriptions/`
-}
-
-export const subscriptionsList = async (
- projectId: string,
- params?: SubscriptionsListParams,
- options?: RequestInit
-): Promise<PaginatedSubscriptionListApi> => {
- return apiMutator<PaginatedSubscriptionListApi>(getSubscriptionsListUrl(projectId, params), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getSubscriptionsCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/subscriptions/`
-}
-
-export const subscriptionsCreate = async (
- projectId: string,
- subscriptionApi: NonReadonly<SubscriptionApi>,
- options?: RequestInit
-): Promise<SubscriptionApi> => {
- return apiMutator<SubscriptionApi>(getSubscriptionsCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(subscriptionApi),
- })
-}
-
-export const getSubscriptionsRetrieveUrl = (projectId: string, id: number) => {
- return `/api/projects/${projectId}/subscriptions/${id}/`
-}
-
-export const subscriptionsRetrieve = async (
- projectId: string,
- id: number,
- options?: RequestInit
-): Promise<SubscriptionApi> => {
- return apiMutator<SubscriptionApi>(getSubscriptionsRetrieveUrl(projectId, id), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getSubscriptionsUpdateUrl = (projectId: string, id: number) => {
- return `/api/projects/${projectId}/subscriptions/${id}/`
-}
-
-export const subscriptionsUpdate = async (
- projectId: string,
- id: number,
- subscriptionApi: NonReadonly<SubscriptionApi>,
- options?: RequestInit
-): Promise<SubscriptionApi> => {
- return apiMutator<SubscriptionApi>(getSubscriptionsUpdateUrl(projectId, id), {
- ...options,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(subscriptionApi),
- })
-}
-
-export const getSubscriptionsPartialUpdateUrl = (projectId: string, id: number) => {
- return `/api/projects/${projectId}/subscriptions/${id}/`
-}
-
-export const subscriptionsPartialUpdate = async (
- projectId: string,
- id: number,
- patchedSubscriptionApi?: NonReadonly<PatchedSubscriptionApi>,
- options?: RequestInit
-): Promise<SubscriptionApi> => {
- return apiMutator<SubscriptionApi>(getSubscriptionsPartialUpdateUrl(projectId, id), {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedSubscriptionApi),
- })
-}
-
-export const getSubscriptionsDestroyUrl = (projectId: string, id: number) => {
- return `/api/projects/${projectId}/subscriptions/${id}/`
-}
-
-/**
- * Hard delete of this model is not allowed. Use a patch API call to set "deleted" to true
- */
-export const subscriptionsDestroy = async (projectId: string, id: number, options?: RequestInit): Promise<unknown> => {
- return apiMutator<unknown>(getSubscriptionsDestroyUrl(projectId, id), {
- ...options,
- method: 'DELETE',
- })
-}
-
-export const getSubscriptionsTestDeliveryCreateUrl = (projectId: string, id: number) => {
- return `/api/projects/${projectId}/subscriptions/${id}/test-delivery/`
-}
-
-export const subscriptionsTestDeliveryCreate = async (
- projectId: string,
- id: number,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getSubscriptionsTestDeliveryCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- })
-}
-
-export const getSubscriptionsSummaryQuotaRetrieveUrl = (projectId: string) => {
- return `/api/projects/${projectId}/subscriptions/summary_quota/`
-}
-
-export const subscriptionsSummaryQuotaRetrieve = async (
- projectId: string,
- options?: RequestInit
-): Promise<SubscriptionsSummaryQuotaRetrieve200> => {
- return apiMutator<SubscriptionsSummaryQuotaRetrieve200>(getSubscriptionsSummaryQuotaRetrieveUrl(projectId), {
- ...options,
- method: 'GET',
- })
-}
-
export const getUsersListUrl = (params?: UsersListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index c5a3d139396e..75e37b0f8971 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -3228,331 +3228,6 @@ export const SessionRecordingsSharingRefreshCreateBody = /* @__PURE__ */ zod.obj
password_required: zod.boolean().optional(),
})
-export const subscriptionsCreateBodyIntervalMax = 2147483647
-
-export const subscriptionsCreateBodyBysetposMin = -2147483648
-export const subscriptionsCreateBodyBysetposMax = 2147483647
-
-export const subscriptionsCreateBodyCountMin = -2147483648
-export const subscriptionsCreateBodyCountMax = 2147483647
-
-export const subscriptionsCreateBodyTitleMax = 100
-
-export const subscriptionsCreateBodySummaryPromptGuideMax = 500
-
-export const SubscriptionsCreateBody = /* @__PURE__ */ zod
- .object({
- dashboard: zod
- .number()
- .nullish()
- .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
- insight: zod
- .number()
- .nullish()
- .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
- dashboard_export_insights: zod
- .array(zod.number())
- .optional()
- .describe(
- 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
- ),
- target_type: zod
- .enum(['email', 'slack', 'webhook'])
- .describe('\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook')
- .describe(
- 'Delivery channel: email, slack, or webhook.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook'
- ),
- target_value: zod
- .string()
- .describe(
- 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or full URL for webhook.'
- ),
- frequency: zod
- .enum(['daily', 'weekly', 'monthly', 'yearly'])
- .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')
- .describe(
- 'How often to deliver: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'
- ),
- interval: zod
- .number()
- .min(1)
- .max(subscriptionsCreateBodyIntervalMax)
- .describe(
- 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
- ),
- byweekday: zod
- .array(
- zod
- .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
- .describe(
- '\* `monday` - Monday\n\* `tuesday` - Tuesday\n\* `wednesday` - Wednesday\n\* `thursday` - Thursday\n\* `friday` - Friday\n\* `saturday` - Saturday\n\* `sunday` - Sunday'
- )
- )
- .nullish()
- .describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
- ),
- bysetpos: zod
- .number()
- .min(subscriptionsCreateBodyBysetposMin)
- .max(subscriptionsCreateBodyBysetposMax)
- .nullish()
- .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
- count: zod
- .number()
- .min(subscriptionsCreateBodyCountMin)
- .max(subscriptionsCreateBodyCountMax)
- .nullish()
- .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
- start_date: zod.iso.datetime({ offset: true }).describe('When to start delivering (ISO 8601 datetime).'),
- until_date: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
- deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
- enabled: zod
- .boolean()
- .optional()
- .describe(
- 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
- ),
- title: zod
- .string()
- .max(subscriptionsCreateBodyTitleMax)
- .nullish()
- .describe('Human-readable name for this subscription.'),
- integration_id: zod
- .number()
- .nullish()
- .describe('ID of a connected Slack integration. Required when target_type is slack.'),
- invite_message: zod
- .string()
- .nullish()
- .describe('Optional message included in the invitation email when adding new recipients.'),
- summary_enabled: zod.boolean().optional(),
- summary_prompt_guide: zod.string().max(subscriptionsCreateBodySummaryPromptGuideMax).optional(),
- })
- .describe('Standard Subscription serializer.')
-
-export const subscriptionsUpdateBodyIntervalMax = 2147483647
-
-export const subscriptionsUpdateBodyBysetposMin = -2147483648
-export const subscriptionsUpdateBodyBysetposMax = 2147483647
-
-export const subscriptionsUpdateBodyCountMin = -2147483648
-export const subscriptionsUpdateBodyCountMax = 2147483647
-
-export const subscriptionsUpdateBodyTitleMax = 100
-
-export const subscriptionsUpdateBodySummaryPromptGuideMax = 500
-
-export const SubscriptionsUpdateBody = /* @__PURE__ */ zod
- .object({
- dashboard: zod
- .number()
- .nullish()
- .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
- insight: zod
- .number()
- .nullish()
- .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
- dashboard_export_insights: zod
- .array(zod.number())
- .optional()
- .describe(
- 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
- ),
- target_type: zod
- .enum(['email', 'slack', 'webhook'])
- .describe('\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook')
- .describe(
- 'Delivery channel: email, slack, or webhook.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook'
- ),
- target_value: zod
- .string()
- .describe(
- 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or full URL for webhook.'
- ),
- frequency: zod
- .enum(['daily', 'weekly', 'monthly', 'yearly'])
- .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')
- .describe(
- 'How often to deliver: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'
- ),
- interval: zod
- .number()
- .min(1)
- .max(subscriptionsUpdateBodyIntervalMax)
- .describe(
- 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
- ),
- byweekday: zod
- .array(
- zod
- .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
- .describe(
- '\* `monday` - Monday\n\* `tuesday` - Tuesday\n\* `wednesday` - Wednesday\n\* `thursday` - Thursday\n\* `friday` - Friday\n\* `saturday` - Saturday\n\* `sunday` - Sunday'
- )
- )
- .nullish()
- .describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
- ),
- bysetpos: zod
- .number()
- .min(subscriptionsUpdateBodyBysetposMin)
- .max(subscriptionsUpdateBodyBysetposMax)
- .nullish()
- .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
- count: zod
- .number()
- .min(subscriptionsUpdateBodyCountMin)
- .max(subscriptionsUpdateBodyCountMax)
- .nullish()
- .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
- start_date: zod.iso.datetime({ offset: true }).describe('When to start delivering (ISO 8601 datetime).'),
- until_date: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
- deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
- enabled: zod
- .boolean()
- .optional()
- .describe(
- 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
- ),
- title: zod
- .string()
- .max(subscriptionsUpdateBodyTitleMax)
- .nullish()
- .describe('Human-readable name for this subscription.'),
- integration_id: zod
- .number()
- .nullish()
- .describe('ID of a connected Slack integration. Required when target_type is slack.'),
- invite_message: zod
- .string()
- .nullish()
- .describe('Optional message included in the invitation email when adding new recipients.'),
- summary_enabled: zod.boolean().optional(),
- summary_prompt_guide: zod.string().max(subscriptionsUpdateBodySummaryPromptGuideMax).optional(),
- })
- .describe('Standard Subscription serializer.')
-
-export const subscriptionsPartialUpdateBodyIntervalMax = 2147483647
-
-export const subscriptionsPartialUpdateBodyBysetposMin = -2147483648
-export const subscriptionsPartialUpdateBodyBysetposMax = 2147483647
-
-export const subscriptionsPartialUpdateBodyCountMin = -2147483648
-export const subscriptionsPartialUpdateBodyCountMax = 2147483647
-
-export const subscriptionsPartialUpdateBodyTitleMax = 100
-
-export const subscriptionsPartialUpdateBodySummaryPromptGuideMax = 500
-
-export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod
- .object({
- dashboard: zod
- .number()
- .nullish()
- .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
- insight: zod
- .number()
- .nullish()
- .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
- dashboard_export_insights: zod
- .array(zod.number())
- .optional()
- .describe(
- 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
- ),
- target_type: zod
- .enum(['email', 'slack', 'webhook'])
- .describe('\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook')
- .optional()
- .describe(
- 'Delivery channel: email, slack, or webhook.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook'
- ),
- target_value: zod
- .string()
- .optional()
- .describe(
- 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or full URL for webhook.'
- ),
- frequency: zod
- .enum(['daily', 'weekly', 'monthly', 'yearly'])
- .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')
- .optional()
- .describe(
- 'How often to deliver: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'
- ),
- interval: zod
- .number()
- .min(1)
- .max(subscriptionsPartialUpdateBodyIntervalMax)
- .optional()
- .describe(
- 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
- ),
- byweekday: zod
- .array(
- zod
- .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
- .describe(
- '\* `monday` - Monday\n\* `tuesday` - Tuesday\n\* `wednesday` - Wednesday\n\* `thursday` - Thursday\n\* `friday` - Friday\n\* `saturday` - Saturday\n\* `sunday` - Sunday'
- )
- )
- .nullish()
- .describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
- ),
- bysetpos: zod
- .number()
- .min(subscriptionsPartialUpdateBodyBysetposMin)
- .max(subscriptionsPartialUpdateBodyBysetposMax)
- .nullish()
- .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
- count: zod
- .number()
- .min(subscriptionsPartialUpdateBodyCountMin)
- .max(subscriptionsPartialUpdateBodyCountMax)
- .nullish()
- .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
- start_date: zod.iso
- .datetime({ offset: true })
- .optional()
- .describe('When to start delivering (ISO 8601 datetime).'),
- until_date: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
- deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
- enabled: zod
- .boolean()
- .optional()
- .describe(
- 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
- ),
- title: zod
- .string()
- .max(subscriptionsPartialUpdateBodyTitleMax)
- .nullish()
- .describe('Human-readable name for this subscription.'),
- integration_id: zod
- .number()
- .nullish()
- .describe('ID of a connected Slack integration. Required when target_type is slack.'),
- invite_message: zod
- .string()
- .nullish()
- .describe('Optional message included in the invitation email when adding new recipients.'),
- summary_enabled: zod.boolean().optional(),
- summary_prompt_guide: zod.string().max(subscriptionsPartialUpdateBodySummaryPromptGuideMax).optional(),
- })
- .describe('Standard Subscription serializer.')
-
/**
* Replace the authenticated user's profile and settings. Pass `@me` as the UUID to update the authenticated user. Prefer the PATCH endpoint for partial updates — PUT requires every writable field to be provided.
*/
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 92c9a0d9cd76..12489e4018f7 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -5916,14 +5916,18 @@ const api = {
async list({
insightId,
dashboardId,
+ resourceType,
}: {
insightId?: number
dashboardId?: number
+ resourceType?: SubscriptionType['resource_type']
}): Promise<PaginatedResponse<SubscriptionType>> {
- return await new ApiRequest()
- .subscriptions()
- .withQueryString(insightId ? `insight=${insightId}` : dashboardId ? `dashboard=${dashboardId}` : '')
- .get()
+ const params = [
+ insightId ? `insight=${insightId}` : null,
+ dashboardId ? `dashboard=${dashboardId}` : null,
+ resourceType ? `resource_type=${resourceType}` : null,
+ ].filter(Boolean)
+ return await new ApiRequest().subscriptions().withQueryString(params.join('&')).get()
},
determineDeleteEndpoint(): string {
return new ApiRequest().subscriptions().assembleEndpointUrl()
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.test.ts b/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.test.ts
index 4dbbbe82d64a..9a0e5603bada 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.test.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.test.ts
@@ -1,11 +1,12 @@
import { expectLogic } from 'kea-test-utils'
-import { subscriptionsList } from '~/generated/core/api'
+import { subscriptionsList } from '@posthog/products-subscriptions/frontend/generated/api'
+
import { initKeaTests } from '~/test/init'
import { subscriptionCountLogic } from './subscriptionCountLogic'
-jest.mock('~/generated/core/api', () => ({
+jest.mock('@posthog/products-subscriptions/frontend/generated/api', () => ({
subscriptionsList: jest.fn(),
}))
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.ts
index a6315280a97d..1b3823f0ba29 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionCountLogic.ts
@@ -1,9 +1,9 @@
import { afterMount, kea, path } from 'kea'
import { loaders } from 'kea-loaders'
-import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { subscriptionsList } from '@posthog/products-subscriptions/frontend/generated/api'
-import { subscriptionsList } from '~/generated/core/api'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
import type { subscriptionCountLogicType } from './subscriptionCountLogicType'
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionLogic.test.ts b/frontend/src/lib/components/Subscriptions/subscriptionLogic.test.ts
index 300ed0e34b3f..fbf9a08a48b4 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionLogic.test.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionLogic.test.ts
@@ -159,4 +159,95 @@ describe('subscriptionLogic', () => {
expect(getRecentSlackChannelIds(7)).toEqual(expectedIds)
})
+
+ it('rejects empty prompt when resource_type is ai_prompt', async () => {
+ // The parent-less /subscriptions/new route is the AI flow; its urlToAction sets
+ // resource_type='ai_prompt' (the /insights/... route forces 'insight').
+ router.actions.push('/subscriptions/new')
+ await expectLogic(newLogic).toFinishListeners()
+ newLogic.actions.setSubscriptionValues({ resource_type: 'ai_prompt', prompt: ' ', title: 'AI test' })
+ newLogic.actions.submitSubscription()
+ await expectLogic(newLogic).toFinishListeners()
+ expect(newLogic.values.subscriptionErrors.prompt).toBeTruthy()
+ })
+
+ it('rejects prompts exceeding 4000 characters when resource_type is ai_prompt', async () => {
+ router.actions.push('/subscriptions/new')
+ await expectLogic(newLogic).toFinishListeners()
+ newLogic.actions.setSubscriptionValues({
+ resource_type: 'ai_prompt',
+ prompt: 'x'.repeat(4001),
+ title: 'AI test',
+ })
+ newLogic.actions.submitSubscription()
+ await expectLogic(newLogic).toFinishListeners()
+ expect(newLogic.values.subscriptionErrors.prompt).toContain('4000')
+ })
+
+ it('accepts a valid AI prompt', async () => {
+ router.actions.push('/insights/123/subscriptions/new')
+ await expectLogic(newLogic).toFinishListeners()
+ newLogic.actions.setSubscriptionValues({
+ resource_type: 'ai_prompt',
+ prompt: 'Show me the biggest event gains last week',
+ title: 'AI test',
+ })
+ await expectLogic(newLogic).toFinishListeners()
+ expect(newLogic.values.subscriptionErrors.prompt).toBeUndefined()
+ })
+
+ it('clears a carried-over insight selection when saving an AI subscription', async () => {
+ // Opening the AI flow from a dashboard pre-populates dashboard_export_insights;
+ // those must not be sent, else the backend rejects insights without a dashboard.
+ let capturedBody: Partial<SubscriptionType> | undefined
+ useMocks({
+ post: {
+ '/api/environments/:team/subscriptions': (req, res, ctx) => {
+ capturedBody = req.body as Partial<SubscriptionType>
+ return res(ctx.json({ id: 42, ...capturedBody } as SubscriptionType))
+ },
+ },
+ })
+ router.actions.push('/subscriptions/new')
+ await expectLogic(newLogic).toFinishListeners()
+ newLogic.actions.setSubscriptionValues({
+ resource_type: 'ai_prompt',
+ prompt: 'Show me the biggest event gains last week',
+ title: 'AI test',
+ target_type: 'email',
+ target_value: '[email protected]',
+ dashboard_export_insights: [1, 2, 3],
+ })
+ newLogic.actions.submitSubscription()
+ await expectLogic(newLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])
+ expect(capturedBody?.dashboard_export_insights).toEqual([])
+ expect(capturedBody?.dashboard).toBeUndefined()
+ expect(capturedBody?.insight).toBeUndefined()
+ })
+
+ it('drops a stale prompt when saving a non-AI subscription', async () => {
+ // Toggling resource_type back to insight after typing a prompt leaves it in form state;
+ // it must not be sent, else the backend rejects a non-AI sub that carries a prompt.
+ let capturedBody: Partial<SubscriptionType> | undefined
+ useMocks({
+ post: {
+ '/api/environments/:team/subscriptions': (req, res, ctx) => {
+ capturedBody = req.body as Partial<SubscriptionType>
+ return res(ctx.json({ id: 43, ...capturedBody } as SubscriptionType))
+ },
+ },
+ })
+ router.actions.push('/subscriptions/new')
+ await expectLogic(newLogic).toFinishListeners()
+ newLogic.actions.setSubscriptionValues({
+ resource_type: 'insight',
+ prompt: 'stale prompt left over from the AI toggle',
+ title: 'Insight test',
+ target_type: 'email',
+ target_value: '[email protected]',
+ })
+ newLogic.actions.submitSubscription()
+ await expectLogic(newLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])
+ expect(capturedBody?.prompt).toBeUndefined()
+ })
})
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
index b621234a717f..58e11a0c9fab 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionLogic.ts
@@ -2,6 +2,7 @@ import { actions, events, kea, key, listeners, path, props, reducers } from 'kea
import { forms } from 'kea-forms'
import { loaders } from 'kea-loaders'
import { beforeUnload, router, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
import api, { ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
@@ -10,11 +11,28 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { isEmail, isURL } from 'lib/utils'
import { getInsightId } from 'scenes/insights/utils'
-import { ExportedAssetType, ExporterFormat, SubscriptionType } from '~/types'
+import { ExportedAssetType, ExporterFormat, SubscriptionResourceTypes, SubscriptionType } from '~/types'
import type { subscriptionLogicType } from './subscriptionLogicType'
import { subscriptionsLogic } from './subscriptionsLogic'
-import { SubscriptionBaseProps, urlForSubscription } from './utils'
+import { AI_PROMPT_MAX_LENGTH, SubscriptionBaseProps, urlForSubscription } from './utils'
+
+function validatePrompt(
+ resource_type: SubscriptionType['resource_type'],
+ prompt: string | null | undefined
+): string | undefined {
+ if (resource_type !== SubscriptionResourceTypes.AiPrompt) {
+ return undefined
+ }
+ const trimmedPrompt = prompt?.trim()
+ if (!trimmedPrompt) {
+ return 'A prompt is required for prompt subscriptions'
+ }
+ if (trimmedPrompt.length > AI_PROMPT_MAX_LENGTH) {
+ return `Prompt cannot exceed ${AI_PROMPT_MAX_LENGTH} characters`
+ }
+ return undefined
+}
function subscriptionSaveErrorMessage(error: unknown): string {
if (error instanceof ApiError) {
@@ -28,6 +46,7 @@ function subscriptionSaveErrorMessage(error: unknown): string {
}
const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {
+ resource_type: SubscriptionResourceTypes.Insight,
frequency: 'weekly',
interval: 1,
start_date: dayjs().hour(9).minute(0).second(0).toISOString(),
@@ -55,6 +74,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
setPreviewLoading: (loading: boolean) => ({ loading }),
setPreviewError: (error: string | null) => ({ error }),
setPreviewImageUrl: (url: string | null) => ({ url }),
+ selectAiExamplePrompt: (prompt: string, label: string) => ({ prompt, label }),
}),
reducers({
@@ -113,6 +133,8 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
title,
start_date,
dashboard_export_insights,
+ resource_type,
+ prompt,
}) => ({
frequency: !frequency ? 'You need to set a schedule frequency' : undefined,
title: !title ? 'You need to give your subscription a name' : undefined,
@@ -121,6 +143,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
target_type: !['slack', 'email', 'webhook'].includes(target_type)
? 'Unsupported target type'
: undefined,
+ prompt: validatePrompt(resource_type, prompt),
target_value: !target_value
? 'This field is required.'
: target_type == 'email'
@@ -139,17 +162,26 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
: undefined
: undefined,
dashboard_export_insights:
- props.dashboardId && (!dashboard_export_insights || dashboard_export_insights.length === 0)
+ resource_type !== SubscriptionResourceTypes.AiPrompt &&
+ props.dashboardId &&
+ (!dashboard_export_insights || dashboard_export_insights.length === 0)
? ('Select at least one insight' as any)
: undefined,
}),
submit: async (subscription, breakpoint) => {
- const insightId = props.insightShortId ? await getInsightId(props.insightShortId) : undefined
+ const isAi = subscription.resource_type === SubscriptionResourceTypes.AiPrompt
+ const insightId = !isAi && props.insightShortId ? await getInsightId(props.insightShortId) : undefined
const payload = {
...subscription,
- insight: insightId,
- dashboard: props.dashboardId,
+ insight: isAi ? undefined : insightId,
+ dashboard: isAi ? undefined : props.dashboardId,
+ // AI subscriptions have no dashboard, so a carried-over insight selection would
+ // trip the backend's "insights without a dashboard" guard. Clear it.
+ dashboard_export_insights: isAi ? [] : subscription.dashboard_export_insights,
+ // Only AI subscriptions carry a prompt; a stale one on a non-AI sub (e.g. after
+ // toggling resource_type back) would be rejected by the backend, so drop it.
+ prompt: isAi ? subscription.prompt?.trim() : undefined,
}
breakpoint()
@@ -165,9 +197,11 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
router.actions.replace(urlForSubscription(updatedSub.id, props))
}
- // If a subscriptionsLogic for this insight/dashboard is mounted already, let's make sure
- // this change is propagated to `subscriptions` there
- subscriptionsLogic.findMounted(props)?.actions.loadSubscriptions()
+ // If a subscriptionsLogic for this insight/dashboard is mounted already, refresh both
+ // its resource-scoped list and the AI subscriptions section so new entries show up
+ const mountedSubscriptionsLogic = subscriptionsLogic.findMounted(props)
+ mountedSubscriptionsLogic?.actions.loadSubscriptions()
+ mountedSubscriptionsLogic?.actions.loadAiSubscriptions()
actions.loadSubscriptionSuccess(updatedSub)
actions.loadSummaryQuota()
lemonToast.success(`Subscription saved.`)
@@ -183,6 +217,10 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
recordRecentSlackChannel(subscription.integration_id, slackChannelId(subscription.target_value))
}
},
+ selectAiExamplePrompt: ({ prompt, label }) => {
+ posthog.capture('subscription_ai_example_prompt_selected', { label })
+ actions.setSubscriptionValue('prompt', prompt)
+ },
submitSubscriptionFailure: ({ error }) => {
// Kea-forms emits this when client validation fails; fields already show errors.
if (error instanceof Error && error.message === 'Validation Failed') {
@@ -318,6 +356,15 @@ export const subscriptionLogic = kea<subscriptionLogicType>([
'/*/*/subscriptions/:id': () => {
actions.loadSubscription()
},
+ '/subscriptions/new': (_, searchParams) => {
+ actions.loadSubscriptionSuccess({ ...NEW_SUBSCRIPTION, resource_type: SubscriptionResourceTypes.AiPrompt })
+ if (searchParams.target_type) {
+ actions.setSubscriptionValue('target_type', searchParams.target_type)
+ }
+ },
+ '/subscriptions/:id/edit': () => {
+ actions.loadSubscription()
+ },
})),
])
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionsLogic.test.ts b/frontend/src/lib/components/Subscriptions/subscriptionsLogic.test.ts
index e09c18ca544f..258f174be7d6 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionsLogic.test.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionsLogic.test.ts
@@ -1,5 +1,8 @@
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import {
@@ -50,8 +53,10 @@ function fixtureInsightResponse(id: number, data?: Partial<InsightModel>): Parti
describe('subscriptionsLogic', () => {
let logic: ReturnType<typeof subscriptionsLogic.build>
let subscriptions: SubscriptionType[] = []
+ let aiSubscriptions: SubscriptionType[] = []
beforeEach(async () => {
subscriptions = [fixtureSubscriptionResponse(1), fixtureSubscriptionResponse(2)]
+ aiSubscriptions = [fixtureSubscriptionResponse(10, { resource_type: 'ai_prompt', prompt: 'Weekly report' })]
useMocks({
get: {
'/api/environments/:team_id/insights/1': fixtureInsightResponse(1),
@@ -64,9 +69,12 @@ describe('subscriptionsLogic', () => {
'/api/environments/:team_id/subscriptions': (req) => {
const insightId = req.url.searchParams.get('insight')
+ const resourceType = req.url.searchParams.get('resource_type')
let results: SubscriptionType[] = []
- if (insightId === Insight2) {
+ if (resourceType === 'ai_prompt') {
+ results = aiSubscriptions
+ } else if (insightId === Insight2) {
results = subscriptions
}
@@ -103,4 +111,29 @@ describe('subscriptionsLogic', () => {
subscriptionsLoading: false,
})
})
+
+ it('does not load AI subscriptions when the flag is off', async () => {
+ await expectLogic(logic).toFinishListeners().toMatchValues({
+ aiSubscriptions: [],
+ aiSubscriptionsLoading: false,
+ })
+ })
+
+ it('loads AI subscriptions separately when the flag is on', async () => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: true,
+ })
+
+ // Distinct key so afterMount fetches fresh with the flag now on.
+ logic = subscriptionsLogic({
+ insightShortId: Insight2,
+ })
+ logic.mount()
+
+ await expectLogic(logic).toFinishListeners().toMatchValues({
+ aiSubscriptions: aiSubscriptions,
+ aiSubscriptionsLoading: false,
+ })
+ })
})
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionsLogic.ts b/frontend/src/lib/components/Subscriptions/subscriptionsLogic.ts
index abba8a849eee..372240234aef 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionsLogic.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionsLogic.ts
@@ -1,11 +1,13 @@
-import { BreakPointFunction, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+import { BreakPointFunction, actions, afterMount, connect, kea, key, listeners, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
import { getInsightId } from 'scenes/insights/utils'
-import { SubscriptionType } from '~/types'
+import { SubscriptionResourceTypes, SubscriptionType } from '~/types'
import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'
import type { subscriptionsLogicType } from './subscriptionsLogicType'
@@ -18,6 +20,7 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([
key(({ insightShortId, dashboardId }) =>
insightShortId ? `insight-${insightShortId}` : dashboardId ? `dashboard-${dashboardId}` : 'subscriptions'
),
+ connect({ values: [featureFlagLogic, ['featureFlags']] }),
actions({
deleteSubscription: (id: number) => ({ id }),
deliverSubscription: (id: number) => ({ id }),
@@ -28,7 +31,7 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([
setSubscriptionEnabledFailure: true,
}),
- loaders(({ props }) => ({
+ loaders(({ props, values }) => ({
subscriptions: {
__default: [] as SubscriptionType[],
loadSubscriptions: async (_?: any, breakpoint?: BreakPointFunction) => {
@@ -47,12 +50,30 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([
return response.results
},
},
+ // AI subscriptions are project-scoped (not tied to a specific insight/dashboard), so they're
+ // fetched separately and rendered in their own section. Gated behind the AI prompt flag.
+ aiSubscriptions: {
+ __default: [] as SubscriptionType[],
+ loadAiSubscriptions: async (_?: any, breakpoint?: BreakPointFunction) => {
+ const inResourceContext = !!props.dashboardId || !!props.insightShortId
+ if (!inResourceContext || !values.featureFlags[FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]) {
+ return []
+ }
+ breakpoint?.()
+ const response = await api.subscriptions.list({ resourceType: SubscriptionResourceTypes.AiPrompt })
+ breakpoint?.()
+ return response.results
+ },
+ },
})),
reducers({
subscriptions: {
deleteSubscription: (state, { id }) => state.filter((a) => a.id !== id),
},
+ aiSubscriptions: {
+ deleteSubscription: (state, { id }) => state.filter((a) => a.id !== id),
+ },
deliveringSubscriptionId: [
null as number | null,
{
@@ -76,7 +97,10 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([
await deleteWithUndo({
endpoint: api.subscriptions.determineDeleteEndpoint(),
object: { name: 'Subscription', id },
- callback: () => actions.loadSubscriptions(),
+ callback: () => {
+ actions.loadSubscriptions()
+ actions.loadAiSubscriptions()
+ },
})
},
deliverSubscription: async ({ id }) => {
@@ -95,8 +119,14 @@ export const subscriptionsLogic = kea<subscriptionsLogicType>([
actions.setSubscriptionEnabledFailure()
}
},
- setSubscriptionEnabledSuccess: () => actions.loadSubscriptions(),
+ setSubscriptionEnabledSuccess: () => {
+ actions.loadSubscriptions()
+ actions.loadAiSubscriptions()
+ },
})),
- afterMount(({ actions }) => actions.loadSubscriptions()),
+ afterMount(({ actions }) => {
+ actions.loadSubscriptions()
+ actions.loadAiSubscriptions()
+ }),
])
diff --git a/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.test.ts b/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.test.ts
index f74fe5864e1e..49fb7875c653 100644
--- a/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.test.ts
+++ b/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.test.ts
@@ -1,6 +1,6 @@
-import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import * as generatedApi from '@posthog/products-subscriptions/frontend/generated/api'
-import * as generatedApi from '~/generated/core/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { toggleSubscriptionEnabled } from './toggleSubscriptionEnabled'
diff --git a/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.ts b/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.ts
index 68c664c00d23..642d287818f7 100644
--- a/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.ts
+++ b/frontend/src/lib/components/Subscriptions/toggleSubscriptionEnabled.ts
@@ -1,8 +1,8 @@
+import { subscriptionsPartialUpdate } from '@posthog/products-subscriptions/frontend/generated/api'
+
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { getCurrentTeamId } from 'lib/utils/getAppContext'
-import { subscriptionsPartialUpdate } from '~/generated/core/api'
-
export async function toggleSubscriptionEnabled(id: number, enabled: boolean): Promise<boolean> {
try {
await subscriptionsPartialUpdate(String(getCurrentTeamId()), id, { enabled })
diff --git a/frontend/src/lib/components/Subscriptions/utils.test.ts b/frontend/src/lib/components/Subscriptions/utils.test.ts
index 6fd64f4dd85d..8fc15fec9bc6 100644
--- a/frontend/src/lib/components/Subscriptions/utils.test.ts
+++ b/frontend/src/lib/components/Subscriptions/utils.test.ts
@@ -1,4 +1,4 @@
-import { getNextDeliveryDate } from './utils'
+import { getAiSubscriptionGate, getNextDeliveryDate } from './utils'
describe('getNextDeliveryDate', () => {
beforeEach(() => {
@@ -55,3 +55,58 @@ describe('getNextDeliveryDate', () => {
expect(result).toBeNull()
})
})
+
+describe('getAiSubscriptionGate', () => {
+ // Fully-enabled baseline (insight flow, new sub, consent + cloud + flag all on); each case overrides.
+ const base = {
+ isAiPrompt: false,
+ isParentless: false,
+ isEditing: false,
+ aiConsentApproved: true,
+ isCloud: true,
+ isDebug: false,
+ aiFlagEnabled: true,
+ } as const
+
+ it.each([
+ [
+ 'flag off hides every AI affordance',
+ { aiFlagEnabled: false },
+ { aiAllowed: false, showResourceTypeToggle: false, showConsentHint: false, showAiFormConsentBanner: false },
+ ],
+ [
+ 'flag on + consent + cloud fully enables AI',
+ {},
+ {
+ aiAllowed: true,
+ showResourceTypeToggle: true,
+ aiOptionEnabled: true,
+ showConsentHint: false,
+ submitBlocked: false,
+ },
+ ],
+ [
+ 'flag on + no consent greys AI and shows the consent hint (insight flow)',
+ { aiConsentApproved: false },
+ { aiAllowed: false, showResourceTypeToggle: true, aiOptionEnabled: false, showConsentHint: true },
+ ],
+ [
+ 'top-level AI form blocks submit and shows the banner when consent is missing',
+ { isParentless: true, isAiPrompt: true, aiConsentApproved: false },
+ { showResourceTypeToggle: false, showAiFormConsentBanner: true, submitBlocked: true },
+ ],
+ [
+ 'editing an AI sub never blocks, even without consent',
+ { isEditing: true, isAiPrompt: true, aiConsentApproved: false },
+ { showAiFormConsentBanner: false, submitBlocked: false, showResourceTypeToggle: false },
+ ],
+ ['debug mode satisfies the cloud requirement locally', { isCloud: false, isDebug: true }, { aiAllowed: true }],
+ [
+ 'flag off shows no misleading consent banner on the AI-only form (but still blocks submit)',
+ { isParentless: true, isAiPrompt: true, aiFlagEnabled: false, aiConsentApproved: false },
+ { showAiFormConsentBanner: false, submitBlocked: true },
+ ],
+ ] as const)('%s', (_label, overrides, expected) => {
+ expect(getAiSubscriptionGate({ ...base, ...overrides })).toMatchObject(expected)
+ })
+})
diff --git a/frontend/src/lib/components/Subscriptions/utils.tsx b/frontend/src/lib/components/Subscriptions/utils.tsx
index efa22ce64bc4..e22c602d5cbe 100644
--- a/frontend/src/lib/components/Subscriptions/utils.tsx
+++ b/frontend/src/lib/components/Subscriptions/utils.tsx
@@ -7,8 +7,11 @@ import { IconSlack } from 'lib/lemon-ui/icons'
import { range } from 'lib/utils'
import { urls } from 'scenes/urls'
+import { SubscriptionAIPromptMaxLength } from '~/queries/schema/schema-general'
import { InsightShortId, SubscriptionType } from '~/types'
+export const AI_PROMPT_MAX_LENGTH = SubscriptionAIPromptMaxLength.CHARACTERS
+
export interface SubscriptionBaseProps {
dashboardId?: number
insightShortId?: InsightShortId
@@ -20,7 +23,8 @@ export const urlForSubscriptions = ({ dashboardId, insightShortId }: Subscriptio
} else if (dashboardId) {
return urls.dashboardSubscriptions(dashboardId)
}
- return ''
+ // Parent-less (e.g. AI prompt) subscriptions live at the top-level list.
+ return urls.subscriptions()
}
export const urlForSubscription = (
@@ -32,7 +36,8 @@ export const urlForSubscription = (
} else if (dashboardId) {
return urls.dashboardSubscription(dashboardId, id.toString())
}
- return ''
+ // Parent-less (e.g. AI prompt) subscriptions: top-level detail/new page.
+ return id === 'new' ? urls.subscriptionNew() : urls.subscription(id)
}
export const targetTypeOptions: LemonSelectOptions<'email' | 'slack'> = [
@@ -123,3 +128,52 @@ export function getNextDeliveryDate(subscription: Partial<SubscriptionType>): Da
return null
}
}
+
+export interface AiSubscriptionGateInputs {
+ isAiPrompt: boolean
+ isParentless: boolean
+ isEditing: boolean
+ aiConsentApproved: boolean
+ isCloud: boolean
+ isDebug: boolean
+ aiFlagEnabled: boolean
+}
+
+export interface AiSubscriptionGate {
+ /** Org cleared every gate (consent + cloud/debug + flag) needed to author an AI report. */
+ aiAllowed: boolean
+ /** Show the "What to send" (insight vs AI) toggle — new parent-anchored subs, feature on. */
+ showResourceTypeToggle: boolean
+ /** The AI option in the toggle is selectable (vs greyed with a consent reason). */
+ aiOptionEnabled: boolean
+ /** Insight-flow hint: feature exists but consent is missing. */
+ showConsentHint: boolean
+ /** AI-only-form banner: feature exists, consent missing, creating (not editing). */
+ showAiFormConsentBanner: boolean
+ /** Block submit on a new AI subscription that can't be created — mirrors the create-only backend gate. */
+ submitBlocked: boolean
+}
+
+/**
+ * Single source of truth for how the AI-subscription feature flag (visibility) and the
+ * org AI-data-processing consent (enablement) gate the subscription form. Pure so the
+ * flag-off / consent-missing combinations are provable without rendering the component.
+ *
+ * - flag off → the feature does not exist: hide the toggle, option, and banners.
+ * - flag on, no consent → it exists but is blocked: toggle shows with AI greyed + a consent
+ * hint; submit is blocked on the AI-only form.
+ * - editing → never block (the backend gates creation only; users must be able to edit/disable).
+ */
+export function getAiSubscriptionGate(inputs: AiSubscriptionGateInputs): AiSubscriptionGate {
+ const { isAiPrompt, isParentless, isEditing, aiConsentApproved, isCloud, isDebug, aiFlagEnabled } = inputs
+ const aiAllowed = aiConsentApproved && (isCloud || isDebug) && aiFlagEnabled
+ const showResourceTypeToggle = !isParentless && !isEditing && aiFlagEnabled
+ return {
+ aiAllowed,
+ showResourceTypeToggle,
+ aiOptionEnabled: aiAllowed,
+ showConsentHint: showResourceTypeToggle && !aiAllowed,
+ showAiFormConsentBanner: isAiPrompt && !isEditing && aiFlagEnabled && !aiAllowed,
+ submitBlocked: isAiPrompt && !isEditing && !aiAllowed,
+ }
+}
diff --git a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx
index 4fa88abd4626..68b06cd276e7 100644
--- a/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx
+++ b/frontend/src/lib/components/Subscriptions/views/EditSubscription.tsx
@@ -11,6 +11,7 @@ import { UserActivityIndicator } from 'lib/components/UserActivityIndicator/User
import { usersLemonSelectOptions } from 'lib/components/UserSelectItem'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
@@ -19,19 +20,21 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { membersLogic } from 'scenes/organization/membersLogic'
+import { organizationLogic } from 'scenes/organizationLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'
-import { AvailableFeature, DashboardType, InsightShortId } from '~/types'
+import { AvailableFeature, DashboardType, InsightShortId, SubscriptionResourceTypes, SubscriptionType } from '~/types'
import { InsightSelector } from '../InsightSelector'
import { subscriptionCountLogic } from '../subscriptionCountLogic'
@@ -41,6 +44,7 @@ import {
bysetposOptions,
frequencyOptionsPlural,
frequencyOptionsSingular,
+ getAiSubscriptionGate,
getNextDeliveryDate,
intervalOptions,
monthlyWeekdayOptions,
@@ -48,8 +52,45 @@ import {
timeOptions,
weekdayOptions,
WEEKDAYS,
+ AI_PROMPT_MAX_LENGTH,
} from '../utils'
+// Shown wherever AI subscriptions are gated off (org hasn't approved AI data
+// processing). Mirrors the backend gate in `_ai_create_gate_reason`, which 403s
+// the create regardless — so the form must block before submit, not after.
+const AI_NOT_ALLOWED_REASON = 'Enable AI data processing in your Organization settings to use AI subscriptions.'
+
+function AiConsentGateMessage(): JSX.Element {
+ return (
+ <>
+ {AI_NOT_ALLOWED_REASON}{' '}
+ <Link to={urls.settings('organization-details', 'organization-ai-consent')}>Manage AI data processing</Link>
+ </>
+ )
+}
+
+// Concrete starter prompts — each one maps cleanly to a flat HogQL pattern the
+// planner already knows (see PLAN_GENERATION_PROMPT reference patterns). Click
+// populates the textarea verbatim so users can tweak rather than start cold.
+const AI_PROMPT_EXAMPLES: { label: string; prompt: string }[] = [
+ {
+ label: 'Top events this week',
+ prompt: 'Top 5 events by volume in the last 7 days, with counts and unique users for each.',
+ },
+ {
+ label: 'Week-over-week growth',
+ prompt: 'For the top 10 events by volume, compare this week vs last week and rank by growth rate. Flag any event that more than doubled or halved.',
+ },
+ {
+ label: 'Weekly health check',
+ prompt: 'Weekly health check: total event volume and unique active users in the last 7 days, and how each compares to the previous 7 days.',
+ },
+ {
+ label: 'Tracking gaps',
+ prompt: 'Which events we normally track received no data in the last 7 days? List them so I can catch broken instrumentation.',
+ },
+]
+
interface EditSubscriptionProps {
id: number | 'new'
insightShortId?: InsightShortId
@@ -118,6 +159,87 @@ function FreeTierCreateGate(props: EditSubscriptionProps): JSX.Element {
return <EditSubscriptionForm {...props} />
}
+function AiPromptFields({
+ prompt,
+ showConsentBanner,
+ onSelectExample,
+}: {
+ prompt?: string | null
+ showConsentBanner: boolean
+ onSelectExample: (prompt: string, label: string) => void
+}): JSX.Element {
+ return (
+ <>
+ {showConsentBanner && (
+ <LemonBanner type="warning" className="text-sm">
+ <AiConsentGateMessage />
+ </LemonBanner>
+ )}
+ <LemonBanner type="info" className="text-sm">
+ The AI analyzes your project's recent events and writes a markdown report. Each delivery is generated
+ independently.
+ </LemonBanner>
+ <LemonField
+ name="prompt"
+ label="Prompt"
+ help="Describe what the AI should look for. The same prompt runs every time the subscription fires."
+ >
+ <LemonTextArea
+ placeholder="e.g. Which events grew the most week-over-week? Highlight any unusual spikes."
+ minRows={4}
+ maxLength={AI_PROMPT_MAX_LENGTH}
+ />
+ </LemonField>
+ {/* Starter chips replace the whole prompt, so only offer them while the field is empty — once the
+ user has typed anything, a stray click would wipe their prompt with no undo. */}
+ {!prompt?.trim() && (
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-secondary">Try one of these prompts:</span>
+ <div className="flex flex-wrap gap-1">
+ {AI_PROMPT_EXAMPLES.map((example) => (
+ <LemonButton
+ key={example.label}
+ size="xsmall"
+ type="secondary"
+ onClick={() => onSelectExample(example.prompt, example.label)}
+ >
+ {example.label}
+ </LemonButton>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ )
+}
+
+function DashboardInsightsField({
+ dashboard,
+ subscription,
+ onResetSubscription,
+}: {
+ dashboard: DashboardType<any>
+ subscription: SubscriptionType
+ onResetSubscription: (subscription: SubscriptionType) => void
+}): JSX.Element {
+ return (
+ <LemonField name="dashboard_export_insights" label="Insights to include">
+ {({ value, onChange }) => (
+ <InsightSelector
+ tiles={dashboard.tiles}
+ selectedInsightIds={value ?? []}
+ onChange={onChange}
+ // Reset the form's "changed" state after auto-selecting defaults so it doesn't trip the
+ // unsaved-changes warning; merge the IDs into the subscription to preserve them.
+ onDefaultsApplied={(selectedIds) =>
+ onResetSubscription({ ...subscription, dashboard_export_insights: selectedIds })
+ }
+ />
+ )}
+ </LemonField>
+ )
+}
+
function EditSubscriptionForm({
id,
insightShortId,
@@ -143,12 +265,18 @@ function EditSubscriptionForm({
const { previewLoading, previewError, previewImageUrl } = useValues(logic)
const { resetSubscription, generatePreview } = useActions(logic)
const { preflight, siteUrlMisconfigured } = useValues(preflightLogic)
+ const { currentOrganization } = useValues(organizationLogic)
const { deleteSubscription } = useActions(subscriptionslogic)
const { slackIntegrations, integrations } = useValues(integrationsLogic)
const { dataProcessingAccepted } = useValues(maxGlobalLogic)
+ const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')
const emailDisabled = !preflight?.email_service_available
-
+ const isAiPrompt = subscription?.resource_type === SubscriptionResourceTypes.AiPrompt
+ // Parent-less = reached from the top-level /subscriptions page, not the kebab
+ // modal on an insight/dashboard. There's nothing to snapshot here, so AI report
+ // is the only valid content type — hide the snapshot/AI toggle entirely.
+ const isParentless = !insightShortId && !dashboardId
const availableFrequencyOptions = subscription?.interval === 1 ? frequencyOptionsSingular : frequencyOptionsPlural
// For new subscriptions, show InsightSelector immediately (useEffect will auto-select)
@@ -156,6 +284,15 @@ function EditSubscriptionForm({
// We check target_type instead of dashboard_export_insights because old subscriptions
// may have no insights selected yet
const isEditing = id !== 'new'
+ const aiGate = getAiSubscriptionGate({
+ isAiPrompt,
+ isParentless,
+ isEditing,
+ aiConsentApproved: Boolean(currentOrganization?.is_ai_data_processing_approved),
+ isCloud: Boolean(preflight?.cloud),
+ isDebug: Boolean(preflight?.is_debug),
+ aiFlagEnabled: Boolean(aiSubscriptionsEnabled),
+ })
const subscriptionLoaded = !!subscription?.target_type
const selectionReady = !isEditing || subscriptionLoaded
@@ -257,28 +394,53 @@ function EditSubscriptionForm({
</LemonField>
</div>
- {dashboard?.tiles && selectionReady && (
- <LemonField name="dashboard_export_insights" label="Insights to include">
+ {aiGate.showResourceTypeToggle && (
+ <LemonField name="resource_type" label="What to send">
{({ value, onChange }) => (
- <InsightSelector
- tiles={dashboard.tiles}
- selectedInsightIds={value ?? []}
+ <LemonSegmentedButton
+ value={value}
onChange={onChange}
- // After auto-selecting default insights, reset the form's "changed"
- // state so that auto-selection alone doesn't trigger the
- // "unsaved changes" warning when leaving. We merge the selected IDs
- // into the subscription to preserve the auto-selected values.
- onDefaultsApplied={(selectedIds) =>
- resetSubscription({
- ...subscription,
- dashboard_export_insights: selectedIds,
- })
- }
+ fullWidth
+ options={[
+ {
+ value: SubscriptionResourceTypes.Insight,
+ label: 'Insight or dashboard snapshot',
+ },
+ {
+ value: SubscriptionResourceTypes.AiPrompt,
+ label: 'Report from a prompt (beta)',
+ disabledReason: !aiGate.aiOptionEnabled
+ ? AI_NOT_ALLOWED_REASON
+ : undefined,
+ },
+ ]}
/>
)}
</LemonField>
)}
+ {dashboard?.tiles && selectionReady && !isAiPrompt && (
+ <DashboardInsightsField
+ dashboard={dashboard}
+ subscription={subscription}
+ onResetSubscription={resetSubscription}
+ />
+ )}
+
+ {aiGate.showConsentHint && (
+ <LemonBanner type="info" className="text-sm">
+ <AiConsentGateMessage />
+ </LemonBanner>
+ )}
+
+ {isAiPrompt ? (
+ <AiPromptFields
+ prompt={subscription.prompt}
+ showConsentBanner={aiGate.showAiFormConsentBanner}
+ onSelectExample={logic.actions.selectAiExamplePrompt}
+ />
+ ) : null}
+
<LemonField name="target_type" label="Destination">
<LemonSelect options={targetTypeOptions} />
</LemonField>
@@ -503,55 +665,64 @@ function EditSubscriptionForm({
)}
</div>
- <FlaggedFeature flag={FEATURE_FLAGS.HACKATHONS_SUBSCRIPTIONS}>
- <LemonField name="summary_enabled">
- {({ value, onChange }) => (
- <AIConsentPopoverWrapper>
- <LemonSwitch
- checked={value}
- onChange={onChange}
- bordered
- label="Include an automatic AI summary"
- fullWidth
- disabledReason={
- !dataProcessingAccepted && !value
- ? 'Your organization needs to approve AI data processing before enabling AI summaries'
- : summaryQuota?.at_limit && !value
- ? `Plan limit reached (${summaryQuota.limit} active AI summaries). See details below.`
- : undefined
- }
- />
- </AIConsentPopoverWrapper>
- )}
- </LemonField>
-
- {summaryQuota?.at_limit && !subscription.summary_enabled && summaryQuota.limit !== null && (
- <UsageLimitPaywall
- title="AI summary limit reached"
- description="Disable an existing AI summary or upgrade your plan to add more."
- limit={summaryQuota.limit}
- currentUsage={summaryQuota.active_count}
- unit="active AI summaries on your plan"
- />
- )}
+ {/*
+ * AI-prompt subscriptions are themselves an LLM-generated report —
+ * appending an insight-style "automatic AI summary" on top would be
+ * a summary of a summary. Hide the toggle entirely for AI subs.
+ */}
+ {!isAiPrompt && (
+ <FlaggedFeature flag={FEATURE_FLAGS.HACKATHONS_SUBSCRIPTIONS}>
+ <LemonField name="summary_enabled">
+ {({ value, onChange }) => (
+ <AIConsentPopoverWrapper>
+ <LemonSwitch
+ checked={value}
+ onChange={onChange}
+ bordered
+ label="Include an automatic AI summary"
+ fullWidth
+ disabledReason={
+ !dataProcessingAccepted && !value
+ ? 'Your organization needs to approve AI data processing before enabling AI summaries'
+ : summaryQuota?.at_limit && !value
+ ? `Plan limit reached (${summaryQuota.limit} active AI summaries). See details below.`
+ : undefined
+ }
+ />
+ </AIConsentPopoverWrapper>
+ )}
+ </LemonField>
- {subscription.summary_enabled && (
- <FlaggedFeature flag={FEATURE_FLAGS.SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE}>
- <LemonField
- name="summary_prompt_guide"
- label="Context for the AI summary"
- showOptional
- >
- <LemonTextArea
- placeholder="e.g. This is a daily revenue health check - focus on revenue drop-off and churn signals"
- maxLength={500}
+ {summaryQuota?.at_limit &&
+ !subscription.summary_enabled &&
+ summaryQuota.limit !== null && (
+ <UsageLimitPaywall
+ title="AI summary limit reached"
+ description="Disable an existing AI summary or upgrade your plan to add more."
+ limit={summaryQuota.limit}
+ currentUsage={summaryQuota.active_count}
+ unit="active AI summaries on your plan"
/>
- </LemonField>
- </FlaggedFeature>
- )}
- </FlaggedFeature>
+ )}
+
+ {subscription.summary_enabled && (
+ <FlaggedFeature flag={FEATURE_FLAGS.SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE}>
+ <LemonField
+ name="summary_prompt_guide"
+ label="Context for the AI summary"
+ showOptional
+ >
+ <LemonTextArea
+ placeholder="e.g. This is a daily revenue health check - focus on revenue drop-off and churn signals"
+ maxLength={500}
+ />
+ </LemonField>
+ </FlaggedFeature>
+ )}
+ </FlaggedFeature>
+ )}
- {insightShortId && (
+ {insightShortId && !isAiPrompt && (
<div>
<LemonLabel className="mb-2">Preview</LemonLabel>
<div className="border rounded p-2">
@@ -607,7 +778,7 @@ function EditSubscriptionForm({
type="primary"
htmlType="submit"
loading={isSubscriptionSubmitting}
- disabled={!subscriptionChanged || subscriptionLoading}
+ disabled={!subscriptionChanged || subscriptionLoading || aiGate.submitBlocked}
>
{id === 'new' ? 'Create subscription' : 'Save'}
</LemonButton>
diff --git a/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx b/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx
index de097eb8b052..fd1a2518c1d1 100644
--- a/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx
+++ b/frontend/src/lib/components/Subscriptions/views/ManageSubscriptions.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconEllipsis } from '@posthog/icons'
-import { LemonTag } from '@posthog/lemon-ui'
+import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
import { IconSlack } from 'lib/lemon-ui/icons'
@@ -12,12 +12,18 @@ import { ProfileBubbles } from 'lib/lemon-ui/ProfilePicture'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { capitalizeFirstLetter, pluralize } from 'lib/utils'
import { isSubscriptionEnabled } from 'scenes/subscriptions/components/SubscriptionsTable'
+import { urls } from 'scenes/urls'
-import { SubscriptionType } from '~/types'
+import { SubscriptionResourceTypes, SubscriptionType } from '~/types'
import { subscriptionsLogic } from '../subscriptionsLogic'
import { SubscriptionBaseProps } from '../utils'
+const PROMPT_PREVIEW_MAX_CHARS = 80
+// AI subscriptions are supplementary context in this modal, so only a few are shown inline —
+// the rest are reachable via the full subscriptions list.
+const AI_PREVIEW_LIMIT = 3
+
interface SubscriptionListItemProps {
subscription: SubscriptionType
onClick: () => void
@@ -41,6 +47,10 @@ export function SubscriptionListItem({
const enabled = isSubscriptionEnabled(subscription)
const sideActionBusy = isDelivering || isToggling
+ const aiPrompt = subscription.resource_type === SubscriptionResourceTypes.AiPrompt ? subscription.prompt : null
+ const aiPromptTruncated = aiPrompt && aiPrompt.length > PROMPT_PREVIEW_MAX_CHARS
+ const aiPromptPreview = aiPromptTruncated ? `${aiPrompt.slice(0, PROMPT_PREVIEW_MAX_CHARS)}…` : aiPrompt
+
return (
<LemonButton
type="secondary"
@@ -91,6 +101,11 @@ export function SubscriptionListItem({
<div className="flex justify-between flex-auto items-center p-2">
<div>
<div className={`font-medium ${enabled ? 'text-link' : 'text-muted'}`}>{subscription.title}</div>
+ {aiPrompt ? (
+ <Tooltip title={aiPromptTruncated ? aiPrompt : undefined}>
+ <div className="text-sm text-muted italic">{`"${aiPromptPreview}"`}</div>
+ </Tooltip>
+ ) : null}
<div className="text-sm text-text-3000">
{capitalizeFirstLetter(subscription.summary)}
{selectedInsightsCount
@@ -135,10 +150,33 @@ export function ManageSubscriptions({
dashboardId,
})
- const { subscriptions, subscriptionsLoading, deliveringSubscriptionId, togglingEnabledId } = useValues(logic)
+ const {
+ subscriptions,
+ subscriptionsLoading,
+ aiSubscriptions,
+ aiSubscriptionsLoading,
+ deliveringSubscriptionId,
+ togglingEnabledId,
+ } = useValues(logic)
const { deleteSubscription, deliverSubscription, setSubscriptionEnabled } = useActions(logic)
const subscriptionResourceNoun = !insightShortId && dashboardId ? 'dashboard' : 'insight'
+ const hasResourceSubs = subscriptions.length > 0
+ const hasAiSubs = aiSubscriptions.length > 0
+ const loading = (subscriptionsLoading || aiSubscriptionsLoading) && !hasResourceSubs && !hasAiSubs
+
+ const renderItem = (sub: SubscriptionType): JSX.Element => (
+ <SubscriptionListItem
+ key={sub.id}
+ subscription={sub}
+ onClick={() => onSelect(sub.id)}
+ onDelete={() => deleteSubscription(sub.id)}
+ onDeliver={() => deliverSubscription(sub.id)}
+ onToggleEnabled={(enabled) => setSubscriptionEnabled(sub.id, enabled)}
+ isDelivering={deliveringSubscriptionId === sub.id}
+ isToggling={togglingEnabledId === sub.id}
+ />
+ )
return (
<>
@@ -146,34 +184,12 @@ export function ManageSubscriptions({
<h3> Manage Subscriptions</h3>
</LemonModal.Header>
<LemonModal.Content>
- {subscriptionsLoading && !subscriptions.length ? (
+ {loading ? (
<div className="deprecated-space-y-2">
<LemonSkeleton className="w-1/2 h-4" />
<LemonSkeleton.Row repeat={2} />
</div>
- ) : subscriptions.length ? (
- <div className="deprecated-space-y-2">
- <div>
- <strong>{subscriptions?.length}</strong>{' '}
- {pluralize(subscriptions.length || 0, 'subscription', 'subscriptions', false)}
- </div>
-
- <div className="max-h-[50vh] overflow-y-auto flex flex-col gap-2">
- {subscriptions.map((sub) => (
- <SubscriptionListItem
- key={sub.id}
- subscription={sub}
- onClick={() => onSelect(sub.id)}
- onDelete={() => deleteSubscription(sub.id)}
- onDeliver={() => deliverSubscription(sub.id)}
- onToggleEnabled={(enabled) => setSubscriptionEnabled(sub.id, enabled)}
- isDelivering={deliveringSubscriptionId === sub.id}
- isToggling={togglingEnabledId === sub.id}
- />
- ))}
- </div>
- </div>
- ) : (
+ ) : !hasResourceSubs && !hasAiSubs ? (
<div className="flex flex-col p-4 items-center text-center">
<h3>There are no subscriptions for this {subscriptionResourceNoun}</h3>
@@ -183,16 +199,64 @@ export function ManageSubscriptions({
Add subscription
</LemonButton>
</div>
+ ) : (
+ <div className="deprecated-space-y-4">
+ <div className="deprecated-space-y-2">
+ {hasResourceSubs ? (
+ <>
+ <div>
+ <strong>{subscriptions.length}</strong>{' '}
+ {pluralize(subscriptions.length, 'subscription', 'subscriptions', false)}
+ </div>
+ <div className="max-h-[50vh] overflow-y-auto flex flex-col gap-2">
+ {subscriptions.map(renderItem)}
+ </div>
+ </>
+ ) : (
+ <div className="text-muted">
+ No subscriptions for this {subscriptionResourceNoun} yet.
+ </div>
+ )}
+ </div>
+
+ {hasAiSubs ? (
+ <div className="deprecated-space-y-2">
+ <div>
+ <strong>{aiSubscriptions.length}</strong>{' '}
+ {pluralize(
+ aiSubscriptions.length,
+ 'prompt subscription',
+ 'prompt subscriptions',
+ false
+ )}
+ <div className="text-xs text-muted">
+ Not tied to this {subscriptionResourceNoun}, shared across your project.
+ </div>
+ </div>
+ <div className="flex flex-col gap-2">
+ {aiSubscriptions.slice(0, AI_PREVIEW_LIMIT).map(renderItem)}
+ </div>
+ {aiSubscriptions.length > AI_PREVIEW_LIMIT ? (
+ <Link to={urls.subscriptions()} className="text-xs">
+ View all {aiSubscriptions.length} prompt subscriptions
+ </Link>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
)}
</LemonModal.Content>
<LemonModal.Footer>
- <div className="flex-1">
- {subscriptions.length ? (
+ <div className="flex-1 flex gap-2">
+ {hasResourceSubs || hasAiSubs ? (
<LemonButton type="secondary" onClick={() => onSelect('new')}>
Add subscription
</LemonButton>
) : null}
+ <LemonButton type="tertiary" to={urls.subscriptions()}>
+ View all subscriptions
+ </LemonButton>
</div>
<LemonButton type="secondary" onClick={onCancel}>
Close
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index d685eaa3ffee..d3aadf178d95 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -479,6 +479,7 @@ export const FEATURE_FLAGS = {
SNAPCHAT_ADS_SOURCE: 'snapchat-ads-source', // owner: @jabahamondes #team-web-analytics
SQL_EDITOR_VIM_MODE: 'sql-editor-vim-mode', // owner: @arthurdedeus
SSE_DASHBOARDS: 'sse-dashboards', // owner: @aspicer #team-analytics-platform
+ SUBSCRIPTION_AI_PROMPT: 'ai-subscriptions', // owner: #team-analytics-platform, gates AI prompt-based subscriptions
SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE: 'subscription-ai-summary-prompt-guide', // owner: #team-analytics-platform, gates the per-subscription prompt guide textarea
SURVEY_HEADLINE_SUMMARY: 'survey-headline-summary', // owner: @adboio #team-surveys
SURVEYS_ERROR_TRACKING_CROSS_SELL: 'surveys-in-error-tracking', // owner: @adboio #team-surveys
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index d6988fdc11a0..fecc743c4f80 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -40239,6 +40239,11 @@
"required": ["id", "tool_call_id", "content"],
"type": "object"
},
+ "SubscriptionAIPromptMaxLength": {
+ "const": 4000,
+ "description": "Maximum length, in characters, of an AI subscription prompt.",
+ "type": "number"
+ },
"SubscriptionDropoffMode": {
"enum": ["last_event", "after_dropoff_period"],
"type": "string"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 898a2e32ab04..311629ce0e39 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -6353,6 +6353,11 @@ export enum SubscriptionFreeTierLimit {
COUNT = 5,
}
+/** Maximum length, in characters, of an AI subscription prompt. */
+export enum SubscriptionAIPromptMaxLength {
+ CHARACTERS = 4000,
+}
+
export type UsageMetricFormat = 'numeric' | 'currency'
export type UsageMetricDisplay = 'number' | 'sparkline'
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index dd67d26ca98b..8ced562d7e30 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -929,6 +929,12 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.healthCategory(':category')]: [Scene.HealthCategoryDetail, 'healthCategoryDetail'],
[urls.exports()]: [Scene.Exports, 'exports'],
[urls.subscriptions()]: [Scene.Subscriptions, 'subscriptions'],
+ // Static + edit routes MUST come before `/subscriptions/:subscriptionId`,
+ // otherwise the wildcard captures "new" / "<id>/edit" and mounts the detail
+ // scene → 404 "Subscription not found" with a removeChild reconciliation
+ // error from the racing mounts.
+ [urls.subscriptionNew()]: [Scene.Subscriptions, 'subscriptionNew'],
+ [urls.subscriptionEdit(':subscriptionId')]: [Scene.Subscriptions, 'subscriptionEdit'],
[urls.subscription(':subscriptionId')]: [Scene.Subscription, 'subscription'],
[urls.startups()]: [Scene.StartupProgram, 'startupProgram'],
[urls.startups(':referrer')]: [Scene.StartupProgram, 'startupProgramWithReferrer'],
diff --git a/frontend/src/scenes/subscriptions/SubscriptionScene.tsx b/frontend/src/scenes/subscriptions/SubscriptionScene.tsx
index ecb261cee27a..2e5cd3ad41b5 100644
--- a/frontend/src/scenes/subscriptions/SubscriptionScene.tsx
+++ b/frontend/src/scenes/subscriptions/SubscriptionScene.tsx
@@ -2,6 +2,7 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { LemonButton, LemonTag } from '@posthog/lemon-ui'
+import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { NotFound } from 'lib/components/NotFound'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
@@ -9,7 +10,6 @@ import { getCurrentTeamId } from 'lib/utils/getAppContext'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
-import type { SubscriptionApi } from '~/generated/core/api.schemas'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
diff --git a/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx b/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx
index 61b6c037ee65..c95302e4305f 100644
--- a/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx
+++ b/frontend/src/scenes/subscriptions/SubscriptionsScene.tsx
@@ -2,10 +2,13 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { IconEllipsis } from '@posthog/icons'
-import { LemonButton, LemonMenu, Link } from '@posthog/lemon-ui'
+import { LemonButton, LemonMenu, LemonModal, Link } from '@posthog/lemon-ui'
+import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { DetectiveHog } from 'lib/components/hedgehogs'
import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
+import { EditSubscription } from 'lib/components/Subscriptions/views/EditSubscription'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonTab, LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { deleteWithUndo } from 'lib/utils/deleteWithUndo'
@@ -14,7 +17,6 @@ import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
-import type { SubscriptionApi } from '~/generated/core/api.schemas'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
@@ -101,8 +103,10 @@ export function SubscriptionsScene(): JSX.Element {
currentTab,
subscriptionsSorting,
targetTypeFilter,
+ subscriptionModalId,
} = useValues(subscriptionsSceneLogic)
const { setCurrentTab, setSubscriptionsSorting } = useActions(subscriptionsSceneLogic)
+ const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')
const isFiltered =
Boolean(search.trim()) ||
@@ -115,6 +119,7 @@ export function SubscriptionsScene(): JSX.Element {
{ key: SubscriptionsTab.Mine, label: 'My subscriptions' },
{ key: SubscriptionsTab.Dashboard, label: 'Dashboard' },
{ key: SubscriptionsTab.Insight, label: 'Insight' },
+ ...(aiSubscriptionsEnabled ? [{ key: SubscriptionsTab.AI, label: 'Prompt' }] : []),
]
const showProductIntroduction =
subscriptions.length === 0 && !subscriptionsLoading && !isFiltered && !subscriptionsListAwaitingDebouncedFetch
@@ -125,6 +130,17 @@ export function SubscriptionsScene(): JSX.Element {
name={sceneConfigurations[Scene.Subscriptions].name}
description={sceneConfigurations[Scene.Subscriptions].description}
resourceType={{ type: 'inbox' }}
+ actions={
+ aiSubscriptionsEnabled ? (
+ <LemonButton
+ type="primary"
+ data-attr="new-subscription-button"
+ onClick={() => router.actions.push(urls.subscriptionNew())}
+ >
+ New prompt subscription
+ </LemonButton>
+ ) : undefined
+ }
/>
<LemonTabs
activeKey={currentTab}
@@ -167,6 +183,15 @@ export function SubscriptionsScene(): JSX.Element {
</>
)}
</div>
+ {subscriptionModalId !== null && (
+ <LemonModal isOpen onClose={() => router.actions.push(urls.subscriptions())} simple={false} width={650}>
+ <EditSubscription
+ id={subscriptionModalId}
+ onCancel={() => router.actions.push(urls.subscriptions())}
+ onDelete={() => router.actions.push(urls.subscriptions())}
+ />
+ </LemonModal>
+ )}
</SceneContent>
)
}
diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.stories.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.stories.tsx
index 16ce36adc39e..155d72120fe6 100644
--- a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.stories.tsx
+++ b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.stories.tsx
@@ -4,7 +4,7 @@ import { useMemo, useState } from 'react'
import type {
PaginatedSubscriptionDeliveryListApi,
SubscriptionsDeliveriesListStatus,
-} from '~/generated/core/api.schemas'
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { SubscriptionDeliveryHistory } from './SubscriptionDeliveryHistory'
import { MOCK_SUBSCRIPTION_DELIVERIES } from './subscriptionStoryFixtures'
diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx
index c2826001ef77..4fca350f271a 100644
--- a/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx
+++ b/frontend/src/scenes/subscriptions/components/SubscriptionDeliveryHistory.tsx
@@ -8,18 +8,17 @@ import {
LemonTag,
Tooltip,
} from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-
import type {
PaginatedSubscriptionDeliveryListApi,
SubscriptionApi,
SubscriptionDeliveryApi,
-} from '~/generated/core/api.schemas'
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import {
SubscriptionDeliveryStatusEnumApi,
SubscriptionsDeliveriesListStatus as SubscriptionDeliveriesListStatusByValue,
-} from '~/generated/core/api.schemas'
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
+
+import { TZLabel } from 'lib/components/TZLabel'
import { SubscriptionDeliveryDestinationCell } from './SubscriptionDestinationCell'
import { TARGET_TYPE_LABEL } from './subscriptionLabels'
diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionDestinationCell.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionDestinationCell.tsx
index c45d88ab13f3..71e180b2e268 100644
--- a/frontend/src/scenes/subscriptions/components/SubscriptionDestinationCell.tsx
+++ b/frontend/src/scenes/subscriptions/components/SubscriptionDestinationCell.tsx
@@ -1,12 +1,11 @@
import { IconChevronDown, IconCopy } from '@posthog/icons'
import { LemonMenu, LemonTag } from '@posthog/lemon-ui'
+import { TargetTypeEnumApi, type SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { parseCommaSeparatedSlackTargetDisplayLabels } from 'lib/utils/slackChannelValue'
-import { TargetTypeEnumApi, type SubscriptionApi } from '~/generated/core/api.schemas'
-
function parseEmailRecipients(targetValue: string): string[] {
return targetValue
.split(',')
diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionSummary.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionSummary.tsx
index b43691eea410..3a3b5617a879 100644
--- a/frontend/src/scenes/subscriptions/components/SubscriptionSummary.tsx
+++ b/frontend/src/scenes/subscriptions/components/SubscriptionSummary.tsx
@@ -1,9 +1,9 @@
import { Link } from '@posthog/lemon-ui'
+import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { TZLabel } from 'lib/components/TZLabel'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import type { SubscriptionApi } from '~/generated/core/api.schemas'
import type { HedgehogConfig, MinimalHedgehogConfig } from '~/types'
import { SubscriptionDestinationCell } from './SubscriptionDestinationCell'
diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionsFiltersBar.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionsFiltersBar.tsx
index b2911dc3c417..355983bd5ea7 100644
--- a/frontend/src/scenes/subscriptions/components/SubscriptionsFiltersBar.tsx
+++ b/frontend/src/scenes/subscriptions/components/SubscriptionsFiltersBar.tsx
@@ -1,11 +1,13 @@
import { useActions, useValues } from 'kea'
import { LemonInput, LemonSelect } from '@posthog/lemon-ui'
+import {
+ TargetTypeEnumApi,
+ type SubscriptionsListTargetType,
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { MemberSelect } from 'lib/components/MemberSelect'
-import { TargetTypeEnumApi, type SubscriptionsListTargetType } from '~/generated/core/api.schemas'
-
import { SubscriptionsTab, subscriptionsSceneLogic } from '../subscriptionsSceneLogic'
const CHANNEL_FILTER_OPTIONS: { label: string; value: SubscriptionsListTargetType | null }[] = [
diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx
index 7f1dcce14a44..528ee5607c9c 100644
--- a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx
+++ b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.stories.tsx
@@ -4,9 +4,12 @@ import { useState, type ComponentProps } from 'react'
import { IconEllipsis } from '@posthog/icons'
import { LemonButton } from '@posthog/lemon-ui'
import type { PaginationManual } from '@posthog/lemon-ui'
-
-import type { SubscriptionApi } from '~/generated/core/api.schemas'
-import { SubscriptionFrequencyEnumApi, TargetTypeEnumApi } from '~/generated/core/api.schemas'
+import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
+import {
+ ResourceTypeEnumApi,
+ SubscriptionFrequencyEnumApi,
+ TargetTypeEnumApi,
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { SubscriptionsTable } from './SubscriptionsTable'
@@ -22,6 +25,7 @@ const MOCK_USER = {
const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [
{
id: 1,
+ resource_type: ResourceTypeEnumApi.Insight,
insight: 101,
dashboard: null,
insight_short_id: 'abc123',
@@ -43,6 +47,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [
},
{
id: 2,
+ resource_type: ResourceTypeEnumApi.Dashboard,
insight: null,
dashboard: 501,
insight_short_id: null,
@@ -64,6 +69,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [
},
{
id: 3,
+ resource_type: ResourceTypeEnumApi.Insight,
insight: 103,
dashboard: null,
insight_short_id: 'ghi789',
@@ -84,6 +90,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [
},
{
id: 4,
+ resource_type: ResourceTypeEnumApi.Insight,
insight: 104,
dashboard: null,
insight_short_id: 'webhook-insight',
@@ -104,6 +111,7 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [
},
{
id: 5,
+ resource_type: ResourceTypeEnumApi.Insight,
insight: 105,
dashboard: null,
insight_short_id: 'disabled-insight',
@@ -123,6 +131,28 @@ const MOCK_SUBSCRIPTIONS: SubscriptionApi[] = [
enabled: false,
integration_id: 1,
},
+ {
+ id: 6,
+ resource_type: ResourceTypeEnumApi.AiPrompt,
+ insight: null,
+ dashboard: null,
+ insight_short_id: null,
+ resource_name: null,
+ prompt: 'Summarize weekly signups and flag any anomalies worth a closer look',
+ title: 'AI weekly digest',
+ dashboard_export_insights: [],
+ target_type: TargetTypeEnumApi.Email,
+ target_value: '[email protected]',
+ frequency: SubscriptionFrequencyEnumApi.Weekly,
+ interval: 1,
+ start_date: '2022-01-01T00:00:00Z',
+ created_at: '2023-04-27T10:04:37.977401Z',
+ created_by: MOCK_USER,
+ summary: 'sent every week',
+ next_delivery_date: '2026-04-09T08:00:00Z',
+ deleted: false,
+ enabled: true,
+ },
]
const PAGINATION_PAGE_SIZE = 20
@@ -144,6 +174,7 @@ function buildMockSubscriptions(total: number): SubscriptionApi[] {
const isSlack = i % 3 === 0
return {
id: n,
+ resource_type: isInsight ? ResourceTypeEnumApi.Insight : ResourceTypeEnumApi.Dashboard,
insight: isInsight ? 1000 + n : null,
dashboard: isInsight ? null : 2000 + n,
insight_short_id: isInsight ? `short${n}` : null,
diff --git a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.tsx b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.tsx
index 625419a64b8e..58459cb6bae5 100644
--- a/frontend/src/scenes/subscriptions/components/SubscriptionsTable.tsx
+++ b/frontend/src/scenes/subscriptions/components/SubscriptionsTable.tsx
@@ -1,12 +1,14 @@
+import { IconAI, IconDashboard, IconGraph } from '@posthog/icons'
import { LemonTable, LemonTableColumn, LemonTableColumns, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
import type { PaginationManual, Sorting } from '@posthog/lemon-ui'
+import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { TZLabel } from 'lib/components/TZLabel'
import { atColumn, createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
import { urls } from 'scenes/urls'
-import type { SubscriptionApi } from '~/generated/core/api.schemas'
import type { InsightShortId } from '~/types'
+import { SubscriptionResourceTypes } from '~/types'
import { SubscriptionDestinationCell } from './SubscriptionDestinationCell'
import { TARGET_TYPE_LABEL } from './subscriptionLabels'
@@ -31,6 +33,9 @@ export function subscriptionEditHref(sub: SubscriptionApi): string | null {
if (sub.dashboard) {
return urls.dashboardSubscription(sub.dashboard, String(sub.id))
}
+ if (sub.resource_type === SubscriptionResourceTypes.AiPrompt) {
+ return urls.subscriptionEdit(sub.id)
+ }
return null
}
@@ -112,9 +117,24 @@ function buildColumns(renderRowActions: (sub: SubscriptionApi) => JSX.Element):
title: 'Type',
key: 'type',
width: '7rem',
- render: (_value: unknown, sub: SubscriptionApi) => (
- <span className="whitespace-nowrap">{sub.insight ? 'Insight' : sub.dashboard ? 'Dashboard' : '—'}</span>
- ),
+ render: (_value: unknown, sub: SubscriptionApi) => {
+ let typeTag: { icon: JSX.Element; label: string } | null = null
+ if (sub.resource_type === SubscriptionResourceTypes.AiPrompt) {
+ typeTag = { icon: <IconAI />, label: 'Prompt' }
+ } else if (sub.insight) {
+ typeTag = { icon: <IconGraph />, label: 'Insight' }
+ } else if (sub.dashboard) {
+ typeTag = { icon: <IconDashboard />, label: 'Dashboard' }
+ }
+ if (!typeTag) {
+ return <span className="text-secondary">—</span>
+ }
+ return (
+ <LemonTag type="default" size="small" icon={typeTag.icon}>
+ {typeTag.label}
+ </LemonTag>
+ )
+ },
},
{
title: 'Resource',
@@ -124,6 +144,23 @@ function buildColumns(renderRowActions: (sub: SubscriptionApi) => JSX.Element):
maxWidth: 0,
}),
render: (_value: unknown, sub: SubscriptionApi) => {
+ // AI subs have no insight/dashboard FK — surface the prompt instead so the row
+ // reads as intentional ("this is what the AI was asked to do") rather than empty.
+ if (sub.resource_type === SubscriptionResourceTypes.AiPrompt) {
+ const prompt = sub.prompt?.trim()
+ if (!prompt) {
+ return <span className="text-secondary">—</span>
+ }
+ return (
+ <Tooltip title={prompt}>
+ <div className="min-w-0 w-full overflow-hidden">
+ <span className="text-muted italic block truncate" data-attr="subscription-ai-prompt">
+ {prompt}
+ </span>
+ </div>
+ </Tooltip>
+ )
+ }
const href = subscriptionResourceViewUrl(sub)
if (!href) {
return <span className="text-secondary">—</span>
diff --git a/frontend/src/scenes/subscriptions/components/subscriptionLabels.ts b/frontend/src/scenes/subscriptions/components/subscriptionLabels.ts
index 29d9878f2e2c..a72ff597d52b 100644
--- a/frontend/src/scenes/subscriptions/components/subscriptionLabels.ts
+++ b/frontend/src/scenes/subscriptions/components/subscriptionLabels.ts
@@ -1,5 +1,5 @@
-import type { SubscriptionApi } from '~/generated/core/api.schemas'
-import { TargetTypeEnumApi } from '~/generated/core/api.schemas'
+import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
+import { TargetTypeEnumApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
export const TARGET_TYPE_LABEL: Record<SubscriptionApi['target_type'], string> = {
[TargetTypeEnumApi.Email]: 'Email',
diff --git a/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts b/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts
index 46316aaa4f1b..040c25338a13 100644
--- a/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts
+++ b/frontend/src/scenes/subscriptions/components/subscriptionStoryFixtures.ts
@@ -1,10 +1,11 @@
import {
+ ResourceTypeEnumApi,
SubscriptionDeliveryStatusEnumApi,
SubscriptionFrequencyEnumApi,
TargetTypeEnumApi,
type SubscriptionApi,
type SubscriptionDeliveryApi,
-} from '~/generated/core/api.schemas'
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
export const MOCK_SUBSCRIPTION_USER = {
id: 1,
@@ -17,6 +18,7 @@ export const MOCK_SUBSCRIPTION_USER = {
export const MOCK_SUBSCRIPTION_INSIGHT: SubscriptionApi = {
id: 1,
+ resource_type: ResourceTypeEnumApi.Insight,
insight: 101,
dashboard: null,
insight_short_id: 'abc123',
@@ -47,6 +49,7 @@ export const MOCK_SUBSCRIPTION_INSIGHT_MANY_DESTINATIONS: SubscriptionApi = {
export const MOCK_SUBSCRIPTION_DASHBOARD: SubscriptionApi = {
id: 2,
+ resource_type: ResourceTypeEnumApi.Dashboard,
insight: null,
dashboard: 501,
insight_short_id: null,
diff --git a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts
index 13f8e2554b0e..1962dd521568 100644
--- a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts
+++ b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts
@@ -2,15 +2,17 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-
import {
+ ResourceTypeEnumApi,
SubscriptionFrequencyEnumApi,
SubscriptionsDeliveriesListStatus,
TargetTypeEnumApi,
-} from '~/generated/core/api.schemas'
-import type { SubscriptionApi } from '~/generated/core/api.schemas'
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
+import type { SubscriptionApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -27,6 +29,7 @@ const MOCK_USER = {
const MOCK_SUBSCRIPTION: SubscriptionApi = {
id: 1,
+ resource_type: ResourceTypeEnumApi.Insight,
insight: 101,
dashboard: null,
insight_short_id: 'abc123',
@@ -45,6 +48,28 @@ const MOCK_SUBSCRIPTION: SubscriptionApi = {
deleted: false,
}
+const MOCK_AI_SUBSCRIPTION: SubscriptionApi = {
+ id: 2,
+ resource_type: ResourceTypeEnumApi.AiPrompt,
+ insight: null,
+ dashboard: null,
+ insight_short_id: null,
+ resource_name: null,
+ prompt: 'Summarize weekly signups and flag any anomalies',
+ title: 'Weekly AI digest',
+ dashboard_export_insights: [],
+ target_type: TargetTypeEnumApi.Email,
+ target_value: '[email protected]',
+ frequency: SubscriptionFrequencyEnumApi.Weekly,
+ interval: 1,
+ start_date: '2022-01-01T00:00:00Z',
+ created_at: '2023-04-27T10:04:37.977401Z',
+ created_by: MOCK_USER,
+ summary: 'sent every week',
+ next_delivery_date: '2026-04-07T17:00:00Z',
+ deleted: false,
+}
+
describe('subscriptionSceneLogic', () => {
let deliveriesRequestUrls: string[]
@@ -161,4 +186,39 @@ describe('subscriptionSceneLogic', () => {
logic.unmount()
featureFlagLogic.unmount()
})
+
+ it('loads an AI prompt subscription and its deliveries when the flag is on', async () => {
+ useMocks({
+ get: {
+ // Function form, not the `[200, body]` shorthand: useMocks serializes a bare array as
+ // the whole response body, so only a function-returned tuple delivers the object itself.
+ [`/api/projects/${MOCK_TEAM_ID}/subscriptions/2/`]: () => [200, MOCK_AI_SUBSCRIPTION],
+ [`/api/environments/${MOCK_TEAM_ID}/subscriptions/2/deliveries/`]: () => {
+ deliveriesRequestUrls.push('deliveries')
+ return [200, { results: [], next: null, previous: null }]
+ },
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ // HACKATHONS_SUBSCRIPTIONS gates the delivery history this test asserts; SUBSCRIPTION_AI_PROMPT
+ // is what makes AI prompt subscriptions exist in the first place, so both are on in a realistic run.
+ featureFlagLogic.actions.setFeatureFlags(
+ [FEATURE_FLAGS.HACKATHONS_SUBSCRIPTIONS, FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT],
+ {
+ [FEATURE_FLAGS.HACKATHONS_SUBSCRIPTIONS]: true,
+ [FEATURE_FLAGS.SUBSCRIPTION_AI_PROMPT]: true,
+ }
+ )
+
+ const logic = subscriptionSceneLogic({ id: '2' })
+ logic.mount()
+
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.subscription?.resource_type).toEqual(ResourceTypeEnumApi.AiPrompt)
+ expect(logic.values.subscription?.prompt).toBeTruthy()
+ expect(deliveriesRequestUrls).toHaveLength(1)
+ logic.unmount()
+ featureFlagLogic.unmount()
+ })
})
diff --git a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx
index 973bc66776f5..7108bce7348c 100644
--- a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx
+++ b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.tsx
@@ -2,26 +2,27 @@ import { actions, afterMount, connect, kea, key, listeners, path, props, reducer
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'
-import { runSubscriptionTestDelivery } from 'lib/components/Subscriptions/runSubscriptionTestDelivery'
-import { FEATURE_FLAGS } from 'lib/constants'
-import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { getCurrentTeamId } from 'lib/utils/getAppContext'
-import { sceneConfigurations } from 'scenes/scenes'
-import { Scene } from 'scenes/sceneTypes'
-import { urls } from 'scenes/urls'
-
import {
subscriptionsDeliveriesList,
subscriptionsPartialUpdate,
subscriptionsRetrieve,
subscriptionsTestDeliveryCreate,
-} from '~/generated/core/api'
+} from '@posthog/products-subscriptions/frontend/generated/api'
import type {
PaginatedSubscriptionDeliveryListApi,
SubscriptionApi,
SubscriptionsDeliveriesListStatus,
-} from '~/generated/core/api.schemas'
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
+
+import { runSubscriptionTestDelivery } from 'lib/components/Subscriptions/runSubscriptionTestDelivery'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { getCurrentTeamId } from 'lib/utils/getAppContext'
+import { sceneConfigurations } from 'scenes/scenes'
+import { Scene } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
+
import { Breadcrumb } from '~/types'
import { subscriptionName } from './components/SubscriptionsTable'
diff --git a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
index 2b2ae47b1c49..98c118075f52 100644
--- a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
+++ b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
@@ -3,12 +3,13 @@ import { MOCK_DEFAULT_USER, MOCK_USER_UUID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
+import { TargetTypeEnumApi } from '@posthog/products-subscriptions/frontend/generated/api.schemas'
+
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
-import { TargetTypeEnumApi } from '~/generated/core/api.schemas'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -86,6 +87,19 @@ describe('subscriptionsSceneLogic', () => {
expect(params.get('resource_type')).toBe('insight')
})
+ it('sends resource_type=ai_prompt on AI reports tab', async () => {
+ await expectLogic(logic).toDispatchActions(['loadSubscriptionsSuccess'])
+ subscriptionRequestUrls.length = 0
+
+ await expectLogic(logic, () => {
+ logic.actions.setCurrentTab(SubscriptionsTab.AI)
+ }).toDispatchActions(['setCurrentTab', 'loadSubscriptions', 'loadSubscriptionsSuccess'])
+
+ expect(subscriptionRequestUrls).toHaveLength(1)
+ const params = subscriptionListParamsFromUrl(subscriptionRequestUrls[0])
+ expect(params.get('resource_type')).toBe('ai_prompt')
+ })
+
it('sends created_by for Mine tab', async () => {
await expectLogic(logic).toDispatchActions(['loadSubscriptionsSuccess'])
subscriptionRequestUrls.length = 0
@@ -183,4 +197,26 @@ describe('subscriptionsSceneLogic', () => {
expect(params.get('target_type')).toBe('slack')
})
})
+
+ describe('modal routing', () => {
+ it('opens the modal on /subscriptions/new and closes when navigating back to the list', async () => {
+ await expectLogic(logic).toDispatchActions(['loadSubscriptionsSuccess'])
+
+ await expectLogic(logic, () => {
+ router.actions.push(urls.subscriptionNew())
+ }).toMatchValues({ subscriptionModalId: 'new' })
+
+ await expectLogic(logic, () => {
+ router.actions.push(urls.subscriptions())
+ }).toMatchValues({ subscriptionModalId: null })
+ })
+
+ it('opens the modal with the subscription id on /subscriptions/:id/edit', async () => {
+ await expectLogic(logic).toDispatchActions(['loadSubscriptionsSuccess'])
+
+ await expectLogic(logic, () => {
+ router.actions.push(urls.subscriptionEdit('42'))
+ }).toMatchValues({ subscriptionModalId: 42 })
+ })
+ })
})
diff --git a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.tsx b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.tsx
index 65aaa00b07bb..53ba5c70882a 100644
--- a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.tsx
+++ b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.tsx
@@ -3,6 +3,16 @@ import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { Sorting } from '@posthog/lemon-ui'
+import {
+ subscriptionsList,
+ subscriptionsTestDeliveryCreate,
+} from '@posthog/products-subscriptions/frontend/generated/api'
+import {
+ SubscriptionsListResourceType,
+ TargetTypeEnumApi,
+ type PaginatedSubscriptionListApi,
+ type SubscriptionsListTargetType,
+} from '@posthog/products-subscriptions/frontend/generated/api.schemas'
import { runSubscriptionTestDelivery } from 'lib/components/Subscriptions/runSubscriptionTestDelivery'
import { toggleSubscriptionEnabled } from 'lib/components/Subscriptions/toggleSubscriptionEnabled'
@@ -13,13 +23,6 @@ import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
-import { subscriptionsList, subscriptionsTestDeliveryCreate } from '~/generated/core/api'
-import {
- SubscriptionsListResourceType,
- TargetTypeEnumApi,
- type PaginatedSubscriptionListApi,
- type SubscriptionsListTargetType,
-} from '~/generated/core/api.schemas'
import { Breadcrumb } from '~/types'
import type { subscriptionsSceneLogicType } from './subscriptionsSceneLogicType'
@@ -31,6 +34,7 @@ export enum SubscriptionsTab {
Mine = 'mine',
Dashboard = 'dashboard',
Insight = 'insight',
+ AI = 'ai_prompt',
}
/** Return type is full `SubscriptionsTab` so Kea typegen does not collapse state to the `All` literal. */
@@ -56,10 +60,9 @@ export interface SubscriptionsQueryFromUrl {
function parseSubscriptionsSearchParams(searchParams: Record<string, unknown>): SubscriptionsQueryFromUrl {
const rawTab = searchParams['tab']
- const tab: SubscriptionsTab =
- rawTab === SubscriptionsTab.Mine || rawTab === SubscriptionsTab.Dashboard || rawTab === SubscriptionsTab.Insight
- ? rawTab
- : SubscriptionsTab.All
+ const tab: SubscriptionsTab = (Object.values(SubscriptionsTab) as string[]).includes(rawTab as string)
+ ? (rawTab as SubscriptionsTab)
+ : SubscriptionsTab.All
const search = urlSearchParamToString(searchParams['search'])
@@ -203,6 +206,7 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([
setSubscriptionsSorting: (sorting: Sorting | null) => ({ sorting }),
setTargetTypeFilter: (targetType: SubscriptionsListTargetType | null) => ({ targetType }),
applySubscriptionsQueryFromUrl: (query: SubscriptionsQueryFromUrl) => ({ query }),
+ setSubscriptionModalId: (id: number | 'new' | null) => ({ id }),
deleteSubscriptionSuccess: true,
deliverSubscription: (id: number) => ({ id }),
deliverSubscriptionSuccess: true,
@@ -261,6 +265,14 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([
applySubscriptionsQueryFromUrl: (_, { query }) => query.targetTypeFilter,
},
],
+ // Drives the create/edit modal that now renders OVER the list (route-driven), so the
+ // list stays painted behind it instead of swapping to a separate scene. `null` = closed.
+ subscriptionModalId: [
+ null as number | 'new' | null,
+ {
+ setSubscriptionModalId: (_, { id }) => id,
+ },
+ ],
/**
* True after `setSearch` until the debounced list request finishes. Avoids treating stale
* empty `subscriptionsResponse` as "no subscriptions in project" when filters were cleared.
@@ -303,6 +315,8 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([
resourceType = SubscriptionsListResourceType.Dashboard
} else if (values.currentTab === SubscriptionsTab.Insight) {
resourceType = SubscriptionsListResourceType.Insight
+ } else if (values.currentTab === SubscriptionsTab.AI) {
+ resourceType = SubscriptionsListResourceType.AiPrompt
}
const createdBy =
values.currentTab === SubscriptionsTab.Mine
@@ -423,7 +437,17 @@ export const subscriptionsSceneLogic = kea<subscriptionsSceneLogicType>([
}
}),
urlToAction(({ actions, values }) => ({
+ [urls.subscriptionNew()]: () => {
+ actions.setSubscriptionModalId('new')
+ },
+ [urls.subscriptionEdit(':subscriptionId')]: ({ subscriptionId }) => {
+ const editingId = Number(subscriptionId)
+ actions.setSubscriptionModalId(Number.isFinite(editingId) ? editingId : 'new')
+ },
[urls.subscriptions()]: (_, searchParams) => {
+ if (values.subscriptionModalId !== null) {
+ actions.setSubscriptionModalId(null)
+ }
const parsed = parseSubscriptionsSearchParams(searchParams)
const listState = {
currentTab: values.currentTab,
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 4579fec0d120..1a9db087c0e4 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -300,6 +300,8 @@ export const urls = {
exports: (): string => '/exports',
subscriptions: (): string => '/subscriptions',
subscription: (id: string | number): string => `/subscriptions/${id}`,
+ subscriptionNew: (): string => '/subscriptions/new',
+ subscriptionEdit: (id: string | number): string => `/subscriptions/${id}/edit`,
}
export interface UrlMatcher {
diff --git a/frontend/src/test/mocks.ts b/frontend/src/test/mocks.ts
index bdfeddd6a319..a2ff9832473a 100644
--- a/frontend/src/test/mocks.ts
+++ b/frontend/src/test/mocks.ts
@@ -195,6 +195,7 @@ export const mockCohort: CohortType = {
export const mockSubscription: SubscriptionType = {
id: 1,
+ resource_type: 'insight',
title: 'My example subscription',
target_type: 'email',
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 0b16fb5dfe07..ba329d31f8d3 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5132,17 +5132,28 @@ export enum ValueOptionType {
export type WeekdayType = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday'
-// TODO: migrate to SubscriptionApi from frontend/src/generated/core/api.schemas.ts.
+export type SubscriptionResourceType = 'insight' | 'dashboard' | 'ai_prompt'
+// Value map for the above — kept a distinct name from the type so kea-typegen still imports
+// the type correctly (a const+type sharing a name drops it from generated `import type` lines).
+export const SubscriptionResourceTypes = {
+ Insight: 'insight',
+ Dashboard: 'dashboard',
+ AiPrompt: 'ai_prompt',
+} as const satisfies Record<string, SubscriptionResourceType>
+
+// TODO: migrate to SubscriptionApi from @posthog/products-subscriptions/frontend/generated/api.schemas.
// This hand-written interface predates the generated type and now requires
// dual-maintenance for every backend field change.
export interface SubscriptionType {
id: number
+ resource_type: SubscriptionResourceType
insight?: number
dashboard?: number
insight_short_id?: string | null
resource_name?: string | null
dashboard_export_insights?: number[]
integration_id?: number | null
+ prompt?: string | null
target_type: string
target_value: string
frequency: 'daily' | 'weekly' | 'monthly' | 'yearly'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8ae407dfd3ea..304b7195f9ee 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -715,6 +715,9 @@ importers:
'@posthog/products-session-summaries':
specifier: workspace:*
version: link:../products/session_summaries
+ '@posthog/products-subscriptions':
+ specifier: workspace:*
+ version: link:../products/subscriptions
'@posthog/products-surveys':
specifier: workspace:*
version: link:../products/surveys
@@ -3454,6 +3457,8 @@ importers:
products/streamlit_apps: {}
+ products/subscriptions: {}
+
products/surveys:
dependencies:
'@posthog/icons':
diff --git a/posthog/schema.py b/posthog/schema.py
index 380ba386867c..597190e76a94 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -4979,6 +4979,10 @@ class SubagentUpdateEvent(BaseModel):
tool_call_id: str
+class SubscriptionAIPromptMaxLength(RootModel[Literal[4000]]):
+ root: Literal[4000] = Field(4000, description="Maximum length, in characters, of an AI subscription prompt.")
+
+
class SubscriptionDropoffMode(StrEnum):
LAST_EVENT = "last_event"
AFTER_DROPOFF_PERIOD = "after_dropoff_period"
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
index 35d75f0b4f13..48a0cc10e173 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/spec_generator.py
@@ -6,7 +6,7 @@ from django.db.models import F, Q
import structlog
-from posthog.schema import CachedTeamTaxonomyQueryResponse, TeamTaxonomyQuery
+from posthog.schema import CachedTeamTaxonomyQueryResponse, SubscriptionAIPromptMaxLength, TeamTaxonomyQuery
from posthog.hogql_queries.ai.team_taxonomy_query_runner import TeamTaxonomyQueryRunner
from posthog.hogql_queries.query_runner import ExecutionMode
@@ -26,7 +26,11 @@ from ee.hogai.llm import MaxChatOpenAI
logger = structlog.get_logger(__name__)
-PROMPT_MAX_LENGTH = 4000
+# Single source of truth lives in the generated schema (frontend/src/queries/schema/schema-general.ts),
+# so the backend limit and the frontend's cannot drift. Read the field default rather than
+# instantiating: the generated RootModel carries a Field() default, which the pydantic mypy plugin
+# treats as a required __init__ arg.
+PROMPT_MAX_LENGTH: int = int(SubscriptionAIPromptMaxLength.model_fields["root"].default)
EVENT_NAMES_SAMPLE_LIMIT = 20
# bounds the Postgres scan + context size for the dormant-events list
NO_DATA_EVENT_NAMES_LIMIT = 25
diff --git a/products/subscriptions/__init__.py b/products/subscriptions/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..18370b68d93a
--- /dev/null
+++ b/products/subscriptions/frontend/generated/api.schemas.ts
@@ -0,0 +1,537 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+/**
+ * * `starting` - Starting
+ * `completed` - Completed
+ * `failed` - Failed
+ * `skipped` - Skipped
+ */
+export type SubscriptionDeliveryStatusEnumApi =
+ (typeof SubscriptionDeliveryStatusEnumApi)[keyof typeof SubscriptionDeliveryStatusEnumApi]
+
+export const SubscriptionDeliveryStatusEnumApi = {
+ Starting: 'starting',
+ Completed: 'completed',
+ Failed: 'failed',
+ Skipped: 'skipped',
+} as const
+
+export interface SubscriptionDeliveryApi {
+ /** Primary key for this delivery row. */
+ readonly id: string
+ /** Parent subscription id. */
+ readonly subscription: number
+ /** Temporal workflow id for this delivery run. */
+ readonly temporal_workflow_id: string
+ /** Dedupes activity retries for the same logical run. */
+ readonly idempotency_key: string
+ /** Why the run started (e.g. scheduled, manual, target_change). */
+ readonly trigger_type: string
+ /**
+ * Planned send time when applicable.
+ * @nullable
+ */
+ readonly scheduled_at: string | null
+ /** Channel snapshot at send time (email, slack, webhook). */
+ readonly target_type: string
+ /** Destination snapshot at send time (emails, channel id, URL). */
+ readonly target_value: string
+ /** ExportedAsset ids generated for this send. */
+ readonly exported_asset_ids: readonly number[]
+ /** Snapshot at send time: dashboard metadata, total_insight_count, and per-exported-insight entries (id, short_id, name, query_hash, cache_key, query_results, optional query_error). */
+ readonly content_snapshot: unknown
+ /** Per-destination outcomes; items use status success, failed, or partial. */
+ readonly recipient_results: unknown
+ /** Overall run status: starting, completed, failed, or skipped.
+
+ * `starting` - Starting
+ * `completed` - Completed
+ * `failed` - Failed
+ * `skipped` - Skipped */
+ readonly status: SubscriptionDeliveryStatusEnumApi
+ /** Top-level failure payload when status is failed, if any. */
+ readonly error: unknown
+ /** When the delivery row was created. */
+ readonly created_at: string
+ /** Last ORM update to this row. */
+ readonly last_updated_at: string
+ /**
+ * When the run finished, if applicable.
+ * @nullable
+ */
+ readonly finished_at: string | null
+ /**
+ * AI-generated summary included in this delivery, when one was produced.
+ * @nullable
+ */
+ readonly change_summary: string | null
+}
+
+export interface PaginatedSubscriptionDeliveryListApi {
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: SubscriptionDeliveryApi[]
+}
+
+/**
+ * * `insight` - Insight
+ * `dashboard` - Dashboard
+ * `ai_prompt` - AI prompt
+ */
+export type ResourceTypeEnumApi = (typeof ResourceTypeEnumApi)[keyof typeof ResourceTypeEnumApi]
+
+export const ResourceTypeEnumApi = {
+ Insight: 'insight',
+ Dashboard: 'dashboard',
+ AiPrompt: 'ai_prompt',
+} as const
+
+/**
+ * * `email` - Email
+ * `slack` - Slack
+ * `webhook` - Webhook
+ */
+export type TargetTypeEnumApi = (typeof TargetTypeEnumApi)[keyof typeof TargetTypeEnumApi]
+
+export const TargetTypeEnumApi = {
+ Email: 'email',
+ Slack: 'slack',
+ Webhook: 'webhook',
+} as const
+
+/**
+ * * `daily` - Daily
+ * `weekly` - Weekly
+ * `monthly` - Monthly
+ * `yearly` - Yearly
+ */
+export type SubscriptionFrequencyEnumApi =
+ (typeof SubscriptionFrequencyEnumApi)[keyof typeof SubscriptionFrequencyEnumApi]
+
+export const SubscriptionFrequencyEnumApi = {
+ Daily: 'daily',
+ Weekly: 'weekly',
+ Monthly: 'monthly',
+ Yearly: 'yearly',
+} as const
+
+/**
+ * * `monday` - Monday
+ * `tuesday` - Tuesday
+ * `wednesday` - Wednesday
+ * `thursday` - Thursday
+ * `friday` - Friday
+ * `saturday` - Saturday
+ * `sunday` - Sunday
+ */
+export type SubscriptionApiByweekdayItem =
+ (typeof SubscriptionApiByweekdayItem)[keyof typeof SubscriptionApiByweekdayItem]
+
+export const SubscriptionApiByweekdayItem = {
+ Monday: 'monday',
+ Tuesday: 'tuesday',
+ Wednesday: 'wednesday',
+ Thursday: 'thursday',
+ Friday: 'friday',
+ Saturday: 'saturday',
+ Sunday: 'sunday',
+} as const
+
+/**
+ * * `engineering` - Engineering
+ * `data` - Data
+ * `product` - Product Management
+ * `founder` - Founder
+ * `leadership` - Leadership
+ * `marketing` - Marketing
+ * `sales` - Sales / Success
+ * `other` - Other
+ */
+export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]
+
+export const RoleAtOrganizationEnumApi = {
+ Engineering: 'engineering',
+ Data: 'data',
+ Product: 'product',
+ Founder: 'founder',
+ Leadership: 'leadership',
+ Marketing: 'marketing',
+ Sales: 'sales',
+ Other: 'other',
+} as const
+
+export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
+
+export const BlankEnumApi = {
+ '': '',
+} as const
+
+/**
+ * @nullable
+ */
+export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null
+
+export interface UserBasicApi {
+ readonly id: number
+ readonly uuid: string
+ /**
+ * @maxLength 200
+ * @nullable
+ */
+ distinct_id?: string | null
+ /** @maxLength 150 */
+ first_name?: string
+ /** @maxLength 150 */
+ last_name?: string
+ /** @maxLength 254 */
+ email: string
+ /** @nullable */
+ is_email_verified?: boolean | null
+ /** @nullable */
+ readonly hedgehog_config: UserBasicApiHedgehogConfig
+ role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
+}
+
+/**
+ * Standard Subscription serializer.
+ */
+export interface SubscriptionApi {
+ 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: ResourceTypeEnumApi
+ /**
+ * 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 6. */
+ 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
+ /** Delivery channel: email, slack, or webhook.
+
+ * `email` - Email
+ * `slack` - Slack
+ * `webhook` - Webhook */
+ target_type: TargetTypeEnumApi
+ /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or full URL for webhook. */
+ target_value: string
+ /** How often to deliver: daily, weekly, monthly, or yearly.
+
+ * `daily` - Daily
+ * `weekly` - Weekly
+ * `monthly` - Monthly
+ * `yearly` - Yearly */
+ frequency: SubscriptionFrequencyEnumApi
+ /**
+ * 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 weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
+ * @nullable
+ */
+ byweekday?: SubscriptionApiByweekdayItem[] | 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). */
+ 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
+ summary_enabled?: boolean
+ /** @maxLength 500 */
+ summary_prompt_guide?: string
+}
+
+export interface PaginatedSubscriptionListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: SubscriptionApi[]
+}
+
+/**
+ * * `monday` - Monday
+ * `tuesday` - Tuesday
+ * `wednesday` - Wednesday
+ * `thursday` - Thursday
+ * `friday` - Friday
+ * `saturday` - Saturday
+ * `sunday` - Sunday
+ */
+export type PatchedSubscriptionApiByweekdayItem =
+ (typeof PatchedSubscriptionApiByweekdayItem)[keyof typeof PatchedSubscriptionApiByweekdayItem]
+
+export const PatchedSubscriptionApiByweekdayItem = {
+ Monday: 'monday',
+ Tuesday: 'tuesday',
+ Wednesday: 'wednesday',
+ Thursday: 'thursday',
+ Friday: 'friday',
+ Saturday: 'saturday',
+ Sunday: 'sunday',
+} as const
+
+/**
+ * Standard Subscription serializer.
+ */
+export interface PatchedSubscriptionApi {
+ 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?: ResourceTypeEnumApi
+ /**
+ * 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 6. */
+ 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
+ /** Delivery channel: email, slack, or webhook.
+
+ * `email` - Email
+ * `slack` - Slack
+ * `webhook` - Webhook */
+ target_type?: TargetTypeEnumApi
+ /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or full URL for webhook. */
+ target_value?: string
+ /** How often to deliver: daily, weekly, monthly, or yearly.
+
+ * `daily` - Daily
+ * `weekly` - Weekly
+ * `monthly` - Monthly
+ * `yearly` - Yearly */
+ frequency?: SubscriptionFrequencyEnumApi
+ /**
+ * 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 weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.
+ * @nullable
+ */
+ byweekday?: PatchedSubscriptionApiByweekdayItem[] | 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). */
+ 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
+ summary_enabled?: boolean
+ /** @maxLength 500 */
+ summary_prompt_guide?: string
+}
+
+export type SubscriptionsDeliveriesListParams = {
+ /**
+ * The pagination cursor value.
+ */
+ cursor?: string
+ /**
+ * Return only deliveries in this run status (starting, completed, failed, or skipped).
+ */
+ status?: SubscriptionsDeliveriesListStatus
+}
+
+export type SubscriptionsDeliveriesListStatus =
+ (typeof SubscriptionsDeliveriesListStatus)[keyof typeof SubscriptionsDeliveriesListStatus]
+
+export const SubscriptionsDeliveriesListStatus = {
+ Completed: 'completed',
+ Failed: 'failed',
+ Skipped: 'skipped',
+ Starting: 'starting',
+} as const
+
+export type SubscriptionsListParams = {
+ /**
+ * Filter by creator user UUID.
+ */
+ created_by?: string
+ /**
+ * Filter by dashboard ID.
+ */
+ dashboard?: number
+ /**
+ * Filter by insight ID.
+ */
+ insight?: number
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Which field to use when ordering the results.
+ */
+ ordering?: string
+ /**
+ * Filter by subscription resource: insight, dashboard export, or AI report.
+ */
+ resource_type?: SubscriptionsListResourceType
+ /**
+ * A search term.
+ */
+ search?: string
+ /**
+ * Filter by delivery channel (email, Slack, or webhook).
+ */
+ target_type?: SubscriptionsListTargetType
+}
+
+export type SubscriptionsListResourceType =
+ (typeof SubscriptionsListResourceType)[keyof typeof SubscriptionsListResourceType]
+
+export const SubscriptionsListResourceType = {
+ AiPrompt: 'ai_prompt',
+ Dashboard: 'dashboard',
+ Insight: 'insight',
+} as const
+
+export type SubscriptionsListTargetType = (typeof SubscriptionsListTargetType)[keyof typeof SubscriptionsListTargetType]
+
+export const SubscriptionsListTargetType = {
+ Email: 'email',
+ Slack: 'slack',
+ Webhook: 'webhook',
+} as const
+
+export type SubscriptionsSummaryQuotaRetrieve200 = {
+ active_count: number
+ /** @nullable */
+ limit: number | null
+ at_limit: boolean
+}
diff --git a/products/subscriptions/frontend/generated/api.ts b/products/subscriptions/frontend/generated/api.ts
new file mode 100644
index 000000000000..ed7db56587ad
--- /dev/null
+++ b/products/subscriptions/frontend/generated/api.ts
@@ -0,0 +1,234 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ PaginatedSubscriptionDeliveryListApi,
+ PaginatedSubscriptionListApi,
+ PatchedSubscriptionApi,
+ SubscriptionApi,
+ SubscriptionDeliveryApi,
+ SubscriptionsDeliveriesListParams,
+ SubscriptionsListParams,
+ SubscriptionsSummaryQuotaRetrieve200,
+} from './api.schemas'
+
+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
+
+type WritableKeys<T> = {
+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
+}[keyof T]
+
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
+
+type Writable<T> = Pick<T, WritableKeys<T>>
+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
+ ? {
+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
+ }
+ : DistributeReadOnlyOverUnions<T>
+
+export const getSubscriptionsDeliveriesListUrl = (
+ projectId: string,
+ subscriptionId: number,
+ params?: SubscriptionsDeliveriesListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/environments/${projectId}/subscriptions/${subscriptionId}/deliveries/?${stringifiedParams}`
+ : `/api/environments/${projectId}/subscriptions/${subscriptionId}/deliveries/`
+}
+
+/**
+ * Paginated delivery history for a subscription. Requires premium subscriptions.
+ * @summary List subscription deliveries
+ */
+export const subscriptionsDeliveriesList = async (
+ projectId: string,
+ subscriptionId: number,
+ params?: SubscriptionsDeliveriesListParams,
+ options?: RequestInit
+): Promise<PaginatedSubscriptionDeliveryListApi> => {
+ return apiMutator<PaginatedSubscriptionDeliveryListApi>(
+ getSubscriptionsDeliveriesListUrl(projectId, subscriptionId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getSubscriptionsDeliveriesRetrieveUrl = (projectId: string, subscriptionId: number, id: string) => {
+ return `/api/environments/${projectId}/subscriptions/${subscriptionId}/deliveries/${id}/`
+}
+
+/**
+ * Fetch one delivery row by id.
+ * @summary Retrieve subscription delivery
+ */
+export const subscriptionsDeliveriesRetrieve = async (
+ projectId: string,
+ subscriptionId: number,
+ id: string,
+ options?: RequestInit
+): Promise<SubscriptionDeliveryApi> => {
+ return apiMutator<SubscriptionDeliveryApi>(getSubscriptionsDeliveriesRetrieveUrl(projectId, subscriptionId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSubscriptionsListUrl = (projectId: string, params?: SubscriptionsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/subscriptions/?${stringifiedParams}`
+ : `/api/projects/${projectId}/subscriptions/`
+}
+
+export const subscriptionsList = async (
+ projectId: string,
+ params?: SubscriptionsListParams,
+ options?: RequestInit
+): Promise<PaginatedSubscriptionListApi> => {
+ return apiMutator<PaginatedSubscriptionListApi>(getSubscriptionsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSubscriptionsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/subscriptions/`
+}
+
+export const subscriptionsCreate = async (
+ projectId: string,
+ subscriptionApi: NonReadonly<SubscriptionApi>,
+ options?: RequestInit
+): Promise<SubscriptionApi> => {
+ return apiMutator<SubscriptionApi>(getSubscriptionsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(subscriptionApi),
+ })
+}
+
+export const getSubscriptionsRetrieveUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/subscriptions/${id}/`
+}
+
+export const subscriptionsRetrieve = async (
+ projectId: string,
+ id: number,
+ options?: RequestInit
+): Promise<SubscriptionApi> => {
+ return apiMutator<SubscriptionApi>(getSubscriptionsRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getSubscriptionsUpdateUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/subscriptions/${id}/`
+}
+
+export const subscriptionsUpdate = async (
+ projectId: string,
+ id: number,
+ subscriptionApi: NonReadonly<SubscriptionApi>,
+ options?: RequestInit
+): Promise<SubscriptionApi> => {
+ return apiMutator<SubscriptionApi>(getSubscriptionsUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(subscriptionApi),
+ })
+}
+
+export const getSubscriptionsPartialUpdateUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/subscriptions/${id}/`
+}
+
+export const subscriptionsPartialUpdate = async (
+ projectId: string,
+ id: number,
+ patchedSubscriptionApi?: NonReadonly<PatchedSubscriptionApi>,
+ options?: RequestInit
+): Promise<SubscriptionApi> => {
+ return apiMutator<SubscriptionApi>(getSubscriptionsPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedSubscriptionApi),
+ })
+}
+
+export const getSubscriptionsDestroyUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/subscriptions/${id}/`
+}
+
+/**
+ * Hard delete of this model is not allowed. Use a patch API call to set "deleted" to true
+ */
+export const subscriptionsDestroy = async (projectId: string, id: number, options?: RequestInit): Promise<unknown> => {
+ return apiMutator<unknown>(getSubscriptionsDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getSubscriptionsTestDeliveryCreateUrl = (projectId: string, id: number) => {
+ return `/api/projects/${projectId}/subscriptions/${id}/test-delivery/`
+}
+
+export const subscriptionsTestDeliveryCreate = async (
+ projectId: string,
+ id: number,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getSubscriptionsTestDeliveryCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
+export const getSubscriptionsSummaryQuotaRetrieveUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/subscriptions/summary_quota/`
+}
+
+export const subscriptionsSummaryQuotaRetrieve = async (
+ projectId: string,
+ options?: RequestInit
+): Promise<SubscriptionsSummaryQuotaRetrieve200> => {
+ return apiMutator<SubscriptionsSummaryQuotaRetrieve200>(getSubscriptionsSummaryQuotaRetrieveUrl(projectId), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/subscriptions/frontend/generated/api.zod.ts b/products/subscriptions/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..4295f66aac65
--- /dev/null
+++ b/products/subscriptions/frontend/generated/api.zod.ts
@@ -0,0 +1,353 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+export const subscriptionsCreateBodyIntervalMax = 2147483647
+
+export const subscriptionsCreateBodyBysetposMin = -2147483648
+export const subscriptionsCreateBodyBysetposMax = 2147483647
+
+export const subscriptionsCreateBodyCountMin = -2147483648
+export const subscriptionsCreateBodyCountMax = 2147483647
+
+export const subscriptionsCreateBodyTitleMax = 100
+
+export const subscriptionsCreateBodySummaryPromptGuideMax = 500
+
+export const SubscriptionsCreateBody = /* @__PURE__ */ zod
+ .object({
+ dashboard: zod
+ .number()
+ .nullish()
+ .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
+ insight: zod
+ .number()
+ .nullish()
+ .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
+ dashboard_export_insights: zod
+ .array(zod.number())
+ .optional()
+ .describe(
+ 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
+ ),
+ prompt: zod
+ .string()
+ .nullish()
+ .describe(
+ "Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."
+ ),
+ target_type: zod
+ .enum(['email', 'slack', 'webhook'])
+ .describe('\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook')
+ .describe(
+ 'Delivery channel: email, slack, or webhook.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook'
+ ),
+ target_value: zod
+ .string()
+ .describe(
+ 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or full URL for webhook.'
+ ),
+ frequency: zod
+ .enum(['daily', 'weekly', 'monthly', 'yearly'])
+ .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')
+ .describe(
+ 'How often to deliver: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'
+ ),
+ interval: zod
+ .number()
+ .min(1)
+ .max(subscriptionsCreateBodyIntervalMax)
+ .describe(
+ 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
+ ),
+ byweekday: zod
+ .array(
+ zod
+ .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
+ .describe(
+ '\* `monday` - Monday\n\* `tuesday` - Tuesday\n\* `wednesday` - Wednesday\n\* `thursday` - Thursday\n\* `friday` - Friday\n\* `saturday` - Saturday\n\* `sunday` - Sunday'
+ )
+ )
+ .nullish()
+ .describe(
+ 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ ),
+ bysetpos: zod
+ .number()
+ .min(subscriptionsCreateBodyBysetposMin)
+ .max(subscriptionsCreateBodyBysetposMax)
+ .nullish()
+ .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
+ count: zod
+ .number()
+ .min(subscriptionsCreateBodyCountMin)
+ .max(subscriptionsCreateBodyCountMax)
+ .nullish()
+ .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
+ start_date: zod.iso.datetime({ offset: true }).describe('When to start delivering (ISO 8601 datetime).'),
+ until_date: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
+ deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
+ ),
+ title: zod
+ .string()
+ .max(subscriptionsCreateBodyTitleMax)
+ .nullish()
+ .describe('Human-readable name for this subscription.'),
+ integration_id: zod
+ .number()
+ .nullish()
+ .describe('ID of a connected Slack integration. Required when target_type is slack.'),
+ invite_message: zod
+ .string()
+ .nullish()
+ .describe('Optional message included in the invitation email when adding new recipients.'),
+ summary_enabled: zod.boolean().optional(),
+ summary_prompt_guide: zod.string().max(subscriptionsCreateBodySummaryPromptGuideMax).optional(),
+ })
+ .describe('Standard Subscription serializer.')
+
+export const subscriptionsUpdateBodyIntervalMax = 2147483647
+
+export const subscriptionsUpdateBodyBysetposMin = -2147483648
+export const subscriptionsUpdateBodyBysetposMax = 2147483647
+
+export const subscriptionsUpdateBodyCountMin = -2147483648
+export const subscriptionsUpdateBodyCountMax = 2147483647
+
+export const subscriptionsUpdateBodyTitleMax = 100
+
+export const subscriptionsUpdateBodySummaryPromptGuideMax = 500
+
+export const SubscriptionsUpdateBody = /* @__PURE__ */ zod
+ .object({
+ dashboard: zod
+ .number()
+ .nullish()
+ .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
+ insight: zod
+ .number()
+ .nullish()
+ .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
+ dashboard_export_insights: zod
+ .array(zod.number())
+ .optional()
+ .describe(
+ 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
+ ),
+ prompt: zod
+ .string()
+ .nullish()
+ .describe(
+ "Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."
+ ),
+ target_type: zod
+ .enum(['email', 'slack', 'webhook'])
+ .describe('\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook')
+ .describe(
+ 'Delivery channel: email, slack, or webhook.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook'
+ ),
+ target_value: zod
+ .string()
+ .describe(
+ 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or full URL for webhook.'
+ ),
+ frequency: zod
+ .enum(['daily', 'weekly', 'monthly', 'yearly'])
+ .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')
+ .describe(
+ 'How often to deliver: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'
+ ),
+ interval: zod
+ .number()
+ .min(1)
+ .max(subscriptionsUpdateBodyIntervalMax)
+ .describe(
+ 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
+ ),
+ byweekday: zod
+ .array(
+ zod
+ .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
+ .describe(
+ '\* `monday` - Monday\n\* `tuesday` - Tuesday\n\* `wednesday` - Wednesday\n\* `thursday` - Thursday\n\* `friday` - Friday\n\* `saturday` - Saturday\n\* `sunday` - Sunday'
+ )
+ )
+ .nullish()
+ .describe(
+ 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ ),
+ bysetpos: zod
+ .number()
+ .min(subscriptionsUpdateBodyBysetposMin)
+ .max(subscriptionsUpdateBodyBysetposMax)
+ .nullish()
+ .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
+ count: zod
+ .number()
+ .min(subscriptionsUpdateBodyCountMin)
+ .max(subscriptionsUpdateBodyCountMax)
+ .nullish()
+ .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
+ start_date: zod.iso.datetime({ offset: true }).describe('When to start delivering (ISO 8601 datetime).'),
+ until_date: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
+ deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
+ ),
+ title: zod
+ .string()
+ .max(subscriptionsUpdateBodyTitleMax)
+ .nullish()
+ .describe('Human-readable name for this subscription.'),
+ integration_id: zod
+ .number()
+ .nullish()
+ .describe('ID of a connected Slack integration. Required when target_type is slack.'),
+ invite_message: zod
+ .string()
+ .nullish()
+ .describe('Optional message included in the invitation email when adding new recipients.'),
+ summary_enabled: zod.boolean().optional(),
+ summary_prompt_guide: zod.string().max(subscriptionsUpdateBodySummaryPromptGuideMax).optional(),
+ })
+ .describe('Standard Subscription serializer.')
+
+export const subscriptionsPartialUpdateBodyIntervalMax = 2147483647
+
+export const subscriptionsPartialUpdateBodyBysetposMin = -2147483648
+export const subscriptionsPartialUpdateBodyBysetposMax = 2147483647
+
+export const subscriptionsPartialUpdateBodyCountMin = -2147483648
+export const subscriptionsPartialUpdateBodyCountMax = 2147483647
+
+export const subscriptionsPartialUpdateBodyTitleMax = 100
+
+export const subscriptionsPartialUpdateBodySummaryPromptGuideMax = 500
+
+export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ dashboard: zod
+ .number()
+ .nullish()
+ .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
+ insight: zod
+ .number()
+ .nullish()
+ .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
+ dashboard_export_insights: zod
+ .array(zod.number())
+ .optional()
+ .describe(
+ 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
+ ),
+ prompt: zod
+ .string()
+ .nullish()
+ .describe(
+ "Free-text prompt that drives the AI-generated report. Required when resource_type is 'ai_prompt'. Max 4000 characters."
+ ),
+ target_type: zod
+ .enum(['email', 'slack', 'webhook'])
+ .describe('\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook')
+ .optional()
+ .describe(
+ 'Delivery channel: email, slack, or webhook.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `webhook` - Webhook'
+ ),
+ target_value: zod
+ .string()
+ .optional()
+ .describe(
+ 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or full URL for webhook.'
+ ),
+ frequency: zod
+ .enum(['daily', 'weekly', 'monthly', 'yearly'])
+ .describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')
+ .optional()
+ .describe(
+ 'How often to deliver: daily, weekly, monthly, or yearly.\n\n\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly'
+ ),
+ interval: zod
+ .number()
+ .min(1)
+ .max(subscriptionsPartialUpdateBodyIntervalMax)
+ .optional()
+ .describe(
+ 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
+ ),
+ byweekday: zod
+ .array(
+ zod
+ .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
+ .describe(
+ '\* `monday` - Monday\n\* `tuesday` - Tuesday\n\* `wednesday` - Wednesday\n\* `thursday` - Thursday\n\* `friday` - Friday\n\* `saturday` - Saturday\n\* `sunday` - Sunday'
+ )
+ )
+ .nullish()
+ .describe(
+ 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ ),
+ bysetpos: zod
+ .number()
+ .min(subscriptionsPartialUpdateBodyBysetposMin)
+ .max(subscriptionsPartialUpdateBodyBysetposMax)
+ .nullish()
+ .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
+ count: zod
+ .number()
+ .min(subscriptionsPartialUpdateBodyCountMin)
+ .max(subscriptionsPartialUpdateBodyCountMax)
+ .nullish()
+ .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
+ start_date: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('When to start delivering (ISO 8601 datetime).'),
+ until_date: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
+ deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
+ ),
+ title: zod
+ .string()
+ .max(subscriptionsPartialUpdateBodyTitleMax)
+ .nullish()
+ .describe('Human-readable name for this subscription.'),
+ integration_id: zod
+ .number()
+ .nullish()
+ .describe('ID of a connected Slack integration. Required when target_type is slack.'),
+ invite_message: zod
+ .string()
+ .nullish()
+ .describe('Optional message included in the invitation email when adding new recipients.'),
+ summary_enabled: zod.boolean().optional(),
+ summary_prompt_guide: zod.string().max(subscriptionsPartialUpdateBodySummaryPromptGuideMax).optional(),
+ })
+ .describe('Standard Subscription serializer.')
diff --git a/products/subscriptions/mcp/tools.yaml b/products/subscriptions/mcp/tools.yaml
new file mode 100644
index 000000000000..04efe1c517b0
--- /dev/null
+++ b/products/subscriptions/mcp/tools.yaml
@@ -0,0 +1,154 @@
+# MCP tool definition — tool entries are scaffolded from the OpenAPI schema.
+# The tool list and operation IDs are kept in sync automatically:
+# pnpm --filter=@posthog/mcp run scaffold-yaml -- --sync-all
+#
+# To enable a tool, set enabled: true and add required scopes + annotations.
+# All other fields (title, description, enrich_url, etc.) are yours to configure.
+category: Subscriptions
+feature: subscriptions
+url_prefix: /subscriptions
+ui_apps: {}
+tools:
+ subscriptions-create:
+ operation: subscriptions_create
+ enabled: true
+ scopes:
+ - subscription:write
+ annotations:
+ readOnly: false
+ destructive: false
+ idempotent: false
+ title: Create subscription
+ description: >
+ Create a new subscription to receive scheduled deliveries of an insight or dashboard. Requires either an
+ insight ID or dashboard ID. Set target_type to email, slack, or webhook and target_value to the
+ recipient(s). For email: comma-separated addresses. For slack: requires an integration_id for a connected
+ Slack workspace plus a channel name in target_value. For webhook: a URL. Set frequency (daily, weekly,
+ monthly, yearly) and interval (required, minimum 1 — use 1 for no multiplier; e.g. 2 with weekly = every 2
+ weeks), plus optional byweekday, start_date, and until_date. Dashboard subscriptions also require
+ dashboard_export_insights (list of insight IDs from that dashboard, max 6).
+ exclude_params:
+ - created_by
+ - next_delivery_date
+ - summary
+ - insight_short_id
+ - resource_name
+ - prompt
+ subscriptions-deliveries-list:
+ operation: subscriptions_deliveries_list
+ enabled: true
+ scopes:
+ - subscription:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List subscription deliveries
+ description: >
+ List delivery history for a subscription — one row per send attempt. Each entry includes status (starting,
+ completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at,
+ finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated
+ newest first. content_snapshot, recipient_results, and error are excluded to match what the web UI exposes
+ and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.
+ response:
+ exclude:
+ - content_snapshot
+ - recipient_results
+ - error
+ subscriptions-deliveries-retrieve:
+ operation: subscriptions_deliveries_retrieve
+ enabled: true
+ scopes:
+ - subscription:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get subscription delivery
+ description: >
+ Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value,
+ timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozen
+ dashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state.
+ recipient_results and error are also excluded to match what the web UI exposes and to avoid leaking
+ recipient identifiers or upstream response bodies that may contain tokens / PII.
+ response:
+ exclude:
+ - content_snapshot
+ - recipient_results
+ - error
+ subscriptions-destroy:
+ operation: subscriptions_destroy
+ enabled: false
+ subscriptions-list:
+ operation: subscriptions_list
+ enabled: true
+ scopes:
+ - subscription:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ list: true
+ title: List subscriptions
+ description: >
+ List subscriptions for the project. Returns scheduled email, Slack, or webhook deliveries of insight or
+ dashboard snapshots. Each subscription includes its schedule (frequency, interval, byweekday),
+ next_delivery_date, and a human-readable summary.
+ subscriptions-partial-update:
+ operation: subscriptions_partial_update
+ enabled: true
+ scopes:
+ - subscription:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: true
+ title: Update subscription
+ description: >
+ Update an existing subscription by ID. Can change target_type, target_value, frequency, interval, byweekday,
+ start_date, until_date, title, or deleted status. Set deleted to true to deactivate a subscription
+ (subscriptions are soft-deleted). Changing target_value triggers notifications to new recipients.
+ exclude_params:
+ - created_by
+ - next_delivery_date
+ - summary
+ - insight_short_id
+ - resource_name
+ - prompt
+ subscriptions-retrieve:
+ operation: subscriptions_retrieve
+ enabled: true
+ scopes:
+ - subscription:read
+ annotations:
+ readOnly: true
+ destructive: false
+ idempotent: true
+ title: Get subscription
+ description: >
+ Get a specific subscription by ID. Returns the full subscription configuration including target type and
+ value, schedule details, next delivery date, and associated insight or dashboard.
+ subscriptions-summary-quota-retrieve:
+ operation: subscriptions_summary_quota_retrieve
+ enabled: false
+ subscriptions-test-delivery-create:
+ operation: subscriptions_test_delivery_create
+ enabled: true
+ scopes:
+ - subscription:write
+ annotations:
+ readOnly: false
+ destructive: true
+ idempotent: false
+ title: Send test delivery
+ description: >
+ Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or webhook).
+ Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery
+ record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202
+ Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or
+ subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription
+ is already in flight.
+ subscriptions-update:
+ operation: subscriptions_update
+ enabled: false
diff --git a/products/subscriptions/package.json b/products/subscriptions/package.json
new file mode 100644
index 000000000000..468efedb3025
--- /dev/null
+++ b/products/subscriptions/package.json
@@ -0,0 +1,4 @@
+{
+ "name": "@posthog/products-subscriptions",
+ "scripts": {}
+}
diff --git a/products/subscriptions/product.yaml b/products/subscriptions/product.yaml
new file mode 100644
index 000000000000..5b12532bee52
--- /dev/null
+++ b/products/subscriptions/product.yaml
@@ -0,0 +1,3 @@
+name: Subscriptions
+owners:
+ - team-product-analytics
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 8575fd287dcb..adc354fa19b9 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -526,147 +526,6 @@ tools:
session-recordings-sharing-refresh-create:
operation: session_recordings_sharing_refresh_create
enabled: false
- subscriptions-create:
- operation: subscriptions_create
- enabled: true
- scopes:
- - subscription:write
- annotations:
- readOnly: false
- destructive: false
- idempotent: false
- title: Create subscription
- description: >
- Create a new subscription to receive scheduled deliveries of an insight or dashboard. Requires either an
- insight ID or dashboard ID. Set target_type to email, slack, or webhook and target_value to the
- recipient(s). For email: comma-separated addresses. For slack: requires an integration_id for a connected
- Slack workspace plus a channel name in target_value. For webhook: a URL. Set frequency (daily, weekly,
- monthly, yearly) and interval (the multiplier, e.g. 2 with weekly means every 2 weeks; required, minimum 1 —
- use 1 for no multiplier). byweekday, start_date, and until_date are optional. Dashboard subscriptions also
- require dashboard_export_insights (list of insight IDs from that dashboard, max 6).
- exclude_params:
- - created_by
- - next_delivery_date
- - summary
- - insight_short_id
- - resource_name
- subscriptions-deliveries-list:
- operation: subscriptions_deliveries_list
- enabled: true
- scopes:
- - subscription:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- list: true
- title: List subscription deliveries
- description: >
- List delivery history for a subscription — one row per send attempt. Each entry includes status (starting,
- completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at,
- finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated
- newest first. content_snapshot, recipient_results, and error are excluded to match what the web UI exposes
- and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.
- response:
- exclude:
- - content_snapshot
- - recipient_results
- - error
- subscriptions-deliveries-retrieve:
- operation: subscriptions_deliveries_retrieve
- enabled: true
- scopes:
- - subscription:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- title: Get subscription delivery
- description: >
- Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value,
- timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozen
- dashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state.
- recipient_results and error are also excluded to match what the web UI exposes and to avoid leaking
- recipient identifiers or upstream response bodies that may contain tokens / PII.
- response:
- exclude:
- - content_snapshot
- - recipient_results
- - error
- subscriptions-destroy:
- operation: subscriptions_destroy
- enabled: false
- subscriptions-list:
- operation: subscriptions_list
- enabled: true
- scopes:
- - subscription:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- list: true
- title: List subscriptions
- description: >
- List subscriptions for the project. Returns scheduled email, Slack, or webhook deliveries of insight or
- dashboard snapshots. Each subscription includes its schedule (frequency, interval, byweekday),
- next_delivery_date, and a human-readable summary.
- subscriptions-partial-update:
- operation: subscriptions_partial_update
- enabled: true
- scopes:
- - subscription:write
- annotations:
- readOnly: false
- destructive: true
- idempotent: true
- title: Update subscription
- description: >
- Update an existing subscription by ID. Can change target_type, target_value, frequency, interval, byweekday,
- start_date, until_date, title, or deleted status. Set deleted to true to deactivate a subscription
- (subscriptions are soft-deleted). Changing target_value triggers notifications to new recipients.
- exclude_params:
- - created_by
- - next_delivery_date
- - summary
- - insight_short_id
- - resource_name
- subscriptions-retrieve:
- operation: subscriptions_retrieve
- enabled: true
- scopes:
- - subscription:read
- annotations:
- readOnly: true
- destructive: false
- idempotent: true
- title: Get subscription
- description: >
- Get a specific subscription by ID. Returns the full subscription configuration including target type and
- value, schedule details, next delivery date, and associated insight or dashboard.
- subscriptions-summary-quota-retrieve:
- operation: subscriptions_summary_quota_retrieve
- enabled: false
- subscriptions-test-delivery-create:
- operation: subscriptions_test_delivery_create
- enabled: true
- scopes:
- - subscription:write
- annotations:
- readOnly: false
- destructive: true
- idempotent: false
- title: Send test delivery
- description: >
- Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or webhook).
- Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery
- record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202
- Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or
- subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription
- is already in flight.
- subscriptions-update:
- operation: subscriptions_update
- enabled: false
user-get:
operation: users_retrieve
enabled: true
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index fc8f9d343000..a24ca19035b5 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -5146,9 +5146,9 @@
}
},
"subscriptions-create": {
- "description": "Create a new subscription to receive scheduled deliveries of an insight or dashboard. Requires either an insight ID or dashboard ID. Set target_type to email, slack, or webhook and target_value to the recipient(s). For email: comma-separated addresses. For slack: requires an integration_id for a connected Slack workspace plus a channel name in target_value. For webhook: a URL. Set frequency (daily, weekly, monthly, yearly) and interval (the multiplier, e.g. 2 with weekly means every 2 weeks; required, minimum 1 — use 1 for no multiplier). byweekday, start_date, and until_date are optional. Dashboard subscriptions also require dashboard_export_insights (list of insight IDs from that dashboard, max 6).",
- "category": "Core",
- "feature": "core",
+ "description": "Create a new subscription to receive scheduled deliveries of an insight or dashboard. Requires either an insight ID or dashboard ID. Set target_type to email, slack, or webhook and target_value to the recipient(s). For email: comma-separated addresses. For slack: requires an integration_id for a connected Slack workspace plus a channel name in target_value. For webhook: a URL. Set frequency (daily, weekly, monthly, yearly) and interval (required, minimum 1 — use 1 for no multiplier; e.g. 2 with weekly = every 2 weeks), plus optional byweekday, start_date, and until_date. Dashboard subscriptions also require dashboard_export_insights (list of insight IDs from that dashboard, max 6).",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Create subscription",
"title": "Create subscription",
"required_scopes": ["subscription:write"],
@@ -5161,8 +5161,8 @@
},
"subscriptions-deliveries-list": {
"description": "List delivery history for a subscription — one row per send attempt. Each entry includes status (starting, completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at, finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated newest first. content_snapshot, recipient_results, and error are excluded to match what the web UI exposes and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "List subscription deliveries",
"title": "List subscription deliveries",
"required_scopes": ["subscription:read"],
@@ -5175,8 +5175,8 @@
},
"subscriptions-deliveries-retrieve": {
"description": "Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value, timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozen dashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state. recipient_results and error are also excluded to match what the web UI exposes and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Get subscription delivery",
"title": "Get subscription delivery",
"required_scopes": ["subscription:read"],
@@ -5189,8 +5189,8 @@
},
"subscriptions-list": {
"description": "List subscriptions for the project. Returns scheduled email, Slack, or webhook deliveries of insight or dashboard snapshots. Each subscription includes its schedule (frequency, interval, byweekday), next_delivery_date, and a human-readable summary.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "List subscriptions",
"title": "List subscriptions",
"required_scopes": ["subscription:read"],
@@ -5203,8 +5203,8 @@
},
"subscriptions-partial-update": {
"description": "Update an existing subscription by ID. Can change target_type, target_value, frequency, interval, byweekday, start_date, until_date, title, or deleted status. Set deleted to true to deactivate a subscription (subscriptions are soft-deleted). Changing target_value triggers notifications to new recipients.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Update subscription",
"title": "Update subscription",
"required_scopes": ["subscription:write"],
@@ -5217,8 +5217,8 @@
},
"subscriptions-retrieve": {
"description": "Get a specific subscription by ID. Returns the full subscription configuration including target type and value, schedule details, next delivery date, and associated insight or dashboard.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Get subscription",
"title": "Get subscription",
"required_scopes": ["subscription:read"],
@@ -5231,8 +5231,8 @@
},
"subscriptions-test-delivery-create": {
"description": "Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or webhook). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription is already in flight.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Send test delivery",
"title": "Send test delivery",
"required_scopes": ["subscription:write"],
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 77ba9b68a671..51d0f17f4d47 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -5473,9 +5473,9 @@
}
},
"subscriptions-create": {
- "description": "Create a new subscription to receive scheduled deliveries of an insight or dashboard. Requires either an insight ID or dashboard ID. Set target_type to email, slack, or webhook and target_value to the recipient(s). For email: comma-separated addresses. For slack: requires an integration_id for a connected Slack workspace plus a channel name in target_value. For webhook: a URL. Set frequency (daily, weekly, monthly, yearly) and interval (the multiplier, e.g. 2 with weekly means every 2 weeks; required, minimum 1 — use 1 for no multiplier). byweekday, start_date, and until_date are optional. Dashboard subscriptions also require dashboard_export_insights (list of insight IDs from that dashboard, max 6).",
- "category": "Core",
- "feature": "core",
+ "description": "Create a new subscription to receive scheduled deliveries of an insight or dashboard. Requires either an insight ID or dashboard ID. Set target_type to email, slack, or webhook and target_value to the recipient(s). For email: comma-separated addresses. For slack: requires an integration_id for a connected Slack workspace plus a channel name in target_value. For webhook: a URL. Set frequency (daily, weekly, monthly, yearly) and interval (required, minimum 1 — use 1 for no multiplier; e.g. 2 with weekly = every 2 weeks), plus optional byweekday, start_date, and until_date. Dashboard subscriptions also require dashboard_export_insights (list of insight IDs from that dashboard, max 6).",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Create subscription",
"title": "Create subscription",
"required_scopes": ["subscription:write"],
@@ -5488,8 +5488,8 @@
},
"subscriptions-deliveries-list": {
"description": "List delivery history for a subscription — one row per send attempt. Each entry includes status (starting, completed, failed, skipped), trigger_type (scheduled, manual, target_change), and timestamps (created_at, finished_at). Filter with status=failed to quickly surface failed deliveries. Results are cursor-paginated newest first. content_snapshot, recipient_results, and error are excluded to match what the web UI exposes and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "List subscription deliveries",
"title": "List subscription deliveries",
"required_scopes": ["subscription:read"],
@@ -5502,8 +5502,8 @@
},
"subscriptions-deliveries-retrieve": {
"description": "Fetch a single subscription delivery attempt by id. Returns status, trigger_type, target_type, target_value, timestamps, workflow/idempotency metadata, and exported_asset_ids. content_snapshot (the frozen dashboard/insight state at send time) is not returned — use the insight/dashboard tools for current state. recipient_results and error are also excluded to match what the web UI exposes and to avoid leaking recipient identifiers or upstream response bodies that may contain tokens / PII.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Get subscription delivery",
"title": "Get subscription delivery",
"required_scopes": ["subscription:read"],
@@ -5516,8 +5516,8 @@
},
"subscriptions-list": {
"description": "List subscriptions for the project. Returns scheduled email, Slack, or webhook deliveries of insight or dashboard snapshots. Each subscription includes its schedule (frequency, interval, byweekday), next_delivery_date, and a human-readable summary.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "List subscriptions",
"title": "List subscriptions",
"required_scopes": ["subscription:read"],
@@ -5530,8 +5530,8 @@
},
"subscriptions-partial-update": {
"description": "Update an existing subscription by ID. Can change target_type, target_value, frequency, interval, byweekday, start_date, until_date, title, or deleted status. Set deleted to true to deactivate a subscription (subscriptions are soft-deleted). Changing target_value triggers notifications to new recipients.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Update subscription",
"title": "Update subscription",
"required_scopes": ["subscription:write"],
@@ -5544,8 +5544,8 @@
},
"subscriptions-retrieve": {
"description": "Get a specific subscription by ID. Returns the full subscription configuration including target type and value, schedule details, next delivery date, and associated insight or dashboard.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Get subscription",
"title": "Get subscription",
"required_scopes": ["subscription:read"],
@@ -5558,8 +5558,8 @@
},
"subscriptions-test-delivery-create": {
"description": "Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or webhook). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription is already in flight.",
- "category": "Core",
- "feature": "core",
+ "category": "Subscriptions",
+ "feature": "subscriptions",
"summary": "Send test delivery",
"title": "Send test delivery",
"required_scopes": ["subscription:write"],
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 848876c7ffc6..4d71c45b1bc1 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -26106,6 +26106,20 @@ export namespace Schemas {
results: SubscriptionDelivery[];
}
+ /**
+ * * `insight` - Insight
+ * `dashboard` - Dashboard
+ * `ai_prompt` - AI prompt
+ */
+ export type ResourceTypeEnum = typeof ResourceTypeEnum[keyof typeof ResourceTypeEnum];
+
+
+ export const ResourceTypeEnum = {
+ Insight: 'insight',
+ Dashboard: 'dashboard',
+ AiPrompt: 'ai_prompt',
+ } as const;
+
/**
* * `email` - Email
* `slack` - Slack
@@ -26163,6 +26177,12 @@ export namespace Schemas {
*/
export interface Subscription {
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: ResourceTypeEnum;
/**
* Dashboard ID to subscribe to (mutually exclusive with insight on create).
* @nullable
@@ -26179,6 +26199,11 @@ export namespace Schemas {
readonly resource_name: string | null;
/** List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6. */
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;
/** Delivery channel: email, slack, or webhook.
* `email` - Email
@@ -32132,6 +32157,12 @@ export namespace Schemas {
*/
export interface PatchedSubscription {
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?: ResourceTypeEnum;
/**
* Dashboard ID to subscribe to (mutually exclusive with insight on create).
* @nullable
@@ -32148,6 +32179,11 @@ export namespace Schemas {
readonly resource_name?: string | null;
/** List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6. */
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;
/** Delivery channel: email, slack, or webhook.
* `email` - Email
@@ -45459,7 +45495,7 @@ export namespace Schemas {
*/
ordering?: string;
/**
- * Filter by subscription resource: insight vs dashboard export.
+ * Filter by subscription resource: insight, dashboard export, or AI report.
*/
resource_type?: EnvironmentsSubscriptionsListResourceType;
/**
@@ -45476,6 +45512,7 @@ export namespace Schemas {
export const EnvironmentsSubscriptionsListResourceType = {
+ AiPrompt: 'ai_prompt',
Dashboard: 'dashboard',
Insight: 'insight',
} as const;
@@ -51636,7 +51673,7 @@ export namespace Schemas {
*/
ordering?: string;
/**
- * Filter by subscription resource: insight vs dashboard export.
+ * Filter by subscription resource: insight, dashboard export, or AI report.
*/
resource_type?: SubscriptionsListResourceType;
/**
@@ -51653,6 +51690,7 @@ export namespace Schemas {
export const SubscriptionsListResourceType = {
+ AiPrompt: 'ai_prompt',
Dashboard: 'dashboard',
Insight: 'insight',
} as const;
diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.ts
index 919dfcb10b40..ea386958b0ed 100644
--- a/services/mcp/src/generated/core/api.ts
+++ b/services/mcp/src/generated/core/api.ts
@@ -3,46 +3,11 @@
* MCP service uses these Zod schemas for generated tool handlers.
* To regenerate: hogli build:openapi
*
- * PostHog API - MCP 16 enabled ops
+ * PostHog API - MCP 9 enabled ops
* OpenAPI spec version: 1.0.0
*/
import * as zod from 'zod'
-/**
- * Paginated delivery history for a subscription. Requires premium subscriptions.
- * @summary List subscription deliveries
- */
-export const SubscriptionsDeliveriesListParams = /* @__PURE__ */ zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
- ),
- subscription_id: zod.number(),
-})
-
-export const SubscriptionsDeliveriesListQueryParams = /* @__PURE__ */ zod.object({
- cursor: zod.string().optional().describe('The pagination cursor value.'),
- status: zod
- .enum(['completed', 'failed', 'skipped', 'starting'])
- .optional()
- .describe('Return only deliveries in this run status (starting, completed, failed, or skipped).'),
-})
-
-/**
- * Fetch one delivery row by id.
- * @summary Retrieve subscription delivery
- */
-export const SubscriptionsDeliveriesRetrieveParams = /* @__PURE__ */ zod.object({
- id: zod.string().describe('A UUID string identifying this subscription delivery.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
- ),
- subscription_id: zod.number(),
-})
-
/**
* Retrieve a project and its settings.
*/
@@ -366,286 +331,6 @@ export const DesktopFileSystemInstructionsPartialUpdateBody = /* @__PURE__ */ zo
),
})
-export const SubscriptionsListParams = /* @__PURE__ */ zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
- ),
-})
-
-export const SubscriptionsListQueryParams = /* @__PURE__ */ zod.object({
- created_by: zod.string().optional().describe('Filter by creator user UUID.'),
- dashboard: zod.number().optional().describe('Filter by dashboard ID.'),
- insight: zod.number().optional().describe('Filter by insight ID.'),
- limit: zod.number().optional().describe('Number of results to return per page.'),
- offset: zod.number().optional().describe('The initial index from which to return the results.'),
- ordering: zod.string().optional().describe('Which field to use when ordering the results.'),
- resource_type: zod
- .enum(['dashboard', 'insight'])
- .optional()
- .describe('Filter by subscription resource: insight vs dashboard export.'),
- search: zod.string().optional().describe('A search term.'),
- target_type: zod
- .enum(['email', 'slack', 'webhook'])
- .optional()
- .describe('Filter by delivery channel (email, Slack, or webhook).'),
-})
-
-export const SubscriptionsCreateParams = /* @__PURE__ */ zod.object({
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
- ),
-})
-
-export const subscriptionsCreateBodyIntervalMax = 2147483647
-
-export const subscriptionsCreateBodyBysetposMin = -2147483648
-export const subscriptionsCreateBodyBysetposMax = 2147483647
-
-export const subscriptionsCreateBodyCountMin = -2147483648
-export const subscriptionsCreateBodyCountMax = 2147483647
-
-export const subscriptionsCreateBodyTitleMax = 100
-
-export const subscriptionsCreateBodySummaryPromptGuideMax = 500
-
-export const SubscriptionsCreateBody = /* @__PURE__ */ zod
- .object({
- dashboard: zod
- .number()
- .nullish()
- .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
- insight: zod
- .number()
- .nullish()
- .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
- dashboard_export_insights: zod
- .array(zod.number())
- .optional()
- .describe(
- 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
- ),
- target_type: zod
- .enum(['email', 'slack', 'webhook'])
- .describe('* `email` - Email\n* `slack` - Slack\n* `webhook` - Webhook')
- .describe(
- 'Delivery channel: email, slack, or webhook.\n\n* `email` - Email\n* `slack` - Slack\n* `webhook` - Webhook'
- ),
- target_value: zod
- .string()
- .describe(
- 'Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or full URL for webhook.'
- ),
- frequency: zod
- .enum(['daily', 'weekly', 'monthly', 'yearly'])
- .describe('* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly')
- .describe(
- 'How often to deliver: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly'
- ),
- interval: zod
- .number()
- .min(1)
- .max(subscriptionsCreateBodyIntervalMax)
- .describe(
- 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
- ),
- byweekday: zod
- .array(
- zod
- .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
- .describe(
- '* `monday` - Monday\n* `tuesday` - Tuesday\n* `wednesday` - Wednesday\n* `thursday` - Thursday\n* `friday` - Friday\n* `saturday` - Saturday\n* `sunday` - Sunday'
- )
- )
- .nullish()
- .describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
- ),
- bysetpos: zod
- .number()
- .min(subscriptionsCreateBodyBysetposMin)
- .max(subscriptionsCreateBodyBysetposMax)
- .nullish()
- .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
- count: zod
- .number()
- .min(subscriptionsCreateBodyCountMin)
- .max(subscriptionsCreateBodyCountMax)
- .nullish()
- .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
- start_date: zod.iso.datetime({ offset: true }).describe('When to start delivering (ISO 8601 datetime).'),
- until_date: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
- deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
- enabled: zod
- .boolean()
- .optional()
- .describe(
- 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
- ),
- title: zod
- .string()
- .max(subscriptionsCreateBodyTitleMax)
- .nullish()
- .describe('Human-readable name for this subscription.'),
- integration_id: zod
- .number()
- .nullish()
- .describe('ID of a connected Slack integration. Required when target_type is slack.'),
- invite_message: zod
- .string()
- .nullish()
- .describe('Optional message included in the invitation email when adding new recipients.'),
- summary_enabled: zod.boolean().optional(),
- summary_prompt_guide: zod.string().max(subscriptionsCreateBodySummaryPromptGuideMax).optional(),
- })
- .describe('Standard Subscription serializer.')
-
-export const SubscriptionsRetrieveParams = /* @__PURE__ */ zod.object({
- id: zod.number().describe('A unique integer value identifying this subscription.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
- ),
-})
-
-export const SubscriptionsPartialUpdateParams = /* @__PURE__ */ zod.object({
- id: zod.number().describe('A unique integer value identifying this subscription.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
- ),
-})
-
-export const subscriptionsPartialUpdateBodyIntervalMax = 2147483647
-
-export const subscriptionsPartialUpdateBodyBysetposMin = -2147483648
-export const subscriptionsPartialUpdateBodyBysetposMax = 2147483647
-
-export const subscriptionsPartialUpdateBodyCountMin = -2147483648
-export const subscriptionsPartialUpdateBodyCountMax = 2147483647
-
-export const subscriptionsPartialUpdateBodyTitleMax = 100
-
-export const subscriptionsPartialUpdateBodySummaryPromptGuideMax = 500
-
-export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod
- .object({
- dashboard: zod
- .number()
- .nullish()
- .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
- insight: zod
- .number()
- .nullish()
- .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
- dashboard_export_insights: zod
- .array(zod.number())
- .optional()
- .describe(
- 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
- ),
- target_type: zod
- .enum(['email', 'slack', 'webhook'])
- .describe('* `email` - Email\n* `slack` - Slack\n* `webhook` - Webhook')
- .optional()
- .describe(
- 'Delivery channel: email, slack, or webhook.\n\n* `email` - Email\n* `slack` - Slack\n* `webhook` - Webhook'
- ),
- target_value: zod
- .string()
- .optional()
- .describe(
- 'Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or full URL for webhook.'
- ),
- frequency: zod
- .enum(['daily', 'weekly', 'monthly', 'yearly'])
- .describe('* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly')
- .optional()
- .describe(
- 'How often to deliver: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly'
- ),
- interval: zod
- .number()
- .min(1)
- .max(subscriptionsPartialUpdateBodyIntervalMax)
- .optional()
- .describe(
- 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
- ),
- byweekday: zod
- .array(
- zod
- .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
- .describe(
- '* `monday` - Monday\n* `tuesday` - Tuesday\n* `wednesday` - Wednesday\n* `thursday` - Thursday\n* `friday` - Friday\n* `saturday` - Saturday\n* `sunday` - Sunday'
- )
- )
- .nullish()
- .describe(
- 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
- ),
- bysetpos: zod
- .number()
- .min(subscriptionsPartialUpdateBodyBysetposMin)
- .max(subscriptionsPartialUpdateBodyBysetposMax)
- .nullish()
- .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
- count: zod
- .number()
- .min(subscriptionsPartialUpdateBodyCountMin)
- .max(subscriptionsPartialUpdateBodyCountMax)
- .nullish()
- .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
- start_date: zod.iso
- .datetime({ offset: true })
- .optional()
- .describe('When to start delivering (ISO 8601 datetime).'),
- until_date: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
- deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
- enabled: zod
- .boolean()
- .optional()
- .describe(
- 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
- ),
- title: zod
- .string()
- .max(subscriptionsPartialUpdateBodyTitleMax)
- .nullish()
- .describe('Human-readable name for this subscription.'),
- integration_id: zod
- .number()
- .nullish()
- .describe('ID of a connected Slack integration. Required when target_type is slack.'),
- invite_message: zod
- .string()
- .nullish()
- .describe('Optional message included in the invitation email when adding new recipients.'),
- summary_enabled: zod.boolean().optional(),
- summary_prompt_guide: zod.string().max(subscriptionsPartialUpdateBodySummaryPromptGuideMax).optional(),
- })
- .describe('Standard Subscription serializer.')
-
-export const SubscriptionsTestDeliveryCreateParams = /* @__PURE__ */ zod.object({
- id: zod.number().describe('A unique integer value identifying this subscription.'),
- project_id: zod
- .string()
- .describe(
- "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
- ),
-})
-
/**
* Retrieve a user's profile and settings. Pass `@me` as the UUID to fetch the authenticated user; non-staff callers may only access their own account.
*/
diff --git a/services/mcp/src/generated/subscriptions/api.ts b/services/mcp/src/generated/subscriptions/api.ts
new file mode 100644
index 000000000000..3e15cdb823ac
--- /dev/null
+++ b/services/mcp/src/generated/subscriptions/api.ts
@@ -0,0 +1,324 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * MCP service uses these Zod schemas for generated tool handlers.
+ * To regenerate: hogli build:openapi
+ *
+ * PostHog API - MCP 7 enabled ops
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Paginated delivery history for a subscription. Requires premium subscriptions.
+ * @summary List subscription deliveries
+ */
+export const SubscriptionsDeliveriesListParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ subscription_id: zod.number(),
+})
+
+export const SubscriptionsDeliveriesListQueryParams = /* @__PURE__ */ zod.object({
+ cursor: zod.string().optional().describe('The pagination cursor value.'),
+ status: zod
+ .enum(['completed', 'failed', 'skipped', 'starting'])
+ .optional()
+ .describe('Return only deliveries in this run status (starting, completed, failed, or skipped).'),
+})
+
+/**
+ * Fetch one delivery row by id.
+ * @summary Retrieve subscription delivery
+ */
+export const SubscriptionsDeliveriesRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.string().describe('A UUID string identifying this subscription delivery.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+ subscription_id: zod.number(),
+})
+
+export const SubscriptionsListParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const SubscriptionsListQueryParams = /* @__PURE__ */ zod.object({
+ created_by: zod.string().optional().describe('Filter by creator user UUID.'),
+ dashboard: zod.number().optional().describe('Filter by dashboard ID.'),
+ insight: zod.number().optional().describe('Filter by insight ID.'),
+ limit: zod.number().optional().describe('Number of results to return per page.'),
+ offset: zod.number().optional().describe('The initial index from which to return the results.'),
+ ordering: zod.string().optional().describe('Which field to use when ordering the results.'),
+ resource_type: zod
+ .enum(['ai_prompt', 'dashboard', 'insight'])
+ .optional()
+ .describe('Filter by subscription resource: insight, dashboard export, or AI report.'),
+ search: zod.string().optional().describe('A search term.'),
+ target_type: zod
+ .enum(['email', 'slack', 'webhook'])
+ .optional()
+ .describe('Filter by delivery channel (email, Slack, or webhook).'),
+})
+
+export const SubscriptionsCreateParams = /* @__PURE__ */ zod.object({
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const subscriptionsCreateBodyIntervalMax = 2147483647
+
+export const subscriptionsCreateBodyBysetposMin = -2147483648
+export const subscriptionsCreateBodyBysetposMax = 2147483647
+
+export const subscriptionsCreateBodyCountMin = -2147483648
+export const subscriptionsCreateBodyCountMax = 2147483647
+
+export const subscriptionsCreateBodyTitleMax = 100
+
+export const subscriptionsCreateBodySummaryPromptGuideMax = 500
+
+export const SubscriptionsCreateBody = /* @__PURE__ */ zod
+ .object({
+ dashboard: zod
+ .number()
+ .nullish()
+ .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
+ insight: zod
+ .number()
+ .nullish()
+ .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
+ dashboard_export_insights: zod
+ .array(zod.number())
+ .optional()
+ .describe(
+ 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
+ ),
+ target_type: zod
+ .enum(['email', 'slack', 'webhook'])
+ .describe('* `email` - Email\n* `slack` - Slack\n* `webhook` - Webhook')
+ .describe(
+ 'Delivery channel: email, slack, or webhook.\n\n* `email` - Email\n* `slack` - Slack\n* `webhook` - Webhook'
+ ),
+ target_value: zod
+ .string()
+ .describe(
+ 'Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or full URL for webhook.'
+ ),
+ frequency: zod
+ .enum(['daily', 'weekly', 'monthly', 'yearly'])
+ .describe('* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly')
+ .describe(
+ 'How often to deliver: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly'
+ ),
+ interval: zod
+ .number()
+ .min(1)
+ .max(subscriptionsCreateBodyIntervalMax)
+ .describe(
+ 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
+ ),
+ byweekday: zod
+ .array(
+ zod
+ .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
+ .describe(
+ '* `monday` - Monday\n* `tuesday` - Tuesday\n* `wednesday` - Wednesday\n* `thursday` - Thursday\n* `friday` - Friday\n* `saturday` - Saturday\n* `sunday` - Sunday'
+ )
+ )
+ .nullish()
+ .describe(
+ 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ ),
+ bysetpos: zod
+ .number()
+ .min(subscriptionsCreateBodyBysetposMin)
+ .max(subscriptionsCreateBodyBysetposMax)
+ .nullish()
+ .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
+ count: zod
+ .number()
+ .min(subscriptionsCreateBodyCountMin)
+ .max(subscriptionsCreateBodyCountMax)
+ .nullish()
+ .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
+ start_date: zod.iso.datetime({ offset: true }).describe('When to start delivering (ISO 8601 datetime).'),
+ until_date: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
+ deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
+ ),
+ title: zod
+ .string()
+ .max(subscriptionsCreateBodyTitleMax)
+ .nullish()
+ .describe('Human-readable name for this subscription.'),
+ integration_id: zod
+ .number()
+ .nullish()
+ .describe('ID of a connected Slack integration. Required when target_type is slack.'),
+ invite_message: zod
+ .string()
+ .nullish()
+ .describe('Optional message included in the invitation email when adding new recipients.'),
+ summary_enabled: zod.boolean().optional(),
+ summary_prompt_guide: zod.string().max(subscriptionsCreateBodySummaryPromptGuideMax).optional(),
+ })
+ .describe('Standard Subscription serializer.')
+
+export const SubscriptionsRetrieveParams = /* @__PURE__ */ zod.object({
+ id: zod.number().describe('A unique integer value identifying this subscription.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const SubscriptionsPartialUpdateParams = /* @__PURE__ */ zod.object({
+ id: zod.number().describe('A unique integer value identifying this subscription.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
+
+export const subscriptionsPartialUpdateBodyIntervalMax = 2147483647
+
+export const subscriptionsPartialUpdateBodyBysetposMin = -2147483648
+export const subscriptionsPartialUpdateBodyBysetposMax = 2147483647
+
+export const subscriptionsPartialUpdateBodyCountMin = -2147483648
+export const subscriptionsPartialUpdateBodyCountMax = 2147483647
+
+export const subscriptionsPartialUpdateBodyTitleMax = 100
+
+export const subscriptionsPartialUpdateBodySummaryPromptGuideMax = 500
+
+export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod
+ .object({
+ dashboard: zod
+ .number()
+ .nullish()
+ .describe('Dashboard ID to subscribe to (mutually exclusive with insight on create).'),
+ insight: zod
+ .number()
+ .nullish()
+ .describe('Insight ID to subscribe to (mutually exclusive with dashboard on create).'),
+ dashboard_export_insights: zod
+ .array(zod.number())
+ .optional()
+ .describe(
+ 'List of insight IDs from the dashboard to include. Required for dashboard subscriptions, max 6.'
+ ),
+ target_type: zod
+ .enum(['email', 'slack', 'webhook'])
+ .describe('* `email` - Email\n* `slack` - Slack\n* `webhook` - Webhook')
+ .optional()
+ .describe(
+ 'Delivery channel: email, slack, or webhook.\n\n* `email` - Email\n* `slack` - Slack\n* `webhook` - Webhook'
+ ),
+ target_value: zod
+ .string()
+ .optional()
+ .describe(
+ 'Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or full URL for webhook.'
+ ),
+ frequency: zod
+ .enum(['daily', 'weekly', 'monthly', 'yearly'])
+ .describe('* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly')
+ .optional()
+ .describe(
+ 'How often to deliver: daily, weekly, monthly, or yearly.\n\n* `daily` - Daily\n* `weekly` - Weekly\n* `monthly` - Monthly\n* `yearly` - Yearly'
+ ),
+ interval: zod
+ .number()
+ .min(1)
+ .max(subscriptionsPartialUpdateBodyIntervalMax)
+ .optional()
+ .describe(
+ 'Interval multiplier (e.g. 2 with weekly frequency means every 2 weeks). Required on create; must be 1 or greater.'
+ ),
+ byweekday: zod
+ .array(
+ zod
+ .enum(['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'])
+ .describe(
+ '* `monday` - Monday\n* `tuesday` - Tuesday\n* `wednesday` - Wednesday\n* `thursday` - Thursday\n* `friday` - Friday\n* `saturday` - Saturday\n* `sunday` - Sunday'
+ )
+ )
+ .nullish()
+ .describe(
+ 'Days of week for weekly subscriptions: monday, tuesday, wednesday, thursday, friday, saturday, sunday.'
+ ),
+ bysetpos: zod
+ .number()
+ .min(subscriptionsPartialUpdateBodyBysetposMin)
+ .max(subscriptionsPartialUpdateBodyBysetposMax)
+ .nullish()
+ .describe('Position within byweekday set for monthly frequency (e.g. 1 for first, -1 for last).'),
+ count: zod
+ .number()
+ .min(subscriptionsPartialUpdateBodyCountMin)
+ .max(subscriptionsPartialUpdateBodyCountMax)
+ .nullish()
+ .describe('Total number of deliveries before the subscription stops. Null for unlimited.'),
+ start_date: zod.iso
+ .datetime({ offset: true })
+ .optional()
+ .describe('When to start delivering (ISO 8601 datetime).'),
+ until_date: zod.iso
+ .datetime({ offset: true })
+ .nullish()
+ .describe('When to stop delivering (ISO 8601 datetime). Null for indefinite.'),
+ deleted: zod.boolean().optional().describe('Set to true to soft-delete. Subscriptions cannot be hard-deleted.'),
+ enabled: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.'
+ ),
+ title: zod
+ .string()
+ .max(subscriptionsPartialUpdateBodyTitleMax)
+ .nullish()
+ .describe('Human-readable name for this subscription.'),
+ integration_id: zod
+ .number()
+ .nullish()
+ .describe('ID of a connected Slack integration. Required when target_type is slack.'),
+ invite_message: zod
+ .string()
+ .nullish()
+ .describe('Optional message included in the invitation email when adding new recipients.'),
+ summary_enabled: zod.boolean().optional(),
+ summary_prompt_guide: zod.string().max(subscriptionsPartialUpdateBodySummaryPromptGuideMax).optional(),
+ })
+ .describe('Standard Subscription serializer.')
+
+export const SubscriptionsTestDeliveryCreateParams = /* @__PURE__ */ zod.object({
+ id: zod.number().describe('A unique integer value identifying this subscription.'),
+ project_id: zod
+ .string()
+ .describe(
+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."
+ ),
+})
diff --git a/services/mcp/src/tools/generated/core.ts b/services/mcp/src/tools/generated/core.ts
index 69266976f545..fe016d386109 100644
--- a/services/mcp/src/tools/generated/core.ts
+++ b/services/mcp/src/tools/generated/core.ts
@@ -12,21 +12,12 @@ import {
OrganizationsProjectsPartialUpdateBody,
OrganizationsProjectsPartialUpdateParams,
OrganizationsProjectsRetrieveParams,
- SubscriptionsCreateBody,
- SubscriptionsDeliveriesListParams,
- SubscriptionsDeliveriesListQueryParams,
- SubscriptionsDeliveriesRetrieveParams,
- SubscriptionsListQueryParams,
- SubscriptionsPartialUpdateBody,
- SubscriptionsPartialUpdateParams,
- SubscriptionsRetrieveParams,
- SubscriptionsTestDeliveryCreateParams,
UsersPartialUpdateBody,
UsersPartialUpdateParams,
UsersRetrieveParams,
} from '@/generated/core/api'
import { castStringToInt } from '@/tools/cast-helpers'
-import { withPostHogUrl, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
+import { omitResponseFields } from '@/tools/tool-utils'
import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
const DesktopFileSystemCreateSchema = DesktopFileSystemCreateBody.extend({
@@ -377,264 +368,6 @@ const projectSettingsUpdate = (): ToolBase<typeof ProjectSettingsUpdateSchema, S
},
})
-const SubscriptionsCreateSchema = SubscriptionsCreateBody
-
-const subscriptionsCreate = (): ToolBase<typeof SubscriptionsCreateSchema, Schemas.Subscription> => ({
- name: 'subscriptions-create',
- schema: SubscriptionsCreateSchema,
- handler: async (context: Context, params: z.infer<typeof SubscriptionsCreateSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.dashboard !== undefined) {
- body['dashboard'] = params.dashboard
- }
- if (params.insight !== undefined) {
- body['insight'] = params.insight
- }
- if (params.dashboard_export_insights !== undefined) {
- body['dashboard_export_insights'] = params.dashboard_export_insights
- }
- if (params.target_type !== undefined) {
- body['target_type'] = params.target_type
- }
- if (params.target_value !== undefined) {
- body['target_value'] = params.target_value
- }
- if (params.frequency !== undefined) {
- body['frequency'] = params.frequency
- }
- if (params.interval !== undefined) {
- body['interval'] = params.interval
- }
- if (params.byweekday !== undefined) {
- body['byweekday'] = params.byweekday
- }
- if (params.bysetpos !== undefined) {
- body['bysetpos'] = params.bysetpos
- }
- if (params.count !== undefined) {
- body['count'] = params.count
- }
- if (params.start_date !== undefined) {
- body['start_date'] = params.start_date
- }
- if (params.until_date !== undefined) {
- body['until_date'] = params.until_date
- }
- if (params.deleted !== undefined) {
- body['deleted'] = params.deleted
- }
- if (params.enabled !== undefined) {
- body['enabled'] = params.enabled
- }
- if (params.title !== undefined) {
- body['title'] = params.title
- }
- if (params.integration_id !== undefined) {
- body['integration_id'] = params.integration_id
- }
- if (params.invite_message !== undefined) {
- body['invite_message'] = params.invite_message
- }
- if (params.summary_enabled !== undefined) {
- body['summary_enabled'] = params.summary_enabled
- }
- if (params.summary_prompt_guide !== undefined) {
- body['summary_prompt_guide'] = params.summary_prompt_guide
- }
- const result = await context.api.request<Schemas.Subscription>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/`,
- body,
- })
- return result
- },
-})
-
-const SubscriptionsDeliveriesListSchema = SubscriptionsDeliveriesListParams.omit({ project_id: true }).extend(
- SubscriptionsDeliveriesListQueryParams.shape
-)
-
-const subscriptionsDeliveriesList = (): ToolBase<
- typeof SubscriptionsDeliveriesListSchema,
- WithPostHogUrl<Schemas.PaginatedSubscriptionDeliveryList>
-> => ({
- name: 'subscriptions-deliveries-list',
- schema: SubscriptionsDeliveriesListSchema,
- handler: async (context: Context, params: z.infer<typeof SubscriptionsDeliveriesListSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedSubscriptionDeliveryList>({
- method: 'GET',
- path: `/api/environments/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.subscription_id))}/deliveries/`,
- query: {
- cursor: params.cursor,
- status: params.status,
- },
- })
- const filtered = {
- ...result,
- results: (result.results ?? []).map((item: any) =>
- omitResponseFields(item, ['content_snapshot', 'recipient_results', 'error'])
- ),
- } as typeof result
- return await withPostHogUrl(context, filtered, '/')
- },
-})
-
-const SubscriptionsDeliveriesRetrieveSchema = SubscriptionsDeliveriesRetrieveParams.omit({ project_id: true })
-
-const subscriptionsDeliveriesRetrieve = (): ToolBase<
- typeof SubscriptionsDeliveriesRetrieveSchema,
- Schemas.SubscriptionDelivery
-> => ({
- name: 'subscriptions-deliveries-retrieve',
- schema: SubscriptionsDeliveriesRetrieveSchema,
- handler: async (context: Context, params: z.infer<typeof SubscriptionsDeliveriesRetrieveSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.SubscriptionDelivery>({
- method: 'GET',
- path: `/api/environments/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.subscription_id))}/deliveries/${encodeURIComponent(String(params.id))}/`,
- })
- const filtered = omitResponseFields(result, ['content_snapshot', 'recipient_results', 'error']) as typeof result
- return filtered
- },
-})
-
-const SubscriptionsListSchema = SubscriptionsListQueryParams
-
-const subscriptionsList = (): ToolBase<
- typeof SubscriptionsListSchema,
- WithPostHogUrl<Schemas.PaginatedSubscriptionList>
-> => ({
- name: 'subscriptions-list',
- schema: SubscriptionsListSchema,
- handler: async (context: Context, params: z.infer<typeof SubscriptionsListSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedSubscriptionList>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/`,
- query: {
- created_by: params.created_by,
- dashboard: params.dashboard,
- insight: params.insight,
- limit: params.limit,
- offset: params.offset,
- ordering: params.ordering,
- resource_type: params.resource_type,
- search: params.search,
- target_type: params.target_type,
- },
- })
- return await withPostHogUrl(context, result, '/')
- },
-})
-
-const SubscriptionsPartialUpdateSchema = SubscriptionsPartialUpdateParams.omit({ project_id: true }).extend(
- SubscriptionsPartialUpdateBody.shape
-)
-
-const subscriptionsPartialUpdate = (): ToolBase<typeof SubscriptionsPartialUpdateSchema, Schemas.Subscription> => ({
- name: 'subscriptions-partial-update',
- schema: SubscriptionsPartialUpdateSchema,
- handler: async (context: Context, params: z.infer<typeof SubscriptionsPartialUpdateSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.dashboard !== undefined) {
- body['dashboard'] = params.dashboard
- }
- if (params.insight !== undefined) {
- body['insight'] = params.insight
- }
- if (params.dashboard_export_insights !== undefined) {
- body['dashboard_export_insights'] = params.dashboard_export_insights
- }
- if (params.target_type !== undefined) {
- body['target_type'] = params.target_type
- }
- if (params.target_value !== undefined) {
- body['target_value'] = params.target_value
- }
- if (params.frequency !== undefined) {
- body['frequency'] = params.frequency
- }
- if (params.interval !== undefined) {
- body['interval'] = params.interval
- }
- if (params.byweekday !== undefined) {
- body['byweekday'] = params.byweekday
- }
- if (params.bysetpos !== undefined) {
- body['bysetpos'] = params.bysetpos
- }
- if (params.count !== undefined) {
- body['count'] = params.count
- }
- if (params.start_date !== undefined) {
- body['start_date'] = params.start_date
- }
- if (params.until_date !== undefined) {
- body['until_date'] = params.until_date
- }
- if (params.deleted !== undefined) {
- body['deleted'] = params.deleted
- }
- if (params.enabled !== undefined) {
- body['enabled'] = params.enabled
- }
- if (params.title !== undefined) {
- body['title'] = params.title
- }
- if (params.integration_id !== undefined) {
- body['integration_id'] = params.integration_id
- }
- if (params.invite_message !== undefined) {
- body['invite_message'] = params.invite_message
- }
- if (params.summary_enabled !== undefined) {
- body['summary_enabled'] = params.summary_enabled
- }
- if (params.summary_prompt_guide !== undefined) {
- body['summary_prompt_guide'] = params.summary_prompt_guide
- }
- const result = await context.api.request<Schemas.Subscription>({
- method: 'PATCH',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.id))}/`,
- body,
- })
- return result
- },
-})
-
-const SubscriptionsRetrieveSchema = SubscriptionsRetrieveParams.omit({ project_id: true })
-
-const subscriptionsRetrieve = (): ToolBase<typeof SubscriptionsRetrieveSchema, Schemas.Subscription> => ({
- name: 'subscriptions-retrieve',
- schema: SubscriptionsRetrieveSchema,
- handler: async (context: Context, params: z.infer<typeof SubscriptionsRetrieveSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.Subscription>({
- method: 'GET',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.id))}/`,
- })
- return result
- },
-})
-
-const SubscriptionsTestDeliveryCreateSchema = SubscriptionsTestDeliveryCreateParams.omit({ project_id: true })
-
-const subscriptionsTestDeliveryCreate = (): ToolBase<typeof SubscriptionsTestDeliveryCreateSchema, unknown> => ({
- name: 'subscriptions-test-delivery-create',
- schema: SubscriptionsTestDeliveryCreateSchema,
- handler: async (context: Context, params: z.infer<typeof SubscriptionsTestDeliveryCreateSchema>) => {
- const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<unknown>({
- method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.id))}/test-delivery/`,
- })
- return result
- },
-})
-
const UserGetSchema = UsersRetrieveParams.extend({
uuid: UsersRetrieveParams.shape['uuid'].describe('User UUID, or `@me` to target the authenticated user.'),
})
@@ -743,13 +476,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'desktop-file-system-retrieve': desktopFileSystemRetrieve,
'project-get': projectGet,
'project-settings-update': projectSettingsUpdate,
- 'subscriptions-create': subscriptionsCreate,
- 'subscriptions-deliveries-list': subscriptionsDeliveriesList,
- 'subscriptions-deliveries-retrieve': subscriptionsDeliveriesRetrieve,
- 'subscriptions-list': subscriptionsList,
- 'subscriptions-partial-update': subscriptionsPartialUpdate,
- 'subscriptions-retrieve': subscriptionsRetrieve,
- 'subscriptions-test-delivery-create': subscriptionsTestDeliveryCreate,
'user-get': userGet,
'user-settings-update': userSettingsUpdate,
}
diff --git a/services/mcp/src/tools/generated/index.ts b/services/mcp/src/tools/generated/index.ts
index 6ece761878b5..44925d33281f 100644
--- a/services/mcp/src/tools/generated/index.ts
+++ b/services/mcp/src/tools/generated/index.ts
@@ -33,6 +33,7 @@ import { GENERATED_TOOLS as replay } from './replay'
import { GENERATED_TOOLS as replay_vision } from './replay_vision'
import { GENERATED_TOOLS as sdk_health } from './sdk_health'
import { GENERATED_TOOLS as signals } from './signals'
+import { GENERATED_TOOLS as subscriptions } from './subscriptions'
import { GENERATED_TOOLS as surveys } from './surveys'
import { GENERATED_TOOLS as tasks } from './tasks'
import { GENERATED_TOOLS as tracing } from './tracing'
@@ -74,6 +75,7 @@ export const GENERATED_TOOL_MAP: Record<string, () => ToolBase<ZodObjectAny>> =
...replay_vision,
...sdk_health,
...signals,
+ ...subscriptions,
...surveys,
...tasks,
...tracing,
diff --git a/services/mcp/src/tools/generated/subscriptions.ts b/services/mcp/src/tools/generated/subscriptions.ts
new file mode 100644
index 000000000000..ee2480aa264e
--- /dev/null
+++ b/services/mcp/src/tools/generated/subscriptions.ts
@@ -0,0 +1,285 @@
+// AUTO-GENERATED from products/subscriptions/mcp/tools.yaml + OpenAPI — do not edit
+import { z } from 'zod'
+
+import type { Schemas } from '@/api/generated'
+import {
+ SubscriptionsCreateBody,
+ SubscriptionsDeliveriesListParams,
+ SubscriptionsDeliveriesListQueryParams,
+ SubscriptionsDeliveriesRetrieveParams,
+ SubscriptionsListQueryParams,
+ SubscriptionsPartialUpdateBody,
+ SubscriptionsPartialUpdateParams,
+ SubscriptionsRetrieveParams,
+ SubscriptionsTestDeliveryCreateParams,
+} from '@/generated/subscriptions/api'
+import { withPostHogUrl, omitResponseFields, type WithPostHogUrl } from '@/tools/tool-utils'
+import type { Context, ToolBase, ZodObjectAny } from '@/tools/types'
+
+const SubscriptionsCreateSchema = SubscriptionsCreateBody
+
+const subscriptionsCreate = (): ToolBase<typeof SubscriptionsCreateSchema, Schemas.Subscription> => ({
+ name: 'subscriptions-create',
+ schema: SubscriptionsCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof SubscriptionsCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.dashboard !== undefined) {
+ body['dashboard'] = params.dashboard
+ }
+ if (params.insight !== undefined) {
+ body['insight'] = params.insight
+ }
+ if (params.dashboard_export_insights !== undefined) {
+ body['dashboard_export_insights'] = params.dashboard_export_insights
+ }
+ if (params.target_type !== undefined) {
+ body['target_type'] = params.target_type
+ }
+ if (params.target_value !== undefined) {
+ body['target_value'] = params.target_value
+ }
+ if (params.frequency !== undefined) {
+ body['frequency'] = params.frequency
+ }
+ if (params.interval !== undefined) {
+ body['interval'] = params.interval
+ }
+ if (params.byweekday !== undefined) {
+ body['byweekday'] = params.byweekday
+ }
+ if (params.bysetpos !== undefined) {
+ body['bysetpos'] = params.bysetpos
+ }
+ if (params.count !== undefined) {
+ body['count'] = params.count
+ }
+ if (params.start_date !== undefined) {
+ body['start_date'] = params.start_date
+ }
+ if (params.until_date !== undefined) {
+ body['until_date'] = params.until_date
+ }
+ if (params.deleted !== undefined) {
+ body['deleted'] = params.deleted
+ }
+ if (params.enabled !== undefined) {
+ body['enabled'] = params.enabled
+ }
+ if (params.title !== undefined) {
+ body['title'] = params.title
+ }
+ if (params.integration_id !== undefined) {
+ body['integration_id'] = params.integration_id
+ }
+ if (params.invite_message !== undefined) {
+ body['invite_message'] = params.invite_message
+ }
+ if (params.summary_enabled !== undefined) {
+ body['summary_enabled'] = params.summary_enabled
+ }
+ if (params.summary_prompt_guide !== undefined) {
+ body['summary_prompt_guide'] = params.summary_prompt_guide
+ }
+ const result = await context.api.request<Schemas.Subscription>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/`,
+ body,
+ })
+ return result
+ },
+})
+
+const SubscriptionsDeliveriesListSchema = SubscriptionsDeliveriesListParams.omit({ project_id: true }).extend(
+ SubscriptionsDeliveriesListQueryParams.shape
+)
+
+const subscriptionsDeliveriesList = (): ToolBase<
+ typeof SubscriptionsDeliveriesListSchema,
+ WithPostHogUrl<Schemas.PaginatedSubscriptionDeliveryList>
+> => ({
+ name: 'subscriptions-deliveries-list',
+ schema: SubscriptionsDeliveriesListSchema,
+ handler: async (context: Context, params: z.infer<typeof SubscriptionsDeliveriesListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedSubscriptionDeliveryList>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.subscription_id))}/deliveries/`,
+ query: {
+ cursor: params.cursor,
+ status: params.status,
+ },
+ })
+ const filtered = {
+ ...result,
+ results: (result.results ?? []).map((item: any) =>
+ omitResponseFields(item, ['content_snapshot', 'recipient_results', 'error'])
+ ),
+ } as typeof result
+ return await withPostHogUrl(context, filtered, '/subscriptions')
+ },
+})
+
+const SubscriptionsDeliveriesRetrieveSchema = SubscriptionsDeliveriesRetrieveParams.omit({ project_id: true })
+
+const subscriptionsDeliveriesRetrieve = (): ToolBase<
+ typeof SubscriptionsDeliveriesRetrieveSchema,
+ Schemas.SubscriptionDelivery
+> => ({
+ name: 'subscriptions-deliveries-retrieve',
+ schema: SubscriptionsDeliveriesRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof SubscriptionsDeliveriesRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.SubscriptionDelivery>({
+ method: 'GET',
+ path: `/api/environments/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.subscription_id))}/deliveries/${encodeURIComponent(String(params.id))}/`,
+ })
+ const filtered = omitResponseFields(result, ['content_snapshot', 'recipient_results', 'error']) as typeof result
+ return filtered
+ },
+})
+
+const SubscriptionsListSchema = SubscriptionsListQueryParams
+
+const subscriptionsList = (): ToolBase<
+ typeof SubscriptionsListSchema,
+ WithPostHogUrl<Schemas.PaginatedSubscriptionList>
+> => ({
+ name: 'subscriptions-list',
+ schema: SubscriptionsListSchema,
+ handler: async (context: Context, params: z.infer<typeof SubscriptionsListSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.PaginatedSubscriptionList>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/`,
+ query: {
+ created_by: params.created_by,
+ dashboard: params.dashboard,
+ insight: params.insight,
+ limit: params.limit,
+ offset: params.offset,
+ ordering: params.ordering,
+ resource_type: params.resource_type,
+ search: params.search,
+ target_type: params.target_type,
+ },
+ })
+ return await withPostHogUrl(context, result, '/subscriptions')
+ },
+})
+
+const SubscriptionsPartialUpdateSchema = SubscriptionsPartialUpdateParams.omit({ project_id: true }).extend(
+ SubscriptionsPartialUpdateBody.shape
+)
+
+const subscriptionsPartialUpdate = (): ToolBase<typeof SubscriptionsPartialUpdateSchema, Schemas.Subscription> => ({
+ name: 'subscriptions-partial-update',
+ schema: SubscriptionsPartialUpdateSchema,
+ handler: async (context: Context, params: z.infer<typeof SubscriptionsPartialUpdateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const body: Record<string, unknown> = {}
+ if (params.dashboard !== undefined) {
+ body['dashboard'] = params.dashboard
+ }
+ if (params.insight !== undefined) {
+ body['insight'] = params.insight
+ }
+ if (params.dashboard_export_insights !== undefined) {
+ body['dashboard_export_insights'] = params.dashboard_export_insights
+ }
+ if (params.target_type !== undefined) {
+ body['target_type'] = params.target_type
+ }
+ if (params.target_value !== undefined) {
+ body['target_value'] = params.target_value
+ }
+ if (params.frequency !== undefined) {
+ body['frequency'] = params.frequency
+ }
+ if (params.interval !== undefined) {
+ body['interval'] = params.interval
+ }
+ if (params.byweekday !== undefined) {
+ body['byweekday'] = params.byweekday
+ }
+ if (params.bysetpos !== undefined) {
+ body['bysetpos'] = params.bysetpos
+ }
+ if (params.count !== undefined) {
+ body['count'] = params.count
+ }
+ if (params.start_date !== undefined) {
+ body['start_date'] = params.start_date
+ }
+ if (params.until_date !== undefined) {
+ body['until_date'] = params.until_date
+ }
+ if (params.deleted !== undefined) {
+ body['deleted'] = params.deleted
+ }
+ if (params.enabled !== undefined) {
+ body['enabled'] = params.enabled
+ }
+ if (params.title !== undefined) {
+ body['title'] = params.title
+ }
+ if (params.integration_id !== undefined) {
+ body['integration_id'] = params.integration_id
+ }
+ if (params.invite_message !== undefined) {
+ body['invite_message'] = params.invite_message
+ }
+ if (params.summary_enabled !== undefined) {
+ body['summary_enabled'] = params.summary_enabled
+ }
+ if (params.summary_prompt_guide !== undefined) {
+ body['summary_prompt_guide'] = params.summary_prompt_guide
+ }
+ const result = await context.api.request<Schemas.Subscription>({
+ method: 'PATCH',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.id))}/`,
+ body,
+ })
+ return result
+ },
+})
+
+const SubscriptionsRetrieveSchema = SubscriptionsRetrieveParams.omit({ project_id: true })
+
+const subscriptionsRetrieve = (): ToolBase<typeof SubscriptionsRetrieveSchema, Schemas.Subscription> => ({
+ name: 'subscriptions-retrieve',
+ schema: SubscriptionsRetrieveSchema,
+ handler: async (context: Context, params: z.infer<typeof SubscriptionsRetrieveSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<Schemas.Subscription>({
+ method: 'GET',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.id))}/`,
+ })
+ return result
+ },
+})
+
+const SubscriptionsTestDeliveryCreateSchema = SubscriptionsTestDeliveryCreateParams.omit({ project_id: true })
+
+const subscriptionsTestDeliveryCreate = (): ToolBase<typeof SubscriptionsTestDeliveryCreateSchema, unknown> => ({
+ name: 'subscriptions-test-delivery-create',
+ schema: SubscriptionsTestDeliveryCreateSchema,
+ handler: async (context: Context, params: z.infer<typeof SubscriptionsTestDeliveryCreateSchema>) => {
+ const projectId = await context.stateManager.getProjectId()
+ const result = await context.api.request<unknown>({
+ method: 'POST',
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.id))}/test-delivery/`,
+ })
+ return result
+ },
+})
+
+export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
+ 'subscriptions-create': subscriptionsCreate,
+ 'subscriptions-deliveries-list': subscriptionsDeliveriesList,
+ 'subscriptions-deliveries-retrieve': subscriptionsDeliveriesRetrieve,
+ 'subscriptions-list': subscriptionsList,
+ 'subscriptions-partial-update': subscriptionsPartialUpdate,
+ 'subscriptions-retrieve': subscriptionsRetrieve,
+ 'subscriptions-test-delivery-create': subscriptionsTestDeliveryCreate,
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json
index f1e52ced2042..e773356567cc 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json
@@ -26,8 +26,8 @@
"type": "string"
},
"resource_type": {
- "description": "Filter by subscription resource: insight vs dashboard export.",
- "enum": ["dashboard", "insight"],
+ "description": "Filter by subscription resource: insight, dashboard export, or AI report.",
+ "enum": ["ai_prompt", "dashboard", "insight"],
"type": "string"
},
"search": {