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 report display options (#95909)

Vasco de Krijger7d91d5185c6c
diff --git a/ee/api/subscription.py b/ee/api/subscription.py
index 1d92613d1495..dd11ebfb193f 100644
--- a/ee/api/subscription.py
+++ b/ee/api/subscription.py
@@ -79,6 +79,9 @@ from ee.tasks.subscriptions.teams_subscriptions import TEAMS_WEBHOOK_URL_ERROR,
SUMMARY_QUOTA_CACHE_TTL_SECONDS = 60
SUMMARY_CAP_HIT_DEDUPE_TTL_SECONDS = 600
+AI_DELIVERY_DISPLAY_FIELDS = frozenset(
+ {"include_images", "include_feedback", "include_manage_link", "include_posthog_hint"}
+)
def _summary_quota_cache_key(organization_id) -> str:
@@ -269,6 +272,25 @@ class DeliveryConfigSerializer(serializers.Serializer):
"Defaults to false."
),
)
+ include_images = serializers.BooleanField(
+ required=False,
+ help_text="AI prompt subscriptions only: include generated chart images. Defaults to true when omitted.",
+ )
+ include_feedback = serializers.BooleanField(
+ required=False,
+ help_text="AI prompt subscriptions only: include report feedback links. Defaults to true when omitted.",
+ )
+ include_manage_link = serializers.BooleanField(
+ required=False,
+ help_text="AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted.",
+ )
+ include_posthog_hint = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "AI prompt subscriptions only: include PostHog product guidance. Slack only. "
+ "Email and Microsoft Teams reports do not include it. Defaults to true when omitted."
+ ),
+ )
class SubscriptionSerializer(serializers.ModelSerializer):
@@ -552,6 +574,14 @@ class SubscriptionSerializer(serializers.ModelSerializer):
)
except ValueError as exc:
raise ValidationError(str(exc))
+ if (
+ resource_type == Subscription.ResourceType.AI_PROMPT
+ and self.partial
+ and existing is not None
+ and "delivery_config" in attrs
+ ):
+ existing_delivery_config = existing.delivery_config if isinstance(existing.delivery_config, dict) else {}
+ attrs["delivery_config"] = {**existing_delivery_config, **attrs["delivery_config"]}
content_validators: dict[str, Callable[[dict, Optional[Subscription]], None]] = {
Subscription.ResourceType.INSIGHT: self._validate_insight_content,
Subscription.ResourceType.DASHBOARD: self._validate_dashboard_content,
@@ -591,6 +621,12 @@ class SubscriptionSerializer(serializers.ModelSerializer):
if "delivery_config" in attrs
else (self.instance.delivery_config if self.instance else None)
) or {}
+ if resource_type != Subscription.ResourceType.AI_PROMPT and any(
+ field in effective_delivery_config for field in AI_DELIVERY_DISPLAY_FIELDS
+ ):
+ raise ValidationError(
+ {"delivery_config": ["AI delivery display options are only supported for prompt subscriptions."]}
+ )
# Reject re-enables of subscriptions whose delivery prerequisite is still
# permanently broken — otherwise the next delivery would just auto-disable
diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.py
index a0c14498e260..4a44a940ed3c 100644
--- a/ee/api/test/test_subscription.py
+++ b/ee/api/test/test_subscription.py
@@ -753,6 +753,25 @@ class TestSubscriptionTemporal(APILicensedTest):
assert response.status_code == status.HTTP_200_OK
assert response.json()["delivery_config"] == {"post_all_insights_in_main_message": True}
+ def test_patch_replaces_delivery_config_on_non_ai_subscription(self):
+ integration = Integration.objects.create(
+ team=self.team, kind="slack", config={"scope": "chat:write,files:write"}
+ )
+ subscription_id = self._create_subscription(
+ target_type="slack",
+ target_value="C1234|#general",
+ integration_id=integration.id,
+ delivery_config={"post_all_insights_in_main_message": True},
+ ).json()["id"]
+
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{subscription_id}",
+ {"delivery_config": {}},
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["delivery_config"] == {}
+
def test_post_all_in_main_requires_files_write_scope(self):
integration = Integration.objects.create(
team=self.team, kind="slack", config={"scope": "chat:write,channels:read"}
@@ -2965,15 +2984,30 @@ class TestAISubscriptionAPI(APILicensedTest):
[
(
"prompt_change_clears_plan",
+ {},
{"prompt": "A completely different question about retention?"},
False,
AIQueryPlanStatus.NOT_FROZEN.value,
),
- ("title_change_keeps_plan", {"title": "Renamed"}, True, AIQueryPlanStatus.FROZEN.value),
+ (
+ "enabling_images_clears_plan",
+ {"include_images": False},
+ {"delivery_config": {"include_images": True}},
+ False,
+ AIQueryPlanStatus.NOT_FROZEN.value,
+ ),
+ (
+ "disabling_images_keeps_plan",
+ {"include_images": True},
+ {"delivery_config": {"include_images": False}},
+ True,
+ AIQueryPlanStatus.FROZEN.value,
+ ),
+ ("title_change_keeps_plan", {}, {"title": "Renamed"}, True, AIQueryPlanStatus.FROZEN.value),
]
)
- def test_editing_prompt_invalidates_frozen_query_plan(
- self, mock_is_cloud, mock_flag, mock_sync, _name, body, plan_survives, expected_status
+ def test_edits_that_require_replanning_invalidate_frozen_query_plan(
+ self, mock_is_cloud, mock_flag, mock_sync, _name, delivery_config, body, plan_survives, expected_status
):
self._mock_temporal(mock_sync)
frozen = {
@@ -2981,7 +3015,7 @@ class TestAISubscriptionAPI(APILicensedTest):
"plan": VALID_AI_QUERY_PLAN,
}
sub_id = self._create_subscription_for("ai_prompt")
- Subscription.objects.filter(id=sub_id).update(ai_query_plan=frozen)
+ Subscription.objects.filter(id=sub_id).update(ai_query_plan=frozen, delivery_config=delivery_config)
response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", body)
assert response.status_code == status.HTTP_200_OK, response.json()
@@ -3412,6 +3446,131 @@ class TestAISubscriptionAPI(APILicensedTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
assert "ai_prompt_config" in str(response.json()), response.json()
+ def test_ai_delivery_display_flags_round_trip_independently(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ display_flags = {
+ "include_images": True,
+ "include_feedback": False,
+ "include_manage_link": True,
+ "include_posthog_hint": False,
+ }
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(delivery_config=display_flags),
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ expected_config = {"post_all_insights_in_main_message": False, **display_flags}
+ assert response.json()["delivery_config"] == expected_config
+ subscription = Subscription.objects.get(id=response.json()["id"])
+ assert subscription.delivery_config == expected_config
+
+ @parameterized.expand(
+ [
+ ("changed_flag", False, 1),
+ ("unchanged_flag", True, 0),
+ ]
+ )
+ def test_patch_merges_ai_delivery_display_flags(
+ self, mock_is_cloud, mock_flag, mock_sync, _name, include_images, expected_redelivery_count
+ ):
+ self._enable_ai()
+ mock_client = self._mock_temporal(mock_sync)
+ display_flags = {
+ "include_images": True,
+ "include_feedback": False,
+ "include_manage_link": False,
+ "include_posthog_hint": False,
+ }
+ create_response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(delivery_config=display_flags),
+ )
+ assert create_response.status_code == status.HTTP_201_CREATED, create_response.json()
+ mock_client.start_workflow.reset_mock()
+
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{create_response.json()['id']}",
+ {"delivery_config": {"include_images": include_images}},
+ )
+
+ assert patch_response.status_code == status.HTTP_200_OK, patch_response.json()
+ expected_config = {
+ "post_all_insights_in_main_message": False,
+ **display_flags,
+ "include_images": include_images,
+ }
+ assert patch_response.json()["delivery_config"] == expected_config
+ subscription = Subscription.objects.get(id=create_response.json()["id"])
+ assert subscription.delivery_config == expected_config
+ assert mock_client.start_workflow.call_count == expected_redelivery_count
+
+ def test_patch_replaces_malformed_existing_ai_delivery_config(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ create_response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(),
+ )
+ assert create_response.status_code == status.HTTP_201_CREATED, create_response.json()
+ subscription_id = create_response.json()["id"]
+ Subscription.objects.filter(id=subscription_id).update(delivery_config="invalid")
+
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{subscription_id}",
+ {"delivery_config": {"include_images": False}},
+ )
+
+ assert patch_response.status_code == status.HTTP_200_OK, patch_response.json()
+ expected_config = {"include_images": False}
+ assert patch_response.json()["delivery_config"] == expected_config
+ assert Subscription.objects.get(id=subscription_id).delivery_config == expected_config
+
+ def test_patch_validates_the_merged_delivery_config(self, mock_is_cloud, mock_flag, mock_sync):
+ self._enable_ai()
+ self._mock_temporal(mock_sync)
+ integration = Integration.objects.create(
+ team=self.team, kind="slack", config={"scope": "chat:write,files:write"}
+ )
+ without_files_write = Integration.objects.create(
+ team=self.team, kind="slack", config={"scope": "chat:write,channels:read"}
+ )
+ create_response = self.client.post(
+ f"/api/projects/{self.team.id}/subscriptions",
+ self._make_ai_payload(
+ target_type="slack",
+ target_value="C1234|#general",
+ integration_id=integration.id,
+ delivery_config={"post_all_insights_in_main_message": True},
+ ),
+ )
+ assert create_response.status_code == status.HTTP_201_CREATED, create_response.json()
+
+ patch_response = self.client.patch(
+ f"/api/projects/{self.team.id}/subscriptions/{create_response.json()['id']}",
+ {
+ "integration_id": without_files_write.id,
+ "delivery_config": {"include_images": False},
+ },
+ )
+
+ assert patch_response.status_code == status.HTTP_400_BAD_REQUEST, patch_response.json()
+ assert "files:write" in str(patch_response.json())
+
+ def test_ai_delivery_display_flags_are_rejected_for_insight_subscriptions(
+ self, mock_is_cloud, mock_flag, mock_sync
+ ):
+ self._mock_temporal(mock_sync)
+ payload = self._insight_payload()
+ payload["delivery_config"] = {"include_images": False}
+
+ response = self.client.post(f"/api/projects/{self.team.id}/subscriptions", payload)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert "only supported for prompt subscriptions" in str(response.json())
+
class TestSubscriptionObjectAccessControl(APILicensedTest):
def setUp(self):
diff --git a/posthog/models/test/test_subscription_model.py b/posthog/models/test/test_subscription_model.py
index 8897cb9c6e26..5af100cfccc5 100644
--- a/posthog/models/test/test_subscription_model.py
+++ b/posthog/models/test/test_subscription_model.py
@@ -93,6 +93,26 @@ class TestSubscriptionScheduling:
assert next_delivery_date is None
+class TestSubscriptionDeliveryConfig:
+ @parameterized.expand(
+ [
+ ("omitted_option", {}, "include_feedback", True),
+ ("malformed_config", "invalid", "include_images", True),
+ ("enabled_option", {"include_manage_link": True}, "include_manage_link", True),
+ ("disabled_option", {"include_manage_link": False}, "include_manage_link", False),
+ ]
+ )
+ def test_includes_delivery_part(self, _name: str, delivery_config, option: str, expected: bool) -> None:
+ subscription = Subscription(
+ delivery_config=delivery_config,
+ frequency=Subscription.SubscriptionFrequency.WEEKLY,
+ interval=1,
+ start_date=datetime(2026, 1, 1, tzinfo=ZoneInfo("UTC")),
+ )
+
+ assert subscription.includes_delivery_part(option) is expected
+
+
@patch.object(settings, "JWT_SIGNING_KEY", "not-so-secret")
@freeze_time("2022-01-01")
class TestSubscription(BaseTest):
@@ -226,6 +246,29 @@ class TestSubscription(BaseTest):
subscription.save()
assert old_date == subscription.next_delivery_date
+ @parameterized.expand(
+ [
+ ("enabling_images_clears_plan", {"include_images": False}, {"include_images": True}, False),
+ ("images_already_enabled_keeps_plan", {"include_images": True}, {"include_images": True}, True),
+ ]
+ )
+ def test_deferred_delivery_config_preserves_plan_invalidation_state(
+ self, _name: str, initial_config: dict, updated_config: dict, plan_survives: bool
+ ) -> None:
+ plan = {"version": 1, "plan": {}}
+ subscription = self._create_subscription(
+ prompt="Summarize signups",
+ delivery_config=initial_config,
+ ai_query_plan=plan,
+ )
+
+ deferred_subscription = Subscription.objects.defer("delivery_config").get(id=subscription.id)
+ deferred_subscription.delivery_config = updated_config
+ deferred_subscription.save(update_fields=["delivery_config"])
+
+ subscription.refresh_from_db()
+ assert subscription.ai_query_plan == (plan if plan_survives else None)
+
@freeze_time("2022-01-11 09:55:00")
def test_set_next_delivery_date_when_in_upcoming_delta(self):
subscription = Subscription.objects.create(
diff --git a/posthog/templates/email/ai_subscription_report.html b/posthog/templates/email/ai_subscription_report.html
index a9199928d0df..53e7a05671da 100644
--- a/posthog/templates/email/ai_subscription_report.html
+++ b/posthog/templates/email/ai_subscription_report.html
@@ -12,14 +12,18 @@
{% endfor %}
</div>
{% endif %}
- <div class="mb mt text-center">
- <a class="button primary" href="{{ subscription_url }}">Manage subscription</a>
- </div>
- <p class="text-center">
- Was this report useful?
- <a href="{{ feedback_positive_url }}">👍 Yes</a> ·
- <a href="{{ feedback_negative_url }}">👎 No</a>
- </p>
+ {% if include_manage_link %}
+ <div class="mb mt text-center">
+ <a class="button primary" href="{{ subscription_url }}">Manage subscription</a>
+ </div>
+ {% endif %}
+ {% if include_feedback %}
+ <p class="text-center">
+ Was this report useful?
+ <a href="{{ feedback_positive_url }}">👍 Yes</a> ·
+ <a href="{{ feedback_negative_url }}">👎 No</a>
+ </p>
+ {% endif %}
<p class="text-center text-muted">
<a href="{{ unsubscribe_url }}">Unsubscribe from this report</a>
</p>
diff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.py
index 9fef749889f8..483077da45e1 100644
--- a/products/exports/backend/models/subscription.py
+++ b/products/exports/backend/models/subscription.py
@@ -174,8 +174,8 @@ class Subscription(ModelActivityMixin, models.Model):
prompt = models.TextField(null=True, blank=True)
# Frozen by the first successful delivery so later runs reuse the same HogQL deterministically
- # instead of re-running the planner LLM; cleared on prompt change (see save()). Shape is versioned —
- # see report_pipeline._plan_to_freeze.
+ # instead of re-running the planner LLM. Edits that require a fresh plan clear it in save().
+ # Shape is versioned; see report_pipeline._plan_to_freeze.
ai_query_plan = models.JSONField(null=True, blank=True, default=None)
# Source of truth for the shape: ee.api.subscription.AIPromptConfigSerializer (writes) and
# normalize_ai_window below (reads).
@@ -232,6 +232,8 @@ class Subscription(ModelActivityMixin, models.Model):
self._rrule = self.rrule
if "prompt" not in self.get_deferred_fields():
self._initial_prompt = self.prompt
+ if "delivery_config" not in self.get_deferred_fields():
+ self._initial_include_images = self.includes_delivery_part("include_images")
def save(self, *args, **kwargs) -> None:
# Only if the schedule has changed do we update the next delivery date
@@ -240,14 +242,36 @@ class Subscription(ModelActivityMixin, models.Model):
self.set_next_delivery_date()
if "update_fields" in kwargs:
kwargs["update_fields"].append("next_delivery_date")
- # A changed prompt invalidates the frozen AI query plan at the model level (same pattern as
- # next_delivery_date above), so ORM-path edits can't leave a plan answering the old prompt.
- if self.id and self.prompt != getattr(self, "_initial_prompt", self.prompt) and self.ai_query_plan is not None:
+ include_images = self.includes_delivery_part("include_images")
+ initial_include_images = getattr(self, "_initial_include_images", None)
+ if initial_include_images is None and self.id:
+ persisted_delivery_config = (
+ type(self).objects.filter(id=self.id).values_list("delivery_config", flat=True).first()
+ )
+ initial_include_images = (
+ self._delivery_config_includes(persisted_delivery_config, "include_images")
+ if persisted_delivery_config is not None
+ else include_images
+ )
+ prompt_changed = self.prompt != getattr(self, "_initial_prompt", self.prompt)
+ images_just_enabled = include_images and not initial_include_images
+ # Frozen plans skip chart validation while images are hidden. Enabling images needs a new
+ # plan, while feedback and footer options only affect rendering.
+ if self.id and (prompt_changed or images_just_enabled) and self.ai_query_plan is not None:
self.ai_query_plan = None
if kwargs.get("update_fields") is not None:
kwargs["update_fields"] = [*kwargs["update_fields"], "ai_query_plan"]
super().save(*args, **kwargs)
self._initial_prompt = self.prompt
+ self._initial_include_images = include_images
+
+ @staticmethod
+ def _delivery_config_includes(delivery_config: Any, option: str) -> bool:
+ config = delivery_config if isinstance(delivery_config, dict) else {}
+ return bool(config.get(option, True))
+
+ def includes_delivery_part(self, option: str) -> bool:
+ return self._delivery_config_includes(self.delivery_config, option)
@classmethod
def derive_resource_type(cls, insight_id: int | None, dashboard_id: int | None, prompt: str | None) -> str:
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
index 750184913003..e5a01fcef37f 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py
@@ -425,7 +425,7 @@ async def _deliver_ai_subscription(
),
)
if subscription.target_type == Subscription.SubscriptionTarget.TEAMS:
- card = build_ai_teams_card(subscription, markdown, delivery_id=delivery_id)
+ card = build_ai_teams_card(subscription, markdown, delivery_id=delivery_id, charts=chart_images)
return await deliver_teams_webhook(subscription, recipient_results, body=card)
# `validate_subscription_for_delivery` auto-disables unsupported targets up front,
# so reaching here means an invariant was violated.
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
index 8a04957132aa..927284f60416 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py
@@ -4,6 +4,8 @@ from datetime import UTC, datetime, timedelta
from typing import Any
from urllib.parse import urlencode
+from django.db.models import Q
+
import nh3
import structlog
from markdown_it import MarkdownIt
@@ -192,12 +194,25 @@ def _resolve_subscription_context(
return team, subscription.created_by, window, subscription.ai_query_plan
-def _persist_ai_query_plan(subscription_id: int, team_id: int, prompt: str | None, plan: dict) -> bool:
+def _persist_ai_query_plan(
+ subscription_id: int,
+ team_id: int,
+ prompt: str | None,
+ plan: dict,
+ *,
+ expected_include_images: bool,
+) -> bool:
+ image_state = Q(delivery_config__include_images=expected_include_images)
+ if expected_include_images:
+ # Existing subscriptions omit this key and default to including images.
+ image_state |= ~Q(delivery_config__has_key="include_images")
+
# Targeted update, never a full save() — that would re-emit the activity-log/analytics signals.
- # Filtering on the planning-time prompt closes a race: a prompt edited mid-generation clears the
- # plan via Subscription.save(), and this no-ops instead of re-freezing a plan for the old prompt.
+ # Matching both planning inputs prevents a concurrent edit from restoring an invalidated plan.
return bool(
- Subscription.objects.filter(id=subscription_id, team_id=team_id, prompt=prompt).update(ai_query_plan=plan)
+ Subscription.objects.filter(id=subscription_id, team_id=team_id, prompt=prompt)
+ .filter(image_state)
+ .update(ai_query_plan=plan)
)
@@ -209,6 +224,7 @@ async def build_ai_subscription_report(subscription: Subscription) -> AiReportRe
if user is None:
raise PromptRejectedError("AI subscription has no creator (created_by deleted); cannot deliver.")
+ include_images = subscription.includes_delivery_part("include_images")
result = await generate_ai_report(
team=team,
user=user,
@@ -216,13 +232,19 @@ async def build_ai_subscription_report(subscription: Subscription) -> AiReportRe
window=window,
ai_query_plan=ai_query_plan,
trace_correlation_id=subscription.id,
+ include_charts=include_images,
+ include_manage_link=subscription.includes_delivery_part("include_manage_link"),
)
if result.plan_to_persist is not None:
plan_persisted = False
try:
plan_persisted = await database_sync_to_async(_persist_ai_query_plan, thread_sensitive=False)(
- subscription.id, subscription.team_id, subscription.prompt, result.plan_to_persist
+ subscription.id,
+ subscription.team_id,
+ subscription.prompt,
+ result.plan_to_persist,
+ expected_include_images=include_images,
)
except Exception as exc:
# The frozen plan is an optimization — losing this write must not abort the delivery (the
@@ -299,7 +321,9 @@ def send_email_ai_subscription_report(
template_context={
"title": title,
"rendered_html": html,
- "charts": charts or [],
+ "charts": (charts or []) if subscription.includes_delivery_part("include_images") else [],
+ "include_feedback": subscription.includes_delivery_part("include_feedback"),
+ "include_manage_link": subscription.includes_delivery_part("include_manage_link"),
# `delivery` lets the frontend capture `ai_report_clicked` on landing — the
# click-through signal for whether delivered reports actually get read.
"subscription_url": f"{subscription_url}?{utm_tags}&delivery={delivery_id}",
@@ -364,7 +388,7 @@ def _build_ai_slack_message(
{"type": "section", "text": {"type": "mrkdwn", "text": f"*{title}*"}},
{"type": "section", "text": {"type": "mrkdwn", "text": first_section}},
]
- for chart in charts or []:
+ for chart in (charts or []) if subscription.includes_delivery_part("include_images") else []:
caption = chart.get("title") or "Chart"
image_block: dict = {
"type": "image",
@@ -382,20 +406,24 @@ def _build_ai_slack_message(
subscription_url = subscription.url or absolute_uri(
f"/project/{subscription.team_id}/subscriptions/{subscription.id}"
)
- feedback_positive_url = _build_feedback_url(subscription_url, delivery_id, "positive", "slack")
- feedback_negative_url = _build_feedback_url(subscription_url, delivery_id, "negative", "slack")
-
- action_elements: list[dict] = [
- {
- "type": "button",
- "text": {"type": "plain_text", "text": "Manage subscription"},
- "url": f"{subscription_url}?{utm_tags}",
- }
- ]
- blocks.extend(
- [
- {"type": "divider"},
- {"type": "actions", "elements": action_elements},
+ footer_blocks: list[dict] = []
+ if subscription.includes_delivery_part("include_manage_link"):
+ footer_blocks.append(
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Manage subscription"},
+ "url": f"{subscription_url}?{utm_tags}",
+ }
+ ],
+ }
+ )
+ if subscription.includes_delivery_part("include_feedback"):
+ feedback_positive_url = _build_feedback_url(subscription_url, delivery_id, "positive", "slack")
+ feedback_negative_url = _build_feedback_url(subscription_url, delivery_id, "negative", "slack")
+ footer_blocks.append(
{
"type": "context",
"elements": [
@@ -407,12 +435,15 @@ def _build_ai_slack_message(
),
}
],
- },
- ]
- )
- # AI consent is enforced upstream before this report is built, so the hint always shows here.
- if explore_hint := build_explore_hint(integration, utm_tags=utm_tags, ai_enabled=True):
- blocks.append(explore_hint)
+ }
+ )
+ # AI consent is enforced before report generation, so this renderer only applies the delivery option.
+ if subscription.includes_delivery_part("include_posthog_hint"):
+ if explore_hint := build_explore_hint(integration, utm_tags=utm_tags, ai_enabled=True):
+ footer_blocks.append(explore_hint)
+ if footer_blocks:
+ blocks.append({"type": "divider"})
+ blocks.extend(footer_blocks)
thread_messages = [
{"blocks": [{"type": "section", "text": {"type": "mrkdwn", "text": section}}]} for section in sections[1:]
@@ -429,25 +460,36 @@ async def send_slack_ai_subscription_report(
delivery_id: uuid.UUID,
charts: list[dict] | None = None,
) -> SlackDeliveryResult:
+ # Resolve the charts the message will really carry, so the retry-without-charts decision
+ # cannot promise a different payload than the first send: a report that hides its charts
+ # would otherwise resend an identical message and double the posts Slack rate-limits.
+ effective_charts = charts if subscription.includes_delivery_part("include_images") else None
+
def build(with_charts: list[dict] | None) -> SlackMessage:
return _build_ai_slack_message(
subscription, markdown, delivery_id=delivery_id, integration=integration, charts=with_charts
)
try:
- return await deliver_slack_message_data(integration, subscription, build(charts))
+ return await deliver_slack_message_data(integration, subscription, build(effective_charts))
except SlackApiError as exc:
- if not charts or exc.response.get("error") != "invalid_blocks":
+ if not effective_charts or exc.response.get("error") != "invalid_blocks":
raise
logger.warning(
"ai_report.slack_charts_rejected_resending_without_them",
subscription_id=subscription.id,
- chart_count=len(charts),
+ chart_count=len(effective_charts),
)
return await deliver_slack_message_data(integration, subscription, build(None))
-def build_ai_teams_card(subscription: Subscription, markdown: str, *, delivery_id: uuid.UUID) -> dict[str, Any]:
+def build_ai_teams_card(
+ subscription: Subscription,
+ markdown: str,
+ *,
+ delivery_id: uuid.UUID,
+ charts: list[dict] | None = None,
+) -> dict[str, Any]:
"""Adaptive Card for an AI report. Adaptive Cards render a restricted markdown subset in a
TextBlock, so the report goes through mostly as written and a table degrades to plain text."""
title = strip_external_links_markdown(subscription.title or "Your PostHog AI report")
@@ -459,9 +501,11 @@ def build_ai_teams_card(subscription: Subscription, markdown: str, *, delivery_i
sections = _split_text_into_chunks(report[:_TEAMS_REPORT_CHUNKING_LIMIT], TEAMS_TEXT_BLOCK_LIMIT)
heading = f"**{title}**"
- shortened_notice = (
- f"This report was shortened to fit. [Read all of it in PostHog]({subscription_url}?{TEAMS_UTM_TAGS})"
- )
+ include_manage_link = subscription.includes_delivery_part("include_manage_link")
+ include_feedback = subscription.includes_delivery_part("include_feedback")
+ shortened_notice = "This report was shortened to fit."
+ if include_manage_link:
+ shortened_notice += f" [Read all of it in PostHog]({subscription_url}?{TEAMS_UTM_TAGS})"
feedback_positive_url = _build_feedback_url(subscription_url, delivery_id, "positive", "teams")
feedback_negative_url = _build_feedback_url(subscription_url, delivery_id, "negative", "teams")
feedback = f"Was this report useful? [👍 Yes]({feedback_positive_url}) · [👎 No]({feedback_negative_url})"
@@ -473,7 +517,7 @@ def build_ai_teams_card(subscription: Subscription, markdown: str, *, delivery_i
TEAMS_CARD_TEXT_BUDGET
- teams_byte_size(heading)
- teams_byte_size(shortened_notice)
- - teams_byte_size(feedback)
+ - (teams_byte_size(feedback) if include_feedback else 0)
)
kept: list[str] = []
@@ -494,11 +538,25 @@ def build_ai_teams_card(subscription: Subscription, markdown: str, *, delivery_i
body.extend(teams_text_block(section) for section in kept)
else:
body.append(teams_text_block("_No report content was generated._"))
+ for chart in (charts or []) if subscription.includes_delivery_part("include_images") else []:
+ body.append(
+ {
+ "type": "Image",
+ "url": chart["image_url"],
+ "size": "Stretch",
+ "altText": chart.get("title") or "Chart",
+ }
+ )
if over_budget or len(kept) < len(sections) or len(report) > _TEAMS_REPORT_CHUNKING_LIMIT:
body.append(teams_text_block(shortened_notice, is_subtle=True))
- body.append(teams_text_block(feedback, is_subtle=True))
+ if include_feedback:
+ body.append(teams_text_block(feedback, is_subtle=True))
- actions = [teams_open_url_action("Manage subscription", f"{subscription_url}?{TEAMS_UTM_TAGS}")]
+ actions = (
+ [teams_open_url_action("Manage subscription", f"{subscription_url}?{TEAMS_UTM_TAGS}")]
+ if include_manage_link
+ else []
+ )
return teams_card_message(body, actions)
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
index 6912e20663bb..6de57577fe0f 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/report_pipeline.py
@@ -116,12 +116,14 @@ _RETRYABLE_QUERY_ERRORS: tuple[type[BaseException], ...] = (
)
-def _all_queries_failed_notice(total_steps: int) -> str:
+def _all_queries_failed_notice(total_steps: int, *, include_manage_link: bool = True) -> str:
noun = "the query" if total_steps == 1 else f"all {total_steps} queries"
- return (
- f"> ⚠️ This report could not be generated — {noun} the assistant wrote failed to run. "
- "Use the Manage subscription link to review the generated queries and the errors they hit.\n\n"
- )
+ notice = f"> ⚠️ This report could not be generated — {noun} the assistant wrote failed to run."
+ # Every channel renders this one markdown body, so a report whose recipients get no manage
+ # control must not tell them to use it.
+ if include_manage_link:
+ notice += " Use the Manage subscription link to review the generated queries and the errors they hit."
+ return notice + "\n\n"
def _validate_step_chart(
@@ -210,6 +212,8 @@ async def generate_ai_report(
window: ReportWindow,
ai_query_plan: Optional[dict] = None,
trace_correlation_id: Optional[Union[int, str]] = None,
+ include_charts: bool = True,
+ include_manage_link: bool = True,
) -> AiReportResult:
if user is None:
raise PromptRejectedError("AI report must have a user to run.")
@@ -246,7 +250,11 @@ async def generate_ai_report(
else:
spec = await _plan(team=team, user=user, prompt=prompt, window=window, trace_id=trace_correlation_id)
freshly_planned = True
- charts_enabled_for_team = await database_sync_to_async(charts_enabled, thread_sensitive=False)(team, user)
+ # A report that will not show its charts must not build or render them: each render is a
+ # headless PNG export holding a slot in a pool every concurrent report shares.
+ charts_enabled_for_team = include_charts and await database_sync_to_async(
+ charts_enabled, thread_sensitive=False
+ )(team, user)
execution = await _execute_plan(
spec, team, user, window, trace_correlation_id, charts_enabled_for_team=charts_enabled_for_team
)
@@ -313,7 +321,7 @@ async def generate_ai_report(
# Every query failed, so the body is all "could not be computed" placeholders. Lead with a
# deterministic notice (not left to the synthesis LLM) so the recipient gets a clear signal
# instead of a confident-looking but empty report.
- report = _all_queries_failed_notice(total_steps) + report
+ report = _all_queries_failed_notice(total_steps, include_manage_link=include_manage_link) + report
plan_to_persist = _plan_to_freeze(
spec.plan,
freshly_planned=freshly_planned,
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
index 288d148e2718..dfb3e4582a63 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_delivery.py
@@ -13,6 +13,7 @@ from slack_sdk.errors import SlackApiError
from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES
from products.exports.backend.models.subscription import AIQueryPlanStatus, Subscription, SubscriptionDelivery
+from products.exports.backend.temporal.subscriptions.ai_subscription.activities import _deliver_ai_subscription
from products.exports.backend.temporal.subscriptions.ai_subscription.delivery import (
CHART_IMAGE_URL_TTL,
SLACK_MRKDWN_SECTION_LIMIT,
@@ -31,12 +32,20 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.delivery im
)
from products.exports.backend.temporal.subscriptions.ai_subscription.report_pipeline import AiReportResult
from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generator import ReportWindow
-from products.exports.backend.temporal.subscriptions.types import AI_REPORT_WINDOW_END_KEY, SubscriptionTriggerType
+from products.exports.backend.temporal.subscriptions.types import (
+ AI_REPORT_CHARTS_KEY,
+ AI_REPORT_SNAPSHOT_KEY,
+ AI_REPORT_WINDOW_END_KEY,
+ DeliverSubscriptionInputs,
+ DeliverSubscriptionResult,
+ SubscriptionTriggerType,
+)
from ee.tasks.subscriptions.slack_subscriptions import SlackMessage
from ee.tasks.subscriptions.teams_subscriptions import TEAMS_CARD_TEXT_BUDGET
_DELIVERY = "products.exports.backend.temporal.subscriptions.ai_subscription.delivery"
+_ACTIVITIES = "products.exports.backend.temporal.subscriptions.ai_subscription.activities"
_PARA = "a" * (SLACK_MRKDWN_SECTION_LIMIT - 100)
_DELIVERY_ID = uuid.UUID("12345678-1234-5678-1234-567812345678")
@@ -211,6 +220,10 @@ def _mock_subscription() -> MagicMock:
sub.url = _SUBSCRIPTION_URL
sub.team_id = 1
sub.id = 2
+ sub.delivery_config = {}
+ sub.includes_delivery_part.side_effect = lambda option: Subscription._delivery_config_includes(
+ sub.delivery_config, option
+ )
return sub
@@ -294,6 +307,30 @@ class TestChartsOnSlackMessages:
assert all(block["type"] != "image" for block in sent[1])
assert any("A short report." in block.get("text", {}).get("text", "") for block in sent[1])
+ async def test_a_hidden_chart_does_not_trigger_the_resend(self) -> None:
+ # A report that hides its charts already sends a payload with no image block, so the
+ # retry would repeat an identical message and double the posts Slack rate-limits.
+ subscription = _mock_subscription()
+ subscription.delivery_config = {"include_images": False}
+ sent: list[list[dict]] = []
+
+ async def _deliver(_integration, _subscription, message_data):
+ sent.append(message_data.blocks)
+ raise SlackApiError("bad blocks", response={"error": "invalid_blocks"})
+
+ with patch(f"{_DELIVERY}.deliver_slack_message_data", side_effect=_deliver):
+ with pytest.raises(SlackApiError):
+ await send_slack_ai_subscription_report(
+ subscription=subscription,
+ markdown="A short report.",
+ integration=MagicMock(),
+ delivery_id=_DELIVERY_ID,
+ charts=[_CHART],
+ )
+
+ assert len(sent) == 1
+ assert all(block["type"] != "image" for block in sent[0])
+
async def test_a_slack_error_that_is_not_about_blocks_still_raises(self) -> None:
with patch(
f"{_DELIVERY}.deliver_slack_message_data",
@@ -340,12 +377,118 @@ class TestBuildAISlackMessage:
for block in thread_msg["blocks"]:
assert block["text"]["text"].strip(), "thread section text must be non-empty"
+ def test_minimal_delivery_keeps_only_the_title_and_report(self) -> None:
+ subscription = _mock_subscription()
+ subscription.delivery_config = {
+ "include_images": False,
+ "include_feedback": False,
+ "include_manage_link": False,
+ "include_posthog_hint": False,
+ }
+
+ message = _build_ai_slack_message(
+ subscription,
+ "A short report.",
+ delivery_id=_DELIVERY_ID,
+ integration=_mock_integration(REQUIRED_SLACK_SCOPES),
+ charts=[_CHART],
+ )
+
+ assert [block["type"] for block in message.blocks] == ["section", "section"]
+ assert message.blocks[1]["text"]["text"] == "A short report."
+
+ def test_with_images_delivery_keeps_charts_without_posthog_controls(self) -> None:
+ subscription = _mock_subscription()
+ subscription.delivery_config = {
+ "include_images": True,
+ "include_feedback": False,
+ "include_manage_link": False,
+ "include_posthog_hint": False,
+ }
+
+ message = _build_ai_slack_message(
+ subscription,
+ "A short report.",
+ delivery_id=_DELIVERY_ID,
+ integration=_mock_integration(REQUIRED_SLACK_SCOPES),
+ charts=[_CHART],
+ )
+
+ assert [block["type"] for block in message.blocks] == ["section", "section", "image"]
+ assert message.blocks[2]["image_url"] == _CHART["image_url"]
+
class TestBuildAITeamsCard:
def _body(self, markdown: str) -> list[dict]:
card = build_ai_teams_card(_mock_subscription(), markdown, delivery_id=_DELIVERY_ID)
return card["attachments"][0]["content"]["body"]
+ def test_charts_follow_the_report_text(self) -> None:
+ card = build_ai_teams_card(_mock_subscription(), "A short report.", delivery_id=_DELIVERY_ID, charts=[_CHART])
+ body = card["attachments"][0]["content"]["body"]
+
+ image_blocks = [block for block in body if block["type"] == "Image"]
+ assert image_blocks == [
+ {
+ "type": "Image",
+ "url": _CHART["image_url"],
+ "size": "Stretch",
+ "altText": _CHART["title"],
+ }
+ ]
+
+ def test_hidden_charts_do_not_appear(self) -> None:
+ subscription = _mock_subscription()
+ subscription.delivery_config = {"include_images": False}
+
+ card = build_ai_teams_card(subscription, "A short report.", delivery_id=_DELIVERY_ID, charts=[_CHART])
+ body = card["attachments"][0]["content"]["body"]
+
+ assert all(block["type"] != "Image" for block in body)
+
+ @pytest.mark.asyncio
+ async def test_delivery_includes_generated_chart_urls(self) -> None:
+ subscription = _mock_subscription()
+ subscription.target_type = Subscription.SubscriptionTarget.TEAMS
+
+ with (
+ patch(
+ f"{_ACTIVITIES}._load_snapshot",
+ new=AsyncMock(
+ return_value={
+ AI_REPORT_SNAPSHOT_KEY: "A short report.",
+ AI_REPORT_CHARTS_KEY: [{"export_asset_id": 99, "title": "signups by day"}],
+ }
+ ),
+ ),
+ patch(f"{_ACTIVITIES}.build_chart_image_urls", return_value=[_CHART]),
+ patch(
+ f"{_ACTIVITIES}.deliver_teams_webhook",
+ new=AsyncMock(return_value=DeliverSubscriptionResult()),
+ ) as deliver_teams,
+ ):
+ await _deliver_ai_subscription(
+ subscription,
+ DeliverSubscriptionInputs(
+ subscription_id=subscription.id,
+ exported_asset_ids=[],
+ total_insight_count=0,
+ delivery_id=_DELIVERY_ID,
+ ),
+ [],
+ )
+
+ assert deliver_teams.await_args is not None
+ body = deliver_teams.await_args.kwargs["body"]["attachments"][0]["content"]["body"]
+ assert [block for block in body if block["type"] == "Image"] == [
+ {
+ "type": "Image",
+ "url": _CHART["image_url"],
+ "size": "Stretch",
+ "altText": _CHART["title"],
+ }
+ ]
+
def test_long_report_is_split_across_text_blocks(self) -> None:
body = self._body("\n\n".join("x" * (TEAMS_TEXT_BLOCK_LIMIT - 50) for _ in range(3)))
@@ -383,6 +526,40 @@ class TestBuildAITeamsCard:
assert body[0]["text"] == "**Open report**"
+ def test_minimal_delivery_removes_feedback_and_manage_action(self) -> None:
+ subscription = _mock_subscription()
+ subscription.delivery_config = {
+ "include_images": False,
+ "include_feedback": False,
+ "include_manage_link": False,
+ "include_posthog_hint": False,
+ }
+
+ card = build_ai_teams_card(subscription, "A short report.", delivery_id=_DELIVERY_ID)
+ content = card["attachments"][0]["content"]
+
+ assert "Was this report useful?" not in str(content["body"])
+ assert content["actions"] == []
+
+ def test_minimal_delivery_shortening_notice_has_no_posthog_link(self) -> None:
+ subscription = _mock_subscription()
+ subscription.delivery_config = {
+ "include_images": False,
+ "include_feedback": False,
+ "include_manage_link": False,
+ "include_posthog_hint": False,
+ }
+
+ card = build_ai_teams_card(
+ subscription,
+ "\n\n".join("x" * (TEAMS_TEXT_BLOCK_LIMIT - 50) for _ in range(20)),
+ delivery_id=_DELIVERY_ID,
+ )
+ content = card["attachments"][0]["content"]
+
+ assert "This report was shortened to fit." in str(content["body"])
+ assert "Read all of it in PostHog" not in str(content["body"])
+
def _mock_integration(scopes: frozenset[str]) -> MagicMock:
integration = MagicMock()
@@ -473,20 +650,67 @@ class TestFeedbackFooter:
context = self._send_email_and_get_context()
assert f"&delivery={_DELIVERY_ID}" in context["subscription_url"]
+ def test_minimal_email_keeps_unsubscribe_without_images_or_posthog_controls(self) -> None:
+ subscription = _mock_subscription()
+ subscription.delivery_config = {
+ "include_images": False,
+ "include_feedback": False,
+ "include_manage_link": False,
+ "include_posthog_hint": False,
+ }
+ with (
+ patch(
+ "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.EmailMessage"
+ ) as email_message,
+ patch(
+ "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.get_unsubscribe_token",
+ return_value="tok",
+ ),
+ patch(
+ "products.exports.backend.temporal.subscriptions.ai_subscription.delivery.raise_if_delivery_rejected"
+ ),
+ ):
+ send_email_ai_subscription_report(
+ subscription=subscription,
+ markdown="Report body",
+ delivery_run_id="run-1",
+ delivery_id=_DELIVERY_ID,
+ charts=[_CHART],
+ )
+
+ html = render_to_string("email/ai_subscription_report.html", email_message.call_args.kwargs["template_context"])
+
+ assert "Report body" in html
+ assert _CHART["image_url"] not in html
+ assert "Manage subscription" not in html
+ assert "Was this report useful?" not in html
+ assert "Unsubscribe from this report" in html
-class TestPersistAiQueryPlanRaceGuard(APIBaseTest):
+
+class TestPersistAiQueryPlan(APIBaseTest):
@parameterized.expand(
[
- # The write is conditional on the planning-time prompt: an edit that landed mid-generation
- # (clearing the plan via save()) must not be overwritten with a plan for the old prompt.
- ("prompt_unchanged_persists", "original prompt?", True),
- ("prompt_changed_noops", "edited mid-generation?", False),
+ ("unchanged_prompt_and_images_persist", "original prompt?", {"include_images": False}, False, True),
+ ("changed_prompt_noops", "edited mid-generation?", {"include_images": False}, False, False),
+ ("images_enabled_mid_generation_noops", "original prompt?", {"include_images": True}, False, False),
+ ("images_disabled_mid_generation_noops", "original prompt?", {"include_images": False}, True, False),
+ ("explicitly_enabled_images_persist", "original prompt?", {"include_images": True}, True, True),
+ ("omitted_images_default_to_enabled", "original prompt?", {}, True, True),
]
)
- def test_persist_is_conditional_on_planning_prompt(self, _name: str, current_prompt: str, written: bool) -> None:
+ def test_persist_is_conditional_on_generation_inputs(
+ self,
+ _name: str,
+ current_prompt: str,
+ current_delivery_config: dict,
+ expected_include_images: bool,
+ written: bool,
+ ) -> None:
sub = Subscription.objects.create(
team=self.team,
prompt=current_prompt,
+ delivery_config=current_delivery_config,
target_type="email",
target_value="[email protected]",
frequency="weekly",
@@ -495,7 +719,13 @@ class TestPersistAiQueryPlanRaceGuard(APIBaseTest):
)
plan = {"version": 1, "plan": {}}
- persisted = _persist_ai_query_plan(sub.id, self.team.id, "original prompt?", plan)
+ persisted = _persist_ai_query_plan(
+ sub.id,
+ self.team.id,
+ "original prompt?",
+ plan,
+ expected_include_images=expected_include_images,
+ )
sub.refresh_from_db()
assert persisted is written
@@ -583,24 +813,39 @@ class TestLastSuccessfulDeliveryAnchor(APIBaseTest):
class TestFreezePlanPersistence:
"""build_ai_subscription_report freezes a freshly-generated plan and skips persistence on reuse.
- These guard the freeze contract without touching the DB — the persist write itself is a one-line
- queryset .update() exercised by the integration/activity suites."""
-
- def _subscription(self, ai_query_plan: dict | None) -> MagicMock:
- sub = MagicMock()
- sub.id = 42
- sub.team_id = 7
- sub.prompt = "how are exports doing?"
- sub.ai_query_plan = ai_query_plan
- return sub
-
- def _context(self, sub: MagicMock) -> tuple[MagicMock, MagicMock, ReportWindow, dict | None]:
+ These guard the freeze contract without touching the DB — the conditional persist write itself is
+ exercised by the integration/activity suites."""
+
+ def _subscription(self, ai_query_plan: dict | None) -> Subscription:
+ return Subscription(
+ id=42,
+ team_id=7,
+ prompt="how are exports doing?",
+ ai_query_plan=ai_query_plan,
+ delivery_config={},
+ target_type="email",
+ target_value="[email protected]",
+ frequency="weekly",
+ interval=1,
+ start_date=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ def _context(self, sub: Subscription) -> tuple[MagicMock, MagicMock, ReportWindow, dict | None]:
end = datetime(2026, 6, 29, 16, 0, tzinfo=UTC)
window = ReportWindow(start=end - timedelta(days=1), end=end)
return MagicMock(), MagicMock(), window, sub.ai_query_plan
- async def test_first_run_persists_freshly_generated_plan(self) -> None:
+ @parameterized.expand(
+ [
+ ("legacy_config", {}, True),
+ ("images_off", {"include_images": False}, False),
+ ]
+ )
+ async def test_first_run_persists_freshly_generated_plan(
+ self, _name: str, delivery_config: dict, expected_include_images: bool
+ ) -> None:
sub = self._subscription(ai_query_plan=None)
+ sub.delivery_config = delivery_config
fresh_plan = {
"overall_intent": "i",
"steps": [{"description": "d", "query_type": "hogql", "hogql": "SELECT 1"}],
@@ -624,7 +869,13 @@ class TestFreezePlanPersistence:
returned = await build_ai_subscription_report(sub)
# The plan generated on the first delivery is frozen onto the (id, team_id)-scoped subscription.
- mock_persist.assert_called_once_with(sub.id, sub.team_id, sub.prompt, fresh_plan)
+ mock_persist.assert_called_once_with(
+ sub.id,
+ sub.team_id,
+ sub.prompt,
+ fresh_plan,
+ expected_include_images=expected_include_images,
+ )
assert returned.query_plan_status == AIQueryPlanStatus.FROZEN
async def test_persist_failure_does_not_abort_the_delivery(self) -> None:
@@ -697,3 +948,33 @@ class TestFreezePlanPersistence:
assert mock_gen.await_args.kwargs["ai_query_plan"] == frozen
mock_ctx.assert_called_once()
assert returned.query_plan_status == AIQueryPlanStatus.FROZEN
+
+ @parameterized.expand(
+ [
+ ("legacy_config", {}, True, True),
+ ("images_on", {"include_images": True}, True, True),
+ ("images_off", {"include_images": False}, False, True),
+ ("manage_link_off", {"include_manage_link": False}, True, False),
+ ]
+ )
+ async def test_forwards_the_display_options_to_generation(
+ self, _name: str, delivery_config: dict, expected_charts: bool, expected_manage_link: bool
+ ) -> None:
+ # Generation renders the charts, so the option has to reach it — gating only the delivery
+ # renderers would still run a headless PNG export per chart for a report that hides them.
+ # Generation also writes the all-queries-failed notice, whose recovery sentence names the
+ # manage control, so it has to know whether the delivery renderers ship one.
+ sub = self._subscription(ai_query_plan=None)
+ sub.delivery_config = delivery_config
+ result = AiReportResult(
+ markdown="# R", diagnostics=(), window_end_utc="2026-06-29T16:00:00+00:00", plan_to_persist=None
+ )
+ with (
+ patch(f"{_DELIVERY}._resolve_subscription_context", return_value=self._context(sub)),
+ patch(f"{_DELIVERY}.generate_ai_report", new=AsyncMock(return_value=result)) as mock_gen,
+ ):
+ await build_ai_subscription_report(sub)
+
+ assert mock_gen.await_args is not None
+ assert mock_gen.await_args.kwargs["include_charts"] is expected_charts
+ assert mock_gen.await_args.kwargs["include_manage_link"] is expected_manage_link
diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py
index 0569845f7cc7..0510e0c51640 100644
--- a/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py
+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/test/test_report_pipeline.py
@@ -274,6 +274,23 @@ async def test_degraded_report_still_synthesizes(
assert props["query_coverage"] == 0.0
+ [
+ ("manage_link_shown", True, True),
+ ("manage_link_hidden", False, False),
+ ]
+)
+def test_the_all_failed_notice_only_points_at_a_manage_link_that_ships(
+ _name: str, include_manage_link: bool, expects_recovery: bool
+) -> None:
+ # Without the gate the notice sends recipients to a manage control the delivered message does
+ # not contain, on every channel at once.
+ notice = _all_queries_failed_notice(2, include_manage_link=include_manage_link)
+
+ assert "all 2 queries the assistant wrote failed to run" in notice
+ assert ("Manage subscription link" in notice) is expects_recovery
+
+
@patch(_SLO_CAPTURE)
@patch(f"{_RP}.MaxChatOpenAI")
@patch(f"{_RP}._run_steps", new_callable=AsyncMock)
@@ -1065,16 +1082,26 @@ async def test_only_a_spec_invalid_chart_drop_blocks_freezing(
assert result.plan_to_persist is None
[email protected]([("flag_off", False), ("flag_on", True)])
+ [
+ ("flag_off", False, True, False),
+ ("flag_on", True, True, True),
+ # A report that hides its charts closes the same gate as an unflagged team, so it
+ # builds no chart candidate and renders no PNG.
+ ("charts_not_included", True, False, False),
+ ]
+)
@patch(_SLO_CAPTURE)
@patch(f"{_RP}.MaxChatOpenAI")
@patch(f"{_RP}.charts_enabled")
@patch(f"{_RP}.render_charts", new_callable=AsyncMock)
@patch(f"{_RP}._run_steps", new_callable=AsyncMock)
@patch(f"{_RP}.build_enriched_prompt")
-async def test_charts_render_only_for_a_flagged_team(
+async def test_charts_render_only_for_a_flagged_team_that_includes_them(
_name: str,
enabled: bool,
+ include_charts: bool,
+ expected: bool,
mock_bep: MagicMock,
mock_run: AsyncMock,
mock_render: AsyncMock,
@@ -1088,9 +1115,11 @@ async def test_charts_render_only_for_a_flagged_team(
mock_render.return_value = ([], [])
mock_chat.return_value.invoke.return_value = MagicMock(content="# Report")
- await generate_ai_report(team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window())
+ await generate_ai_report(
+ team=MagicMock(), user=MagicMock(), prompt="x", window=_test_window(), include_charts=include_charts
+ )
- assert mock_run.call_args.kwargs["charts_enabled_for_team"] is enabled
+ assert mock_run.call_args.kwargs["charts_enabled_for_team"] is expected
def _candidate(step_index: int, importance: int) -> ValidatedChart:
diff --git a/products/subscriptions/frontend/components/Subscriptions/AiPromptFields.tsx b/products/subscriptions/frontend/components/Subscriptions/AiPromptFields.tsx
index d0e6e7b9aa7d..f93602efa0f4 100644
--- a/products/subscriptions/frontend/components/Subscriptions/AiPromptFields.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/AiPromptFields.tsx
@@ -4,14 +4,24 @@ import { IconLineGraph, IconPulse, IconTrending, IconWarning } from '@posthog/ic
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'
import { SubscriptionAIPromptMaxLength } from '~/queries/schema/schema-general'
+import type { SubscriptionType } from '~/types'
-import type { AIWindowConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'
+import type { AIWindowConfigApi, DeliveryConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'
+
+import {
+ type AiSubscriptionDisplayOption,
+ getAiSubscriptionDisplayOptionState,
+ getAiSubscriptionDisplaySummary,
+ updateAiSubscriptionDisplayOption,
+} from './utils'
export function AiPromptSubscriptionIntroduction(): JSX.Element {
return (
@@ -79,9 +89,29 @@ const AI_WINDOW_MODE_OPTIONS = [
},
]
+const AI_DISPLAY_OPTIONS: { option: AiSubscriptionDisplayOption; label: string; description: string }[] = [
+ {
+ option: 'images',
+ label: 'Chart images',
+ description: 'Include chart images when the report generates them.',
+ },
+ {
+ option: 'feedback',
+ label: 'Feedback buttons',
+ description: 'Ask recipients whether the report was useful.',
+ },
+ {
+ option: 'posthog_actions',
+ label: 'PostHog links and suggestions',
+ description:
+ 'Include a link to manage the subscription. Slack reports also suggest asking @PostHog a follow-up question.',
+ },
+]
+
interface AiPromptFieldsProps {
compactAnalysisWindow?: boolean
prompt?: string | null
+ targetType?: SubscriptionType['target_type'] | null
windowMode?: AIWindowConfigApi['mode']
consentBanner?: ReactNode
onSelectAnalysisWindow: (mode: AIWindowConfigApi['mode']) => void
@@ -95,6 +125,7 @@ function shouldShowAiPromptExamples(prompt?: string | null): boolean {
export function AiPromptFields({
compactAnalysisWindow = false,
prompt,
+ targetType,
windowMode,
consentBanner,
onSelectAnalysisWindow,
@@ -198,6 +229,78 @@ export function AiPromptFields({
</LemonField>
</div>
) : null}
+ <LemonField name="delivery_config">
+ {({ value, onChange }) => {
+ const deliveryConfig = value as DeliveryConfigApi | undefined
+ const displaySummary = getAiSubscriptionDisplaySummary(deliveryConfig, targetType)
+
+ return (
+ <LemonCollapse
+ className="bg-bg-light"
+ panels={[
+ {
+ key: 'advanced',
+ header: {
+ children: (
+ <div className="flex min-w-0 w-full items-start justify-between gap-2 py-1">
+ <div className="min-w-0">
+ <div className="font-semibold">Advanced delivery options</div>
+ <div className="text-secondary text-sm font-normal">
+ Choose optional content included in each delivery.
+ </div>
+ </div>
+ <div className="shrink-0 text-tertiary text-xs font-normal">
+ {displaySummary}
+ </div>
+ </div>
+ ),
+ },
+ content: (
+ <div className="flex flex-col gap-2">
+ <p className="text-secondary text-sm mb-1">
+ The report title and AI-written answer are always included.
+ </p>
+ {AI_DISPLAY_OPTIONS.map(({ option, label, description }) => {
+ const state = getAiSubscriptionDisplayOptionState(
+ deliveryConfig,
+ option
+ )
+
+ return (
+ <LemonSwitch
+ key={option}
+ checked={state}
+ onChange={(enabled) =>
+ onChange(
+ updateAiSubscriptionDisplayOption(
+ deliveryConfig,
+ option,
+ enabled
+ )
+ )
+ }
+ bordered
+ fullWidth
+ data-attr={`ai-subscription-display-${option.replace('_', '-')}`}
+ label={
+ <div className="flex flex-col gap-1 py-1">
+ <div className="leading-tight">{label}</div>
+ <div className="text-xs text-secondary font-normal leading-tight">
+ {description}
+ </div>
+ </div>
+ }
+ />
+ )
+ })}
+ </div>
+ ),
+ },
+ ]}
+ />
+ )
+ }}
+ </LemonField>
</>
)
}
diff --git a/products/subscriptions/frontend/components/Subscriptions/SubscriptionWizard.tsx b/products/subscriptions/frontend/components/Subscriptions/SubscriptionWizard.tsx
index bcaee2e7cb8d..74afb63c25be 100644
--- a/products/subscriptions/frontend/components/Subscriptions/SubscriptionWizard.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/SubscriptionWizard.tsx
@@ -42,6 +42,7 @@ import { SubscriptionTimePicker } from './SubscriptionTimePicker'
import {
frequencyOptionsPlural,
frequencyOptionsSingular,
+ getAiSubscriptionDisplaySummary,
getAiSubscriptionGate,
intervalOptions,
bysetposOptions,
@@ -472,6 +473,7 @@ function SubscriptionContentStep({
<AiPromptFields
compactAnalysisWindow
prompt={subscription.prompt}
+ targetType={subscription.target_type}
windowMode={subscription.ai_prompt_config?.window?.mode}
onSelectAnalysisWindow={selectAiAnalysisWindow}
onSelectExample={selectAiExamplePrompt}
@@ -709,6 +711,10 @@ function SubscriptionReviewStep({
? [
{ label: 'Prompt', value: subscription.prompt ?? '' },
{ label: 'Analysis window', value: formatAiAnalysisWindow(subscription) },
+ {
+ label: 'Report contents',
+ value: getAiSubscriptionDisplaySummary(subscription.delivery_config, subscription.target_type),
+ },
]
: []),
{ label: 'Sends to', value: subscription.target_value },
diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
index 3f910e0f5004..5140b82c78bd 100644
--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts
@@ -904,6 +904,32 @@ describe('subscriptionLogic', () => {
expect(capturedBody?.prompt).toBeUndefined()
})
+ it('drops stale AI display options when saving a non-AI subscription', async () => {
+ // Same switch-back path as the stale prompt: the AI display options stay in form state,
+ // and the backend rejects them on a non-AI sub, so the save would dead-end.
+ let capturedBody: Partial<SubscriptionType> | undefined
+ useMocks({
+ post: {
+ '/api/environments/:team/subscriptions': async ({ request }) => {
+ capturedBody = (await request.json()) as Partial<SubscriptionType>
+ return [200, { id: 44, ...capturedBody } as SubscriptionType]
+ },
+ },
+ })
+ router.actions.push('/subscriptions/new')
+ await expectLogic(newLogic).toFinishListeners()
+ newLogic.actions.setSubscriptionValues({
+ resource_type: 'insight',
+ delivery_config: { include_images: false, include_feedback: true },
+ title: 'Insight test',
+ target_type: 'email',
+ target_value: '[email protected]',
+ })
+ newLogic.actions.submitSubscription()
+ await expectLogic(newLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])
+ expect(capturedBody?.delivery_config).toEqual({})
+ })
+
it.each([
['removes the gallery flag when files:write is missing', 'chat:write,channels:read', false],
['keeps the gallery flag when files:write is granted', 'chat:write,files:write', true],
diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
index d150d5dac94c..63a9661c9f7c 100644
--- a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
+++ b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts
@@ -7,6 +7,8 @@ import {
canNudgeToSubscribe,
coerceDeliveryConfigForScope,
formatSubscriptionSchedule,
+ getAiSubscriptionDisplayOptionState,
+ getAiSubscriptionDisplaySummary,
getAiSubscriptionGate,
getNextDeliveryDate,
getSubscriptionAdvancedSettings,
@@ -15,6 +17,7 @@ import {
shouldShowDayPicker,
targetTypeOptions,
toggleSelectedDay,
+ updateAiSubscriptionDisplayOption,
} from './utils'
describe('targetTypeOptions', () => {
@@ -80,6 +83,190 @@ describe('getSubscriptionAdvancedSettings', () => {
})
})
+describe('AI subscription display options', () => {
+ it.each([
+ ['uses full report for legacy subscriptions with no display flags', undefined, 'Full report'],
+ [
+ 'recognizes the report-only state',
+ {
+ include_images: false,
+ include_feedback: false,
+ include_manage_link: false,
+ include_posthog_hint: false,
+ },
+ 'Report only',
+ ],
+ [
+ 'recognizes the report-and-charts state',
+ {
+ include_images: true,
+ include_feedback: false,
+ include_manage_link: false,
+ include_posthog_hint: false,
+ },
+ 'Report + charts',
+ ],
+ [
+ 'names feedback-only content',
+ {
+ include_images: false,
+ include_feedback: true,
+ include_manage_link: false,
+ include_posthog_hint: false,
+ },
+ 'Report + feedback',
+ ],
+ [
+ 'names PostHog-only content',
+ {
+ include_images: false,
+ include_feedback: false,
+ include_manage_link: true,
+ include_posthog_hint: true,
+ },
+ 'Report + PostHog links and suggestions',
+ ],
+ [
+ 'names charts and feedback content',
+ {
+ include_images: true,
+ include_feedback: true,
+ include_manage_link: false,
+ include_posthog_hint: false,
+ },
+ 'Report + charts + feedback',
+ ],
+ [
+ 'names charts and PostHog content',
+ {
+ include_images: true,
+ include_feedback: false,
+ include_manage_link: true,
+ include_posthog_hint: true,
+ },
+ 'Report + charts + PostHog links and suggestions',
+ ],
+ [
+ 'names feedback and PostHog content',
+ {
+ include_images: false,
+ include_feedback: true,
+ include_manage_link: true,
+ include_posthog_hint: true,
+ },
+ 'Report + feedback + PostHog links and suggestions',
+ ],
+ [
+ 'names an API-managed manage-link-only state',
+ {
+ include_images: false,
+ include_feedback: false,
+ include_manage_link: true,
+ include_posthog_hint: false,
+ },
+ 'Report + manage link',
+ ],
+ [
+ 'names an API-managed suggestion-only state',
+ {
+ include_images: false,
+ include_feedback: false,
+ include_manage_link: false,
+ include_posthog_hint: true,
+ },
+ 'Report + PostHog suggestion',
+ ],
+ ] as const)('%s', (_label, deliveryConfig, expected) => {
+ expect(getAiSubscriptionDisplaySummary(deliveryConfig)).toBe(expected)
+ })
+
+ it.each([
+ ['images', false, { include_images: false }],
+ ['feedback', false, { include_feedback: false }],
+ ['posthog_actions', false, { include_manage_link: false, include_posthog_hint: false }],
+ ] as const)('updates %s without losing unrelated delivery settings', (option, enabled, expectedDisplayConfig) => {
+ expect(
+ updateAiSubscriptionDisplayOption(
+ {
+ post_all_insights_in_main_message: true,
+ include_images: true,
+ include_feedback: true,
+ include_manage_link: true,
+ include_posthog_hint: true,
+ },
+ option,
+ enabled
+ )
+ ).toEqual({
+ post_all_insights_in_main_message: true,
+ include_images: true,
+ include_feedback: true,
+ include_manage_link: true,
+ include_posthog_hint: true,
+ ...expectedDisplayConfig,
+ })
+ })
+
+ it('treats either PostHog action flag as enabled', () => {
+ expect(
+ getAiSubscriptionDisplayOptionState(
+ { include_manage_link: true, include_posthog_hint: false },
+ 'posthog_actions'
+ )
+ ).toBe(true)
+ })
+
+ it('treats omitted legacy flags as enabled', () => {
+ expect(getAiSubscriptionDisplayOptionState(undefined, 'images')).toBe(true)
+ expect(getAiSubscriptionDisplayOptionState(undefined, 'feedback')).toBe(true)
+ expect(getAiSubscriptionDisplayOptionState(undefined, 'posthog_actions')).toBe(true)
+ })
+
+ it.each([
+ ['Slack', SubscriptionTargetEnumApi.Slack, 'Full report'],
+ ['email', SubscriptionTargetEnumApi.Email, 'Full report'],
+ ['Microsoft Teams', SubscriptionTargetEnumApi.Teams, 'Full report'],
+ ] as const)('lists the content that %s recipients receive', (_label, targetType, expected) => {
+ expect(getAiSubscriptionDisplaySummary(undefined, targetType)).toBe(expected)
+ })
+
+ it.each([
+ ['the PostHog suggestion', { include_posthog_hint: false }, 'Report + charts + feedback + manage link'],
+ ['the manage link', { include_manage_link: false }, 'Report + charts + feedback + PostHog suggestion'],
+ ] as const)('does not call a Slack report full when it drops %s', (_label, deliveryConfig, expected) => {
+ expect(getAiSubscriptionDisplaySummary(deliveryConfig, SubscriptionTargetEnumApi.Slack)).toBe(expected)
+ })
+
+ it.each([
+ ['insight', undefined],
+ ['dashboard', undefined],
+ ['ai_prompt', false],
+ ] as const)('a %s subscription sends include_images as %s', (resourceType, expected) => {
+ const subscription = {
+ resource_type: resourceType,
+ target_type: 'email',
+ delivery_config: { include_images: false },
+ } as SubscriptionType
+
+ expect(coerceDeliveryConfigForScope(subscription, [])?.include_images).toBe(expected)
+ })
+
+ it('keeps the other delivery options when it drops the AI ones', () => {
+ const subscription = {
+ resource_type: 'insight',
+ target_type: 'slack',
+ integration_id: 7,
+ delivery_config: { post_all_insights_in_main_message: true, include_feedback: true },
+ } as SubscriptionType
+
+ expect(
+ coerceDeliveryConfigForScope(subscription, [
+ { id: 7, kind: 'slack', config: { scope: 'files:write' } } as IntegrationType,
+ ])
+ ).toEqual({ post_all_insights_in_main_message: true })
+ })
+})
+
describe('Slack gallery delivery config', () => {
const slackIntegration = (id: number, scope: string): IntegrationType =>
({ id, kind: 'slack', config: { scope } }) as IntegrationType
diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsx
index b51f0ff38b55..2939d95456c5 100644
--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx
@@ -11,14 +11,118 @@ import { range } from 'lib/utils/arrays'
import { urls } from 'scenes/urls'
import { SubscriptionAIPromptMaxLength, SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'
-import { InsightShortId, IntegrationType, SubscriptionType, WeekdayType } from '~/types'
+import { InsightShortId, IntegrationType, SubscriptionResourceTypes, SubscriptionType, WeekdayType } from '~/types'
import IconMicrosoftTeams from 'public/services/microsoft-teams.png'
-import { SubscriptionTargetEnumApi, type SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'
+import {
+ type DeliveryConfigApi,
+ SubscriptionTargetEnumApi,
+ type SubscriptionApi,
+} from 'products/subscriptions/frontend/generated/api.schemas'
export const AI_PROMPT_MAX_LENGTH = SubscriptionAIPromptMaxLength.CHARACTERS
+const AI_DISPLAY_CONFIG_FIELDS = [
+ 'include_images',
+ 'include_feedback',
+ 'include_manage_link',
+ 'include_posthog_hint',
+] as const satisfies readonly (keyof DeliveryConfigApi)[]
+
+type AiSubscriptionDisplayConfig = Required<Pick<DeliveryConfigApi, (typeof AI_DISPLAY_CONFIG_FIELDS)[number]>>
+
+function aiSubscriptionPostHogHintApplies(targetType?: SubscriptionType['target_type'] | null): boolean {
+ return !targetType || targetType === SubscriptionTargetEnumApi.Slack
+}
+
+function resolveAiSubscriptionDisplayConfig(
+ deliveryConfig: DeliveryConfigApi | null | undefined,
+ targetType?: SubscriptionType['target_type'] | null
+): AiSubscriptionDisplayConfig {
+ return {
+ include_images: deliveryConfig?.include_images ?? true,
+ include_feedback: deliveryConfig?.include_feedback ?? true,
+ include_manage_link: deliveryConfig?.include_manage_link ?? true,
+ include_posthog_hint: aiSubscriptionPostHogHintApplies(targetType)
+ ? (deliveryConfig?.include_posthog_hint ?? true)
+ : false,
+ }
+}
+
+export type AiSubscriptionDisplayOption = 'images' | 'feedback' | 'posthog_actions'
+
+function summarizeAiSubscriptionDisplayConfig(
+ resolved: AiSubscriptionDisplayConfig,
+ posthogHintApplies: boolean
+): string {
+ // Slack renders the manage link and the @PostHog suggestion separately, so a report missing
+ // either one is not full. Other targets never get the suggestion, so the link alone is full.
+ const allPostHogActions = resolved.include_manage_link && (resolved.include_posthog_hint || !posthogHintApplies)
+ const anyPostHogActions = resolved.include_manage_link || resolved.include_posthog_hint
+
+ if (resolved.include_images && resolved.include_feedback && allPostHogActions) {
+ return 'Full report'
+ }
+ if (!resolved.include_images && !resolved.include_feedback && !anyPostHogActions) {
+ return 'Report only'
+ }
+
+ const includedContent = ['Report']
+ if (resolved.include_images) {
+ includedContent.push('charts')
+ }
+ if (resolved.include_feedback) {
+ includedContent.push('feedback')
+ }
+ if (resolved.include_manage_link && resolved.include_posthog_hint) {
+ includedContent.push('PostHog links and suggestions')
+ } else if (resolved.include_manage_link) {
+ includedContent.push('manage link')
+ } else if (resolved.include_posthog_hint) {
+ includedContent.push('PostHog suggestion')
+ }
+
+ return includedContent.join(' + ')
+}
+
+export function getAiSubscriptionDisplaySummary(
+ deliveryConfig: DeliveryConfigApi | null | undefined,
+ targetType?: SubscriptionType['target_type'] | null
+): string {
+ const resolved = resolveAiSubscriptionDisplayConfig(deliveryConfig, targetType)
+ return summarizeAiSubscriptionDisplayConfig(resolved, aiSubscriptionPostHogHintApplies(targetType))
+}
+
+export function getAiSubscriptionDisplayOptionState(
+ deliveryConfig: DeliveryConfigApi | null | undefined,
+ option: AiSubscriptionDisplayOption
+): boolean {
+ const resolved = resolveAiSubscriptionDisplayConfig(deliveryConfig)
+
+ if (option === 'images') {
+ return resolved.include_images
+ }
+ if (option === 'feedback') {
+ return resolved.include_feedback
+ }
+ return resolved.include_manage_link || resolved.include_posthog_hint
+}
+
+export function updateAiSubscriptionDisplayOption(
+ deliveryConfig: DeliveryConfigApi | null | undefined,
+ option: AiSubscriptionDisplayOption,
+ enabled: boolean
+): DeliveryConfigApi {
+ if (option === 'images') {
+ return { ...deliveryConfig, include_images: enabled }
+ }
+ if (option === 'feedback') {
+ return { ...deliveryConfig, include_feedback: enabled }
+ }
+ return { ...deliveryConfig, include_manage_link: enabled, include_posthog_hint: enabled }
+}
+
export function requestSubscriptionWizardCancellation({
onCancel,
resetSubscription,
@@ -200,27 +304,49 @@ export function integrationHasFilesWrite(integration: IntegrationType | null | u
return integration ? getGrantedScopes(integration).includes('files:write') : false
}
+/**
+ * The API accepts the AI display options on prompt subscriptions only. Toggling resource_type
+ * back to insight or dashboard leaves them in form state, so drop them here rather than let the
+ * save fail on options the non-AI form no longer shows.
+ */
+function dropAiDisplayConfigForNonAi(subscription: SubscriptionType): SubscriptionType['delivery_config'] {
+ const deliveryConfig = subscription.delivery_config
+ if (subscription.resource_type === SubscriptionResourceTypes.AiPrompt || !deliveryConfig) {
+ return deliveryConfig
+ }
+ if (!AI_DISPLAY_CONFIG_FIELDS.some((field) => field in deliveryConfig)) {
+ return deliveryConfig
+ }
+
+ const remaining = { ...deliveryConfig }
+ for (const field of AI_DISPLAY_CONFIG_FIELDS) {
+ delete remaining[field]
+ }
+ return remaining
+}
+
export function coerceDeliveryConfigForScope(
subscription: SubscriptionType,
integrations: IntegrationType[] | null | undefined
): SubscriptionType['delivery_config'] {
- if (!subscription.delivery_config?.post_all_insights_in_main_message) {
- return subscription.delivery_config
+ const deliveryConfig = dropAiDisplayConfigForNonAi(subscription)
+ if (!deliveryConfig?.post_all_insights_in_main_message) {
+ return deliveryConfig
}
if (subscription.target_type !== 'slack') {
- return { ...subscription.delivery_config, post_all_insights_in_main_message: false }
+ return { ...deliveryConfig, post_all_insights_in_main_message: false }
}
if (integrations == null) {
- return subscription.delivery_config
+ return deliveryConfig
}
const selectedIntegration = subscription.integration_id
? integrations.find((integration) => integration.id === subscription.integration_id)
: undefined
if (!integrationHasFilesWrite(selectedIntegration)) {
- return { ...subscription.delivery_config, post_all_insights_in_main_message: false }
+ return { ...deliveryConfig, post_all_insights_in_main_message: false }
}
- return subscription.delivery_config
+ return deliveryConfig
}
function formatSelectedDeliveryDays(selectedDays: WeekdayType[]): string {
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
index 62236210d171..ed7d188b2d0f 100644
--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx
@@ -453,6 +453,7 @@ function EditSubscriptionForm({
<AiPromptSubscriptionIntroduction />
<AiPromptFields
prompt={subscription.prompt}
+ targetType={subscription.target_type}
windowMode={subscription.ai_prompt_config?.window?.mode}
consentBanner={
aiGate.showAiFormConsentBanner ? <AiConsentGateMessage /> : undefined
diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.ts
index 2029da413e29..0aaf62ea37c4 100644
--- a/products/subscriptions/frontend/generated/api.schemas.ts
+++ b/products/subscriptions/frontend/generated/api.schemas.ts
@@ -187,6 +187,14 @@ export interface UserBasicApi {
export interface DeliveryConfigApi {
/** Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false. */
post_all_insights_in_main_message?: boolean
+ /** AI prompt subscriptions only: include generated chart images. Defaults to true when omitted. */
+ include_images?: boolean
+ /** AI prompt subscriptions only: include report feedback links. Defaults to true when omitted. */
+ include_feedback?: boolean
+ /** AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted. */
+ include_manage_link?: boolean
+ /** AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted. */
+ include_posthog_hint?: boolean
}
/**
diff --git a/products/subscriptions/frontend/generated/api.zod.ts b/products/subscriptions/frontend/generated/api.zod.ts
index ea3d7b88d9f7..55275080a4b8 100644
--- a/products/subscriptions/frontend/generated/api.zod.ts
+++ b/products/subscriptions/frontend/generated/api.zod.ts
@@ -194,6 +194,30 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod
.describe(
'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'
),
+ include_images: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include generated chart images. Defaults to true when omitted.'
+ ),
+ include_feedback: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include report feedback links. Defaults to true when omitted.'
+ ),
+ include_manage_link: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted.'
+ ),
+ include_posthog_hint: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted.'
+ ),
})
.describe('Typed view over the Subscription.delivery_config JSON blob.')
.optional()
@@ -386,6 +410,30 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod
.describe(
'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'
),
+ include_images: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include generated chart images. Defaults to true when omitted.'
+ ),
+ include_feedback: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include report feedback links. Defaults to true when omitted.'
+ ),
+ include_manage_link: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted.'
+ ),
+ include_posthog_hint: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted.'
+ ),
})
.describe('Typed view over the Subscription.delivery_config JSON blob.')
.optional()
@@ -583,6 +631,30 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod
.describe(
'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'
),
+ include_images: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include generated chart images. Defaults to true when omitted.'
+ ),
+ include_feedback: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include report feedback links. Defaults to true when omitted.'
+ ),
+ include_manage_link: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted.'
+ ),
+ include_posthog_hint: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted.'
+ ),
})
.describe('Typed view over the Subscription.delivery_config JSON blob.')
.optional()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0b0c7ff9258b..73743c9a4745 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -28339,6 +28339,14 @@ export namespace Schemas {
export interface DeliveryConfig {
/** Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false. */
post_all_insights_in_main_message?: boolean;
+ /** AI prompt subscriptions only: include generated chart images. Defaults to true when omitted. */
+ include_images?: boolean;
+ /** AI prompt subscriptions only: include report feedback links. Defaults to true when omitted. */
+ include_feedback?: boolean;
+ /** AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted. */
+ include_manage_link?: boolean;
+ /** AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted. */
+ include_posthog_hint?: boolean;
}
/**
diff --git a/services/mcp/src/generated/subscriptions/api.ts b/services/mcp/src/generated/subscriptions/api.ts
index a5b60067a520..fc8eb011e6e9 100644
--- a/services/mcp/src/generated/subscriptions/api.ts
+++ b/services/mcp/src/generated/subscriptions/api.ts
@@ -227,6 +227,30 @@ export const SubscriptionsCreateBody = () => zod
.describe(
'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'
),
+ include_images: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include generated chart images. Defaults to true when omitted.'
+ ),
+ include_feedback: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include report feedback links. Defaults to true when omitted.'
+ ),
+ include_manage_link: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted.'
+ ),
+ include_posthog_hint: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted.'
+ ),
})
.describe('Typed view over the Subscription.delivery_config JSON blob.')
.optional()
@@ -431,6 +455,30 @@ export const SubscriptionsPartialUpdateBody = () => zod
.describe(
'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'
),
+ include_images: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include generated chart images. Defaults to true when omitted.'
+ ),
+ include_feedback: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include report feedback links. Defaults to true when omitted.'
+ ),
+ include_manage_link: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted.'
+ ),
+ include_posthog_hint: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted.'
+ ),
})
.describe('Typed view over the Subscription.delivery_config JSON blob.')
.optional()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json
index 184cdfda6121..b9a922e919ba 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json
@@ -109,6 +109,22 @@
"delivery_config": {
"description": "Per-delivery rendering options. Each option documents which delivery targets it applies to.",
"properties": {
+ "include_feedback": {
+ "description": "AI prompt subscriptions only: include report feedback links. Defaults to true when omitted.",
+ "type": "boolean"
+ },
+ "include_images": {
+ "description": "AI prompt subscriptions only: include generated chart images. Defaults to true when omitted.",
+ "type": "boolean"
+ },
+ "include_manage_link": {
+ "description": "AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted.",
+ "type": "boolean"
+ },
+ "include_posthog_hint": {
+ "description": "AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted.",
+ "type": "boolean"
+ },
"post_all_insights_in_main_message": {
"default": false,
"description": "Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json
index 20468409be0b..fbf5d01669c9 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-partial-update.json
@@ -108,6 +108,22 @@
"delivery_config": {
"description": "Per-delivery rendering options. Each option documents which delivery targets it applies to.",
"properties": {
+ "include_feedback": {
+ "description": "AI prompt subscriptions only: include report feedback links. Defaults to true when omitted.",
+ "type": "boolean"
+ },
+ "include_images": {
+ "description": "AI prompt subscriptions only: include generated chart images. Defaults to true when omitted.",
+ "type": "boolean"
+ },
+ "include_manage_link": {
+ "description": "AI prompt subscriptions only: include a link to manage the subscription. Defaults to true when omitted.",
+ "type": "boolean"
+ },
+ "include_posthog_hint": {
+ "description": "AI prompt subscriptions only: include PostHog product guidance. Slack only. Email and Microsoft Teams reports do not include it. Defaults to true when omitted.",
+ "type": "boolean"
+ },
"post_all_insights_in_main_message": {
"default": false,
"description": "Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.",