:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(subscriptions): deliver subscription reports to microsoft teams (#86227)
Vasco de Krijger8b51a84f78b0
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex 395b8164349f..038ea6df1575 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -41,6 +41,7 @@ from posthog.models.integration import Integration, SlackIntegrationfrom posthog.rate_limit import SubscriptionTestDeliveryThrottlefrom posthog.resource_limits import LimitKey, check_count_limit, get_organization_limitfrom posthog.scopes import APIScopeObject+from posthog.security.url_validation import is_microsoft_teams_webhook_urlfrom posthog.slo.context import SloSpec, slo_operationfrom posthog.slo.types import SloArea, SloOperationfrom posthog.temporal.common.client import sync_connect@@ -73,6 +74,7 @@ from products.product_analytics.backend.facade.models import Insightfrom ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, is_team_limitedfrom ee.tasks.subscriptions.auto_disable import validate_re_enablefrom ee.tasks.subscriptions.subscription_utils import MAX_INSIGHTS+from ee.tasks.subscriptions.teams_subscriptions import TEAMS_WEBHOOK_URL_ERROR, TEAMS_WEBHOOK_URL_MASKED_ERRORSUMMARY_QUOTA_CACHE_TTL_SECONDS = 60SUMMARY_CAP_HIT_DEDUPE_TTL_SECONDS = 600@@ -385,9 +387,14 @@ class SubscriptionSerializer(serializers.ModelSerializer):},"dashboard": {"help_text": "Dashboard ID to subscribe to (mutually exclusive with insight on create)."},"insight": {"help_text": "Insight ID to subscribe to (mutually exclusive with dashboard on create)."},- "target_type": {"help_text": "Delivery channel: email or slack."},+ "target_type": {"help_text": "Delivery channel: email, slack, or teams."},"target_value": {- "help_text": "Recipient(s): comma-separated email addresses for email, or Slack channel name/ID for slack."+ "help_text": (+ "Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, "+ "or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as "+ "its host, because the URL authorizes a post to the channel by itself. On update, omit the "+ "field to keep the stored URL, or send a full URL to replace it."+ )},"frequency": {"help_text": "How often to deliver: daily, weekly, monthly, or yearly."},"interval": {@@ -466,8 +473,9 @@ class SubscriptionSerializer(serializers.ModelSerializer):if target_type and target_type not in (Subscription.SubscriptionTarget.EMAIL,Subscription.SubscriptionTarget.SLACK,+ Subscription.SubscriptionTarget.TEAMS,):- raise ValidationError({"target_type": ["AI subscriptions only support email or slack delivery."]})+ raise ValidationError({"target_type": ["AI subscriptions only support email, slack, or teams delivery."]})# Gates fire on create only; existing AI subs stay editable.if existing is None:gate_reason = _ai_create_gate_reason(self.context["get_organization"](), self._caller_distinct_id())@@ -536,6 +544,15 @@ class SubscriptionSerializer(serializers.ModelSerializer):self._validate_dashboard_export_subscription(attrs)target_type = attrs.get("target_type") or (self.instance.target_type if self.instance else None)+ if (+ self.instance+ and self.instance.target_type == Subscription.SubscriptionTarget.TEAMS+ and target_type != Subscription.SubscriptionTarget.TEAMS+ and "target_value" not in attrs+ ):+ raise ValidationError(+ {"target_value": ["A new target value is required when changing from Microsoft Teams."]}+ )# Use explicit-key check for integration_id so a deliberate `null` in the PATCH# body falls through to the validation below — `or` would silently coalesce# to the stale instance value and pass `validate_re_enable` with the wrong id.@@ -593,6 +610,14 @@ class SubscriptionSerializer(serializers.ModelSerializer):raise ValidationError({"start_date": [f"{base}."]})raise ValidationError(f"{base}.")+ if target_type == Subscription.SubscriptionTarget.TEAMS:+ submitted = (attrs.get("target_value") or "").strip()+ if self.instance and submitted and submitted == self.instance.recipient_label:+ raise ValidationError({"target_value": [TEAMS_WEBHOOK_URL_MASKED_ERROR]})+ target_value = submitted or (self.instance.target_value if self.instance else "")+ if not is_microsoft_teams_webhook_url(target_value):+ raise ValidationError({"target_value": [TEAMS_WEBHOOK_URL_ERROR]})+if target_type == Subscription.SubscriptionTarget.SLACK:if not integration_id:raise ValidationError({"integration_id": ["A Slack integration is required for Slack subscriptions."]})@@ -842,6 +867,12 @@ class SubscriptionSerializer(serializers.ModelSerializer):})+ def to_representation(self, instance: Subscription) -> dict:+ data = super().to_representation(instance)+ if instance.target_type == Subscription.SubscriptionTarget.TEAMS:+ data["target_value"] = instance.recipient_label+ return data+def create(self, validated_data: dict, *args: Any, **kwargs: Any) -> Subscription:request = self.context["request"]validated_data["team_id"] = self.context["team_id"]@@ -1158,7 +1189,7 @@ def _subscription_is_ai_prompt(subscription_id: str | int, team_id: int) -> boolenum=[m.value for m in Subscription.SubscriptionTarget],location=OpenApiParameter.QUERY,required=False,- description="Filter by delivery channel (email or Slack).",+ description="Filter by delivery channel: email, Slack, or Microsoft Teams.",),OpenApiParameter(name="insight",@@ -1560,8 +1591,13 @@ class SubscriptionDeliverySerializer(serializers.ModelSerializer):"idempotency_key": {"help_text": "Dedupes activity retries for the same logical run."},"trigger_type": {"help_text": "Why the run started (e.g. scheduled, manual, subscription update)."},"scheduled_at": {"help_text": "Planned send time when applicable."},- "target_type": {"help_text": "Channel snapshot at send time (email or slack)."},- "target_value": {"help_text": "Destination snapshot at send time (emails, channel id, URL)."},+ "target_type": {"help_text": "Channel snapshot at send time: email, slack, or teams."},+ "target_value": {+ "help_text": (+ "Destination snapshot at send time: the email list, the Slack channel id, or the "+ "host of the Microsoft Teams webhook. The webhook URL itself is never returned."+ )+ },"exported_asset_ids": {"help_text": "ExportedAsset ids generated for this send."},"content_snapshot": {"help_text": (diff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex b6e9c9e3b2cb..31f9f4be6563 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -1,3 +1,4 @@+import jsonfrom collections.abc import Callablefrom datetime import UTC, datetime, timedeltafrom typing import Optional@@ -44,8 +45,11 @@ from products.product_analytics.backend.facade.models import Insightfrom ee.api.test.base import APILicensedTestfrom ee.tasks.subscriptions.slack_subscriptions import get_slack_integration_for_teamfrom ee.tasks.subscriptions.subscription_utils import MAX_INSIGHTS+from ee.tasks.subscriptions.teams_subscriptions import TEAMS_WEBHOOK_URL_ERROR, TEAMS_WEBHOOK_URL_MASKED_ERRORfrom ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription+VALID_TEAMS_WEBHOOK_URL = "https://prod-25.westeurope.logic.azure.com:443/workflows/abc/triggers/manual/paths/invoke"+class TestSubscriptionTemporal(APILicensedTest):subscription: Subscription = None # type: ignore@@ -841,6 +845,77 @@ class TestSubscriptionTemporal(APILicensedTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "require a Slack integration" in response.json()["detail"]+ def test_can_create_teams_subscription_with_a_webhook_url(self):+ response = self._create_subscription(target_type="teams", target_value=VALID_TEAMS_WEBHOOK_URL)+ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["target_type"] == "teams"++ def test_reading_a_teams_subscription_never_returns_the_webhook_url(self):+ # The URL authorizes a post to the channel on its own, so subscription read access must not+ # be enough to obtain it.+ sub_id = self._create_subscription(target_type="teams", target_value=VALID_TEAMS_WEBHOOK_URL).json()["id"]++ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{sub_id}")+ listed = self.client.get(f"/api/projects/{self.team.id}/subscriptions").json()["results"]++ assert response.json()["target_value"] == "prod-25.westeurope.logic.azure.com"+ assert [s["target_value"] for s in listed if s["id"] == sub_id] == ["prod-25.westeurope.logic.azure.com"]+ assert "/workflows/" not in json.dumps(response.json())+ assert Subscription.objects.get(id=sub_id).target_value == VALID_TEAMS_WEBHOOK_URL++ @parameterized.expand([("email", "[email protected]"), ("slack", "C1234|#general")])+ def test_reading_a_non_teams_subscription_returns_its_target_value(self, target_type, target_value):+ extra = {}+ if target_type == "slack":+ extra["integration_id"] = Integration.objects.create(team=self.team, kind="slack", config={}).id+ sub_id = self._create_subscription(target_type=target_type, target_value=target_value, **extra).json()["id"]++ response = self.client.get(f"/api/projects/{self.team.id}/subscriptions/{sub_id}")++ assert response.json()["target_value"] == target_value++ def test_patching_an_unrelated_field_keeps_a_teams_subscription_saveable(self):+ # target_value is absent from the PATCH body, so the webhook check falls back to the stored+ # URL. Validating an empty string instead would make every edit of a Teams subscription 400.+ sub_id = self._create_subscription(target_type="teams", target_value=VALID_TEAMS_WEBHOOK_URL).json()["id"]++ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", {"title": "Renamed"})++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["title"] == "Renamed"+ assert Subscription.objects.get(id=sub_id).target_value == VALID_TEAMS_WEBHOOK_URL++ def test_patching_a_teams_subscription_with_the_masked_host_is_rejected(self):+ # A client that echoes what it read would otherwise overwrite the stored URL with a value+ # nothing could deliver to.+ sub_id = self._create_subscription(target_type="teams", target_value=VALID_TEAMS_WEBHOOK_URL).json()["id"]++ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{sub_id}",+ {"target_value": "prod-25.westeurope.logic.azure.com"},+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "target_value"+ assert response.json()["detail"] == TEAMS_WEBHOOK_URL_MASKED_ERROR+ assert Subscription.objects.get(id=sub_id).target_value == VALID_TEAMS_WEBHOOK_URL++ def test_cannot_change_a_teams_subscription_to_another_target_without_replacing_its_webhook_url(self):+ sub_id = self._create_subscription(target_type="teams", target_value=VALID_TEAMS_WEBHOOK_URL).json()["id"]++ response = self.client.patch(f"/api/projects/{self.team.id}/subscriptions/{sub_id}", {"target_type": "email"})++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert Subscription.objects.get(id=sub_id).target_type == Subscription.SubscriptionTarget.TEAMS+ assert Subscription.objects.get(id=sub_id).target_value == VALID_TEAMS_WEBHOOK_URL++ def test_cannot_create_teams_subscription_with_a_lookalike_url(self):+ response = self._create_subscription(target_type="teams", target_value="https://evilpowerautomate.com/x")++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "target_value"+ assert response.json()["detail"] == TEAMS_WEBHOOK_URL_ERROR+def test_patch_enabled_true_rejected_when_slack_integration_missing(self):"""Re-enabling a disabled Slack subscription whose integration is gone must berejected up front — otherwise the next delivery would auto-disable it againdiff --git a/ee/tasks/slack.py b/ee/tasks/slack.pyindex c38ab3e53bca..dcd104643371 100644--- a/ee/tasks/slack.py+++ b/ee/tasks/slack.py@@ -11,7 +11,7 @@ from posthog.models.sharing_configuration import SharingConfigurationfrom products.exports.backend.models.exported_asset import ExportedAsset-from ee.tasks.subscriptions.subscription_utils import generate_assets+from ee.tasks.subscriptions.subscription_utils import DEBUG_PLACEHOLDER_IMAGE_URL, generate_assetslogger = structlog.get_logger(__name__)@@ -26,7 +26,7 @@ def _block_for_asset(asset: ExportedAsset) -> dict:alt_text = asset.insight.name or asset.insight.derived_nameif settings.DEBUG:- image_url = "https://source.unsplash.com/random"+ image_url = DEBUG_PLACEHOLDER_IMAGE_URLreturn {"type": "image", "image_url": image_url, "alt_text": alt_text}diff --git a/ee/tasks/subscriptions/__init__.py b/ee/tasks/subscriptions/__init__.pyindex 082926a67df0..1f0b2fd3dbaf 100644--- a/ee/tasks/subscriptions/__init__.py+++ b/ee/tasks/subscriptions/__init__.py@@ -80,7 +80,7 @@ def get_subscription_failure_metric()-SUPPORTED_TARGET_TYPES = frozenset(["email", "slack"])+SUPPORTED_TARGET_TYPES = frozenset(Subscription.SubscriptionTarget.values)def _capture_delivery_failed_event(diff --git a/ee/tasks/subscriptions/auto_disable.py b/ee/tasks/subscriptions/auto_disable.pyindex 55b8607a23c6..0bb7eb45dc66 100644--- a/ee/tasks/subscriptions/auto_disable.py+++ b/ee/tasks/subscriptions/auto_disable.py@@ -26,7 +26,8 @@ class DisableReason(NamedTuple):key: str# Shown in the disabled-subscription email body and the activity's recipient_results.description: str- # Re-enable rejection message surfaced by the API serializer; `{target_type}` is interpolated.+ # Re-enable rejection message surfaced by the API serializer; `{target_type}` is interpolated+ # with the channel's display label, so it reads "Microsoft Teams" rather than "teams".user_message: str@@ -45,6 +46,11 @@ SLACK_PERMISSION_REVOKED_DISABLE_REASON = DisableReason(description="PostHog can no longer post to this Slack channel",user_message="Cannot re-enable {target_type} subscription: PostHog can't post to this Slack channel. Reconnect Slack or re-add the bot to the channel, then try again.",)+WEBHOOK_REJECTED_DISABLE_REASON = DisableReason(+ key="webhook_rejected",+ description="Microsoft Teams stopped accepting messages",+ user_message="Cannot re-enable {target_type} subscription: Microsoft Teams stopped accepting messages. Create a new webhook URL in your Teams channel with the Workflows app, update this subscription with it, then try again.",+)SLACK_FILE_UPLOAD_PERMISSION_REVOKED_DISABLE_REASON = DisableReason(key="slack_file_upload_permission_revoked",description="PostHog can no longer upload files to Slack",@@ -78,12 +84,21 @@ def get_subscription_disable_reason(target_type: str | None, integration_id: intreturn None+def target_type_label(target_type: str | None) -> str:+ if not target_type:+ return ""+ try:+ return str(Subscription.SubscriptionTarget(target_type).label)+ except ValueError:+ return target_type++def validate_re_enable(target_type: str | None, integration_id: int | None) -> str | None:"""API-serializer wrapper — returns the user-facing rejection message, or None if re-enable is OK."""reason = get_subscription_disable_reason(target_type, integration_id)if reason is None:return None- return reason.user_message.format(target_type=target_type)+ return reason.user_message.format(target_type=target_type_label(target_type))def _get_notification_creator(subscription: Subscription) -> User | None:@@ -166,9 +181,12 @@ def create_subscription_auto_disabled_notification(subscription: Subscription, rnotification_type=NotificationType.PIPELINE_FAILURE,priority=Priority.NORMAL,title=f"{title[:75]} was automatically disabled",+ # Every description is a sentence-case fragment, and most open on a brand name+ # ("Microsoft Teams stopped accepting messages"), so it stands as its own sentence.+ # Folding it into a "because ..." clause needs it lowercased, which mangles the brand.body=(- f"PostHog automatically disabled this subscription because {reason.description.lower()}. "- f"{reason.user_message.format(target_type=subscription.target_type)}"+ f"PostHog automatically disabled this subscription. {reason.description}. "+ f"{reason.user_message.format(target_type=target_type_label(subscription.target_type))}"),target_type=TargetType.USER,target_id=str(creator.id),@@ -205,7 +223,7 @@ def send_notifications_for_disabled_subscription("subscription_url": subscription.url,"subscription_title": display_name,"reason": reason.description,- "action_message": reason.user_message.format(target_type=subscription.target_type),+ "action_message": reason.user_message.format(target_type=target_type_label(subscription.target_type)),},)for target in targets:diff --git a/ee/tasks/subscriptions/email_subscriptions.py b/ee/tasks/subscriptions/email_subscriptions.pyindex eef9ef60167f..2a0ba70a9b20 100644--- a/ee/tasks/subscriptions/email_subscriptions.py+++ b/ee/tasks/subscriptions/email_subscriptions.py@@ -10,37 +10,22 @@ from products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.models.subscription import Subscription, get_unsubscribe_tokenfrom ee.tasks.subscriptions.subscription_utils import (- ASSET_GENERATION_FAILED_MESSAGE,UTM_TAGS_BASE,_has_asset_failed,- subscription_asset_error_message,+ failed_asset_details,+ next_delivery_date_display,)logger = structlog.get_logger(__name__)-def _next_delivery_date_display(subscription: Subscription) -> str:- next_delivery_date = subscription.next_delivery_date- return next_delivery_date.strftime("%A %B %d, %Y") if next_delivery_date is not None else "an upcoming date"--def _get_asset_data_for_email(asset: ExportedAsset) -> dict:if _has_asset_failed(asset):- insight_name = asset.insight.name or asset.insight.derived_name if asset.insight else "Unknown insight"-- # Truncate long error messages to avoid long emails- max_error_length = 2000- if asset.exception:- error_message = subscription_asset_error_message(asset)- if len(error_message) > max_error_length:- error_message = error_message[:max_error_length] + "... (truncated)"- else:- error_message = ASSET_GENERATION_FAILED_MESSAGE-+ details = failed_asset_details(asset)return {"error": True,- "insight_name": insight_name,- "error_message": error_message,+ "insight_name": details.insight_name,+ "error_message": details.error_text,}return {@@ -86,7 +71,7 @@ def send_email_subscription_report(if is_invite:invite_summary = (f"This subscription is {subscription.summary}. "- f"The next subscription will be sent on {_next_delivery_date_display(subscription)}"+ f"The next subscription will be sent on {next_delivery_date_display(subscription)}")if self_invite:subject = f"You have been subscribed to a PostHog {resource_info.kind}"diff --git a/ee/tasks/subscriptions/slack_subscriptions.py b/ee/tasks/subscriptions/slack_subscriptions.pyindex 7ac25ed18034..3546279131aa 100644--- a/ee/tasks/subscriptions/slack_subscriptions.py+++ b/ee/tasks/subscriptions/slack_subscriptions.py@@ -19,24 +19,18 @@ from products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.models.subscription import Subscription, SubscriptionResourcefrom ee.tasks.subscriptions.subscription_utils import (- ASSET_GENERATION_FAILED_MESSAGE,+ DEBUG_PLACEHOLDER_IMAGE_URL,UTM_TAGS_BASE,_has_asset_failed,- subscription_asset_error_message,+ failed_asset_details,+ next_delivery_date_display,+ subscription_support_url,+ summary_skipped_over_budget_message,)logger = structlog.get_logger(__name__)-# Shown in place of the AI summary when generation was skipped because the org is-# over its AI credit budget. Wording kept in sync with the email template's notice.-def summary_skipped_over_budget_message(billing_url: str) -> str:- return (- "_AI summary skipped — your organization has reached its AI credit usage limit. "- f"Increase the limit in <{billing_url}|Billing settings> to resume summaries._"- )--# Slack API error codes that indicate transient server-side issues — safe to retry.# These are 5xx-equivalents in Slack's string-coded error model. Permanent errors# (channel_not_found, invalid_auth, etc.) are NOT in this set and should fail fast.@@ -54,11 +48,6 @@ _RETRYABLE_SLACK_ERRORS = frozenset(MAX_SLACK_UPLOAD_BYTES = 1 * 1024 * 1024-def _next_delivery_date_display(subscription: Subscription) -> str:- next_delivery_date = subscription.next_delivery_date- return next_delivery_date.strftime("%A %B %d, %Y") if next_delivery_date is not None else "an upcoming date"--@dataclassclass SlackMessage:channel: str@@ -116,7 +105,7 @@ def _subscription_title(return (f"This channel has been subscribed to {display_name} on PostHog! 🎉\n"f"This subscription is {subscription.summary}. "- f"The next one will be sent on {_next_delivery_date_display(subscription)}"+ f"The next one will be sent on {next_delivery_date_display(subscription)}")return f"Your subscription to {display_name} is ready! 🎉"@@ -195,23 +184,11 @@ def _prepare_slack_gallery(def _block_for_asset(asset: ExportedAsset, resource_url: str) -> dict:if _has_asset_failed(asset):- insight_name = asset.insight.name or asset.insight.derived_name if asset.insight else "Unknown insight"-- # Slack text blocks have a 3000 character limit- # Reserve space for the insight name, formatting, and support message- max_error_length = 2000-- if asset.exception:- exception_text = subscription_asset_error_message(asset)- if len(exception_text) > max_error_length:- exception_text = exception_text[:max_error_length] + "... (truncated)"- else:- exception_text = ASSET_GENERATION_FAILED_MESSAGE-- support_url = f"{resource_url}#panel=support:bug:analytics_platform:high:true"+ details = failed_asset_details(asset)+ support_url = subscription_support_url(resource_url)error_text = (- f"*{insight_name}*\n"- f"There was an error generating your asset: {exception_text}\n"+ f"*{details.insight_name}*\n"+ f"There was an error generating your asset: {details.error_text}\n"f"_If this issue persists, please <{support_url}|contact support>._")@@ -224,7 +201,7 @@ def _block_for_asset(asset: ExportedAsset, resource_url: str) -> dict:alt_text = asset.insight.name or asset.insight.derived_nameif settings.DEBUG:- image_url = "https://posthog.com/icons/icon-512x512.png"+ image_url = DEBUG_PLACEHOLDER_IMAGE_URLreturn {"type": "image", "image_url": image_url, "alt_text": alt_text}@@ -280,12 +257,8 @@ def _prepare_slack_message(blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": _ai_summary_text(change_summary)}})elif summary_skipped_over_budget:billing_url = f"{absolute_uri('/organization/billing')}?{utm_tags}"- blocks.append(- {- "type": "context",- "elements": [{"type": "mrkdwn", "text": summary_skipped_over_budget_message(billing_url)}],- }- )+ notice = summary_skipped_over_budget_message(f"<{billing_url}|Billing settings>")+ blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": f"_{notice}_"}]})blocks.append(_block_for_asset(first_asset, resource_url=resource_info.url))diff --git a/ee/tasks/subscriptions/subscription_utils.py b/ee/tasks/subscriptions/subscription_utils.pyindex 40ea30e2da8b..4c42e63b9006 100644--- a/ee/tasks/subscriptions/subscription_utils.py+++ b/ee/tasks/subscriptions/subscription_utils.py@@ -7,6 +7,7 @@ import structlogfrom celery import chainfrom prometheus_client import Histogram+from posthog.dataclasses import frozenfrom posthog.models.sharing_configuration import SharingConfigurationfrom posthog.tasks import exporterfrom posthog.utils import wait_for_parallel_celery_group@@ -21,6 +22,17 @@ UTM_TAGS_BASE = "utm_source=posthog&utm_campaign=subscription_report"# Keep in sync with MAX_INSIGHTS in products/subscriptions/frontend/components/Subscriptions/insightSelectorLogic.ts.MAX_INSIGHTS = 10ASSET_GENERATION_FAILED_MESSAGE = "Failed to generate content"+# Marks text every channel had to cut short. Shared so email, Slack and Teams read the same.+TRUNCATION_MARKER = "... (truncated)"+# Bounds one failed asset's error text so a run where several fail cannot push a message past the+# destination's payload limit on its own.+_MAX_ASSET_ERROR_LENGTH = 2000+# Locally rendered assets live on a localhost URL that Slack and Microsoft cannot fetch, so the+# message links a public placeholder instead of an image that would render broken. Keep this on a+# domain we control, because a third-party placeholder can be retired without warning.+DEBUG_PLACEHOLDER_IMAGE_URL = (+ "https://raw.githubusercontent.com/PostHog/posthog/master/frontend/public/icons/android-chrome-512x512.png"+)# Prometheus metrics for Temporal workers (web/worker pods)SUBSCRIPTION_ASSET_GENERATION_TIMER = Histogram("subscription_asset_generation_duration_seconds",@@ -34,6 +46,11 @@ def _has_asset_failed(asset: ExportedAsset) -> bool:return (not asset.content and not asset.content_location) or asset.exception is not None+def next_delivery_date_display(subscription: Subscription) -> str:+ next_delivery_date = subscription.next_delivery_date+ return next_delivery_date.strftime("%A %B %d, %Y") if next_delivery_date is not None else "an upcoming date"++_OOM_MESSAGE_MARKER = "ran out of memory"_OOM_EXCEPTION_TYPE = "ClickHouseQueryMemoryLimitExceeded"@@ -51,6 +68,37 @@ def subscription_asset_error_message(asset: ExportedAsset) -> str:return ASSET_GENERATION_FAILED_MESSAGE+@frozen+class FailedAssetDetails:+ insight_name: str+ error_text: str+++def failed_asset_details(asset: ExportedAsset) -> FailedAssetDetails:+ """The two pieces every channel renders for an asset that failed to generate. Callers own the+ markup, since Slack mrkdwn, Adaptive Card markdown and the email template all differ."""+ insight = asset.insight+ insight_name = (insight.name or insight.derived_name or "Unknown insight") if insight else "Unknown insight"+ if asset.exception:+ error_text = subscription_asset_error_message(asset)+ if len(error_text) > _MAX_ASSET_ERROR_LENGTH:+ error_text = error_text[:_MAX_ASSET_ERROR_LENGTH] + TRUNCATION_MARKER+ else:+ error_text = ASSET_GENERATION_FAILED_MESSAGE+ return FailedAssetDetails(insight_name=insight_name, error_text=error_text)+++def subscription_support_url(resource_url: str) -> str:+ return f"{resource_url}#panel=support:bug:analytics_platform:high:true"+++def summary_skipped_over_budget_message(billing_settings_link: str) -> str:+ return (+ "AI summary skipped. Your organization has reached its AI credit usage limit. "+ f"Increase the limit in {billing_settings_link} to resume summaries."+ )++def generate_assets(resource: Union[Subscription, SharingConfiguration],max_asset_count: int = MAX_INSIGHTS,diff --git a/ee/tasks/subscriptions/teams_subscriptions.py b/ee/tasks/subscriptions/teams_subscriptions.pynew file mode 100644index 000000000000..b81e463a4a3d--- /dev/null+++ b/ee/tasks/subscriptions/teams_subscriptions.py@@ -0,0 +1,173 @@+from typing import Any++from django.conf import settings++from posthog.helpers.markdown_safety import strip_external_links_markdown+from posthog.utils import absolute_uri++from products.exports.backend.models.exported_asset import ExportedAsset+from products.exports.backend.models.subscription import Subscription++from ee.tasks.subscriptions.subscription_utils import (+ DEBUG_PLACEHOLDER_IMAGE_URL,+ TRUNCATION_MARKER,+ UTM_TAGS_BASE,+ _has_asset_failed,+ failed_asset_details,+ next_delivery_date_display,+ subscription_support_url,+ summary_skipped_over_budget_message,+)++TEAMS_UTM_TAGS = f"{UTM_TAGS_BASE}&utm_medium=teams"++TEAMS_WEBHOOK_URL_MASKED_ERROR = (+ "The saved webhook URL is hidden, so it cannot be sent back. Leave the field alone to keep it, "+ "or paste the full URL to replace it."+)++TEAMS_WEBHOOK_URL_ERROR = (+ "This does not look like a Microsoft Teams webhook URL. Create one with the Workflows app in the "+ "channel you want reports in, then paste the URL it gives you. Microsoft's setup guide: "+ "https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook"+)++# Teams rejects an incoming webhook payload over roughly 28KB. This bounds the UTF-8 bytes of text+# a card carries, which is the unit Teams measures the payload in, and leaves room for the JSON+# envelope, the image URLs and the actions. Counting characters instead would let a card of emoji+# or non-Latin text pass this check and still be rejected on the wire.+TEAMS_CARD_TEXT_BUDGET = 20000+++def teams_byte_size(text: str) -> int:+ return len(text.encode("utf-8"))+++def teams_text_block(text: str, *, is_subtle: bool = False) -> dict[str, Any]:+ block: dict[str, Any] = {"type": "TextBlock", "text": text, "wrap": True}+ if is_subtle:+ block["isSubtle"] = True+ return block+++def teams_open_url_action(title: str, url: str) -> dict[str, str]:+ return {"type": "Action.OpenUrl", "title": title, "url": url}+++def teams_card_message(body: list[dict[str, Any]], actions: list[dict[str, str]]) -> dict[str, Any]:+ return {+ "type": "message",+ "attachments": [+ {+ "contentType": "application/vnd.microsoft.card.adaptive",+ "contentUrl": None,+ "content": {+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",+ "type": "AdaptiveCard",+ "version": "1.2",+ "body": body,+ "actions": actions,+ },+ }+ ],+ }+++def fit_to_teams_budget(text: str, budget: int) -> str:+ if teams_byte_size(text) <= budget:+ return text+ keep = max(budget - teams_byte_size(TRUNCATION_MARKER), 0)+ # Slicing bytes can land inside a multi-byte character, so drop the partial one on decode.+ return text.encode("utf-8")[:keep].decode("utf-8", errors="ignore") + TRUNCATION_MARKER+++def _element_for_asset(asset: ExportedAsset, resource_url: str) -> dict[str, Any]:+ if _has_asset_failed(asset):+ details = failed_asset_details(asset)+ support_url = subscription_support_url(resource_url)+ insight_name = strip_external_links_markdown(details.insight_name)+ error_text = strip_external_links_markdown(details.error_text)+ return teams_text_block(+ f"**{insight_name}**\n\n"+ f"There was an error generating your asset: {error_text}\n\n"+ f"_If this issue persists, please [contact support]({support_url})._"+ )++ image_url = DEBUG_PLACEHOLDER_IMAGE_URL if settings.DEBUG else asset.get_subscription_delivery_content_url()+ image: dict[str, Any] = {"type": "Image", "url": image_url, "size": "Stretch"}+ alt_text = (asset.insight.name or asset.insight.derived_name) if asset.insight else None+ if alt_text:+ image["altText"] = alt_text+ return image+++def build_teams_subscription_card(+ subscription: Subscription,+ assets: list[ExportedAsset],+ total_asset_count: int,+ *,+ is_new_subscription: bool = False,+ change_summary: str | None = None,+ summary_skipped_over_budget: bool = False,+) -> dict[str, Any]:+ resource_info = subscription.resource_info+ if not resource_info:+ raise NotImplementedError("This type of subscription resource is not supported")++ resource_name = strip_external_links_markdown(resource_info.name)+ if subscription.title:+ subscription_title = strip_external_links_markdown(subscription.title)+ display_name = f"**{subscription_title}** ({resource_info.kind}: {resource_name})"+ else:+ display_name = f"the {resource_info.kind} **{resource_name}**"++ if is_new_subscription:+ title = (+ f"This channel has been subscribed to {display_name} on PostHog! 🎉\n\n"+ f"This subscription is {subscription.summary}. "+ f"The next one will be sent on {next_delivery_date_display(subscription)}"+ )+ else:+ title = f"Your subscription to {display_name} is ready! 🎉"++ body: list[dict[str, Any]] = [teams_text_block(title)]+ remaining = TEAMS_CARD_TEXT_BUDGET - teams_byte_size(title)++ if change_summary:+ # The summary is LLM output over customer data, so it is defanged the same way the AI+ # report is before it reaches a surface that turns a URL into a link.+ summary = fit_to_teams_budget(f"**AI summary**\n\n{strip_external_links_markdown(change_summary)}", remaining)+ body.append(teams_text_block(summary))+ remaining -= teams_byte_size(summary)+ elif summary_skipped_over_budget:+ billing_url = f"{absolute_uri('/organization/billing')}?{TEAMS_UTM_TAGS}"+ link = f"[Billing settings]({billing_url})"+ notice = f"_{summary_skipped_over_budget_message(link)}_"+ body.append(teams_text_block(notice, is_subtle=True))+ remaining -= teams_byte_size(notice)++ shown = 0+ for asset in assets:+ element = _element_for_asset(asset, resource_url=resource_info.url)+ size = teams_byte_size(element.get("text", ""))+ # The first asset always goes in, so a card is never all notice and no content.+ if shown and size > remaining:+ break+ body.append(element)+ remaining -= size+ shown += 1++ if total_asset_count > shown:+ body.append(+ teams_text_block(+ f"Showing {shown} of {total_asset_count} insights. "+ f"[View the rest in PostHog]({resource_info.url}?{TEAMS_UTM_TAGS})",+ is_subtle=True,+ )+ )++ actions = [+ teams_open_url_action("View in PostHog", f"{resource_info.url}?{TEAMS_UTM_TAGS}"),+ teams_open_url_action("Manage subscription", f"{subscription.url}?{TEAMS_UTM_TAGS}"),+ ]+ return teams_card_message(body, actions)diff --git a/ee/tasks/subscriptions/test_auto_disable.py b/ee/tasks/subscriptions/test_auto_disable.pyindex 532dec5333a1..bbef7894c4e9 100644--- a/ee/tasks/subscriptions/test_auto_disable.py+++ b/ee/tasks/subscriptions/test_auto_disable.py@@ -15,6 +15,7 @@ from ee.tasks.subscriptions.auto_disable import (SLACK_DISCONNECTED_DISABLE_REASON,disable_invalid_subscription,send_notifications_for_disabled_subscription,+ target_type_label,validate_re_enable,)from ee.tasks.subscriptions.failure_notifications import (@@ -38,6 +39,7 @@ class TestValidateReEnable:("email_with_integration_passes", "email", 42, None),("slack_with_integration_passes", "slack", 42, None),("slack_no_integration_rejected", "slack", None, "no integration configured"),+ ("teams_passes", "teams", None, None),("webhook_no_integration_rejected", "webhook", None, "this delivery channel is not currently supported"),("webhook_with_integration_rejected", "webhook", 42, "this delivery channel is not currently supported"),]@@ -51,6 +53,22 @@ class TestValidateReEnable:assert expected in result+class TestTargetTypeLabel:+ @parameterized.expand(+ [+ # Every {target_type} placeholder in a disable reason runs through this, so a supported+ # target has to render the name the user picked in the UI, not the stored value.+ ("teams_reads_as_the_channel_name", "teams", "Microsoft Teams"),+ ("email_reads_as_its_label", "email", "Email"),+ ("none_renders_nothing", None, ""),+ ("empty_renders_nothing", "", ""),+ ("removed_target_falls_back_to_its_value", "webhook", "webhook"),+ ]+ )+ def test_target_type_label(self, _label, target_type, expected):+ assert target_type_label(target_type) == expected++class TestDisableInvalidSubscription(APIBaseTest):def _make_subscription(self, **overrides) -> Subscription:defaults = {@@ -82,7 +100,7 @@ class TestDisableInvalidSubscription(APIBaseTest):assert notification.target_id == str(self.user.id)assert notification.resource_id == str(sub.id)assert notification.title == "t was automatically disabled"- assert "slack integration disconnected" in notification.body+ assert "Slack integration disconnected" in notification.bodysend_mock.assert_called_once_with(sub, SLACK_DISCONNECTED_DISABLE_REASON, [self.user.email])def test_compare_and_swap_no_op_when_already_disabled(self):diff --git a/ee/tasks/test/subscriptions/test_teams_subscriptions.py b/ee/tasks/test/subscriptions/test_teams_subscriptions.pynew file mode 100644index 000000000000..e726cc93131e--- /dev/null+++ b/ee/tasks/test/subscriptions/test_teams_subscriptions.py@@ -0,0 +1,167 @@+from posthog.test.base import APIBaseTest++from parameterized import parameterized++from products.exports.backend.models.exported_asset import ExportedAsset+from products.product_analytics.backend.facade.models import Insight++from ee.tasks.subscriptions.subscription_utils import MAX_INSIGHTS, TRUNCATION_MARKER+from ee.tasks.subscriptions.teams_subscriptions import TEAMS_CARD_TEXT_BUDGET, build_teams_subscription_card+from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription++VALID_TEAMS_WEBHOOK_URL = (+ "https://prod-25.westeurope.logic.azure.com:443/workflows/abc123/triggers/manual/paths/invoke?sig=secret"+)+++class TestTeamsSubscriptionCard(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.insight = Insight.objects.create(team=self.team, short_id="123456", name="My Test subscription")+ self.asset = ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ content_location="s3://bucket/test.png",+ )+ self.subscription = create_subscription(+ team=self.team,+ insight=self.insight,+ created_by=self.user,+ target_type="teams",+ target_value=VALID_TEAMS_WEBHOOK_URL,+ )++ def _card_content(self, **kwargs) -> dict:+ message = build_teams_subscription_card(self.subscription, [self.asset], 1, **kwargs)+ assert message["type"] == "message"+ attachment = message["attachments"][0]+ assert attachment["contentType"] == "application/vnd.microsoft.card.adaptive"+ return attachment["content"]++ def test_card_links_the_asset_image_and_action_urls(self) -> None:+ content = self._card_content()++ assert content["version"] == "1.2"+ assert content["body"][0]["text"] == "Your subscription to the Insight **My Test subscription** is ready! 🎉"+ image = content["body"][1]+ assert image["type"] == "Image"+ assert image["url"].startswith("http://localhost:8010/exporter/")+ assert image["altText"] == "My Test subscription"+ assert content["actions"] == [+ {+ "type": "Action.OpenUrl",+ "title": "View in PostHog",+ "url": "http://localhost:8010/insights/123456?utm_source=posthog&utm_campaign=subscription_report&utm_medium=teams",+ },+ {+ "type": "Action.OpenUrl",+ "title": "Manage subscription",+ "url": f"http://localhost:8010/insights/123456/subscriptions/{self.subscription.id}?utm_source=posthog&utm_campaign=subscription_report&utm_medium=teams",+ },+ ]++ def test_external_links_in_subscription_and_resource_names_are_defanged(self) -> None:+ self.subscription.title = "[Open report](https://attacker.example/login)"+ self.subscription.save(update_fields=["title"])+ self.insight.name = "[Quarterly report](https://evil.example.com/report)"+ self.insight.save(update_fields=["name"])++ content = self._card_content()++ assert content["body"][0]["text"] == (+ "Your subscription to **Open report** (Insight: Quarterly report) is ready! 🎉"+ )++ def test_capped_assets_get_a_trailer_pointing_at_the_rest(self) -> None:+ message = build_teams_subscription_card(self.subscription, [self.asset], 4)+ trailer = message["attachments"][0]["content"]["body"][-1]++ assert trailer["type"] == "TextBlock"+ assert trailer["text"].startswith("Showing 1 of 4 insights.")++ def test_failed_asset_renders_as_text_not_a_broken_image(self) -> None:+ self.asset.content_location = None+ self.asset.exception = "Query timed out"+ self.asset.save()++ content = self._card_content()+ block = content["body"][1]++ assert block["type"] == "TextBlock"+ assert "Query timed out" in block["text"]++ def test_failed_asset_external_links_are_defanged(self) -> None:+ self.insight.name = "[Quarterly report](https://evil.example.com/report)"+ self.insight.save(update_fields=["name"])+ self.asset.content_location = None+ self.asset.exception = "[Retry here](https://attacker.example/login)"+ self.asset.save()++ content = self._card_content()+ block = content["body"][1]++ assert "**Quarterly report**" in block["text"]+ assert "There was an error generating your asset: Retry here" in block["text"]+ assert "evil.example.com" not in block["text"]+ assert "attacker.example" not in block["text"]++ def test_a_first_delivery_says_the_channel_is_now_subscribed(self) -> None:+ content = self._card_content(is_new_subscription=True)++ assert content["body"][0]["text"].startswith(+ "This channel has been subscribed to the Insight **My Test subscription** on PostHog!"+ )++ def test_a_summary_skipped_over_budget_says_so_in_subtle_text(self) -> None:+ content = self._card_content(summary_skipped_over_budget=True)+ notice = content["body"][1]++ assert notice["isSubtle"] is True+ assert "Your organization has reached its AI credit usage limit." in notice["text"]+ assert "[Billing settings](" in notice["text"]++ def test_change_summary_is_placed_above_the_charts(self) -> None:+ content = self._card_content(change_summary="Signups doubled")++ assert content["body"][1]["text"] == "**AI summary**\n\nSignups doubled"+ assert content["body"][2]["type"] == "Image"++ def test_change_summary_links_are_defanged(self) -> None:+ content = self._card_content(change_summary="Signups doubled, see [why](https://evil.example.com/x)")++ assert "evil.example.com" not in str(content)++ @parameterized.expand(+ [+ ("single_byte_error_text", "detail "),+ # Three bytes per character, so a card that fits the budget by character count is over+ # it by the byte count Teams measures.+ ("multi_byte_error_text", "詳細 "),+ ]+ )+ def test_a_run_where_every_asset_failed_stays_inside_the_card_budget(self, _label, filler) -> None:+ failed_assets = [+ ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ exception="Query timed out. " + filler * 1000,+ )+ for _ in range(MAX_INSIGHTS)+ ]++ card = build_teams_subscription_card(self.subscription, failed_assets, MAX_INSIGHTS)+ body = card["attachments"][0]["content"]["body"]+ shown = sum(1 for element in body if "Query timed out." in element.get("text", ""))++ assert sum(len(element.get("text", "").encode("utf-8")) for element in body) <= TEAMS_CARD_TEXT_BUDGET+ assert shown < MAX_INSIGHTS+ assert body[-1]["text"].startswith(f"Showing {shown} of {MAX_INSIGHTS} insights.")++ def test_an_oversized_multi_byte_summary_is_truncated_within_the_byte_budget(self) -> None:+ content = self._card_content(change_summary="詳" * TEAMS_CARD_TEXT_BUDGET)+ summary = content["body"][1]["text"]++ assert len(summary.encode("utf-8")) <= TEAMS_CARD_TEXT_BUDGET+ assert summary.endswith(TRUNCATION_MARKER)diff --git a/frontend/src/lib/utils/url.test.ts b/frontend/src/lib/utils/url.test.tsindex 3be855ab2f0a..ab678993e931 100644--- a/frontend/src/lib/utils/url.test.ts+++ b/frontend/src/lib/utils/url.test.ts@@ -1,6 +1,7 @@import {getRelativeNextPath,isExternalLink,+ isHttpsUrl,isURL,parseNumericArrayFilter,parseTagsFilter,@@ -365,4 +366,17 @@ describe('url utils', () => {expect(parseNumericArrayFilter(undefined)).toBeUndefined()})})+ describe('isHttpsUrl', () => {+ it.each([+ ['https://example.com/webhook', true],+ ['https://example.com:444/webhook', true],+ [' https://example.com/webhook ', true],+ ['http://example.com/webhook', false],+ ['not a URL', false],+ [' ', false],+ ['', false],+ ])('returns %s -> %s', (value, expected) => {+ expect(isHttpsUrl(value)).toBe(expected)+ })+ })})diff --git a/frontend/src/lib/utils/url.ts b/frontend/src/lib/utils/url.tsindex 7b20b7981c3c..afd9e97a7bde 100644--- a/frontend/src/lib/utils/url.ts+++ b/frontend/src/lib/utils/url.ts@@ -165,6 +165,23 @@ export function isExternalLink(input: any): boolean {return !!input.trim().match(regexp)}+/**+ * True for a value that parses as an `https://` URL. Whitespace around the value is ignored,+ * because `new URL()` ignores it too. A caller that needs a host allowlist, or that wants to+ * reject embedded credentials, adds that check itself.+ */+export function isHttpsUrl(value: string): boolean {+ const trimmed = value.trim()+ if (!trimmed) {+ return false+ }+ try {+ return new URL(trimmed).protocol === 'https:'+ } catch {+ return false+ }+}+export function isEmail(string: string, options?: { requireTLD?: boolean }): boolean {if (!string) {return falsediff --git a/posthog/security/test/test_url_validation.py b/posthog/security/test/test_url_validation.pyindex 59459d94bd8e..b74670ad6450 100644--- a/posthog/security/test/test_url_validation.py+++ b/posthog/security/test/test_url_validation.py@@ -357,3 +357,42 @@ class TestUrlValidation:)def test_has_ambiguous_authority(self, url, expected):assert uv.has_ambiguous_authority(url) is expected++ @pytest.mark.parametrize(+ "url",+ [+ "https://prod-25.westeurope.logic.azure.com:443/workflows/abc/triggers/manual/paths/invoke?sig=x",+ "https://acme.webhook.office.com/webhookb2/guid@guid/IncomingWebhook/hash/guid",+ "https://europe.powerautomate.com/manual/paths/invoke",+ "https://prod-01.flow.microsoft.com/manual/paths/invoke",+ "https://acme.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/abc",+ ],+ )+ def test_accepts_microsoft_teams_webhook_url(self, url):+ assert uv.is_microsoft_teams_webhook_url(url) is True++ @pytest.mark.parametrize(+ "url",+ [+ # Both hostnames are registrable by anyone and satisfy the unescaped-dot patterns in+ # the CDP Teams template. They must not satisfy these.+ "https://evilpowerautomate.com/x",+ "https://aaaflow-microsoft.com/y",+ "https://evil.example.com/logic.azure.com/workflows/abc",+ "https://logic.azure.com.evil.example.com/workflows/abc",+ "http://prod-25.westeurope.logic.azure.com/workflows/abc/triggers/manual/paths/invoke",+ "https://prod-25.westeurope.logic.azure.com:8443/workflows/abc/triggers/manual/paths/invoke",+ "https://prod-25.westeurope.logic.azure.com/workflows/abc",+ "https://acme.webhook.office.com/webhookb2/guid",+ "https://acme.webhook.office.com/something-else/guid",+ "https://prod-25.westeurope.logic.azure.com\\@evil.example.com/workflows/abc/triggers/manual/paths/invoke",+ "definitely not a url",+ "",+ # `requests` would turn the userinfo into a Basic Authorization header on the send,+ # and the credential would live on in the stored subscription.+ "https://user:[email protected]/workflows/abc/triggers/manual/paths/invoke",+ "https://[email protected]/workflows/abc/triggers/manual/paths/invoke",+ ],+ )+ def test_rejects_non_teams_webhook_url(self, url):+ assert uv.is_microsoft_teams_webhook_url(url) is Falsediff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.pyindex f735541bd628..f897a3800ca1 100644--- a/posthog/security/url_validation.py+++ b/posthog/security/url_validation.py@@ -1,3 +1,4 @@+import reimport ipaddressimport urllib.parse as urlparsefrom collections.abc import Iterable, Mapping@@ -242,6 +243,49 @@ def strip_userinfo(url: str) -> str:return urlparse.urlunparse(parsed._replace(netloc=netloc))+# Hosts that hand out a Microsoft Teams incoming webhook. Dots are escaped and the host is anchored+# at both ends, so a registrable lookalike such as `evilpowerautomate.com` cannot match. The CDP+# Teams template matches the same hosts with unescaped dots, so its patterns are not reusable here.+_TEAMS_LOGIC_APPS_HOST = re.compile(r"^(?:[a-z0-9-]+\.)+logic\.azure\.com$")+_TEAMS_CONNECTOR_HOST = re.compile(r"^(?:[a-z0-9-]+\.)+webhook\.office\.com$")+_TEAMS_POWER_AUTOMATE_HOST = re.compile(r"^(?:[a-z0-9-]+\.)+(?:powerautomate\.com|flow\.microsoft\.com)$")+_TEAMS_POWER_PLATFORM_HOST = re.compile(r"^(?:[a-z0-9-]+\.)+environment\.api\.powerplatform\.com$")+++def is_microsoft_teams_webhook_url(url: str) -> bool:+ """Whether a URL is one of the Microsoft Teams webhook shapes we are willing to post to.++ Checks the scheme, host and path only, with no name resolution, so it is cheap enough for a+ save path. Anything that then delivers to the URL must still run the full SSRF validation,+ because DNS can change between the save and the send.+ """+ if has_authority_bypass_chars(url):+ return False+ try:+ parsed = urlparse.urlparse(url)+ port = parsed.port+ except ValueError:+ return False+ # `requests` turns userinfo into a Basic `Authorization` header on the outbound POST, and the+ # credential would sit in the stored URL for as long as the subscription lives.+ if parsed.username is not None or parsed.password is not None:+ return False+ if parsed.scheme != "https" or port not in (None, 443):+ return False++ host = (parsed.hostname or "").lower()+ path = parsed.path+ if _TEAMS_LOGIC_APPS_HOST.match(host):+ return path.startswith("/workflows/") and "/triggers/manual/paths/invoke" in path+ if _TEAMS_CONNECTOR_HOST.match(host):+ return path.startswith("/webhookb2/") and "/IncomingWebhook/" in path+ if _TEAMS_POWER_AUTOMATE_HOST.match(host):+ return bool(path.strip("/"))+ if _TEAMS_POWER_PLATFORM_HOST.match(host):+ return path.startswith("/powerautomate/automations/direct/") and "/workflows/" in path+ return False++def _dev_bypass_enabled() -> bool:"""Dev mode short-circuits is_url_allowed.diff --git a/posthog/temporal/tests/test_subscriptions_workflows.py b/posthog/temporal/tests/test_subscriptions_workflows.pyindex 3dc112af25e6..7c482ff20dfe 100644--- a/posthog/temporal/tests/test_subscriptions_workflows.py+++ b/posthog/temporal/tests/test_subscriptions_workflows.py@@ -579,6 +579,71 @@ async def test_deliver_subscription_report_slack(assert mock_send_slack_async.await_count == 1+@patch("products.exports.backend.temporal.subscriptions.delivery_webhook.pinned_session")+@patch("posthog.temporal.exports.activities.exporter")+@patch("ee.tasks.subscriptions.get_metric_meter")+async def test_deliver_subscription_report_teams(+ mock_metric_meter: MagicMock,+ mock_exporter: MagicMock,+ mock_pinned_session: MagicMock,+ temporal_client: Client,+ subscriptions_worker,+ team,+ user,+):+ # Power Automate acknowledges an accepted card with 202 rather than 200.+ mock_post = mock_pinned_session.return_value.__enter__.return_value.request+ mock_post.return_value = MagicMock(status_code=202)++ insight = await sync_to_async(Insight.objects.create)(team=team, short_id="tms999", name="Insight")+ subscription = await sync_to_async(create_subscription)(+ team=team,+ insight=insight,+ created_by=user,+ target_type="teams",+ target_value="https://prod-25.westeurope.logic.azure.com:443/workflows/abc/triggers/manual/paths/invoke",+ )++ def fake_export(asset_obj, **kwargs):+ asset_obj.content_location = "s3://bucket/teams.png"+ asset_obj.save(update_fields=["content_location"])++ mock_exporter.export_asset_direct = fake_export++ async with await WorkflowEnvironment.start_time_skipping() as activity_environment:+ async with Worker(+ activity_environment.client,+ task_queue=settings.TEMPORAL_TASK_QUEUE,+ workflows=[HandleSubscriptionValueChangeWorkflow, ProcessSubscriptionWorkflow],+ activities=SUBSCRIPTION_PROCESS_ACTIVITIES,+ interceptors=[SloInterceptor()],+ workflow_runner=UnsandboxedWorkflowRunner(),+ activity_executor=ThreadPoolExecutor(max_workers=50),+ debug_mode=True,+ ):+ await activity_environment.client.execute_workflow(+ HandleSubscriptionValueChangeWorkflow.run,+ ProcessSubscriptionWorkflowInputs(+ subscription_id=subscription.id,+ team_id=subscription.team_id,+ distinct_id=str(subscription.created_by.distinct_id), # type: ignore[union-attr]+ ),+ id=str(uuid.uuid4()),+ task_queue=settings.TEMPORAL_TASK_QUEUE,+ )++ assert mock_post.call_count == 1+ card = mock_post.call_args.kwargs["json"]+ assert card["attachments"][0]["content"]["type"] == "AdaptiveCard"++ delivery = await sync_to_async(SubscriptionDelivery.objects.get)(subscription_id=subscription.id)+ assert delivery.status == DeliveryStatus.COMPLETED+ assert delivery.recipient_results == [{"recipient": "prod-25.westeurope.logic.azure.com", "status": "success"}]+ # The delivery row is read-only history the API returns, so it keeps the host, not the URL.+ assert delivery.target_value == "prod-25.westeurope.logic.azure.com"++@patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription")@patch("products.exports.backend.temporal.subscriptions.activities.build_insight_delivery_snapshot")@patch(@@ -2543,6 +2608,25 @@ async def test_deliver_ai_subscription_missing_slack_integration_auto_disables(tassert sub.enabled is False+async def test_deliver_ai_subscription_posts_the_report_to_teams(team, user):+ sub = await _create_ai_subscription(+ team,+ user,+ target_type="teams",+ target_value="https://prod-25.westeurope.logic.azure.com:443/workflows/abc/triggers/manual/paths/invoke",+ )+ delivery = await _create_ai_delivery(sub, report="# Report")++ with patch("products.exports.backend.temporal.subscriptions.delivery_webhook.pinned_session") as mock_session:+ mock_post = mock_session.return_value.__enter__.return_value.request+ mock_post.return_value = MagicMock(status_code=202)+ result = await ActivityEnvironment().run(deliver_subscription, _ai_delivery_inputs(sub.id, delivery.id))++ body = mock_post.call_args.kwargs["json"]["attachments"][0]["content"]["body"]+ assert any("# Report" in block["text"] for block in body)+ assert result.recipient_results[0].status == "success"++async def test_deliver_ai_subscription_missing_report_raises_for_retry(team, user):# Generation persists the report before delivery is scheduled; a missing report# means the row was lost, so delivery must fail loudly rather than send an empty report.diff --git a/products/billing_alerts/backend/presentation/serializers.py b/products/billing_alerts/backend/presentation/serializers.pyindex 97f7db5cd100..d63e3b2f5aef 100644--- a/products/billing_alerts/backend/presentation/serializers.py+++ b/products/billing_alerts/backend/presentation/serializers.py@@ -11,6 +11,8 @@ from drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializersfrom rest_framework.exceptions import ValidationError+from posthog.security.url_validation import is_microsoft_teams_webhook_url+from products.alerts.backend.facade.api import (AlertDestinationData,AlertDestinationValidationError,@@ -38,21 +40,6 @@ def _any_field_changed(return any(field in validated_data and validated_data[field] != getattr(instance, field) for field in fields)-def _is_microsoft_teams_webhook(webhook_url: str) -> bool:- parsed = urlparse(webhook_url)- hostname = parsed.hostname or ""- path = parsed.path- if hostname.endswith(".logic.azure.com"):- return parsed.port in (None, 443) and path.startswith("/workflows/") and "/triggers/manual/paths/invoke" in path- if hostname.endswith(".webhook.office.com"):- return path.startswith("/webhookb2/") and "/IncomingWebhook/" in path- if hostname.endswith((".powerautomate.com", ".flow.microsoft.com")):- return bool(path.strip("/"))- if hostname.endswith(".environment.api.powerplatform.com"):- return path.startswith("/powerautomate/automations/direct/") and "/workflows/" in path- return False--class BillingAlertEventSerializer(serializers.ModelSerializer):# Model properties derived from the claim, so DRF cannot generate them.evaluation_date = serializers.DateField(@@ -153,7 +140,7 @@ class BillingAlertDestinationCreateDataSerializer(serializers.Serializer):parsed_url = urlparse(webhook_url)if parsed_url.scheme != "https" or not parsed_url.netloc:raise ValidationError({"webhook_url": "Webhook URLs must be valid HTTPS URLs."})- if data["type"] == DestinationType.TEAMS and not _is_microsoft_teams_webhook(webhook_url):+ if data["type"] == DestinationType.TEAMS and not is_microsoft_teams_webhook_url(webhook_url):raise ValidationError({"webhook_url": "Enter a supported Microsoft Teams webhook URL."})return attrsdiff --git a/products/billing_alerts/frontend/billingAlertNotificationLogic.test.ts b/products/billing_alerts/frontend/billingAlertNotificationLogic.test.tsdeleted file mode 100644index 6a324d3fb430..000000000000--- a/products/billing_alerts/frontend/billingAlertNotificationLogic.test.ts+++ /dev/null@@ -1,10 +0,0 @@-import { isHttpsUrl } from './billingAlertNotificationLogic'--describe('billing alert notification input validation', () => {- it('keeps browser validation to HTTPS completeness and leaves destination policy to the server', () => {- expect(isHttpsUrl('https://example.com/webhook')).toBe(true)- expect(isHttpsUrl('https://example.com:444/webhook')).toBe(true)- expect(isHttpsUrl('http://example.com/webhook')).toBe(false)- expect(isHttpsUrl('not a URL')).toBe(false)- })-})diff --git a/products/billing_alerts/frontend/billingAlertNotificationLogic.ts b/products/billing_alerts/frontend/billingAlertNotificationLogic.tsindex 8fc899cf5432..7d1245061d02 100644--- a/products/billing_alerts/frontend/billingAlertNotificationLogic.ts+++ b/products/billing_alerts/frontend/billingAlertNotificationLogic.ts@@ -3,6 +3,7 @@ import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reduimport { lemonToast } from '@posthog/lemon-ui'import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { isHttpsUrl } from 'lib/utils/url'import { billingLogic } from 'scenes/billing/billingLogic'import { teamLogic } from 'scenes/teamLogic'@@ -29,18 +30,6 @@ export interface BillingAlertNotificationLogicProps {alert: BillingAlertConfigurationApi | null}-export function isHttpsUrl(value: string): boolean {- const trimmed = value.trim()- if (!trimmed) {- return false- }- try {- return new URL(trimmed).protocol === 'https:'- } catch {- return false- }-}-export interface billingAlertNotificationLogicValues {currentOrganization: OrganizationType | nullcurrentTeamId: number | nulldiff --git a/products/exports/backend/migrations/0010_alter_subscription_target_type.py b/products/exports/backend/migrations/0010_alter_subscription_target_type.pynew file mode 100644index 000000000000..ce85d7b93cad--- /dev/null+++ b/products/exports/backend/migrations/0010_alter_subscription_target_type.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.17 on 2026-08-20 08:06++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("exports", "0009_subscription_delivery_config"),+ ]++ operations = [+ migrations.AlterField(+ model_name="subscription",+ name="target_type",+ field=models.CharField(+ choices=[+ ("email", "Email"),+ ("slack", "Slack"),+ ("teams", "Microsoft Teams"),+ ],+ max_length=10,+ ),+ ),+ ]diff --git a/products/exports/backend/migrations/max_migration.txt b/products/exports/backend/migrations/max_migration.txtindex 8eb88bb29936..ee9cd8ecaf75 100644--- a/products/exports/backend/migrations/max_migration.txt+++ b/products/exports/backend/migrations/max_migration.txt@@ -1 +1 @@-0009_subscription_delivery_config+0010_alter_subscription_target_typediff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.pyindex c12800c27d45..9fde89d1ac3d 100644--- a/products/exports/backend/models/subscription.py+++ b/products/exports/backend/models/subscription.py@@ -5,6 +5,7 @@ from contextvars import ContextVarfrom dataclasses import dataclassfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literal, Optional, cast+from urllib.parse import urlparsefrom django.contrib.postgres.fields import ArrayFieldfrom django.db import models@@ -105,6 +106,7 @@ class Subscription(ModelActivityMixin, models.Model):class SubscriptionTarget(models.TextChoices):EMAIL = "email"SLACK = "slack"+ TEAMS = "teams", "Microsoft Teams"class SubscriptionFrequency(models.TextChoices):DAILY = "daily"@@ -441,6 +443,20 @@ class Subscription(ModelActivityMixin, models.Model):return info.namereturn self.title or "Subscription"+ @property+ def recipient_label(self) -> str:+ """Names the destination in `RecipientResult.recipient` and in the+ `SubscriptionDelivery.target_value` snapshot, both of which the API returns. A webhook URL+ authorizes a post to the channel on its own, so only its host is recorded.+ """+ if self.target_type != self.SubscriptionTarget.TEAMS:+ return self.target_value+ try:+ host = (urlparse(self.target_value).hostname or "").lower()+ except ValueError:+ host = ""+ return host or "webhook"+@propertydef summary(self):try:diff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.pyindex 0864cbd7dbae..17b4b8e11124 100644--- a/products/exports/backend/temporal/subscriptions/activities.py+++ b/products/exports/backend/temporal/subscriptions/activities.py@@ -23,6 +23,7 @@ from products.exports.backend.temporal.subscriptions.delivery_common import (deliver_email,deliver_slack,)+from products.exports.backend.temporal.subscriptions.delivery_webhook import deliver_teams_webhookfrom products.exports.backend.temporal.subscriptions.insight_snapshot import (build_initial_content_snapshot,build_insight_delivery_snapshot,@@ -57,6 +58,7 @@ from ee.tasks.subscriptions.failure_notifications import ()from ee.tasks.subscriptions.slack_subscriptions import send_slack_message_with_integration_asyncfrom ee.tasks.subscriptions.subscription_utils import MAX_INSIGHTS+from ee.tasks.subscriptions.teams_subscriptions import build_teams_subscription_cardLOGGER = get_logger(__name__)@@ -246,7 +248,7 @@ async def validate_subscription_for_delivery(subscription_id: int) -> DeliveryAbawait database_sync_to_async(disable_invalid_subscription, thread_sensitive=False)(subscription, reason)return DeliveryAbort(failed_recipient=RecipientResult(- recipient=subscription.target_value,+ recipient=subscription.recipient_label,status="failed",error={"message": reason.description, "type": reason.key},human_readable_error=reason.description,@@ -490,7 +492,7 @@ async def _deliver_insight_dashboard_subscription(LOGGER.warning("deliver_subscription.no_assets", subscription_id=inputs.subscription_id)recipient_results.append(RecipientResult(- recipient=subscription.target_value,+ recipient=subscription.recipient_label,status="failed",error={"message": NO_ASSETS_REASON, "type": "no_assets"},human_readable_error=NO_ASSETS_HUMAN_READABLE_REASON,@@ -532,6 +534,16 @@ async def _deliver_insight_dashboard_subscription(summary_skipped_over_budget=inputs.summary_skipped_over_budget,),)+ elif subscription.target_type == Subscription.SubscriptionTarget.TEAMS:+ card = build_teams_subscription_card(+ subscription,+ assets,+ inputs.total_insight_count,+ is_new_subscription=send_only_to_new_recipients,+ change_summary=inputs.change_summary,+ summary_skipped_over_budget=inputs.summary_skipped_over_budget,+ )+ result = await deliver_teams_webhook(subscription, recipient_results, body=card)else:raise ApplicationError(f"Subscription delivery reached an unsupported target {subscription.target_type!r}",@@ -569,7 +581,7 @@ async def create_delivery_record(inputs: CreateDeliveryRecordInputs) -> uuid.UUI"trigger_type": inputs.trigger_type,"scheduled_at": scheduled_at,"target_type": subscription.target_type,- "target_value": subscription.target_value,+ "target_value": subscription.recipient_label,"content_snapshot": content_snapshot,"status": SubscriptionDelivery.Status.STARTING,},diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.pyindex 9cb6e0df70e0..eeb6254a7c7c 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py@@ -19,6 +19,7 @@ from posthog.sync import database_sync_to_asyncfrom products.exports.backend.models.subscription import Subscription, SubscriptionDeliveryfrom products.exports.backend.temporal.subscriptions.ai_subscription.delivery import (build_ai_subscription_report,+ build_ai_teams_card,build_chart_image_urls,send_email_ai_subscription_credit_limited,send_email_ai_subscription_report,@@ -32,6 +33,7 @@ from products.exports.backend.temporal.subscriptions.delivery_common import (deliver_slack,strip_null_bytes,)+from products.exports.backend.temporal.subscriptions.delivery_webhook import deliver_teams_webhookfrom products.exports.backend.temporal.subscriptions.types import (AI_REPORT_CHARTS_KEY,AI_REPORT_DIAGNOSTICS_KEY,@@ -300,7 +302,7 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen# PromptRejectedError messages are handcrafted rejections (empty/too long/no creator), safe to show.recipient_results = [RecipientResult(- recipient=subscription.target_value,+ recipient=subscription.recipient_label,status="failed",error={"message": str(exc), "type": "PromptRejectedError"},human_readable_error=str(exc),@@ -383,6 +385,9 @@ async def _deliver_ai_subscription(charts=chart_images,),)+ if subscription.target_type == Subscription.SubscriptionTarget.TEAMS:+ card = build_ai_teams_card(subscription, markdown, delivery_id=delivery_id)+ 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.raise ApplicationError(diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.pyindex 4cb33294535d..873cbd47004b 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/delivery.py@@ -37,6 +37,15 @@ from ee.tasks.subscriptions.slack_subscriptions import (SlackMessage,deliver_slack_message_data,)+from ee.tasks.subscriptions.teams_subscriptions import (+ TEAMS_CARD_TEXT_BUDGET,+ TEAMS_UTM_TAGS,+ fit_to_teams_budget,+ teams_byte_size,+ teams_card_message,+ teams_open_url_action,+ teams_text_block,+)logger = structlog.get_logger(__name__)@@ -79,6 +88,14 @@ _ALLOWED_EMAIL_ATTRS = {"a": {"href", "title"}}SLACK_MRKDWN_SECTION_LIMIT = 2900SLACK_IMAGE_TITLE_LIMIT = 2000+TEAMS_TEXT_BLOCK_LIMIT = 3000+# Upper bound on report blocks. It only stops the chunker from splitting an unbounded report into+# thousands of pieces; TEAMS_CARD_TEXT_BUDGET is what keeps the payload inside what Teams accepts.+TEAMS_REPORT_BLOCK_COUNT = 10+# Chunking is quadratic in the number of chunks and nothing upstream bounds a report's length, so+# the markdown is cut to what could fill the blocks above before it is chunked at all.+_TEAMS_REPORT_CHUNKING_LIMIT = TEAMS_REPORT_BLOCK_COUNT * TEAMS_TEXT_BLOCK_LIMIT+def _split_text_into_chunks(text: str, limit: int = SLACK_MRKDWN_SECTION_LIMIT) -> list[str]:if len(text) <= limit:@@ -417,8 +434,64 @@ async def send_slack_ai_subscription_report(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]:+ """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")+ subscription_url = subscription.url or absolute_uri(+ f"/project/{subscription.team_id}/subscriptions/{subscription.id}"+ )++ report = strip_external_links_markdown(markdown)+ 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})"+ )+ 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})"++ # Chunking is by character and Teams measures the payload in UTF-8 bytes, so CJK or emoji text+ # is several times the size the chunker accounted for. The report gets whatever the fixed blocks+ # around it leave, which is what keeps such a report from being rejected on every scheduled run.+ remaining = (+ TEAMS_CARD_TEXT_BUDGET+ - teams_byte_size(heading)+ - teams_byte_size(shortened_notice)+ - teams_byte_size(feedback)+ )++ kept: list[str] = []+ over_budget = False+ for section in sections[:TEAMS_REPORT_BLOCK_COUNT]:+ size = teams_byte_size(section)+ if size > remaining:+ fitted = fit_to_teams_budget(section, remaining)+ if teams_byte_size(fitted) <= remaining:+ kept.append(fitted)+ over_budget = True+ break+ kept.append(section)+ remaining -= size++ body: list[dict[str, Any]] = [teams_text_block(heading)]+ if kept:+ body.extend(teams_text_block(section) for section in kept)+ else:+ body.append(teams_text_block("_No report content was generated._"))+ 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))++ actions = [teams_open_url_action("Manage subscription", f"{subscription_url}?{TEAMS_UTM_TAGS}")]+ return teams_card_message(body, actions)++__all__ = ["build_ai_subscription_report",+ "build_ai_teams_card","build_chart_image_urls","render_ai_email_html","send_email_ai_subscription_report",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.pyindex f28747236fdc..fb3b130b8216 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@@ -16,11 +16,14 @@ from products.exports.backend.models.subscription import Subscription, Subscriptfrom products.exports.backend.temporal.subscriptions.ai_subscription.delivery import (CHART_IMAGE_URL_TTL,SLACK_MRKDWN_SECTION_LIMIT,+ TEAMS_REPORT_BLOCK_COUNT,+ TEAMS_TEXT_BLOCK_LIMIT,_build_ai_slack_message,_last_scheduled_report_cutoff,_persist_ai_query_plan,_split_text_into_chunks,build_ai_subscription_report,+ build_ai_teams_card,build_chart_image_urls,render_ai_email_html,send_email_ai_subscription_report,@@ -31,6 +34,7 @@ from products.exports.backend.temporal.subscriptions.ai_subscription.spec_generafrom products.exports.backend.temporal.subscriptions.types import AI_REPORT_WINDOW_END_KEY, SubscriptionTriggerTypefrom 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"@@ -337,6 +341,49 @@ class TestBuildAISlackMessage:assert block["text"]["text"].strip(), "thread section text must be non-empty"+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_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)))++ report_blocks = [b for b in body if set(b["text"]) == {"x"}]+ assert len(report_blocks) == 3+ assert all(len(b["text"]) <= TEAMS_TEXT_BLOCK_LIMIT for b in report_blocks)++ @pytest.mark.parametrize(+ "filler",+ [+ "x",+ # Three bytes per character, so a report that fits by character count is far over the+ # byte count Teams measures the payload in.+ "詳",+ ],+ )+ def test_report_over_the_card_budget_is_shortened_with_a_link_out(self, filler: str) -> None:+ body = self._body("\n\n".join(filler * (TEAMS_TEXT_BLOCK_LIMIT - 50) for _ in range(20)))++ assert sum(len(b["text"].encode("utf-8")) for b in body) <= TEAMS_CARD_TEXT_BUDGET+ assert len([b for b in body if set(b["text"]) == {filler}]) <= TEAMS_REPORT_BLOCK_COUNT+ assert "This report was shortened to fit." in body[-2]["text"]++ def test_external_links_in_the_report_are_stripped(self) -> None:+ body = self._body("See [the docs](https://evil.example.com/x) for more.")++ assert "evil.example.com" not in str(body)++ def test_external_links_in_the_subscription_title_are_stripped(self) -> None:+ subscription = _mock_subscription()+ subscription.title = "[Open report](https://attacker.example/login)"++ card = build_ai_teams_card(subscription, "A short report.", delivery_id=_DELIVERY_ID)+ body = card["attachments"][0]["content"]["body"]++ assert body[0]["text"] == "**Open report**"++def _mock_integration(scopes: frozenset[str]) -> MagicMock:integration = MagicMock()integration.kind = "slack"diff --git a/products/exports/backend/temporal/subscriptions/delivery_common.py b/products/exports/backend/temporal/subscriptions/delivery_common.pyindex 30aa9848f485..6b4f07abc2a5 100644--- a/products/exports/backend/temporal/subscriptions/delivery_common.py+++ b/products/exports/backend/temporal/subscriptions/delivery_common.py@@ -55,6 +55,20 @@ def strip_null_bytes(value: Any) -> Any:return value+def error_detail_results(recipient_results: list[RecipientResult]) -> list[dict[str, Any]]:+ details: list[dict[str, Any]] = [+ {+ "recipient": result.recipient,+ "status": result.status,+ **({"error": result.error} if result.error else {}),+ }+ for result in recipient_results[:_MAX_ERROR_DETAIL_RESULTS]+ ]+ if len(recipient_results) > _MAX_ERROR_DETAIL_RESULTS:+ details.append({"truncated_count": len(recipient_results) - _MAX_ERROR_DETAIL_RESULTS})+ return details++async def auto_disable_and_return(subscription: Subscription,reason: DisableReason,@@ -64,7 +78,7 @@ async def auto_disable_and_return(and auto-disable the subscription. Shared by the insight/dashboard and AI delivery paths."""recipient_results.append(RecipientResult(- recipient=subscription.target_value,+ recipient=subscription.recipient_label,status="failed",error={"message": reason.description, "type": reason.key},human_readable_error=reason.description,@@ -145,16 +159,7 @@ async def deliver_email(# non-retryable — retrying then could never succeed.# Bound the error details: a huge recipient list with a domain-wide bounce would# otherwise exceed Temporal's gRPC payload cap and wedge the workflow mid-failure.- details: list[dict[str, Any]] = [- {- "recipient": result.recipient,- "status": result.status,- **({"error": result.error} if result.error else {}),- }- for result in recipient_results[:_MAX_ERROR_DETAIL_RESULTS]- ]- if len(recipient_results) > _MAX_ERROR_DETAIL_RESULTS:- details.append({"truncated_count": len(recipient_results) - _MAX_ERROR_DETAIL_RESULTS})+ details = error_detail_results(recipient_results)permanent = [err for _, err in failures if isinstance(err, EmailDeliveryError)]if permanent and len(permanent) == len(failures):raise ApplicationError(@@ -227,7 +232,7 @@ async def deliver_slack(if result.is_complete_success:await LOGGER.ainfo("deliver_subscription.slack_sent", subscription_id=subscription.id)- recipient_results.append(RecipientResult(recipient=subscription.target_value, status="success", error=None))+ recipient_results.append(RecipientResult(recipient=subscription.recipient_label, status="success", error=None))elif result.is_partial_failure:await LOGGER.awarning("deliver_subscription.slack_partial_failure",@@ -239,7 +244,7 @@ async def deliver_slack(partial_message = f"{failed_count} thread message{'s' if failed_count != 1 else ''} failed"recipient_results.append(RecipientResult(- recipient=subscription.target_value,+ recipient=subscription.recipient_label,status="partial",error={"message": partial_message, "type": "partial_thread_failure"},human_readable_error=partial_message,diff --git a/products/exports/backend/temporal/subscriptions/delivery_webhook.py b/products/exports/backend/temporal/subscriptions/delivery_webhook.pynew file mode 100644index 000000000000..8dabecbf6eea--- /dev/null+++ b/products/exports/backend/temporal/subscriptions/delivery_webhook.py@@ -0,0 +1,217 @@+import os+import asyncio+from concurrent.futures import ThreadPoolExecutor+from threading import BoundedSemaphore+from typing import Any, NoReturn++import requests+from structlog import get_logger+from temporalio.exceptions import ApplicationError++from posthog.security.pinned_requests import SSRFBlockedError, pinned_session+from posthog.security.url_validation import is_microsoft_teams_webhook_url+from posthog.settings.utils import get_from_env++from products.exports.backend.models.subscription import Subscription+from products.exports.backend.temporal.subscriptions.delivery_common import (+ auto_disable_and_return,+ error_detail_results,+)+from products.exports.backend.temporal.subscriptions.retry_policy import SUBSCRIPTION_DELIVER_ATTEMPT_TIMEOUT+from products.exports.backend.temporal.subscriptions.types import DeliverSubscriptionResult, RecipientResult++from ee.tasks.subscriptions import _capture_delivery_failed_event+from ee.tasks.subscriptions.auto_disable import WEBHOOK_REJECTED_DISABLE_REASON++LOGGER = get_logger(__name__)++WEBHOOK_CONNECT_TIMEOUT_SECONDS = 5.0+# A webhook accepts no idempotency key, so a send still in flight when Temporal gives up on the+# activity and retries it posts the card to the channel a second time. Taking a tenth of the+# attempt budget keeps a stuck send failing inside the activity whichever way that budget moves.+WEBHOOK_READ_TIMEOUT_SECONDS = SUBSCRIPTION_DELIVER_ATTEMPT_TIMEOUT.total_seconds() / 10++# What a deleted or revoked Power Automate flow answers with. Retrying cannot recover any of them.+_PERMANENT_WEBHOOK_STATUSES = frozenset({403, 404, 410})+_WEBHOOK_UNREACHABLE_MESSAGE = "We couldn't reach your Teams channel. PostHog will try again on the next scheduled run."++_WEBHOOK_SEND_MAX_WORKERS: int = get_from_env(+ "SUBSCRIPTION_WEBHOOK_SEND_MAX_WORKERS", min(32, 4 * (os.cpu_count() or 1)), type_cast=int+)+_WEBHOOK_SEND_EXECUTOR = ThreadPoolExecutor(+ max_workers=_WEBHOOK_SEND_MAX_WORKERS, thread_name_prefix="subscription-webhook"+)+_WEBHOOK_SEND_CAPACITY = BoundedSemaphore(2 * _WEBHOOK_SEND_MAX_WORKERS)+++class WebhookSendCapacityExhaustedError(Exception):+ """Raised when all webhook send slots on this worker are busy."""+++def _fail_webhook_delivery(+ subscription: Subscription,+ recipient_results: list[RecipientResult],+ *,+ recipient: str,+ message: str,+ error_type: str,+ human_readable_error: str,+ non_retryable: bool,+) -> NoReturn:+ recipient_results.append(+ RecipientResult(+ recipient=recipient,+ status="failed",+ error={"message": message, "type": error_type},+ human_readable_error=human_readable_error,+ )+ )+ _capture_delivery_failed_event(subscription, Exception(message))+ # `from None` keeps the originating exception out of the Temporal failure chain: a `requests`+ # error carries the full webhook URL in its text, and that URL is a credential.+ raise ApplicationError(+ message, {"recipient_results": error_detail_results(recipient_results)}, non_retryable=non_retryable+ ) from None+++def _post_webhook(url: str, body: dict[str, Any]) -> int:+ """POST the payload and return the status code, without reading the response body.++ `pinned_session` re-validates the URL and pins the connection to the IPs it resolved, which is+ what closes the DNS-rebinding window, so this path must never fall back to plain `requests`.+ `stream=True` keeps an untrusted destination from making us download a response of any size we+ would only throw away.+ """+ with pinned_session(url) as session:+ response = session.request(+ "POST",+ url,+ json=body,+ timeout=(WEBHOOK_CONNECT_TIMEOUT_SECONDS, WEBHOOK_READ_TIMEOUT_SECONDS),+ allow_redirects=False,+ stream=True,+ )+ try:+ return response.status_code+ finally:+ response.close()+++async def _send_webhook(url: str, body: dict[str, Any]) -> int:+ if not _WEBHOOK_SEND_CAPACITY.acquire(blocking=False):+ raise WebhookSendCapacityExhaustedError++ try:+ send = _WEBHOOK_SEND_EXECUTOR.submit(_post_webhook, url, body)+ except Exception:+ _WEBHOOK_SEND_CAPACITY.release()+ raise++ send.add_done_callback(lambda _send: _WEBHOOK_SEND_CAPACITY.release())+ return await asyncio.wrap_future(send)+++async def deliver_teams_webhook(+ subscription: Subscription,+ recipient_results: list[RecipientResult],+ *,+ body: dict[str, Any],+) -> DeliverSubscriptionResult:+ """Deliver a Teams card to the subscription's configured webhook."""+ url = subscription.target_value+ recipient = subscription.recipient_label+ LOGGER.info("deliver_subscription.sending_webhook", subscription_id=subscription.id, recipient=recipient)++ # The serializer runs the same check on save. Re-running it here means a stored value that never+ # went through that path, or went through an older version of it, still cannot make this worker+ # POST to a host outside the Microsoft set.+ if not is_microsoft_teams_webhook_url(url):+ LOGGER.error("deliver_subscription.webhook_url_blocked", subscription_id=subscription.id, recipient=recipient)+ _fail_webhook_delivery(+ subscription,+ recipient_results,+ recipient=recipient,+ message="Webhook URL failed validation: not a Microsoft Teams webhook URL",+ error_type="webhook_url_blocked",+ human_readable_error=_WEBHOOK_UNREACHABLE_MESSAGE,+ non_retryable=False,+ )++ try:+ status = await _send_webhook(url, body)+ except WebhookSendCapacityExhaustedError:+ LOGGER.warning(+ "deliver_subscription.webhook_send_capacity_exhausted",+ subscription_id=subscription.id,+ recipient=recipient,+ )+ _fail_webhook_delivery(+ subscription,+ recipient_results,+ recipient=recipient,+ message="No webhook send capacity on this worker",+ error_type="webhook_send_capacity_exhausted",+ human_readable_error=_WEBHOOK_UNREACHABLE_MESSAGE,+ non_retryable=False,+ )+ except (SSRFBlockedError, requests.RequestException) as exc:+ # Retryable rather than permanent even when the URL was blocked, because the likely cause is+ # a failed name resolution. Callers validate the host on save, so a URL that can never work+ # does not reach here.+ if isinstance(exc, SSRFBlockedError):+ event = "deliver_subscription.webhook_url_blocked"+ error_type = "webhook_url_blocked"+ message = f"Webhook URL failed validation: {exc}"+ else:+ event = "deliver_subscription.webhook_request_failed"+ error_type = "webhook_request_failed"+ message = f"Webhook request failed: {type(exc).__name__}"+ # No exc_info anywhere in this function: a traceback would render the exception text, and a+ # `requests` error carries the full webhook URL in it.+ LOGGER.error( # noqa: TRY400+ event,+ subscription_id=subscription.id,+ recipient=recipient,+ reason=message,+ )+ _fail_webhook_delivery(+ subscription,+ recipient_results,+ recipient=recipient,+ message=message,+ error_type=error_type,+ human_readable_error=_WEBHOOK_UNREACHABLE_MESSAGE,+ non_retryable=False,+ )++ # Any 2xx counts: Power Automate answers 202 on a webhook it accepted for processing.+ if 200 <= status < 300:+ await LOGGER.ainfo(+ "deliver_subscription.webhook_sent",+ subscription_id=subscription.id,+ recipient=recipient,+ status=status,+ )+ recipient_results.append(RecipientResult(recipient=recipient, status="success", error=None))+ return DeliverSubscriptionResult(recipient_results=recipient_results)++ LOGGER.error(+ "deliver_subscription.webhook_rejected",+ subscription_id=subscription.id,+ recipient=recipient,+ status=status,+ next_delivery_date=subscription.next_delivery_date,+ destination=subscription.target_type,+ )+ if status in _PERMANENT_WEBHOOK_STATUSES:+ return await auto_disable_and_return(subscription, WEBHOOK_REJECTED_DISABLE_REASON, recipient_results)++ _fail_webhook_delivery(+ subscription,+ recipient_results,+ recipient=recipient,+ message=f"Webhook destination returned HTTP {status}",+ error_type="webhook_http_error",+ human_readable_error=f"Microsoft Teams returned an error (HTTP {status}).",+ non_retryable=not (status == 429 or status >= 500),+ )diff --git a/products/exports/backend/temporal/subscriptions/retry_policy.py b/products/exports/backend/temporal/subscriptions/retry_policy.pyindex c23c962f1eef..c7c2ce1ba894 100644--- a/products/exports/backend/temporal/subscriptions/retry_policy.py+++ b/products/exports/backend/temporal/subscriptions/retry_policy.py@@ -19,3 +19,8 @@ SUBSCRIPTION_DELIVER_RETRY_POLICY = RetryPolicy(maximum_interval=dt.timedelta(minutes=5),maximum_attempts=5,)++# One attempt of the delivery activity. Temporal stops waiting once this elapses and retries the+# activity while the send it gave up on can still be running, so each channel derives its own send+# timeout from this and stays below it.+SUBSCRIPTION_DELIVER_ATTEMPT_TIMEOUT = dt.timedelta(minutes=5)diff --git a/products/exports/backend/temporal/subscriptions/test_webhook_delivery.py b/products/exports/backend/temporal/subscriptions/test_webhook_delivery.pynew file mode 100644index 000000000000..12713313b992--- /dev/null+++ b/products/exports/backend/temporal/subscriptions/test_webhook_delivery.py@@ -0,0 +1,244 @@+import asyncio+from collections.abc import Iterator+from contextlib import contextmanager+from datetime import datetime+from threading import Event+from zoneinfo import ZoneInfo++import pytest+from unittest.mock import MagicMock, patch++from django.test import override_settings++import requests+from asgiref.sync import sync_to_async+from temporalio.exceptions import ApplicationError++from posthog.security.url_validation import PinnedUrlVerdict++from products.exports.backend.models.subscription import Subscription+from products.exports.backend.temporal.subscriptions.delivery_webhook import (+ _WEBHOOK_SEND_CAPACITY,+ deliver_teams_webhook,+)+from products.exports.backend.temporal.subscriptions.types import RecipientResult++from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscription++pytestmark = pytest.mark.asyncio++WEBHOOK_URL = (+ "https://prod-25.westeurope.logic.azure.com:443/workflows/abc123/triggers/manual/paths/invoke?sig=supersecret"+)+WEBHOOK_HOST = "prod-25.westeurope.logic.azure.com"+CARD = {"type": "message", "attachments": []}++_PINNED_SESSION = "products.exports.backend.temporal.subscriptions.delivery_webhook.pinned_session"+_VALIDATE_URL = "posthog.security.pinned_requests.validate_url_and_pin_ips"+_CAPTURE_FAILED = "products.exports.backend.temporal.subscriptions.delivery_webhook._capture_delivery_failed_event"+_DISABLED_EMAIL = "ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription"+++def _unsaved_teams_subscription(url: str = WEBHOOK_URL) -> Subscription:+ return Subscription(+ id=1,+ team_id=1,+ target_type="teams",+ target_value=url,+ frequency="daily",+ interval=1,+ start_date=datetime(2022, 1, 1, 9, 0, tzinfo=ZoneInfo("UTC")),+ )+++@contextmanager+def _destination_responds(status: int) -> Iterator[MagicMock]:+ with patch(_PINNED_SESSION) as pinned_session:+ request = pinned_session.return_value.__enter__.return_value.request+ request.return_value = MagicMock(status_code=status)+ yield request++[email protected]("target_value", ["https://[::1", "", "not a url"])+async def test_a_target_value_with_no_parseable_host_still_gets_a_label(target_value) -> None:+ # The label is what every delivery receipt and log line names the destination by, so a stored+ # value that no longer parses has to degrade to a placeholder rather than raise mid-delivery.+ assert _unsaved_teams_subscription(target_value).recipient_label == "webhook"+++@override_settings(DEBUG=False)+async def test_a_url_that_stops_resolving_stays_retryable() -> None:+ subscription = _unsaved_teams_subscription()+ recipient_results: list[RecipientResult] = []+ unresolvable = PinnedUrlVerdict(allowed=False, reason="DNS resolution failed", pinned_ips=set())++ with patch(_VALIDATE_URL, return_value=unresolvable), patch("requests.Session.request") as mock_request:+ with patch(_CAPTURE_FAILED), pytest.raises(ApplicationError) as error:+ await deliver_teams_webhook(subscription, recipient_results, body=CARD)++ # A Microsoft host that fails to resolve now may resolve on the next run, so the delivery must+ # not be written off as permanently broken.+ assert mock_request.call_count == 0+ assert error.value.non_retryable is False+ assert recipient_results[0].error is not None+ assert recipient_results[0].error["type"] == "webhook_url_blocked"+++async def test_a_stored_url_outside_the_microsoft_hosts_is_never_posted_to() -> None:+ # The serializer is not the only writer of target_value, so the host allowlist runs again here.+ subscription = _unsaved_teams_subscription("https://evil.example.com/workflows/abc")+ recipient_results: list[RecipientResult] = []++ with patch(_PINNED_SESSION) as pinned_session, patch(_CAPTURE_FAILED):+ with pytest.raises(ApplicationError) as error:+ await deliver_teams_webhook(subscription, recipient_results, body=CARD)++ assert pinned_session.call_count == 0+ assert error.value.non_retryable is False+ assert recipient_results[0].error is not None+ assert recipient_results[0].error["type"] == "webhook_url_blocked"+++async def test_a_worker_out_of_send_slots_refuses_the_send_instead_of_queueing_it() -> None:+ # Every slot taken means every thread is inside a send that has not returned. Queueing behind+ # them would hold this delivery past the activity timeout with nothing to show for it.+ subscription = _unsaved_teams_subscription()+ recipient_results: list[RecipientResult] = []++ held = 0+ while _WEBHOOK_SEND_CAPACITY.acquire(blocking=False):+ held += 1+ try:+ with patch(_PINNED_SESSION) as pinned_session, patch(_CAPTURE_FAILED):+ with pytest.raises(ApplicationError) as error:+ await deliver_teams_webhook(subscription, recipient_results, body=CARD)+ finally:+ for _ in range(held):+ _WEBHOOK_SEND_CAPACITY.release()++ assert pinned_session.call_count == 0+ assert error.value.non_retryable is False+ assert recipient_results[0].error is not None+ assert recipient_results[0].error["type"] == "webhook_send_capacity_exhausted"+++async def test_cancelling_a_delivery_keeps_its_send_slot_until_the_thread_stops() -> None:+ subscription = _unsaved_teams_subscription()+ recipient_results: list[RecipientResult] = []+ send_started = Event()+ release_send = Event()+ send_stopped = Event()++ def blocked_post(*_args, **_kwargs) -> int:+ send_started.set()+ release_send.wait()+ send_stopped.set()+ return 202++ held = 0+ while _WEBHOOK_SEND_CAPACITY.acquire(blocking=False):+ held += 1+ _WEBHOOK_SEND_CAPACITY.release()+ try:+ with patch(+ "products.exports.backend.temporal.subscriptions.delivery_webhook._post_webhook", side_effect=blocked_post+ ):+ delivery = asyncio.create_task(deliver_teams_webhook(subscription, recipient_results, body=CARD))+ await asyncio.wait_for(asyncio.to_thread(send_started.wait), timeout=1)+ delivery.cancel()+ with pytest.raises(asyncio.CancelledError):+ await delivery++ assert not _WEBHOOK_SEND_CAPACITY.acquire(blocking=False)++ release_send.set()+ await asyncio.wait_for(asyncio.to_thread(send_stopped.wait), timeout=1)+ assert _WEBHOOK_SEND_CAPACITY.acquire(blocking=False)+ _WEBHOOK_SEND_CAPACITY.release()+ finally:+ release_send.set()+ for _ in range(held - 1):+ _WEBHOOK_SEND_CAPACITY.release()+++async def test_a_destination_that_stops_answering_stays_retryable() -> None:+ subscription = _unsaved_teams_subscription()+ recipient_results: list[RecipientResult] = []++ with patch(_PINNED_SESSION) as pinned_session, patch(_CAPTURE_FAILED):+ pinned_session.return_value.__enter__.return_value.request.side_effect = requests.ReadTimeout(+ f"Read timed out for {WEBHOOK_URL}"+ )+ with pytest.raises(ApplicationError) as error:+ await deliver_teams_webhook(subscription, recipient_results, body=CARD)++ assert error.value.non_retryable is False+ assert recipient_results[0].error is not None+ assert recipient_results[0].error["type"] == "webhook_request_failed"+ # The exception text carries the URL, so only its class name may reach the receipt.+ assert recipient_results[0].error["message"] == "Webhook request failed: ReadTimeout"+ assert "supersecret" not in str(error.value.details)++[email protected]("status", [200, 202])+async def test_any_2xx_is_a_successful_delivery(status) -> None:+ subscription = _unsaved_teams_subscription()+ recipient_results: list[RecipientResult] = []++ with _destination_responds(status) as request:+ result = await deliver_teams_webhook(subscription, recipient_results, body=CARD)++ assert request.call_args.kwargs["json"] == CARD+ # A destination can answer with a body of any size, and only the status is ever read.+ assert request.call_args.kwargs["stream"] is True+ assert [(r.recipient, r.status) for r in result.recipient_results] == [(WEBHOOK_HOST, "success")]++[email protected]("status,expected_non_retryable", [(429, False), (500, False), (400, True)])+async def test_error_status_raises_with_the_right_retry_semantics(status, expected_non_retryable) -> None:+ subscription = _unsaved_teams_subscription()+ recipient_results: list[RecipientResult] = []++ with _destination_responds(status), patch(_CAPTURE_FAILED):+ with pytest.raises(ApplicationError) as error:+ await deliver_teams_webhook(subscription, recipient_results, body=CARD)++ assert error.value.non_retryable is expected_non_retryable+ assert subscription.enabled is True++[email protected]("status", [202, 500])+async def test_delivery_receipt_never_holds_the_webhook_url(status) -> None:+ subscription = _unsaved_teams_subscription()+ recipient_results: list[RecipientResult] = []++ with _destination_responds(status), patch(_CAPTURE_FAILED):+ try:+ await deliver_teams_webhook(subscription, recipient_results, body=CARD)+ except ApplicationError as error:+ assert "supersecret" not in str(error)+ assert "supersecret" not in str(error.details)++ assert recipient_results+ for result in recipient_results:+ assert result.recipient == WEBHOOK_HOST+ assert "supersecret" not in str(result.error)+ assert "supersecret" not in str(result.human_readable_error)++[email protected]_db(transaction=True)[email protected]("status", [403, 404, 410])+async def test_permanent_status_auto_disables_the_subscription(team, user, status) -> None:+ subscription = await sync_to_async(create_subscription)(+ team=team, created_by=user, target_type="teams", target_value=WEBHOOK_URL+ )+ recipient_results: list[RecipientResult] = []++ with _destination_responds(status), patch(_DISABLED_EMAIL), patch(_CAPTURE_FAILED):+ result = await deliver_teams_webhook(subscription, recipient_results, body=CARD)++ await sync_to_async(subscription.refresh_from_db)()+ assert subscription.enabled is False+ assert result.recipient_results[0].recipient == WEBHOOK_HOST+ assert result.recipient_results[0].error is not None+ assert result.recipient_results[0].error["type"] == "webhook_rejected"diff --git a/products/exports/backend/temporal/subscriptions/workflows.py b/products/exports/backend/temporal/subscriptions/workflows.pyindex 17aae14a594d..cb093055a671 100644--- a/products/exports/backend/temporal/subscriptions/workflows.py+++ b/products/exports/backend/temporal/subscriptions/workflows.py@@ -48,6 +48,7 @@ from products.exports.backend.temporal.subscriptions.activities import ()from products.exports.backend.temporal.subscriptions.ai_subscription.activities import generate_ai_subscription_reportfrom products.exports.backend.temporal.subscriptions.retry_policy import (+ SUBSCRIPTION_DELIVER_ATTEMPT_TIMEOUT,SUBSCRIPTION_DELIVER_RETRY_POLICY,SUBSCRIPTION_RECORD_LIFECYCLE_RETRY_POLICY,SUBSCRIPTION_VALIDATE_RETRY_POLICY,@@ -507,7 +508,7 @@ class ProcessSubscriptionWorkflow(PostHogWorkflow):summary_skipped_over_budget=summary_skipped_over_budget,delivery_id=delivery_id,),- start_to_close_timeout=dt.timedelta(minutes=5),+ start_to_close_timeout=SUBSCRIPTION_DELIVER_ATTEMPT_TIMEOUT,retry_policy=SUBSCRIPTION_DELIVER_RETRY_POLICY,)@@ -743,7 +744,7 @@ class ProcessAISubscriptionWorkflow(PostHogWorkflow):invite_message=inputs.invite_message,delivery_id=delivery_id,),- start_to_close_timeout=dt.timedelta(minutes=5),+ start_to_close_timeout=SUBSCRIPTION_DELIVER_ATTEMPT_TIMEOUT,retry_policy=SUBSCRIPTION_DELIVER_RETRY_POLICY,)delivery_recipient_results = _to_recipient_dicts(deliver_result.recipient_results)diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.tsindex 0573940fc504..9b3f73ee1f80 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts@@ -28,6 +28,9 @@ jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({const Insight1 = '1' as InsightShortId+const TEAMS_WEBHOOK_URL =+ 'https://prod-12.westeurope.logic.azure.com/workflows/00000000/triggers/manual/paths/invoke?api-version=2016-06-01&sig=not-a-real-signature'+export const fixtureSubscriptionResponse = (id: number, args: Partial<SubscriptionType> = {}): SubscriptionType =>({id,@@ -746,6 +749,106 @@ describe('subscriptionLogic', () => {expect(capturedBody?.insight).toBeUndefined()})+ it.each<[string, string, string | undefined]>([+ ['accepts a webhook URL', TEAMS_WEBHOOK_URL, undefined],+ ['accepts a webhook URL pasted with stray whitespace', ` ${TEAMS_WEBHOOK_URL}\n`, undefined],+ ['rejects a channel name', 'reports', 'The webhook URL must start with https://'],+ [+ 'rejects a plain-HTTP URL',+ 'http://prod-12.westeurope.logic.azure.com/workflows/1',+ 'The webhook URL must start with https://',+ ],+ ['rejects an empty value', '', 'A webhook URL is required'],+ ['rejects a whitespace-only value', ' ', 'A webhook URL is required'],+ ])('%s for a Microsoft Teams subscription', async (_label, targetValue, expectedError) => {+ await expectLogic(newLogic).toFinishListeners()+ newLogic.actions.setSubscriptionValues({ target_type: 'teams', target_value: targetValue })+ await expectLogic(newLogic).toFinishListeners()++ // subscriptionErrors is gated on submit or touch; the validation output is what we assert.+ expect(newLogic.values.subscriptionValidationErrors.target_value).toBe(expectedError)+ expect(newLogic.values.subscriptionValidationErrors.target_type).toBeUndefined()+ })++ it('saves a Microsoft Teams subscription with the webhook URL trimmed', async () => {+ 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',+ title: 'Teams test',+ target_type: 'teams',+ target_value: ` ${TEAMS_WEBHOOK_URL}\n`,+ })+ newLogic.actions.submitSubscription()+ await expectLogic(newLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])++ expect(capturedBody?.target_type).toBe('teams')+ expect(capturedBody?.target_value).toBe(TEAMS_WEBHOOK_URL)+ // Without target_type on the create event, Teams adoption is invisible in analytics.+ expect(posthog.capture).toHaveBeenCalledWith(+ 'subscription created',+ expect.objectContaining({ target_type: 'teams', subscription_id: 44 })+ )+ })++ it('saves an existing Microsoft Teams subscription without resending the hidden URL', async () => {+ // The API only ever returns the host, so sending it back would replace the stored URL with+ // something nothing could deliver to. Omitting it tells the backend to keep what it has.+ let capturedBody: Partial<SubscriptionType> | undefined+ useMocks({+ get: {+ '/api/environments/:team/subscriptions/1': fixtureSubscriptionResponse(1, {+ target_type: 'teams',+ target_value: 'prod-12.westeurope.logic.azure.com',+ }),+ },+ patch: {+ '/api/environments/:team/subscriptions/1': async ({ request }) => {+ capturedBody = (await request.json()) as Partial<SubscriptionType>+ return [200, fixtureSubscriptionResponse(1, { target_type: 'teams' })]+ },+ },+ })+ existingLogic.actions.loadSubscription()+ await expectLogic(existingLogic).toFinishListeners()++ expect(existingLogic.values.storedTeamsWebhookHost).toBe('prod-12.westeurope.logic.azure.com')+ existingLogic.actions.setSubscriptionValue('title', 'Renamed')+ existingLogic.actions.submitSubscription()+ await expectLogic(existingLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])++ expect(capturedBody?.target_value).toBeUndefined()+ })++ it('asks for a URL again once the Teams webhook is being replaced', async () => {+ useMocks({+ get: {+ '/api/environments/:team/subscriptions/1': fixtureSubscriptionResponse(1, {+ target_type: 'teams',+ target_value: 'prod-12.westeurope.logic.azure.com',+ }),+ },+ })+ existingLogic.actions.loadSubscription()+ await expectLogic(existingLogic).toFinishListeners()++ existingLogic.actions.replaceTeamsWebhook()+ await expectLogic(existingLogic).toFinishListeners()++ expect(existingLogic.values.storedTeamsWebhookHost).toBeNull()+ expect(existingLogic.values.subscription.target_value).toBe('')+ expect(existingLogic.values.subscriptionValidationErrors.target_value).toBe('A webhook URL is required')+ })+it('drops a stale prompt when saving a non-AI subscription', async () => {// Toggling resource_type back to insight after typing a prompt leaves it in form state;// it must not be sent, else the backend rejects a non-AI sub that carries a prompt.diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.tsindex 20463e82849c..c1936ca43fe7 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts@@ -13,7 +13,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { removeProjectIdIfPresent } from 'lib/utils/kea-router'import { objectsEqual } from 'lib/utils/objects'-import { isEmail } from 'lib/utils/url'+import { isEmail, isHttpsUrl } from 'lib/utils/url'import { getInsightId } from 'scenes/insights/utils'import { organizationLogic } from 'scenes/organizationLogic'import { userLogic } from 'scenes/userLogic'@@ -24,7 +24,12 @@ import {subscriptionsDeliveriesList,subscriptionsTestDeliveryCreate,} from 'products/subscriptions/frontend/generated/api'-import type { AIWindowConfigApi, SubscriptionDeliveryApi } from 'products/subscriptions/frontend/generated/api.schemas'+import {+ SubscriptionTargetEnumApi,+ type AIWindowConfigApi,+ type SubscriptionApi,+ type SubscriptionDeliveryApi,+} from 'products/subscriptions/frontend/generated/api.schemas'import type { SubscriptionResourceType, UserBasicType, WeekdayType } from '../../../../../frontend/src/types'import type { OrganizationType, UserType } from '../../../../../frontend/src/types'@@ -39,6 +44,7 @@ import {AI_PROMPT_MAX_LENGTH,coerceDeliveryConfigForScope,SubscriptionBaseProps,+ targetTypeOptions,urlForSubscription,} from './utils'@@ -101,17 +107,52 @@ function validateAiWindow(subscription: Partial<SubscriptionType>): {return {}}-function validateTargetValue(target_type: string, target_value: string | undefined): string | undefined {- if (!target_value) {- return target_type === 'email'- ? 'At least one email is required'- : target_type === 'slack'- ? 'A channel is required'- : 'This field is required.'+type SubscriptionTargetType = SubscriptionApi['target_type']++// Taken from the destination select, so a type the form has no fields for is never accepted.+const SUPPORTED_TARGET_TYPES: readonly SubscriptionTargetType[] = targetTypeOptions.map(({ value }) => value)++function isSupportedTargetType(target_type: string): target_type is SubscriptionTargetType {+ return SUPPORTED_TARGET_TYPES.some((supported) => supported === target_type)+}++const MISSING_TARGET_VALUE_ERROR: Record<SubscriptionTargetType, string> = {+ [SubscriptionTargetEnumApi.Email]: 'At least one email is required',+ [SubscriptionTargetEnumApi.Slack]: 'A channel is required',+ [SubscriptionTargetEnumApi.Teams]: 'A webhook URL is required',+}++function isTeamsWebhookKept(target_type: string, storedTeamsWebhookHost: string | null): boolean {+ return target_type === SubscriptionTargetEnumApi.Teams && storedTeamsWebhookHost !== null+}++function validateTargetValue(+ target_type: string,+ target_value: string | undefined,+ webhookKept: boolean+): string | undefined {+ if (!isSupportedTargetType(target_type)) {+ // `target_type` reports its own error, and there is nothing to say about a value for a+ // destination this form cannot render.+ return undefined}- if (target_type === 'email' && !target_value.split(',').every((email) => isEmail(email))) {+ // The saved webhook URL is never sent to the browser, so an untouched field means "keep it".+ if (webhookKept) {+ return undefined+ }+ // Submit sends the trimmed value, so validate the same string the backend will receive.+ const trimmed = target_value?.trim()+ if (!trimmed) {+ return MISSING_TARGET_VALUE_ERROR[target_type]+ }+ if (target_type === SubscriptionTargetEnumApi.Email && !trimmed.split(',').every((email) => isEmail(email))) {return 'All emails must be valid'}+ // The serializer owns the host allowlist and reports its own error on save. This check stays+ // loose on purpose, so it cannot reject a URL the backend would have accepted.+ if (target_type === SubscriptionTargetEnumApi.Teams && !isHttpsUrl(trimmed)) {+ return 'The webhook URL must start with https://'+ }return undefined}@@ -207,6 +248,7 @@ export interface subscriptionLogicValues {previewImageUrl: string | nullpreviewLoading: booleanshowSubscriptionErrors: boolean+ storedTeamsWebhookHost: string | nullsubscription: SubscriptionTypesubscriptionAllErrors: Record<string, any>subscriptionChanged: boolean@@ -348,6 +390,9 @@ export interface subscriptionLogicActions {}payload?: any}+ replaceTeamsWebhook: () => {+ value: true+ }resetSubscription: (values?: SubscriptionType) => {values?: SubscriptionType}@@ -447,6 +492,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([setPreviewError: (error: string | null) => ({ error }),setPreviewImageUrl: (url: string | null) => ({ url }),applyDefaultSelectedInsights: (selectedIds: number[]) => ({ selectedIds }),+ replaceTeamsWebhook: true,selectAiExamplePrompt: (prompt: string, label: string) => ({prompt,label,@@ -455,6 +501,18 @@ export const subscriptionLogic = kea<subscriptionLogicType>([}),reducers({+ // The host the API returned for a saved Teams subscription. Null once the user chooses to+ // replace the URL, which is what puts the input back on screen and the validation back on.+ storedTeamsWebhookHost: [+ null as string | null,+ {+ loadSubscriptionSuccess: (_, { subscription }) =>+ subscription?.target_type === SubscriptionTargetEnumApi.Teams+ ? (subscription.target_value ?? null)+ : null,+ replaceTeamsWebhook: () => null,+ },+ ],lastDeliveryLoadFailed: [false,{@@ -556,7 +614,7 @@ export const subscriptionLogic = kea<subscriptionLogicType>([},})),- forms(({ props, actions, cache }) => ({+ forms(({ props, actions, cache, values }) => ({subscription: {defaults: { enabled: NEW_SUBSCRIPTION.enabled } as unknown as SubscriptionType,errors: (subscription) => ({@@ -564,20 +622,28 @@ export const subscriptionLogic = kea<subscriptionLogicType>([title: !subscription.title ? 'You need to give your subscription a name' : undefined,interval: !subscription.interval ? 'You need to set an interval' : undefined,start_date: !subscription.start_date ? 'You need to set a delivery time' : undefined,- target_type: !['slack', 'email'].includes(subscription.target_type)- ? 'Unsupported target type'- : undefined,+ // The destination select cannot produce an unknown value, but a `target_type`+ // search param can.+ target_type: isSupportedTargetType(subscription.target_type) ? undefined : 'Unsupported target type',prompt: validatePrompt(subscription.resource_type, subscription.prompt),...validateAiWindow(subscription),- target_value: validateTargetValue(subscription.target_type, subscription.target_value),+ target_value: validateTargetValue(+ subscription.target_type,+ subscription.target_value,+ isTeamsWebhookKept(subscription.target_type, values.storedTeamsWebhookHost)+ ),dashboard_export_insights: validateDashboardExportInsights(subscription, props.dashboardId),}),submit: async (subscription, breakpoint) => {const isAi = subscription.resource_type === SubscriptionResourceTypes.AiPromptconst insightId = !isAi && props.insightShortId ? await getInsightId(props.insightShortId) : undefined+ const webhookKept = isTeamsWebhookKept(subscription.target_type, values.storedTeamsWebhookHost)const payload = {...subscription,+ // Omitting it tells the backend to keep the stored URL. Sending the host back+ // is rejected, since it is not a URL anything could deliver to.+ target_value: webhookKept ? undefined : subscription.target_value?.trim(),bysetpos: subscription.frequency === 'monthly' ? subscription.bysetpos : null,delivery_config: coerceDeliveryConfigForScope(subscription,@@ -687,6 +753,9 @@ export const subscriptionLogic = kea<subscriptionLogicType>([recordRecentSlackChannel(subscription.integration_id, slackChannelId(subscription.target_value))}},+ replaceTeamsWebhook: () => {+ actions.setSubscriptionValue('target_value', '')+ },applyDefaultSelectedInsights: ({ selectedIds }) => {if (cache.prefillBaseline) {// Prefilled form: the auto-selection joins the programmatic baseline. A reset herediff --git a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts b/products/subscriptions/frontend/components/Subscriptions/utils.test.tsindex b26a908a8874..d150d5dac94c 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts@@ -1,6 +1,8 @@import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'import { IntegrationType, SubscriptionType } from '~/types'+import { SubscriptionTargetEnumApi } from 'products/subscriptions/frontend/generated/api.schemas'+import {canNudgeToSubscribe,coerceDeliveryConfigForScope,@@ -11,9 +13,17 @@ import {integrationHasFilesWrite,selectedDaysToDayPickerLabel,shouldShowDayPicker,+ targetTypeOptions,toggleSelectedDay,} from './utils'+describe('targetTypeOptions', () => {+ it('offers every destination the API accepts', () => {+ // A destination the backend accepts but the select never offers is unreachable in the UI.+ expect(targetTypeOptions.map(({ value }) => value)).toEqual(Object.values(SubscriptionTargetEnumApi))+ })+})+describe('day picker values', () => {it.each([['daily', 1, true],diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsxindex 56147c997b25..b51f0ff38b55 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx@@ -13,6 +13,10 @@ import { urls } from 'scenes/urls'import { SubscriptionAIPromptMaxLength, SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'import { InsightShortId, IntegrationType, SubscriptionType, WeekdayType } from '~/types'+import IconMicrosoftTeams from 'public/services/microsoft-teams.png'++import { SubscriptionTargetEnumApi, type SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'+export const AI_PROMPT_MAX_LENGTH = SubscriptionAIPromptMaxLength.CHARACTERSexport function requestSubscriptionWizardCancellation({@@ -90,9 +94,14 @@ export const urlForSubscription = (return id === 'new' ? urls.subscriptionNew() : urls.subscription(id)}-export const targetTypeOptions: LemonSelectOptions<'email' | 'slack'> = [- { value: 'email', label: 'Email', icon: <IconLetter /> },- { value: 'slack', label: 'Slack', icon: <IconSlack /> },+export const targetTypeOptions: LemonSelectOptionLeaf<SubscriptionApi['target_type']>[] = [+ { value: SubscriptionTargetEnumApi.Email, label: 'Email', icon: <IconLetter /> },+ { value: SubscriptionTargetEnumApi.Slack, label: 'Slack', icon: <IconSlack /> },+ {+ value: SubscriptionTargetEnumApi.Teams,+ label: 'Microsoft Teams',+ icon: <img src={IconMicrosoftTeams} alt="" className="h-4 w-4" />,+ },]export const intervalOptions: LemonSelectOptions<number> = range(1, 13).map((x) => ({ value: x, label: x.toString() }))diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsxindex 8497f61d2ced..03b8190ec672 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx@@ -272,9 +272,10 @@ function EditSubscriptionForm({lastDeliveryLoading,summaryQuota,testDeliveryLoading,+ storedTeamsWebhookHost,} = useValues(logic)const { previewLoading, previewError, previewImageUrl } = useValues(logic)- const { applyDefaultSelectedInsights, generatePreview, sendTestDelivery } = useActions(logic)+ const { applyDefaultSelectedInsights, generatePreview, sendTestDelivery, replaceTeamsWebhook } = useActions(logic)const { preflight, siteUrlMisconfigured } = useValues(preflightLogic)const { currentOrganization } = useValues(organizationLogic)const { deleteSubscription } = useActions(subscriptionslogic)@@ -636,6 +637,43 @@ function EditSubscriptionForm({</>) : null}+ {subscription.target_type === 'teams' ? (+ <LemonField+ name="target_value"+ label="Microsoft Teams webhook URL"+ help={+ <>+ In Teams, add the Workflows app to the channel you want reports in, then pick+ the template for posting to a channel when a webhook request is received. Paste+ the URL it gives you here. Anyone with that URL can post to the channel, so keep+ it private.+ </>+ }+ >+ {storedTeamsWebhookHost ? (+ <div className="flex gap-2 items-center p-1 rounded border border-dashed">+ <span className="flex-1 p-1 text-secondary">+ Posting to {storedTeamsWebhookHost}. The saved URL is not shown here.+ </span>+ <LemonButton+ onClick={replaceTeamsWebhook}+ size="small"+ type="secondary"+ data-attr="subscription-teams-webhook-replace"+ >+ Replace+ </LemonButton>+ </div>+ ) : (+ <LemonInput+ placeholder="https://prod-00.westeurope.logic.azure.com/workflows/..."+ autoComplete="off"+ data-attr="subscription-teams-webhook-url"+ />+ )}+ </LemonField>+ ) : null}+<div><LemonLabel className="mb-2">Recurrence</LemonLabel><div className="rounded border p-2">diff --git a/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx b/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsxindex 11fd7e0635cb..2654435d8841 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx@@ -1,10 +1,9 @@import type { ReactNode } from 'react'-import { IconAI, IconEllipsis, IconGraph, IconLetter, IconPause, IconPlay, IconTrash } from '@posthog/icons'+import { IconAI, IconEllipsis, IconGraph, IconPause, IconPlay, IconTrash } from '@posthog/icons'import { LemonTag, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'-import { IconSlack } from 'lib/lemon-ui/icons'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonCard } from 'lib/lemon-ui/LemonCard'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'@@ -14,7 +13,9 @@ import { urls } from 'scenes/urls'import { SubscriptionResourceTypes, SubscriptionType } from '~/types'+import { subscriptionDestination } from '../../../scenes/components/subscriptionDestination'import { isSubscriptionEnabled } from '../../../scenes/components/SubscriptionsTable'+import { targetTypeOptions } from '../utils'const PROMPT_PREVIEW_MAX_CHARS = 80@@ -28,23 +29,16 @@ interface SubscriptionListItemProps {isToggling?: boolean}-function subscriptionDestination(subscription: SubscriptionType): { label: string; title: string } {- const destinations = subscription.target_value- .split(',')- .map((destination) => destination.trim())- .filter(Boolean)-- if (subscription.target_type === 'email') {- return {- label: destinations.length === 1 ? destinations[0] : `${destinations.length} recipients`,- title: destinations.join(', '),- }- }-- const channels = destinations.map((destination) => destination.split('|')[1] || destination)+function subscriptionListDestination(subscription: SubscriptionType): {+ icon: ReactNode+ label: string+ title: string+} {+ const destination = subscriptionDestination(subscription.target_type, subscription.target_value)return {- label: channels.length === 1 ? channels[0] : `${channels.length} channels`,- title: channels.join(', '),+ icon: targetTypeOptions.find(({ value }) => value === subscription.target_type)?.icon,+ label: destination.label,+ title: destination.title,}}@@ -154,7 +148,7 @@ export function SubscriptionListItem({const aiPrompt = subscription.resource_type === SubscriptionResourceTypes.AiPrompt ? subscription.prompt : nullconst aiPromptTruncated = aiPrompt && aiPrompt.length > PROMPT_PREVIEW_MAX_CHARSconst aiPromptPreview = aiPromptTruncated ? `${aiPrompt.slice(0, PROMPT_PREVIEW_MAX_CHARS)}…` : aiPrompt- const destination = subscriptionDestination(subscription)+ const destination = subscriptionListDestination(subscription)return (<LemonButton@@ -223,8 +217,7 @@ export function SubscriptionListItem({className="flex items-center gap-1 text-xs text-secondary shrink-0"title={destination.title}>- {subscription.target_type === 'email' && <IconLetter />}- {subscription.target_type === 'slack' && <IconSlack />}+ {destination.icon}<span className="max-w-40 truncate">{destination.label}</span></div></div>diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex baa1b074a2f8..5143f482e768 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -69,12 +69,14 @@ export interface AIPromptConfigApi {/*** * `email` - Email* * `slack` - Slack+ * * `teams` - Microsoft Teams*/export type SubscriptionTargetEnumApi = (typeof SubscriptionTargetEnumApi)[keyof typeof SubscriptionTargetEnumApi]export const SubscriptionTargetEnumApi = {Email: 'email',Slack: 'slack',+ Teams: 'teams',} as const/**@@ -213,12 +215,13 @@ export interface SubscriptionApi {prompt?: string | null/** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */ai_prompt_config?: AIPromptConfigApi- /** Delivery channel: email or slack.+ /** Delivery channel: email, slack, or teams.** * `email` - Email- * * `slack` - Slack */+ * * `slack` - Slack+ * * `teams` - Microsoft Teams */target_type: SubscriptionTargetEnumApi- /** Recipient(s): comma-separated email addresses for email, or Slack channel name/ID for slack. */+ /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it. */target_value: string/** How often to deliver: daily, weekly, monthly, or yearly.*@@ -363,12 +366,13 @@ export interface PatchedSubscriptionApi {prompt?: string | null/** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */ai_prompt_config?: AIPromptConfigApi- /** Delivery channel: email or slack.+ /** Delivery channel: email, slack, or teams.** * `email` - Email- * * `slack` - Slack */+ * * `slack` - Slack+ * * `teams` - Microsoft Teams */target_type?: SubscriptionTargetEnumApi- /** Recipient(s): comma-separated email addresses for email, or Slack channel name/ID for slack. */+ /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it. */target_value?: string/** How often to deliver: daily, weekly, monthly, or yearly.*@@ -508,9 +512,9 @@ export interface SubscriptionDeliveryApi {* @nullable*/readonly scheduled_at: string | null- /** Channel snapshot at send time (email or slack). */+ /** Channel snapshot at send time: email, slack, or teams. */readonly target_type: string- /** Destination snapshot at send time (emails, channel id, URL). */+ /** Destination snapshot at send time: the email list, the Slack channel id, or the host of the Microsoft Teams webhook. The webhook URL itself is never returned. */readonly target_value: string/*** ExportedAsset ids generated for this send.@@ -617,7 +621,7 @@ export type SubscriptionsListParams = {*/search?: string/**- * Filter by delivery channel (email or Slack).+ * Filter by delivery channel: email, Slack, or Microsoft Teams.*/target_type?: SubscriptionsListTargetType}@@ -636,6 +640,7 @@ export type SubscriptionsListTargetType = (typeof SubscriptionsListTargetType)[kexport const SubscriptionsListTargetType = {Email: 'email',Slack: 'slack',+ Teams: 'teams',} as constexport type SubscriptionsDeliveriesListParams = {diff --git a/products/subscriptions/frontend/generated/api.zod.ts b/products/subscriptions/frontend/generated/api.zod.tsindex b31e50cd7982..945025147449 100644--- a/products/subscriptions/frontend/generated/api.zod.ts+++ b/products/subscriptions/frontend/generated/api.zod.ts@@ -91,12 +91,16 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod"Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."),target_type: zod- .enum(['email', 'slack'])- .describe('\* `email` - Email\n\* `slack` - Slack')- .describe('Delivery channel: email or slack.\n\n\* `email` - Email\n\* `slack` - Slack'),+ .enum(['email', 'slack', 'teams'])+ .describe('\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams')+ .describe(+ 'Delivery channel: email, slack, or teams.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams'+ ),target_value: zod.string()- .describe('Recipient(s): comma-separated email addresses for email, or Slack channel name\/ID for slack.'),+ .describe(+ 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it.'+ ),frequency: zod.enum(['daily', 'weekly', 'monthly', 'yearly']).describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')@@ -275,12 +279,16 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod"Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."),target_type: zod- .enum(['email', 'slack'])- .describe('\* `email` - Email\n\* `slack` - Slack')- .describe('Delivery channel: email or slack.\n\n\* `email` - Email\n\* `slack` - Slack'),+ .enum(['email', 'slack', 'teams'])+ .describe('\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams')+ .describe(+ 'Delivery channel: email, slack, or teams.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams'+ ),target_value: zod.string()- .describe('Recipient(s): comma-separated email addresses for email, or Slack channel name\/ID for slack.'),+ .describe(+ 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it.'+ ),frequency: zod.enum(['daily', 'weekly', 'monthly', 'yearly']).describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')@@ -459,14 +467,18 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod"Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."),target_type: zod- .enum(['email', 'slack'])- .describe('\* `email` - Email\n\* `slack` - Slack')+ .enum(['email', 'slack', 'teams'])+ .describe('\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams').optional()- .describe('Delivery channel: email or slack.\n\n\* `email` - Email\n\* `slack` - Slack'),+ .describe(+ 'Delivery channel: email, slack, or teams.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams'+ ),target_value: zod.string().optional()- .describe('Recipient(s): comma-separated email addresses for email, or Slack channel name\/ID for slack.'),+ .describe(+ 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it.'+ ),frequency: zod.enum(['daily', 'weekly', 'monthly', 'yearly']).describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionDeliveryHistory.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionDeliveryHistory.tsxindex e2a74c7a7ef5..aedcd6cda736 100644--- a/products/subscriptions/frontend/scenes/components/SubscriptionDeliveryHistory.tsx+++ b/products/subscriptions/frontend/scenes/components/SubscriptionDeliveryHistory.tsx@@ -27,7 +27,8 @@ import {ExpandedDeliveryRow,partialDeliveryTag,} from './SubscriptionAiReportDelivery'-import { SubscriptionDeliveryDestinationCell } from './SubscriptionDestinationCell'+import { deliveryDestination } from './subscriptionDestination'+import { SubscriptionDestinationCell } from './SubscriptionDestinationCell'import { TARGET_TYPE_LABEL } from './subscriptionLabels'/** API query `status` values; alias the const so Babel does not collide with the schema type of the same name. */@@ -159,7 +160,7 @@ function buildDeliveryColumns(): LemonTableColumns<SubscriptionDeliveryApi> {style: () => ({ minWidth: '8rem', maxWidth: 0 }),render: (_v, row) => (<div className="min-w-0 w-full overflow-hidden">- <SubscriptionDeliveryDestinationCell targetType={row.target_type} targetValue={row.target_value} />+ <SubscriptionDestinationCell destination={deliveryDestination(row.target_type, row.target_value)} /></div>),},diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionDestinationCell.test.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionDestinationCell.test.tsxnew file mode 100644index 000000000000..187871d49a94--- /dev/null+++ b/products/subscriptions/frontend/scenes/components/SubscriptionDestinationCell.test.tsx@@ -0,0 +1,43 @@+import '@testing-library/jest-dom'++import { render } from '@testing-library/react'++import { deliveryDestination, subscriptionDestination } from './subscriptionDestination'+import { SubscriptionDestinationCell } from './SubscriptionDestinationCell'++const TEAMS_WEBHOOK_PATH =+ '/workflows/00000000/triggers/manual/paths/invoke?api-version=2016-06-01&sig=not-a-real-signature'+const TEAMS_WEBHOOK_HOST = 'prod-12.westeurope.logic.azure.com'+const TEAMS_WEBHOOK_URL = `https://${TEAMS_WEBHOOK_HOST}${TEAMS_WEBHOOK_PATH}`++describe('SubscriptionDestinationCell', () => {+ it.each([+ ['a webhook URL', TEAMS_WEBHOOK_URL],+ // The canonical Azure form carries :443. Keeping it here would label the same destination+ // differently from the delivery history, which shows the bare host.+ ['a webhook URL with an explicit port', `https://${TEAMS_WEBHOOK_HOST}:443${TEAMS_WEBHOOK_PATH}`],+ ['the host returned by the subscription API', TEAMS_WEBHOOK_HOST],+ ])('shows %s by host and nothing that authorizes a post', (_label, targetValue) => {+ const { container } = render(+ <SubscriptionDestinationCell destination={subscriptionDestination('teams', targetValue)} />+ )++ expect(container.textContent).toBe(TEAMS_WEBHOOK_HOST)+ // A long host truncates in the cell, so the tooltip is the only way to read it in full.+ expect(container.firstElementChild).toHaveAttribute('title', TEAMS_WEBHOOK_HOST)+ // innerHTML, not textContent, so DOM attributes such as title are covered too.+ expect(container.innerHTML).not.toContain('sig=')+ expect(container.innerHTML).not.toContain('/workflows/')+ })++ it.each([+ ['the host the API masked the webhook to', TEAMS_WEBHOOK_HOST],+ ['the placeholder the API sends when the webhook URL did not parse', 'webhook'],+ ])('shows a Teams delivery as %s', (_label, targetValue) => {+ const { container } = render(+ <SubscriptionDestinationCell destination={deliveryDestination('teams', targetValue)} />+ )++ expect(container.textContent).toBe(targetValue)+ })+})diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionDestinationCell.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionDestinationCell.tsxindex 314bf78dc5e6..f86bb35c8112 100644--- a/products/subscriptions/frontend/scenes/components/SubscriptionDestinationCell.tsx+++ b/products/subscriptions/frontend/scenes/components/SubscriptionDestinationCell.tsx@@ -3,25 +3,20 @@ import { LemonMenu, LemonTag } from '@posthog/lemon-ui'import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { copyToClipboard } from 'lib/utils/copyToClipboard'-import { parseCommaSeparatedSlackTargetDisplayLabels } from 'lib/utils/slackChannelValue'-import { SubscriptionTargetEnumApi, type SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'+import type { SubscriptionDestination } from './subscriptionDestination'-function parseEmailRecipients(targetValue: string): string[] {- return targetValue- .split(',')- .map((e) => e.trim())- .filter(Boolean)-}+export function SubscriptionDestinationCell({ destination }: { destination: SubscriptionDestination }): JSX.Element {+ const { parts, copyDescription } = destination-function truncateWebhookUrl(url: string): string {- if (url.length > 48) {- return `${url.slice(0, 24)}…${url.slice(-12)}`+ if (copyDescription === null) {+ return (+ <span className="text-secondary max-w-md truncate block" title={parts[0]}>+ {parts[0]}+ </span>+ )}- return url-}-function DestinationListCell({ parts, copyDescription }: { parts: string[]; copyDescription: string }): JSX.Element {if (parts.length === 0) {return <span className="text-secondary">—</span>}@@ -67,50 +62,3 @@ function DestinationListCell({ parts, copyDescription }: { parts: string[]; copy</span>)}--export function SubscriptionDestinationCell({ sub }: { sub: SubscriptionApi }): JSX.Element {- if (sub.target_type === SubscriptionTargetEnumApi.Email) {- const emails = parseEmailRecipients(sub.target_value)- return <DestinationListCell parts={emails} copyDescription="email recipient" />- }-- if (sub.target_type === SubscriptionTargetEnumApi.Slack) {- const parts = parseCommaSeparatedSlackTargetDisplayLabels(sub.target_value)- return <DestinationListCell parts={parts} copyDescription="Slack destination" />- }-- const text = truncateWebhookUrl(sub.target_value)- return (- <span className="text-secondary max-w-md truncate block" title={sub.target_value}>- {text}- </span>- )-}--/** Same destination UI as {@link SubscriptionDestinationCell}, for snapshot `target_type` / `target_value` (e.g. delivery history rows). */-export function SubscriptionDeliveryDestinationCell({- targetType,- targetValue,-}: {- targetType: string- targetValue: string-}): JSX.Element {- const kind = targetType.toLowerCase()- if (kind === SubscriptionTargetEnumApi.Email) {- return <DestinationListCell parts={parseEmailRecipients(targetValue)} copyDescription="email recipient" />- }- if (kind === SubscriptionTargetEnumApi.Slack) {- return (- <DestinationListCell- parts={parseCommaSeparatedSlackTargetDisplayLabels(targetValue)}- copyDescription="Slack destination"- />- )- }- const text = truncateWebhookUrl(targetValue)- return (- <span className="text-secondary max-w-md truncate block" title={targetValue}>- {text}- </span>- )-}diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionSummary.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionSummary.tsxindex cd3e3ebf5496..c36bf51f4fe8 100644--- a/products/subscriptions/frontend/scenes/components/SubscriptionSummary.tsx+++ b/products/subscriptions/frontend/scenes/components/SubscriptionSummary.tsx@@ -7,6 +7,7 @@ import type { HedgehogConfig, MinimalHedgehogConfig } from '~/types'import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'+import { subscriptionDestination } from './subscriptionDestination'import { SubscriptionDestinationCell } from './SubscriptionDestinationCell'import { TARGET_TYPE_LABEL } from './subscriptionLabels'import { subscriptionResourceLabel, subscriptionResourceViewUrl } from './SubscriptionsTable'@@ -40,7 +41,9 @@ export function SubscriptionSummary({ sub }: { sub: SubscriptionApi }): JSX.Elem<div><dt className="text-sm text-secondary">Destination</dt><dd className="min-w-0">- <SubscriptionDestinationCell sub={sub} />+ <SubscriptionDestinationCell+ destination={subscriptionDestination(sub.target_type, sub.target_value)}+ /></dd></div><div className="min-w-0">diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionsFiltersBar.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionsFiltersBar.tsxindex cdff1d22609e..956d49816ed6 100644--- a/products/subscriptions/frontend/scenes/components/SubscriptionsFiltersBar.tsx+++ b/products/subscriptions/frontend/scenes/components/SubscriptionsFiltersBar.tsx@@ -4,17 +4,14 @@ import { LemonInput, LemonSelect } from '@posthog/lemon-ui'import { MemberSelect } from 'lib/components/MemberSelect'-import {- SubscriptionTargetEnumApi,- type SubscriptionsListTargetType,-} from 'products/subscriptions/frontend/generated/api.schemas'+import { SubscriptionsListTargetType } from 'products/subscriptions/frontend/generated/api.schemas'import { SubscriptionsTab, subscriptionsSceneLogic } from '../subscriptionsSceneLogic'+import { TARGET_TYPE_LABEL } from './subscriptionLabels'const CHANNEL_FILTER_OPTIONS: { label: string; value: SubscriptionsListTargetType | null }[] = [{ label: 'All channels', value: null },- { label: 'Email', value: SubscriptionTargetEnumApi.Email },- { label: 'Slack', value: SubscriptionTargetEnumApi.Slack },+ ...Object.values(SubscriptionsListTargetType).map((value) => ({ label: TARGET_TYPE_LABEL[value], value })),]export function SubscriptionsFiltersBar(): JSX.Element {diff --git a/products/subscriptions/frontend/scenes/components/SubscriptionsTable.tsx b/products/subscriptions/frontend/scenes/components/SubscriptionsTable.tsxindex 74cbc4ba6b4f..d7338a4a7f5c 100644--- a/products/subscriptions/frontend/scenes/components/SubscriptionsTable.tsx+++ b/products/subscriptions/frontend/scenes/components/SubscriptionsTable.tsx@@ -11,6 +11,7 @@ import { SubscriptionResourceTypes } from '~/types'import type { SubscriptionApi } from 'products/subscriptions/frontend/generated/api.schemas'+import { subscriptionDestination } from './subscriptionDestination'import { SubscriptionDestinationCell } from './SubscriptionDestinationCell'import { TARGET_TYPE_LABEL } from './subscriptionLabels'@@ -195,7 +196,9 @@ function buildColumns({title: 'Destination',key: 'target_value',- render: (_value: unknown, sub: SubscriptionApi) => <SubscriptionDestinationCell sub={sub} />,+ render: (_value: unknown, sub: SubscriptionApi) => (+ <SubscriptionDestinationCell destination={subscriptionDestination(sub.target_type, sub.target_value)} />+ ),},{title: 'Recurrence',diff --git a/products/subscriptions/frontend/scenes/components/subscriptionDestination.ts b/products/subscriptions/frontend/scenes/components/subscriptionDestination.tsnew file mode 100644index 000000000000..dd644ac579d3--- /dev/null+++ b/products/subscriptions/frontend/scenes/components/subscriptionDestination.ts@@ -0,0 +1,75 @@+import { parseCommaSeparatedSlackTargetDisplayLabels } from 'lib/utils/slackChannelValue'+import { pluralize } from 'lib/utils/strings'++import { SubscriptionTargetEnumApi } from 'products/subscriptions/frontend/generated/api.schemas'++export interface SubscriptionDestination {+ parts: string[]+ label: string+ title: string+ copyDescription: string | null+}++function destination(parts: string[], copyDescription: string | null, countNoun: string): SubscriptionDestination {+ return {+ parts,+ label: parts.length === 1 ? parts[0] : pluralize(parts.length, countNoun, undefined, true),+ title: parts.join(', '),+ copyDescription,+ }+}++function emailDestination(targetValue: string): SubscriptionDestination {+ return destination(+ targetValue+ .split(',')+ .map((part) => part.trim())+ .filter(Boolean),+ 'email recipient',+ 'recipient'+ )+}++function slackDestination(targetValue: string): SubscriptionDestination {+ return destination(parseCommaSeparatedSlackTargetDisplayLabels(targetValue), 'Slack destination', 'channel')+}++function webhookDestination(host: string): SubscriptionDestination {+ return destination([host], null, 'destination')+}++function webhookHost(url: string): string {+ try {+ // `hostname`, not `host`: an explicit `:443` would make this cell disagree with the+ // delivery history, where the backend records the bare host for the same destination.+ return new URL(url).hostname+ } catch {+ return 'Invalid URL'+ }+}++export function subscriptionDestination(targetType: string, targetValue: string): SubscriptionDestination {+ switch (targetType) {+ case SubscriptionTargetEnumApi.Email:+ return emailDestination(targetValue)+ case SubscriptionTargetEnumApi.Slack:+ return slackDestination(targetValue)+ case SubscriptionTargetEnumApi.Teams:+ return webhookDestination(targetValue.includes('://') ? webhookHost(targetValue) : targetValue)+ default:+ return webhookDestination(webhookHost(targetValue))+ }+}++export function deliveryDestination(targetType: string, targetValue: string): SubscriptionDestination {+ switch (targetType.toLowerCase()) {+ case SubscriptionTargetEnumApi.Email:+ return emailDestination(targetValue)+ case SubscriptionTargetEnumApi.Slack:+ return slackDestination(targetValue)+ case SubscriptionTargetEnumApi.Teams:+ return webhookDestination(targetValue)+ default:+ return webhookDestination(webhookHost(targetValue))+ }+}diff --git a/products/subscriptions/frontend/scenes/components/subscriptionLabels.ts b/products/subscriptions/frontend/scenes/components/subscriptionLabels.tsindex 297688b583e6..a89ce67b9384 100644--- a/products/subscriptions/frontend/scenes/components/subscriptionLabels.ts+++ b/products/subscriptions/frontend/scenes/components/subscriptionLabels.ts@@ -4,4 +4,5 @@ import { SubscriptionTargetEnumApi } from 'products/subscriptions/frontend/generexport const TARGET_TYPE_LABEL: Record<SubscriptionApi['target_type'], string> = {[SubscriptionTargetEnumApi.Email]: 'Email',[SubscriptionTargetEnumApi.Slack]: 'Slack',+ [SubscriptionTargetEnumApi.Teams]: 'Microsoft Teams',}diff --git a/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx b/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsxindex de5d1e759125..bbce3c8e8cb9 100644--- a/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx+++ b/products/subscriptions/frontend/scenes/subscriptionsSceneLogic.tsx@@ -19,9 +19,8 @@ import { Breadcrumb } from '~/types'import { subscriptionsList, subscriptionsTestDeliveryCreate } from 'products/subscriptions/frontend/generated/api'import {SubscriptionsListResourceType,- SubscriptionTargetEnumApi,+ SubscriptionsListTargetType,type PaginatedSubscriptionListApi,- type SubscriptionsListTargetType,} from 'products/subscriptions/frontend/generated/api.schemas'import type { OrganizationType, UserType } from '../../../../frontend/src/types'@@ -47,9 +46,16 @@ function getInitialSubscriptionsTab(): SubscriptionsTab {/** Query keys owned by the subscriptions list scene (merged into the router; other params are preserved). */const SUBSCRIPTIONS_URL_KEYS = ['tab', 'search', 'created_by', 'target_type', 'page'] as const-/** Router may coerce numeric-looking query values; keep text fields as strings. */-function urlSearchParamToString(value: unknown): string {- return `${value ?? ''}`+function parseTargetTypeFilter(raw?: string): SubscriptionsListTargetType | null {+ return Object.values(SubscriptionsListTargetType).find((targetType) => targetType === raw) ?? null+}++interface SubscriptionsSearchParams {+ tab?: string+ search?: string | number+ created_by?: string+ target_type?: string+ page?: string | number}export interface SubscriptionsQueryFromUrl {@@ -60,23 +66,21 @@ export interface SubscriptionsQueryFromUrl {page: number}-function parseSubscriptionsSearchParams(searchParams: Record<string, unknown>): SubscriptionsQueryFromUrl {+function parseSubscriptionsSearchParams(searchParams: SubscriptionsSearchParams): SubscriptionsQueryFromUrl {const rawTab = searchParams['tab']const tab: SubscriptionsTab = (Object.values(SubscriptionsTab) as string[]).includes(rawTab as string)? (rawTab as SubscriptionsTab): SubscriptionsTab.All- const search = urlSearchParamToString(searchParams['search'])+ // Kea Router converts numeric-looking query values to numbers.+ const search = String(searchParams['search'] ?? '')- let createdByUuid: string | null =- typeof searchParams['created_by'] === 'string' ? searchParams['created_by'] : null+ let createdByUuid: string | null = searchParams['created_by'] ?? nullif (tab === SubscriptionsTab.Mine) {createdByUuid = null}- const ttRaw = searchParams['target_type']- const targetTypeFilter: SubscriptionsListTargetType | null =- ttRaw === SubscriptionTargetEnumApi.Email || ttRaw === SubscriptionTargetEnumApi.Slack ? ttRaw : null+ const targetTypeFilter = parseTargetTypeFilter(searchParams['target_type'])let page = 1const pageRaw = searchParams['page']diff --git a/products/subscriptions/mcp/tools.yaml b/products/subscriptions/mcp/tools.yamlindex 73b2da4f0110..cd6307239aa8 100644--- a/products/subscriptions/mcp/tools.yaml+++ b/products/subscriptions/mcp/tools.yaml@@ -34,7 +34,9 @@ tools:is rejected with a 400. Creating a prompt subscription also requires the `query:read` scope — the reportruns LLM-generated HogQL over your data — so a `subscription:write`-only token is rejected for this kind.- Delivery is set by `target_type` — `email` or `slack`.+ Delivery is set by `target_type` — `email`, `slack`, or `teams` (a Microsoft Teams webhook URL in+ `target_value`). A Teams webhook URL is only ever read back as its host. Creating a Teams subscription+ requires the full webhook URL in `target_value`.The kind is fixed at create time — a PATCH that would change the populated relation to a different kind isrejected.@@ -168,6 +170,9 @@ tools:prompt subscription additionally requires the `query:read` scope. Use `subscriptions-delete` to soft-delete— `deleted` is not settable here.+ For Microsoft Teams, omit `target_value` to keep the stored webhook URL. To replace it, send a full Teams+ webhook URL; the host returned by this API is not a valid replacement.+For insight and dashboard subscriptions, toggle the per-delivery AI summary with `summary_enabled` and steerit with `summary_prompt_guide`. Enabling a summary requires the organization to have approved AI dataprocessing and to be within its active-summary cap and AI credit budget; otherwise the update is rejected.@@ -190,9 +195,9 @@ tools:title: Get subscriptiondescription:'Fetch a single subscription by numeric ID. Returns its kind (`resource_type`: insight, dashboard, or- ai_prompt), target (`target_type`/`target_value`), schedule, enabled state, and AI-summary settings.- Metadata only — for the send history and delivered reports, use `subscriptions-deliveries-list` /- `subscriptions-deliveries-retrieve`.'+ ai_prompt), target (`target_type`/`target_value`, host-only for a Teams webhook), schedule, enabled state,+ and AI-summary settings. Metadata only — for the send history and delivered reports, use+ `subscriptions-deliveries-list` / `subscriptions-deliveries-retrieve`.'response:exclude:- invite_message@@ -210,14 +215,14 @@ tools:idempotent: falsetitle: Send test deliverydescription: >- Trigger an immediate test delivery of a subscription to its configured target(s) (email or Slack). Runs the- same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can- inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the- delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or- subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription- is already in flight, or if the subscription is disabled (re-enable it first); 404 if it has been deleted.- Test-delivering a prompt subscription additionally requires the `query:read` scope (it runs the AI HogQL- pipeline).+ Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or Microsoft+ Teams). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real+ delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve.+ Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first)+ or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same+ subscription is already in flight, or if the subscription is disabled (re-enable it first); 404 if it has+ been deleted. Test-delivering a prompt subscription additionally requires the `query:read` scope (it runs+ the AI HogQL pipeline).subscriptions-update:operation: subscriptions_updateenabled: falsediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 8eb7edab090f..849c1882272d 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -10324,7 +10324,7 @@"feature_flag": "streamlit-apps"},"subscriptions-create": {- "description": "Create a recurring subscription. The kind is inferred from which field you populate and returned as the read-only `resource_type`:\n(1) set `insight` — schedule periodic snapshots of one insight (`resource_type: \"insight\"`).\n(2) set `dashboard` and `dashboard_export_insights` (the subset of the dashboard's insights to include, max 10) — schedule periodic snapshots of one dashboard (`resource_type: \"dashboard\"`).\n(3) set `prompt` (≤4000 chars, with no insight or dashboard) — schedule a recurring LLM-generated report (`resource_type: \"ai_prompt\"`). Available on PostHog Cloud (self-hosted production is not eligible) once the organization has approved AI data processing and prompt subscriptions are enabled for it; otherwise create is rejected with a 400. Creating a prompt subscription also requires the `query:read` scope — the report runs LLM-generated HogQL over your data — so a `subscription:write`-only token is rejected for this kind.\nDelivery is set by `target_type` — `email` or `slack`.\nThe kind is fixed at create time — a PATCH that would change the populated relation to a different kind is rejected.\nFor insight and dashboard subscriptions you can attach an AI-generated summary to each delivery by setting `summary_enabled: true` (optionally steered by `summary_prompt_guide`). This requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the create is rejected. Prompt subscriptions are themselves AI-generated, so these fields do not apply to them.\nIMPORTANT — when creating an insight (or dashboard) subscription, always ask the user whether to enable the AI-generated summary before creating it. Present it as their choice: they can turn it on (`summary_enabled: true`) or leave it off, and if they turn it on, offer them the option to add a custom prompt to steer the summary (`summary_prompt_guide`). Do not enable the summary on your own without asking. (Prompt subscriptions are themselves AI-generated, so this does not apply to them.)",+ "description": "Create a recurring subscription. The kind is inferred from which field you populate and returned as the read-only `resource_type`:\n(1) set `insight` — schedule periodic snapshots of one insight (`resource_type: \"insight\"`).\n(2) set `dashboard` and `dashboard_export_insights` (the subset of the dashboard's insights to include, max 10) — schedule periodic snapshots of one dashboard (`resource_type: \"dashboard\"`).\n(3) set `prompt` (≤4000 chars, with no insight or dashboard) — schedule a recurring LLM-generated report (`resource_type: \"ai_prompt\"`). Available on PostHog Cloud (self-hosted production is not eligible) once the organization has approved AI data processing and prompt subscriptions are enabled for it; otherwise create is rejected with a 400. Creating a prompt subscription also requires the `query:read` scope — the report runs LLM-generated HogQL over your data — so a `subscription:write`-only token is rejected for this kind.\nDelivery is set by `target_type` — `email`, `slack`, or `teams` (a Microsoft Teams webhook URL in `target_value`). A Teams webhook URL is only ever read back as its host. Creating a Teams subscription requires the full webhook URL in `target_value`.\nThe kind is fixed at create time — a PATCH that would change the populated relation to a different kind is rejected.\nFor insight and dashboard subscriptions you can attach an AI-generated summary to each delivery by setting `summary_enabled: true` (optionally steered by `summary_prompt_guide`). This requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the create is rejected. Prompt subscriptions are themselves AI-generated, so these fields do not apply to them.\nIMPORTANT — when creating an insight (or dashboard) subscription, always ask the user whether to enable the AI-generated summary before creating it. Present it as their choice: they can turn it on (`summary_enabled: true`) or leave it off, and if they turn it on, offer them the option to add a custom prompt to steer the summary (`summary_prompt_guide`). Do not enable the summary on your own without asking. (Prompt subscriptions are themselves AI-generated, so this does not apply to them.)","category": "Subscriptions","feature": "subscriptions","summary": "Create subscription",@@ -10394,7 +10394,7 @@}},"subscriptions-partial-update": {- "description": "Update a subscription's mutable fields (title, target, schedule, the `prompt` for prompt subscriptions, `enabled`). The kind (`resource_type`) is fixed at create — a PATCH that would introduce another kind's field (e.g. a `prompt` on an insight sub) is rejected with 400. For prompt subs, re-enabling a previously auto-disabled sub requires both a valid `prompt` (already persisted or supplied in the PATCH body) and that the original creator is still an active user; otherwise it is rejected with 400. Editing or re-enabling a prompt subscription additionally requires the `query:read` scope. Use `subscriptions-delete` to soft-delete — `deleted` is not settable here.\nFor insight and dashboard subscriptions, toggle the per-delivery AI summary with `summary_enabled` and steer it with `summary_prompt_guide`. Enabling a summary requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the update is rejected.",+ "description": "Update a subscription's mutable fields (title, target, schedule, the `prompt` for prompt subscriptions, `enabled`). The kind (`resource_type`) is fixed at create — a PATCH that would introduce another kind's field (e.g. a `prompt` on an insight sub) is rejected with 400. For prompt subs, re-enabling a previously auto-disabled sub requires both a valid `prompt` (already persisted or supplied in the PATCH body) and that the original creator is still an active user; otherwise it is rejected with 400. Editing or re-enabling a prompt subscription additionally requires the `query:read` scope. Use `subscriptions-delete` to soft-delete — `deleted` is not settable here.\nFor Microsoft Teams, omit `target_value` to keep the stored webhook URL. To replace it, send a full Teams webhook URL; the host returned by this API is not a valid replacement.\nFor insight and dashboard subscriptions, toggle the per-delivery AI summary with `summary_enabled` and steer it with `summary_prompt_guide`. Enabling a summary requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the update is rejected.","category": "Subscriptions","feature": "subscriptions","summary": "Update subscription",@@ -10408,7 +10408,7 @@}},"subscriptions-retrieve": {- "description": "Fetch a single subscription by numeric ID. Returns its kind (`resource_type`: insight, dashboard, or ai_prompt), target (`target_type`/`target_value`), schedule, enabled state, and AI-summary settings. Metadata only — for the send history and delivered reports, use `subscriptions-deliveries-list` / `subscriptions-deliveries-retrieve`.",+ "description": "Fetch a single subscription by numeric ID. Returns its kind (`resource_type`: insight, dashboard, or ai_prompt), target (`target_type`/`target_value`, host-only for a Teams webhook), schedule, enabled state, and AI-summary settings. Metadata only — for the send history and delivered reports, use `subscriptions-deliveries-list` / `subscriptions-deliveries-retrieve`.","category": "Subscriptions","feature": "subscriptions","summary": "Get subscription",@@ -10422,7 +10422,7 @@}},"subscriptions-test-delivery-create": {- "description": "Trigger an immediate test delivery of a subscription to its configured target(s) (email or Slack). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription is already in flight, or if the subscription is disabled (re-enable it first); 404 if it has been deleted. Test-delivering a prompt subscription additionally requires the `query:read` scope (it runs the AI HogQL pipeline).",+ "description": "Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or Microsoft Teams). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription is already in flight, or if the subscription is disabled (re-enable it first); 404 if it has been deleted. Test-delivering a prompt subscription additionally requires the `query:read` scope (it runs the AI HogQL pipeline).","category": "Subscriptions","feature": "subscriptions","summary": "Send test delivery",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 0b5e8b4824b4..bb4b36a4c866 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -10879,7 +10879,7 @@"feature_flag": "streamlit-apps"},"subscriptions-create": {- "description": "Create a recurring subscription. The kind is inferred from which field you populate and returned as the read-only `resource_type`:\n(1) set `insight` — schedule periodic snapshots of one insight (`resource_type: \"insight\"`).\n(2) set `dashboard` and `dashboard_export_insights` (the subset of the dashboard's insights to include, max 10) — schedule periodic snapshots of one dashboard (`resource_type: \"dashboard\"`).\n(3) set `prompt` (≤4000 chars, with no insight or dashboard) — schedule a recurring LLM-generated report (`resource_type: \"ai_prompt\"`). Available on PostHog Cloud (self-hosted production is not eligible) once the organization has approved AI data processing and prompt subscriptions are enabled for it; otherwise create is rejected with a 400. Creating a prompt subscription also requires the `query:read` scope — the report runs LLM-generated HogQL over your data — so a `subscription:write`-only token is rejected for this kind.\nDelivery is set by `target_type` — `email` or `slack`.\nThe kind is fixed at create time — a PATCH that would change the populated relation to a different kind is rejected.\nFor insight and dashboard subscriptions you can attach an AI-generated summary to each delivery by setting `summary_enabled: true` (optionally steered by `summary_prompt_guide`). This requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the create is rejected. Prompt subscriptions are themselves AI-generated, so these fields do not apply to them.\nIMPORTANT — when creating an insight (or dashboard) subscription, always ask the user whether to enable the AI-generated summary before creating it. Present it as their choice: they can turn it on (`summary_enabled: true`) or leave it off, and if they turn it on, offer them the option to add a custom prompt to steer the summary (`summary_prompt_guide`). Do not enable the summary on your own without asking. (Prompt subscriptions are themselves AI-generated, so this does not apply to them.)",+ "description": "Create a recurring subscription. The kind is inferred from which field you populate and returned as the read-only `resource_type`:\n(1) set `insight` — schedule periodic snapshots of one insight (`resource_type: \"insight\"`).\n(2) set `dashboard` and `dashboard_export_insights` (the subset of the dashboard's insights to include, max 10) — schedule periodic snapshots of one dashboard (`resource_type: \"dashboard\"`).\n(3) set `prompt` (≤4000 chars, with no insight or dashboard) — schedule a recurring LLM-generated report (`resource_type: \"ai_prompt\"`). Available on PostHog Cloud (self-hosted production is not eligible) once the organization has approved AI data processing and prompt subscriptions are enabled for it; otherwise create is rejected with a 400. Creating a prompt subscription also requires the `query:read` scope — the report runs LLM-generated HogQL over your data — so a `subscription:write`-only token is rejected for this kind.\nDelivery is set by `target_type` — `email`, `slack`, or `teams` (a Microsoft Teams webhook URL in `target_value`). A Teams webhook URL is only ever read back as its host. Creating a Teams subscription requires the full webhook URL in `target_value`.\nThe kind is fixed at create time — a PATCH that would change the populated relation to a different kind is rejected.\nFor insight and dashboard subscriptions you can attach an AI-generated summary to each delivery by setting `summary_enabled: true` (optionally steered by `summary_prompt_guide`). This requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the create is rejected. Prompt subscriptions are themselves AI-generated, so these fields do not apply to them.\nIMPORTANT — when creating an insight (or dashboard) subscription, always ask the user whether to enable the AI-generated summary before creating it. Present it as their choice: they can turn it on (`summary_enabled: true`) or leave it off, and if they turn it on, offer them the option to add a custom prompt to steer the summary (`summary_prompt_guide`). Do not enable the summary on your own without asking. (Prompt subscriptions are themselves AI-generated, so this does not apply to them.)","category": "Subscriptions","feature": "subscriptions","summary": "Create subscription",@@ -10949,7 +10949,7 @@}},"subscriptions-partial-update": {- "description": "Update a subscription's mutable fields (title, target, schedule, the `prompt` for prompt subscriptions, `enabled`). The kind (`resource_type`) is fixed at create — a PATCH that would introduce another kind's field (e.g. a `prompt` on an insight sub) is rejected with 400. For prompt subs, re-enabling a previously auto-disabled sub requires both a valid `prompt` (already persisted or supplied in the PATCH body) and that the original creator is still an active user; otherwise it is rejected with 400. Editing or re-enabling a prompt subscription additionally requires the `query:read` scope. Use `subscriptions-delete` to soft-delete — `deleted` is not settable here.\nFor insight and dashboard subscriptions, toggle the per-delivery AI summary with `summary_enabled` and steer it with `summary_prompt_guide`. Enabling a summary requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the update is rejected.",+ "description": "Update a subscription's mutable fields (title, target, schedule, the `prompt` for prompt subscriptions, `enabled`). The kind (`resource_type`) is fixed at create — a PATCH that would introduce another kind's field (e.g. a `prompt` on an insight sub) is rejected with 400. For prompt subs, re-enabling a previously auto-disabled sub requires both a valid `prompt` (already persisted or supplied in the PATCH body) and that the original creator is still an active user; otherwise it is rejected with 400. Editing or re-enabling a prompt subscription additionally requires the `query:read` scope. Use `subscriptions-delete` to soft-delete — `deleted` is not settable here.\nFor Microsoft Teams, omit `target_value` to keep the stored webhook URL. To replace it, send a full Teams webhook URL; the host returned by this API is not a valid replacement.\nFor insight and dashboard subscriptions, toggle the per-delivery AI summary with `summary_enabled` and steer it with `summary_prompt_guide`. Enabling a summary requires the organization to have approved AI data processing and to be within its active-summary cap and AI credit budget; otherwise the update is rejected.","category": "Subscriptions","feature": "subscriptions","summary": "Update subscription",@@ -10963,7 +10963,7 @@}},"subscriptions-retrieve": {- "description": "Fetch a single subscription by numeric ID. Returns its kind (`resource_type`: insight, dashboard, or ai_prompt), target (`target_type`/`target_value`), schedule, enabled state, and AI-summary settings. Metadata only — for the send history and delivered reports, use `subscriptions-deliveries-list` / `subscriptions-deliveries-retrieve`.",+ "description": "Fetch a single subscription by numeric ID. Returns its kind (`resource_type`: insight, dashboard, or ai_prompt), target (`target_type`/`target_value`, host-only for a Teams webhook), schedule, enabled state, and AI-summary settings. Metadata only — for the send history and delivered reports, use `subscriptions-deliveries-list` / `subscriptions-deliveries-retrieve`.","category": "Subscriptions","feature": "subscriptions","summary": "Get subscription",@@ -10977,7 +10977,7 @@}},"subscriptions-test-delivery-create": {- "description": "Trigger an immediate test delivery of a subscription to its configured target(s) (email or Slack). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription is already in flight, or if the subscription is disabled (re-enable it first); 404 if it has been deleted. Test-delivering a prompt subscription additionally requires the `query:read` scope (it runs the AI HogQL pipeline).",+ "description": "Trigger an immediate test delivery of a subscription to its configured target(s) (email, Slack, or Microsoft Teams). Runs the same pipeline as a scheduled delivery but with trigger_type=manual, producing a real delivery record you can inspect via subscriptions-deliveries-list / subscriptions-deliveries-retrieve. Returns 202 Accepted once the delivery workflow is queued; poll subscriptions-deliveries-list (newest first) or subscriptions-deliveries-retrieve for the outcome. Returns 409 if a test delivery for the same subscription is already in flight, or if the subscription is disabled (re-enable it first); 404 if it has been deleted. Test-delivering a prompt subscription additionally requires the `query:read` scope (it runs the AI HogQL pipeline).","category": "Subscriptions","feature": "subscriptions","summary": "Send test delivery",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex acb32cf6b13c..6c512674aa8b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -57050,9 +57050,9 @@ export namespace Schemas {* @nullable*/readonly scheduled_at: string | null;- /** Channel snapshot at send time (email or slack). */+ /** Channel snapshot at send time: email, slack, or teams. */readonly target_type: string;- /** Destination snapshot at send time (emails, channel id, URL). */+ /** Destination snapshot at send time: the email list, the Slack channel id, or the host of the Microsoft Teams webhook. The webhook URL itself is never returned. */readonly target_value: string;/*** ExportedAsset ids generated for this send.@@ -57134,6 +57134,7 @@ export namespace Schemas {/*** * `email` - Email* * `slack` - Slack+ * * `teams` - Microsoft Teams*/export type SubscriptionTargetEnum = typeof SubscriptionTargetEnum[keyof typeof SubscriptionTargetEnum];@@ -57141,6 +57142,7 @@ export namespace Schemas {export const SubscriptionTargetEnum = {Email: 'email',Slack: 'slack',+ Teams: 'teams',} as const;/**@@ -57199,12 +57201,13 @@ export namespace Schemas {prompt?: string | null;/** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */ai_prompt_config?: AIPromptConfig;- /** Delivery channel: email or slack.+ /** Delivery channel: email, slack, or teams.** * `email` - Email- * * `slack` - Slack */+ * * `slack` - Slack+ * * `teams` - Microsoft Teams */target_type: SubscriptionTargetEnum;- /** Recipient(s): comma-separated email addresses for email, or Slack channel name/ID for slack. */+ /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it. */target_value: string;/** How often to deliver: daily, weekly, monthly, or yearly.*@@ -66177,12 +66180,13 @@ export namespace Schemas {prompt?: string | null;/** Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes. */ai_prompt_config?: AIPromptConfig;- /** Delivery channel: email or slack.+ /** Delivery channel: email, slack, or teams.** * `email` - Email- * * `slack` - Slack */+ * * `slack` - Slack+ * * `teams` - Microsoft Teams */target_type?: SubscriptionTargetEnum;- /** Recipient(s): comma-separated email addresses for email, or Slack channel name/ID for slack. */+ /** Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it. */target_value?: string;/** How often to deliver: daily, weekly, monthly, or yearly.*@@ -98764,7 +98768,7 @@ export namespace Schemas {*/search?: string;/**- * Filter by delivery channel (email or Slack).+ * Filter by delivery channel: email, Slack, or Microsoft Teams.*/target_type?: SubscriptionsListTargetType;};@@ -98784,6 +98788,7 @@ export namespace Schemas {export const SubscriptionsListTargetType = {Email: 'email',Slack: 'slack',+ Teams: 'teams',} as const;export type SubscriptionsDeliveriesListParams = {diff --git a/services/mcp/src/generated/subscriptions/api.ts b/services/mcp/src/generated/subscriptions/api.tsindex 9a07fecc9a5f..e6729ecfd5fe 100644--- a/services/mcp/src/generated/subscriptions/api.ts+++ b/services/mcp/src/generated/subscriptions/api.ts@@ -33,7 +33,10 @@ export const SubscriptionsListQueryParams = /* @__PURE__ */ zod.object({.optional().describe('Filter by subscription resource: insight, dashboard export, or AI report.'),search: zod.string().optional().describe('A search term.'),- target_type: zod.enum(['email', 'slack']).optional().describe('Filter by delivery channel (email or Slack).'),+ target_type: zod+ .enum(['email', 'slack', 'teams'])+ .optional()+ .describe('Filter by delivery channel: email, Slack, or Microsoft Teams.'),})export const SubscriptionsCreateParams = /* @__PURE__ */ zod.object({@@ -126,12 +129,16 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod"Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."),target_type: zod- .enum(['email', 'slack'])- .describe('\* `email` - Email\n\* `slack` - Slack')- .describe('Delivery channel: email or slack.\n\n\* `email` - Email\n\* `slack` - Slack'),+ .enum(['email', 'slack', 'teams'])+ .describe('\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams')+ .describe(+ 'Delivery channel: email, slack, or teams.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams'+ ),target_value: zod.string()- .describe('Recipient(s): comma-separated email addresses for email, or Slack channel name\/ID for slack.'),+ .describe(+ 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it.'+ ),frequency: zod.enum(['daily', 'weekly', 'monthly', 'yearly']).describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')@@ -323,14 +330,18 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod"Configuration for AI report subscriptions (analysis window, future knobs). Only valid when resource_type is 'ai_prompt'. Replaced wholesale on writes."),target_type: zod- .enum(['email', 'slack'])- .describe('\* `email` - Email\n\* `slack` - Slack')+ .enum(['email', 'slack', 'teams'])+ .describe('\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams').optional()- .describe('Delivery channel: email or slack.\n\n\* `email` - Email\n\* `slack` - Slack'),+ .describe(+ 'Delivery channel: email, slack, or teams.\n\n\* `email` - Email\n\* `slack` - Slack\n\* `teams` - Microsoft Teams'+ ),target_value: zod.string().optional()- .describe('Recipient(s): comma-separated email addresses for email, or Slack channel name\/ID for slack.'),+ .describe(+ 'Recipient(s): comma-separated email addresses for email, Slack channel name\/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it.'+ ),frequency: zod.enum(['daily', 'weekly', 'monthly', 'yearly']).describe('\* `daily` - Daily\n\* `weekly` - Weekly\n\* `monthly` - Monthly\n\* `yearly` - Yearly')diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.jsonindex b977ef83b6f1..7d1954a81162 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json@@ -185,12 +185,12 @@"type": "string"},"target_type": {- "description": "Delivery channel: email or slack.\n\n* `email` - Email\n* `slack` - Slack",- "enum": ["email", "slack"],+ "description": "Delivery channel: email, slack, or teams.\n\n* `email` - Email\n* `slack` - Slack\n* `teams` - Microsoft Teams",+ "enum": ["email", "slack", "teams"],"type": "string"},"target_value": {- "description": "Recipient(s): comma-separated email addresses for email, or Slack channel name/ID for slack.",+ "description": "Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it.","type": "string"},"title": {diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.jsonindex c7c00e863a71..ac86c089caad 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-list.json@@ -43,8 +43,8 @@"type": "string"},"target_type": {- "description": "Filter by delivery channel (email or Slack).",- "enum": ["email", "slack"],+ "description": "Filter by delivery channel: email, Slack, or Microsoft Teams.",+ "enum": ["email", "slack", "teams"],"type": "string"}},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.jsonindex 19a2ba03eccd..57f7e56dcf62 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@@ -184,12 +184,12 @@"type": "string"},"target_type": {- "description": "Delivery channel: email or slack.\n\n* `email` - Email\n* `slack` - Slack",- "enum": ["email", "slack"],+ "description": "Delivery channel: email, slack, or teams.\n\n* `email` - Email\n* `slack` - Slack\n* `teams` - Microsoft Teams",+ "enum": ["email", "slack", "teams"],"type": "string"},"target_value": {- "description": "Recipient(s): comma-separated email addresses for email, or Slack channel name/ID for slack.",+ "description": "Recipient(s): comma-separated email addresses for email, Slack channel name/ID for slack, or a Microsoft Teams webhook URL for teams. A Teams webhook URL is only ever returned as its host, because the URL authorizes a post to the channel by itself. On update, omit the field to keep the stored URL, or send a full URL to replace it.","type": "string"},"title": {