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): add AI-prompt subscription fields + activity logging (#59629)

Vasco de Krijgered14aaff3fca
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index d3e377bba93d..1dd700b2814f 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -205,9 +205,9 @@ class SubscriptionSerializer(serializers.ModelSerializer):
raise ValidationError({"subscription": [msg]})
if self.instance is None:
- # Create: a subscription must export an insight or a dashboard.
- if not attrs.get("dashboard") and not attrs.get("insight"):
- raise ValidationError("Either dashboard or insight is required for an export.")
+ # 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.")
if attrs.get("dashboard") and attrs["dashboard"].team.id != self.context["team_id"]:
raise ValidationError({"dashboard": ["This dashboard does not belong to your team."]})
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index b4a9df3516bb..a4812ccfdd2f 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -141,7 +141,7 @@ class TestSubscriptionTemporal(APILicensedTest):
},
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- assert "Either dashboard or insight is required" in str(response.json())
+ assert "must have an insight, a dashboard, or a prompt" in str(response.json())
def test_can_update_subscription_without_resending_relation(self):
sub_id = self._create_subscription().json()["id"]
diff --git a/posthog/constants.py b/posthog/constants.py
index e034e35110a9..4821e152e821 100644
--- a/posthog/constants.py
+++ b/posthog/constants.py
@@ -317,6 +317,7 @@ PRODUCT_TOUR_TARGETING_FLAG_PREFIX = "product-tour-targeting-"
# Server-side evaluation via posthoganalytics; keep in sync with frontend FEATURE_FLAGS.
HACKATHONS_SUBSCRIPTIONS_FEATURE_FLAG_KEY = "hackathons_subscriptions"
SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY = "subscription-ai-summary-prompt-guide"
+SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY = "ai-subscriptions"
ALERTS_15_MINUTE_INTERVAL_FEATURE_FLAG_KEY = "alerts-15-minute-interval"
EXPERIMENTS_SYNC_QUERIES_FEATURE_FLAG_KEY = "experiments-sync-queries"
GENERATED_DASHBOARD_PREFIX = "Generated Dashboard"
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index ea85d163c103..72904298e363 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -327,6 +327,9 @@ signal_exclusions: dict[ActivityScope, list[str]] = {
"OrganizationDomain": [
"last_verification_retry",
],
+ "Subscription": [
+ "next_delivery_date",
+ ],
}
# Activity visibility restrictions - controls which users can see certain activity logs
@@ -371,6 +374,11 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"organization",
"scim_provisioned_users",
],
+ "Subscription": [
+ # Scheduler-derived field; keep it out of user-facing change diffs even when another
+ # field changes in the same save (signal_exclusions only governs whether the signal fires).
+ "next_delivery_date",
+ ],
"Cohort": [
"version",
"pending_version",
diff --git a/posthog/models/test/test_subscription_activity_log.py b/posthog/models/test/test_subscription_activity_log.py
new file mode 100644
index 000000000000..f1591faafdbd
--- /dev/null
+++ b/posthog/models/test/test_subscription_activity_log.py
@@ -0,0 +1,193 @@
+from collections.abc import Callable
+from datetime import datetime
+from zoneinfo import ZoneInfo
+
+from freezegun import freeze_time
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.models.activity_logging.activity_log import ActivityLog
+
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.exports.backend.models.subscription import Subscription
+from products.product_analytics.backend.models.insight import Insight
+
+
+@freeze_time("2022-01-01")
+class TestSubscriptionActivityLog(BaseTest):
+ def _create_subscription(self, **kwargs) -> Subscription:
+ params: dict = {
+ "team": self.team,
+ "created_by": self.user,
+ "title": "Weekly AI digest",
+ "prompt": "Summarize last week's signups",
+ "target_type": "email",
+ "target_value": "[email protected]",
+ "frequency": "weekly",
+ "interval": 1,
+ "start_date": datetime(2022, 1, 1, tzinfo=ZoneInfo("UTC")),
+ }
+ params.update(kwargs)
+ return Subscription.objects.create(**params)
+
+ def _subscription_logs(self):
+ return ActivityLog.objects.filter(scope="Subscription").order_by("created_at")
+
+ @parameterized.expand(
+ [
+ ("ai", lambda self: self._create_subscription(), "Weekly AI digest"),
+ (
+ "insight",
+ lambda self: self._create_subscription(
+ prompt=None, title=None, insight=Insight.objects.create(team=self.team, name="My insight")
+ ),
+ "My insight",
+ ),
+ (
+ "dashboard",
+ lambda self: self._create_subscription(
+ prompt=None, title=None, dashboard=Dashboard.objects.create(team=self.team, name="My dashboard")
+ ),
+ "My dashboard",
+ ),
+ ]
+ )
+ def test_creating_subscription_logs_activity(
+ self, _name: str, make_subscription: Callable[..., Subscription], expected_name: str
+ ):
+ subscription = make_subscription(self)
+
+ logs = self._subscription_logs()
+ assert logs.count() == 1
+ assert logs[0].activity == "created"
+ assert logs[0].item_id == str(subscription.id)
+ assert logs[0].detail["name"] == expected_name
+
+ def test_subscription_without_created_by_still_logs(self):
+ self._create_subscription(created_by=None)
+
+ assert self._subscription_logs().count() == 1
+
+ def test_updating_ai_subscription_prompt_records_change(self):
+ subscription = self._create_subscription()
+
+ subscription.prompt = "Summarize last week's churn instead"
+ subscription.save(update_fields=["prompt"])
+
+ logs = self._subscription_logs()
+ assert logs.count() == 2
+ assert logs[1].activity == "updated"
+ prompt_change = next(change for change in logs[1].detail["changes"] if change["field"] == "prompt")
+ assert prompt_change["action"] == "changed"
+ assert prompt_change["before"] == "Summarize last week's signups"
+ assert prompt_change["after"] == "Summarize last week's churn instead"
+
+ @parameterized.expand(
+ [
+ ("adding_a_prompt", None, "Now summarize signups", "created"),
+ ("clearing_a_prompt", "Existing prompt", None, "deleted"),
+ ]
+ )
+ def test_prompt_null_transitions_record_change(
+ self, _name: str, before: str | None, after: str | None, expected_action: str
+ ):
+ subscription = self._create_subscription(prompt=before)
+
+ subscription.prompt = after
+ subscription.save(update_fields=["prompt"])
+
+ prompt_change = next(
+ change for change in self._subscription_logs()[1].detail["changes"] if change["field"] == "prompt"
+ )
+ assert prompt_change["action"] == expected_action
+ assert prompt_change["before"] == before
+ assert prompt_change["after"] == after
+
+ def _unsaved_subscription(self, **kwargs) -> Subscription:
+ return Subscription(
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2022, 1, 1, tzinfo=ZoneInfo("UTC")),
+ **kwargs,
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "ai_title_wins",
+ lambda self: self._unsaved_subscription(title="My title", prompt="the prompt"),
+ "My title",
+ ),
+ (
+ "ai_prompt_snippet_when_no_title",
+ lambda self: self._unsaved_subscription(prompt="x" * 80),
+ "x" * 60,
+ ),
+ (
+ "ai_whitespace_prompt_falls_back",
+ lambda self: self._unsaved_subscription(prompt=" "),
+ "AI report",
+ ),
+ (
+ "insight_uses_insight_name",
+ lambda self: self._unsaved_subscription(
+ insight=Insight.objects.create(team=self.team, name="Signups by week")
+ ),
+ "Signups by week",
+ ),
+ (
+ "dashboard_uses_dashboard_name",
+ lambda self: self._unsaved_subscription(
+ dashboard=Dashboard.objects.create(team=self.team, name="Growth")
+ ),
+ "Growth",
+ ),
+ ]
+ )
+ def test_display_name(self, _name: str, make_subscription: Callable[..., Subscription], expected: str):
+ assert make_subscription(self).display_name == expected
+
+ def test_soft_deleting_ai_subscription_records_change(self):
+ subscription = self._create_subscription()
+
+ subscription.deleted = True
+ subscription.save(update_fields=["deleted"])
+
+ logs = self._subscription_logs()
+ assert logs.count() == 2
+ assert logs[1].activity == "updated"
+ deleted_change = next(change for change in logs[1].detail["changes"] if change["field"] == "deleted")
+ assert deleted_change["before"] is False
+ assert deleted_change["after"] is True
+
+ def test_mixed_save_excludes_next_delivery_date_from_diff(self):
+ subscription = self._create_subscription()
+
+ subscription.prompt = "Updated prompt"
+ subscription.next_delivery_date = datetime(2022, 3, 1, tzinfo=ZoneInfo("UTC"))
+ subscription.save(update_fields=["prompt", "next_delivery_date"])
+
+ changed_fields = {change["field"] for change in self._subscription_logs()[1].detail["changes"]}
+ assert "prompt" in changed_fields
+ assert "next_delivery_date" not in changed_fields
+
+ def test_scheduler_save_with_update_fields_does_not_log(self):
+ subscription = self._create_subscription()
+
+ subscription.next_delivery_date = datetime(2022, 2, 1, tzinfo=ZoneInfo("UTC"))
+ subscription.save(update_fields=["next_delivery_date"])
+
+ # Only the original "created" entry — the schedule bump is excluded via signal_exclusions.
+ assert self._subscription_logs().count() == 1
+
+ def test_scheduler_save_without_update_fields_does_not_log(self):
+ subscription = self._create_subscription()
+
+ subscription.refresh_from_db()
+ subscription.next_delivery_date = datetime(2022, 2, 1, tzinfo=ZoneInfo("UTC"))
+ subscription.save()
+
+ # signal_exclusions also covers the no-update_fields path: the mixin's changed-fields check
+ # honours the exclusion list, so a schedule-only change never emits the signal.
+ assert self._subscription_logs().count() == 1
diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.py
index ce5e9d397f6c..2c86de44e1fe 100644
--- a/posthog/models/test/test_subscription_model.py
+++ b/posthog/models/test/test_subscription_model.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
@@ -16,6 +17,7 @@ from parameterized import parameterized
from posthog.constants import AvailableFeature
from posthog.jwt import PosthogJwtAudience
+from products.dashboards.backend.models.dashboard import Dashboard
from products.exports.backend.models.subscription import (
SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER,
UNSUBSCRIBE_TOKEN_EXP_DAYS,
@@ -55,6 +57,50 @@ class TestSubscription(BaseTest):
subscription.set_next_delivery_date(datetime(2022, 1, 2, 0, 0, 0).replace(tzinfo=ZoneInfo("UTC")))
assert subscription.next_delivery_date == datetime(2022, 1, 15, 0, 0).replace(tzinfo=ZoneInfo("UTC"))
+ def _create_subscription(self, **kwargs) -> Subscription:
+ return Subscription.objects.create(
+ team=self.team,
+ target_type="email",
+ target_value="[email protected]",
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2022, 1, 1, tzinfo=ZoneInfo("UTC")),
+ **kwargs,
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "insight_relation",
+ lambda self: self._create_subscription(insight=Insight.objects.create(team=self.team)),
+ Subscription.ResourceType.INSIGHT,
+ ),
+ (
+ "dashboard_relation",
+ lambda self: self._create_subscription(dashboard=Dashboard.objects.create(team=self.team)),
+ Subscription.ResourceType.DASHBOARD,
+ ),
+ (
+ "prompt_no_relation",
+ lambda self: self._create_subscription(prompt="Summarize signups"),
+ Subscription.ResourceType.AI_PROMPT,
+ ),
+ ]
+ )
+ def test_resource_type_derived_from_relation(
+ self, _name: str, make_subscription: Callable[..., Subscription], expected: "Subscription.ResourceType"
+ ):
+ subscription = make_subscription(self)
+
+ assert subscription.resource_type == expected
+ subscription.refresh_from_db()
+ assert subscription.resource_type == expected
+
+ def test_resource_type_raises_without_relation(self):
+ subscription = self._create_subscription()
+ with self.assertRaises(ValueError):
+ _ = subscription.resource_type
+
def test_update_next_delivery_date_on_save(self):
subscription = self._create_insight_subscription()
subscription.save()
diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
index 4d81dc6a2021..00df46fd5d01 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr
@@ -736,7 +736,7 @@
GROUP BY person_distinct_id_overrides.distinct_id
HAVING ifNull(equals(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
LEFT JOIN
- (SELECT person.id AS id, nullIf(nullIf(person.pmat_email, ''), 'null') AS properties___email
+ (SELECT person.id AS id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email
FROM person
WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
(SELECT person.id AS id, max(person.version) AS version
diff --git a/products/exports/backend/migrations/0002_subscription_prompt.py b/products/exports/backend/migrations/0002_subscription_prompt.py
new file mode 100644
index 000000000000..b10f0157dd10
--- /dev/null
+++ b/products/exports/backend/migrations/0002_subscription_prompt.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("exports", "0001_migrate_exports_models"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="subscription",
+ name="prompt",
+ field=models.TextField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/exports/backend/migrations/max_migration.txt b/products/exports/backend/migrations/max_migration.txt
index b9a56d7d71bf..7f7c1b396bf4 100644
--- a/products/exports/backend/migrations/max_migration.txt
+++ b/products/exports/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_migrate_exports_models
+0002_subscription_prompt
diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.py
index 82c0d8dd544b..8ca332201310 100644
--- a/products/exports/backend/models/subscription.py
+++ b/products/exports/backend/models/subscription.py
@@ -15,6 +15,9 @@ from posthog.schema import SubscriptionFreeTierLimit
from posthog.constants import AvailableFeature
from posthog.exceptions_capture import capture_exception
from posthog.jwt import PosthogJwtAudience, decode_jwt, encode_jwt
+from posthog.models.activity_logging.activity_log import Detail, changes_between, log_activity
+from posthog.models.activity_logging.model_activity import ModelActivityMixin
+from posthog.models.signals import model_activity_signal, mutable_receiver
from posthog.models.utils import UUIDModel
from posthog.utils import absolute_uri
@@ -26,6 +29,9 @@ UNSUBSCRIBE_TOKEN_EXP_DAYS = 30
# Single source of truth shared with the frontend create gate via generated schema (SubscriptionFreeTierLimit.COUNT).
SUBSCRIPTION_COUNT_ALLOWED_ON_FREE_TIER: int = SubscriptionFreeTierLimit.model_fields["root"].default
+# Max length of the prompt snippet used as an AI subscription's display name when it has no title.
+AI_PROMPT_DISPLAY_MAX_LEN = 60
+
RRULE_WEEKDAY_MAP = {
"monday": MO,
"tuesday": TU,
@@ -46,7 +52,7 @@ class SubscriptionResourceInfo:
url: str
-class Subscription(models.Model):
+class Subscription(ModelActivityMixin, models.Model):
"""
Rather than re-invent the wheel, we are roughly following the iCalender format for recurring schedules
https://dateutil.readthedocs.io/en/stable/rrule.html
@@ -74,6 +80,11 @@ class Subscription(models.Model):
SATURDAY = "saturday"
SUNDAY = "sunday"
+ class ResourceType(models.TextChoices):
+ INSIGHT = "insight"
+ DASHBOARD = "dashboard"
+ AI_PROMPT = "ai_prompt", "AI prompt"
+
RRULE_FIELDS = {"frequency", "count", "interval", "start_date", "until_date", "bysetpos", "byweekday"}
_FREQ_MAP: dict[str, int] = {
@@ -100,6 +111,8 @@ class Subscription(models.Model):
db_index=False,
)
+ prompt = models.TextField(null=True, blank=True)
+
# Subscription type (email, slack etc.)
title = models.CharField(max_length=100, null=True, blank=True)
target_type = models.CharField(max_length=10, choices=SubscriptionTarget)
@@ -158,6 +171,16 @@ class Subscription(models.Model):
kwargs["update_fields"].append("next_delivery_date")
super().save(*args, **kwargs)
+ @property
+ def resource_type(self) -> str:
+ if self.insight_id:
+ return self.ResourceType.INSIGHT
+ if self.dashboard_id:
+ return self.ResourceType.DASHBOARD
+ if self.prompt:
+ return self.ResourceType.AI_PROMPT
+ raise ValueError(f"Subscription {self.pk} has no insight, dashboard, or prompt to derive a resource type from")
+
@staticmethod
def _build_rrule(
*,
@@ -228,26 +251,43 @@ class Subscription(models.Model):
return None
@property
- def url(self):
- if self.insight:
- return absolute_uri(f"/insights/{self.insight.short_id}/subscriptions/{self.id}")
- elif self.dashboard:
- return absolute_uri(f"/dashboard/{self.dashboard_id}/subscriptions/{self.id}")
+ def url(self) -> str | None:
+ if not (self.insight_id or self.dashboard_id or self.prompt):
+ return None
+ match self.resource_type:
+ case self.ResourceType.INSIGHT if self.insight:
+ return absolute_uri(f"/insights/{self.insight.short_id}/subscriptions/{self.id}")
+ case self.ResourceType.DASHBOARD if self.dashboard:
+ return absolute_uri(f"/dashboard/{self.dashboard_id}/subscriptions/{self.id}")
+ case self.ResourceType.AI_PROMPT:
+ return absolute_uri(f"/project/{self.team_id}/subscriptions/{self.id}")
return None
@property
def resource_info(self) -> Optional[SubscriptionResourceInfo]:
- if self.insight:
- return SubscriptionResourceInfo(
- "Insight",
- f"{self.insight.name or self.insight.derived_name}",
- self.insight.url,
- )
- elif self.dashboard:
- return SubscriptionResourceInfo("Dashboard", self.dashboard.name or "Dashboard", self.dashboard.url)
-
+ if not (self.insight_id or self.dashboard_id or self.prompt):
+ return None
+ match self.resource_type:
+ case self.ResourceType.INSIGHT if self.insight:
+ return SubscriptionResourceInfo(
+ "Insight",
+ f"{self.insight.name or self.insight.derived_name}",
+ self.insight.url,
+ )
+ case self.ResourceType.DASHBOARD if self.dashboard:
+ return SubscriptionResourceInfo("Dashboard", self.dashboard.name or "Dashboard", self.dashboard.url)
+ case self.ResourceType.AI_PROMPT:
+ ai_name = self.title or (self.prompt or "").strip()[:AI_PROMPT_DISPLAY_MAX_LEN] or "AI report"
+ return SubscriptionResourceInfo("AI", ai_name, self.url or "")
return None
+ @property
+ def display_name(self) -> str:
+ info = self.resource_info
+ if info is not None:
+ return info.name
+ return self.title or "Subscription"
+
@property
def summary(self):
try:
@@ -288,12 +328,14 @@ class Subscription(models.Model):
"""
return {
"id": self.id,
+ "resource_type": self.resource_type,
"target_type": self.target_type,
"num_emails_invited": len(self.target_value.split(",")) if self.target_type == "email" else None,
"frequency": self.frequency,
"interval": self.interval,
"byweekday": self.byweekday,
"bysetpos": self.bysetpos,
+ "prompt_length": len(self.prompt or ""),
}
@@ -306,6 +348,33 @@ def subscription_saved(sender, instance, created, raw, using, **kwargs):
report_user_action(instance.created_by, event_name, instance.get_analytics_metadata())
+@mutable_receiver(model_activity_signal, sender=Subscription)
+def log_subscription_activity(
+ sender, scope, before_update, after_update, activity, user, was_impersonated=False, **kwargs
+):
+ instance = after_update or before_update
+ if instance is None:
+ return
+
+ changes = changes_between("Subscription", previous=before_update, current=after_update)
+ try:
+ log_activity(
+ organization_id=instance.team.organization_id,
+ team_id=instance.team_id,
+ user=user,
+ was_impersonated=was_impersonated,
+ item_id=instance.id,
+ scope="Subscription",
+ activity=activity,
+ detail=Detail(
+ name=instance.display_name,
+ changes=changes,
+ ),
+ )
+ except Exception as exc: # never let activity logging break a save
+ capture_exception(exc)
+
+
def to_rrule_weekdays(weekday: Subscription.SubscriptionByWeekDay):
return {RRULE_WEEKDAY_MAP.get(x) for x in weekday}