: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): option to post all Slack insights in main message (#65407)
Vasco de Krijger8b43ed424cb8
diff --git a/ee/api/subscription.py b/ee/api/subscription.pyindex e1531447d173..395b8164349f 100644--- a/ee/api/subscription.py+++ b/ee/api/subscription.py@@ -37,7 +37,7 @@ from posthog.dataclasses import frozenfrom posthog.event_usage import get_request_analytics_properties, groupsfrom posthog.exceptions import QuotaLimitExceededfrom posthog.exceptions_capture import capture_exception-from posthog.models.integration import Integration+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@@ -254,6 +254,20 @@ class AIPromptConfigSerializer(serializers.Serializer):)+class DeliveryConfigSerializer(serializers.Serializer):+ """Typed view over the Subscription.delivery_config JSON blob."""++ post_all_insights_in_main_message = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "Slack only: when true, upload all insight images together in the main Slack message "+ "instead of posting the first image in the main message and the rest as threaded replies. "+ "Defaults to false."+ ),+ )++class SubscriptionSerializer(serializers.ModelSerializer):"""Standard Subscription serializer."""@@ -261,6 +275,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):"target_value","target_type","integration_id",+ "delivery_config","prompt","insight_id","dashboard_id",@@ -300,6 +315,10 @@ class SubscriptionSerializer(serializers.ModelSerializer):"when resource_type is 'ai_prompt'. Replaced wholesale on writes."),)+ delivery_config = DeliveryConfigSerializer(+ required=False,+ help_text="Per-delivery rendering options. Each option documents which delivery targets it applies to.",+ )insight_short_id = serializers.SerializerMethodField()resource_name = serializers.SerializerMethodField()resource_type = serializers.ChoiceField(@@ -346,6 +365,7 @@ class SubscriptionSerializer(serializers.ModelSerializer):"send_test_now","summary_enabled","summary_prompt_guide",+ "delivery_config",]read_only_fields = ["id",@@ -524,6 +544,11 @@ class SubscriptionSerializer(serializers.ModelSerializer):if "integration_id" in attrselse (self.instance.integration_id if self.instance else None))+ effective_delivery_config = (+ attrs["delivery_config"]+ if "delivery_config" in attrs+ else (self.instance.delivery_config if self.instance else None)+ ) or {}# Reject re-enables of subscriptions whose delivery prerequisite is still# permanently broken — otherwise the next delivery would just auto-disable@@ -579,6 +604,25 @@ class SubscriptionSerializer(serializers.ModelSerializer):)if integration.kind != "slack":raise ValidationError({"integration_id": ["Slack subscriptions require a Slack integration."]})+ if effective_delivery_config.get("post_all_insights_in_main_message") and SlackIntegration(+ integration+ ).missing_scopes({"files:write"}):+ raise ValidationError(+ {+ "delivery_config": [+ "Posting all insights in the main message requires the Slack files:write permission. "+ "Reconnect Slack to grant it."+ ]+ }+ )++ if (+ effective_delivery_config.get("post_all_insights_in_main_message")+ and target_type != Subscription.SubscriptionTarget.SLACK+ ):+ raise ValidationError(+ {"delivery_config": ["post_all_insights_in_main_message is only supported for Slack subscriptions."]}+ )# Only gate non-empty writes to `summary_prompt_guide`. Clearing (empty string)# and field-absent PATCHes always pass through so users aren't stuck with a valuediff --git a/ee/api/test/test_subscription.py b/ee/api/test/test_subscription.pyindex 1b3427ec1b4e..b6e9c9e3b2cb 100644--- a/ee/api/test/test_subscription.py+++ b/ee/api/test/test_subscription.py@@ -143,6 +143,7 @@ class TestSubscriptionTemporal(APILicensedTest):"next_delivery_date": data["next_delivery_date"],"integration_id": None,"invite_message": None,+ "delivery_config": {"post_all_insights_in_main_message": False},"summary": "sent every week","summary_enabled": False,"summary_prompt_guide": "",@@ -697,6 +698,138 @@ class TestSubscriptionTemporal(APILicensedTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert "does not belong to your team" in response.json()["detail"]+ def test_can_create_slack_subscription_with_delivery_config(self):+ integration = Integration.objects.create(+ team=self.team, kind="slack", config={"scope": "chat:write,files:write"}+ )+ response = self._create_subscription(+ target_type="slack",+ target_value="C1234|#general",+ integration_id=integration.id,+ delivery_config={"post_all_insights_in_main_message": True},+ )+ assert response.status_code == status.HTTP_201_CREATED+ assert response.json()["delivery_config"] == {"post_all_insights_in_main_message": True}+ subscription = Subscription.objects.get(id=response.json()["id"])+ assert subscription.delivery_config == {"post_all_insights_in_main_message": True}++ def test_cannot_set_post_all_insights_in_main_message_on_email_subscription(self):+ response = self._create_subscription(delivery_config={"post_all_insights_in_main_message": True})+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "only supported for Slack subscriptions" in response.json()["detail"]++ def test_can_patch_delivery_config_on_slack_subscription(self):+ integration = Integration.objects.create(+ team=self.team, kind="slack", config={"scope": "chat:write,files:write"}+ )+ subscription_id = self._create_subscription(+ target_type="slack",+ target_value="C1234|#general",+ integration_id=integration.id,+ ).json()["id"]+ response = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription_id}",+ {"delivery_config": {"post_all_insights_in_main_message": True}},+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["delivery_config"] == {"post_all_insights_in_main_message": True}++ def test_post_all_in_main_requires_files_write_scope(self):+ integration = Integration.objects.create(+ team=self.team, kind="slack", config={"scope": "chat:write,channels:read"}+ )+ res = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions/",+ {+ "target_type": "slack",+ "target_value": "C1|#x",+ "integration_id": integration.id,+ "frequency": "weekly",+ "interval": 1,+ "insight": self.insight.id,+ "start_date": "2026-01-01T00:00:00Z",+ "delivery_config": {"post_all_insights_in_main_message": True},+ },+ )+ assert res.status_code == status.HTTP_400_BAD_REQUEST+ assert "files:write" in str(res.json())++ def test_patch_post_all_in_main_requires_files_write_scope(self):+ integration = Integration.objects.create(+ team=self.team, kind="slack", config={"scope": "chat:write,channels:read"}+ )+ subscription_id = self._create_subscription(+ target_type="slack",+ target_value="C1234|#general",+ integration_id=integration.id,+ ).json()["id"]+ res = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription_id}",+ {"delivery_config": {"post_all_insights_in_main_message": True}},+ )+ assert res.status_code == status.HTTP_400_BAD_REQUEST+ assert "files:write" in str(res.json())++ def test_patch_to_integration_without_files_write_rejects_persisted_gallery_flag(self):+ # Effective-config validation: moving an existing post_all_insights_in_main_message sub to an+ # integration lacking files:write must be rejected even when the PATCH omits delivery_config.+ with_scope = Integration.objects.create(+ team=self.team, kind="slack", config={"scope": "chat:write,files:write"}+ )+ without_scope = Integration.objects.create(+ team=self.team, kind="slack", config={"scope": "chat:write,channels:read"}+ )+ subscription_id = self._create_subscription(+ target_type="slack",+ target_value="C1234|#general",+ integration_id=with_scope.id,+ delivery_config={"post_all_insights_in_main_message": True},+ ).json()["id"]+ res = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription_id}",+ {"integration_id": without_scope.id},+ )+ assert res.status_code == status.HTTP_400_BAD_REQUEST+ assert "files:write" in str(res.json())++ def test_patch_slack_to_email_rejects_persisted_gallery_flag(self):+ # Effective-config validation across target_type: a Slack sub with the gallery flag PATCHed to+ # email without resubmitting delivery_config must be rejected, not silently saved as email+flag.+ integration = Integration.objects.create(+ team=self.team, kind="slack", config={"scope": "chat:write,files:write"}+ )+ subscription_id = self._create_subscription(+ target_type="slack",+ target_value="C1234|#general",+ integration_id=integration.id,+ delivery_config={"post_all_insights_in_main_message": True},+ ).json()["id"]+ res = self.client.patch(+ f"/api/projects/{self.team.id}/subscriptions/{subscription_id}",+ {"target_type": "email", "target_value": "[email protected]"},+ )+ assert res.status_code == status.HTTP_400_BAD_REQUEST+ assert "only supported for Slack" in str(res.json())++ def test_post_all_in_main_allowed_with_files_write(self):+ integration = Integration.objects.create(+ team=self.team, kind="slack", config={"scope": "chat:write,files:write"}+ )+ res = self.client.post(+ f"/api/projects/{self.team.id}/subscriptions/",+ {+ "target_type": "slack",+ "target_value": "C1|#x",+ "integration_id": integration.id,+ "frequency": "weekly",+ "interval": 1,+ "insight": self.insight.id,+ "start_date": "2026-01-01T00:00:00Z",+ "delivery_config": {"post_all_insights_in_main_message": True},+ },+ )+ assert res.status_code == status.HTTP_201_CREATED+def test_cannot_create_slack_subscription_with_non_slack_integration(self):integration = Integration.objects.create(team=self.team, kind="hubspot", config={})diff --git a/ee/tasks/subscriptions/__init__.py b/ee/tasks/subscriptions/__init__.pyindex dbf7965fa2d5..082926a67df0 100644--- a/ee/tasks/subscriptions/__init__.py+++ b/ee/tasks/subscriptions/__init__.py@@ -15,9 +15,20 @@ if TYPE_CHECKING:logger = structlog.get_logger(__name__)# Slack errors that won't self-heal without user action — skip Temporal retries-# and auto-disable the subscription so it stops re-firing every cycle.+# and auto-disable the subscription so it stops re-firing every cycle. Includes scope+# revocation (`missing_scope`, `not_allowed_token_type`), e.g. when `files:write` is revoked+# between save and delivery: auto-disable and notify the creator rather than silently degrade.SLACK_USER_CONFIG_ERRORS = frozenset(- {"not_in_channel", "account_inactive", "is_archived", "channel_not_found", "invalid_auth", "token_revoked"}+ {+ "not_in_channel",+ "account_inactive",+ "is_archived",+ "channel_not_found",+ "invalid_auth",+ "token_revoked",+ "missing_scope",+ "not_allowed_token_type",+ })diff --git a/ee/tasks/subscriptions/auto_disable.py b/ee/tasks/subscriptions/auto_disable.pyindex 221c0e7d660e..55b8607a23c6 100644--- a/ee/tasks/subscriptions/auto_disable.py+++ b/ee/tasks/subscriptions/auto_disable.py@@ -45,6 +45,14 @@ 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.",)+SLACK_FILE_UPLOAD_PERMISSION_REVOKED_DISABLE_REASON = DisableReason(+ key="slack_file_upload_permission_revoked",+ description="PostHog can no longer upload files to Slack",+ user_message=(+ "Cannot re-enable {target_type} subscription: the Slack app needs the files:write permission. "+ "Add files:write to a custom Slack app, or reconnect PostHog's Slack app, then try again."+ ),+)AI_PROMPT_INVALID_DISABLE_REASON = DisableReason(key="ai_prompt_invalid",description="AI subscription prompt or creator is invalid",diff --git a/ee/tasks/subscriptions/slack_subscriptions.py b/ee/tasks/subscriptions/slack_subscriptions.pyindex 26ac6fddcc22..7ac25ed18034 100644--- a/ee/tasks/subscriptions/slack_subscriptions.py+++ b/ee/tasks/subscriptions/slack_subscriptions.py@@ -8,13 +8,15 @@ import aiohttpimport structlogfrom slack_sdk.errors import SlackApiError-from posthog.helpers.slack_subscription_explore import build_explore_hint+from posthog.dataclasses import frozen+from posthog.helpers.slack_subscription_explore import build_explore_hint, build_explore_hint_textfrom posthog.models.integration import Integration, SlackIntegration+from posthog.storage import object_storagefrom posthog.sync import database_sync_to_asyncfrom posthog.utils import absolute_urifrom products.exports.backend.models.exported_asset import ExportedAsset-from products.exports.backend.models.subscription import Subscription+from products.exports.backend.models.subscription import Subscription, SubscriptionResourcefrom ee.tasks.subscriptions.subscription_utils import (ASSET_GENERATION_FAILED_MESSAGE,@@ -49,6 +51,8 @@ _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@@ -81,6 +85,114 @@ class SlackDeliveryResult:return self.main_message_sent and len(self.failed_thread_message_indices) == 0+@frozen+class SlackGallery:+ channel: str+ initial_comment: str+ file_uploads: list[dict[str, Any]] = field(default_factory=list)+++def _asset_image_bytes(asset: ExportedAsset) -> bytes | None:+ if asset.content:+ return bytes(asset.content)+ if asset.content_location:+ return object_storage.read_bytes(asset.content_location, missing_ok=True)+ return None+++def _insight_name(asset: ExportedAsset) -> str:+ return ((asset.insight.name or asset.insight.derived_name) if asset.insight else "Insight") or "Insight"+++def _subscription_title(+ subscription: Subscription, resource_info: SubscriptionResource, is_new_subscription: bool+) -> str:+ if subscription.title:+ display_name = f"*{subscription.title}* ({resource_info.kind}: {resource_info.name})"+ else:+ display_name = f"the {resource_info.kind} *{resource_info.name}*"++ if is_new_subscription:+ 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)}"+ )+ return f"Your subscription to {display_name} is ready! 🎉"+++def _ai_summary_text(change_summary: str) -> str:+ summary_text = f"*AI summary:*\n{change_summary}"+ return summary_text[:2997] + "..." if len(summary_text) > 3000 else summary_text+++def _overflow_text(shown_count: int, total_asset_count: int, resource_url: str, utm_tags: str) -> str:+ return (+ f"Showing {shown_count} of {total_asset_count} Insights. <{resource_url}?{utm_tags}|View the rest in PostHog>"+ )+++def _prepare_slack_gallery(+ 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,+ integration: Integration | None = None,+) -> SlackGallery:+ utm_tags = f"{UTM_TAGS_BASE}&utm_medium=slack"+ resource_info = subscription.resource_info+ if not resource_info:+ raise NotImplementedError("This type of subscription resource is not supported")++ lines = [_subscription_title(subscription, resource_info, is_new_subscription)]+ if change_summary:+ lines.append(_ai_summary_text(change_summary))+ elif summary_skipped_over_budget:+ billing_url = f"{absolute_uri('/organization/billing')}?{utm_tags}"+ lines.append(summary_skipped_over_budget_message(billing_url))++ file_uploads: list[dict[str, Any]] = []+ failed_names: list[str] = []+ for asset in assets:+ if _has_asset_failed(asset):+ failed_names.append(_insight_name(asset))+ continue+ content = _asset_image_bytes(asset)+ if content is None:+ failed_names.append(_insight_name(asset))+ continue+ if len(content) > MAX_SLACK_UPLOAD_BYTES:+ logger.warning(+ "deliver_slack_gallery.asset_too_large",+ subscription_id=subscription.id,+ filename=asset.filename,+ size_bytes=len(content),+ )+ failed_names.append(_insight_name(asset))+ continue+ file_uploads.append({"content": content, "filename": asset.filename, "title": _insight_name(asset)})++ if failed_names:+ lines.append("_Could not generate: " + ", ".join(failed_names) + "_")+ if total_asset_count > len(assets):+ lines.append(_overflow_text(len(assets), total_asset_count, resource_info.url, utm_tags))+ lines.append(+ f"<{resource_info.url}?{utm_tags}|View in PostHog> · <{subscription.url}?{utm_tags}|Manage subscription>"+ )++ ai_enabled = bool(integration and integration.team.organization.is_ai_data_processing_approved)+ if explore_hint := build_explore_hint_text(integration, utm_tags=utm_tags, ai_enabled=ai_enabled):+ lines.append(explore_hint)++ return SlackGallery(+ channel=subscription.target_value.split("|")[0],+ initial_comment="\n\n".join(lines),+ file_uploads=file_uploads,+ )++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"@@ -112,7 +224,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://source.unsplash.com/random"+ image_url = "https://posthog.com/icons/icon-512x512.png"return {"type": "image", "image_url": image_url, "alt_text": alt_text}@@ -158,29 +270,14 @@ def _prepare_slack_message(channel = subscription.target_value.split("|")[0]first_asset, *other_assets = assets- if subscription.title:- display_name = f"*{subscription.title}* ({resource_info.kind}: {resource_info.name})"- else:- display_name = f"the {resource_info.kind} *{resource_info.name}*"-- if is_new_subscription:- title = f"This channel has been subscribed to {display_name} on PostHog! 🎉"- title += (- f"\nThis 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! 🎉"+ title = _subscription_title(subscription, resource_info, is_new_subscription)blocks: list[dict] = [{"type": "section", "text": {"type": "mrkdwn", "text": title}},]if change_summary:- summary_text = f"*AI summary:*\n{change_summary}"- if len(summary_text) > 3000:- summary_text = summary_text[:2997] + "..."- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": summary_text}})+ 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(@@ -236,7 +333,7 @@ def _prepare_slack_message("type": "section","text": {"type": "mrkdwn",- "text": f"Showing {len(assets)} of {total_asset_count} Insights. <{resource_info.url}?{utm_tags}|View the rest in PostHog>",+ "text": _overflow_text(len(assets), total_asset_count, resource_info.url, utm_tags),},}]@@ -381,6 +478,49 @@ async def deliver_slack_message_data()+async def deliver_slack_gallery(+ integration: Integration, subscription: Subscription, gallery: SlackGallery+) -> SlackDeliveryResult:+ slack_integration = SlackIntegration(integration)+ async with aiohttp.ClientSession(trust_env=True) as slack_session:+ async_client = slack_integration.async_client(session=slack_session)+ if not gallery.file_uploads:+ await _send_slack_message_with_retry(+ async_client,+ channel=gallery.channel,+ text=gallery.initial_comment,+ unfurl_links=False,+ unfurl_media=False,+ )+ return SlackDeliveryResult(+ main_message_sent=True,+ total_thread_messages=0,+ failed_thread_message_indices=[],+ )++ for attempt in range(3):+ try:+ await async_client.files_upload_v2(+ channel=gallery.channel,+ initial_comment=gallery.initial_comment,+ file_uploads=gallery.file_uploads,+ )+ break+ except (TimeoutError, SlackApiError) as error:+ if isinstance(error, SlackApiError) and error.response.get("error", "") not in _RETRYABLE_SLACK_ERRORS:+ raise+ if attempt >= 2:+ raise+ await asyncio.sleep(2**attempt)++ logger.info(+ "deliver_slack_gallery.uploaded",+ subscription_id=subscription.id,+ file_count=len(gallery.file_uploads),+ )+ return SlackDeliveryResult(main_message_sent=True, total_thread_messages=0, failed_thread_message_indices=[])++async def send_slack_message_with_integration_async(integration: Integration,subscription: Subscription,@@ -390,6 +530,18 @@ async def send_slack_message_with_integration_async(change_summary: str | None = None,summary_skipped_over_budget: bool = False,) -> SlackDeliveryResult:+ if subscription.delivery_config.get("post_all_insights_in_main_message"):+ gallery = await database_sync_to_async(_prepare_slack_gallery, thread_sensitive=False)(+ subscription,+ assets,+ total_asset_count,+ is_new_subscription,+ change_summary=change_summary,+ summary_skipped_over_budget=summary_skipped_over_budget,+ integration=integration,+ )+ return await deliver_slack_gallery(integration, subscription, gallery)+# `_prepare_slack_message` reads lazily-loaded ORM relations (e.g. `integration.team.organization`),# which Django forbids on the event loop. Build it in a thread before the async Slack send.message_data = await database_sync_to_async(_prepare_slack_message, thread_sensitive=False)(diff --git a/ee/tasks/test/subscriptions/test_slack_subscriptions.py b/ee/tasks/test/subscriptions/test_slack_subscriptions.pyindex 9b6044d2ce44..3a8f904414c9 100644--- a/ee/tasks/test/subscriptions/test_slack_subscriptions.py+++ b/ee/tasks/test/subscriptions/test_slack_subscriptions.py@@ -18,9 +18,14 @@ from products.exports.backend.models.exported_asset import ExportedAssetfrom products.exports.backend.models.subscription import Subscriptionfrom products.product_analytics.backend.facade.models import Insight+from ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORSfrom ee.tasks.subscriptions.slack_subscriptions import (+ MAX_SLACK_UPLOAD_BYTES,+ SlackGallery,_block_for_asset,+ _prepare_slack_gallery,_prepare_slack_message,+ deliver_slack_gallery,send_slack_message_with_integration_async,send_slack_subscription_report,)@@ -620,6 +625,72 @@ class TestSlackSubscriptionsAsyncTasks(APIBaseTest):assert mock_async_client.chat_postMessage.call_count == 1mock_sleep.assert_not_awaited()+ def test_deliver_slack_gallery_uploads_files(self, MockSlackIntegration: MagicMock) -> None:+ mock_async = self._setup_async_mock(MockSlackIntegration)+ mock_async.files_upload_v2 = AsyncMock(return_value={"ok": True, "files": [{"id": "F1"}]})+ gallery = SlackGallery(+ channel="C1",+ initial_comment="hi",+ file_uploads=[{"content": b"x", "filename": "a.png", "title": "A"}],+ )+ result = asyncio.run(deliver_slack_gallery(self.integration, self.subscription, gallery))+ mock_async.files_upload_v2.assert_awaited_once()+ kwargs = mock_async.files_upload_v2.await_args.kwargs+ assert kwargs["channel"] == "C1"+ assert kwargs["initial_comment"] == "hi"+ assert kwargs["file_uploads"] == gallery.file_uploads+ assert result.main_message_sent is True++ @patch("ee.tasks.subscriptions.slack_subscriptions.asyncio.sleep", new_callable=AsyncMock)+ def test_deliver_slack_gallery_retries_timeout(+ self, mock_sleep: AsyncMock, MockSlackIntegration: MagicMock+ ) -> None:+ mock_async = self._setup_async_mock(MockSlackIntegration)+ mock_async.files_upload_v2 = AsyncMock(side_effect=[TimeoutError(), {"ok": True, "files": [{"id": "F1"}]}])+ gallery = SlackGallery(+ channel="C1",+ initial_comment="hi",+ file_uploads=[{"content": b"x", "filename": "a.png", "title": "A"}],+ )+ result = asyncio.run(deliver_slack_gallery(self.integration, self.subscription, gallery))+ assert mock_async.files_upload_v2.await_count == 2+ mock_sleep.assert_awaited_once_with(1)+ assert result.main_message_sent is True++ def test_deliver_slack_gallery_empty_uploads_sends_plain_message(self, MockSlackIntegration: MagicMock) -> None:+ mock_async = self._setup_async_mock(MockSlackIntegration)+ mock_async.files_upload_v2 = AsyncMock()+ mock_async.chat_postMessage.return_value = {"ts": "1.234"}++ gallery = SlackGallery(channel="C1", initial_comment="hi", file_uploads=[])+ result = asyncio.run(deliver_slack_gallery(self.integration, self.subscription, gallery))++ mock_async.files_upload_v2.assert_not_awaited()+ mock_async.chat_postMessage.assert_awaited_once()+ call_kwargs = mock_async.chat_postMessage.await_args.kwargs+ assert call_kwargs["channel"] == "C1"+ assert call_kwargs["text"] == "hi"+ assert result.main_message_sent is True++ def test_async_send_routes_to_gallery_when_flag_set(self, MockSlackIntegration: MagicMock) -> None:+ mock_async = self._setup_async_mock(MockSlackIntegration)+ mock_async.files_upload_v2 = AsyncMock(return_value={"ok": True})+ self.subscription.delivery_config = {"post_all_insights_in_main_message": True}+ self.subscription.save()+ # Use inline content so _asset_image_bytes doesn't hit object storage in the test.+ asset_with_content = ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ content=b"PNGBYTES",+ )+ assets = list(ExportedAsset.objects.filter(id=asset_with_content.id).select_related("insight"))+ asyncio.run(+ send_slack_message_with_integration_async(self.integration, self.subscription, assets, total_asset_count=1)+ )+ mock_async.files_upload_v2.assert_awaited_once()+ mock_async.chat_postMessage.assert_not_called()+class TestSlackErrorTruncation(APIBaseTest):def setUp(self) -> None:@@ -731,6 +802,169 @@ class TestSlackSummaryNotice(APIBaseTest):assert all("AI summary skipped" not in text for text in texts)+class TestSlackPostAllInMainMessage(APIBaseTest):+ def setUp(self) -> None:+ self.insight = Insight.objects.create(team=self.team, short_id="123456", name="My Test subscription")+ self.insight2 = Insight.objects.create(team=self.team, short_id="654321", name="Second insight")++ def _subscription(self, post_all_in_main: bool) -> Subscription:+ return create_subscription(+ team=self.team,+ insight=self.insight,+ created_by=self.user,+ target_type="slack",+ target_value="C123|#test",+ delivery_config={"post_all_insights_in_main_message": post_all_in_main},+ )++ def test_prepare_slack_gallery_builds_comment_and_uploads(self) -> None:+ subscription = create_subscription(+ team=self.team,+ created_by=self.user,+ target_type="slack",+ target_value="C123|#test",+ insight=self.insight,+ delivery_config={"post_all_insights_in_main_message": True},+ )+ ok = ExportedAsset.objects.create(+ team=self.team, export_format="image/png", content=b"PNGBYTES", insight_id=self.insight.id+ )+ failed = ExportedAsset.objects.create(+ team=self.team, export_format="image/png", exception="boom", insight_id=self.insight2.id+ )+ gallery = _prepare_slack_gallery(subscription, [ok, failed], total_asset_count=2)+ assert gallery.channel == "C123"+ assert len(gallery.file_uploads) == 1 # failed asset excluded+ assert gallery.file_uploads[0]["content"] == b"PNGBYTES"+ assert "View in PostHog" in gallery.initial_comment+ # Failed assets are listed by name with a "Could not generate" notice+ assert "Could not generate" in gallery.initial_comment+ assert "Second insight" in gallery.initial_comment++ def test_prepare_slack_gallery_includes_overflow_note_in_comment(self) -> None:+ subscription = self._subscription(post_all_in_main=True)+ assets = [+ ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ content=b"PNG",+ )+ for _ in range(3)+ ]+ gallery = _prepare_slack_gallery(subscription, assets, total_asset_count=5)+ assert "Showing 3 of 5 Insights" in gallery.initial_comment++ def test_prepare_slack_gallery_no_uploads_when_all_failed(self) -> None:+ subscription = self._subscription(post_all_in_main=True)+ failed = ExportedAsset.objects.create(+ team=self.team, export_format="image/png", exception="err", insight_id=self.insight.id+ )+ gallery = _prepare_slack_gallery(subscription, [failed], total_asset_count=1)+ assert gallery.file_uploads == []+ assert "Could not generate" in gallery.initial_comment++ def test_prepare_slack_gallery_content_location_returns_bytes(self) -> None:+ subscription = self._subscription(post_all_in_main=True)+ asset = ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ content_location="s3://bucket/from-storage.png",+ )+ assets = list(ExportedAsset.objects.filter(id=asset.id).select_related("insight"))+ with patch(+ "ee.tasks.subscriptions.slack_subscriptions.object_storage.read_bytes",+ return_value=b"STORAGEBYTES",+ ):+ gallery = _prepare_slack_gallery(subscription, assets, total_asset_count=1)+ assert len(gallery.file_uploads) == 1+ assert gallery.file_uploads[0]["content"] == b"STORAGEBYTES"++ def test_prepare_slack_gallery_content_location_read_bytes_none_excludes_asset(self) -> None:+ subscription = self._subscription(post_all_in_main=True)+ asset = ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ content_location="s3://bucket/missing.png",+ )+ assets = list(ExportedAsset.objects.filter(id=asset.id).select_related("insight"))+ with patch(+ "ee.tasks.subscriptions.slack_subscriptions.object_storage.read_bytes",+ return_value=None,+ ):+ gallery = _prepare_slack_gallery(subscription, assets, total_asset_count=1)+ assert gallery.file_uploads == []+ assert "Could not generate" in gallery.initial_comment++ def test_prepare_slack_gallery_skips_oversized_asset(self) -> None:+ subscription = self._subscription(post_all_in_main=True)+ oversized = ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ content=b"x" * (MAX_SLACK_UPLOAD_BYTES + 1),+ )+ assets = list(ExportedAsset.objects.filter(id=oversized.id).select_related("insight"))+ gallery = _prepare_slack_gallery(subscription, assets, total_asset_count=1)+ assert gallery.file_uploads == []+ assert "Could not generate" in gallery.initial_comment+ assert "My Test subscription" in gallery.initial_comment++ def _make_integration(self, ai_enabled: bool) -> Integration:+ org = self.team.organization+ org.is_ai_data_processing_approved = ai_enabled+ org.save()+ return Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T12345",+ config={"scope": ",".join(sorted(REQUIRED_SLACK_SCOPES))},+ sensitive_config={"access_token": "xoxb-test"},+ )++ @parameterized.expand([("ai_enabled", True, True), ("ai_disabled", False, False)])+ def test_prepare_slack_gallery_explore_hint_in_comment(+ self, _name: str, ai_enabled: bool, expect_hint: bool+ ) -> None:+ subscription = self._subscription(post_all_in_main=True)+ asset = ExportedAsset.objects.create(+ team=self.team, insight_id=self.insight.id, export_format="image/png", content=b"PNG"+ )+ assets = list(ExportedAsset.objects.filter(id=asset.id).select_related("insight"))+ gallery = _prepare_slack_gallery(+ subscription, assets, total_asset_count=1, integration=self._make_integration(ai_enabled)+ )+ assert ("@PostHog" in gallery.initial_comment) is expect_hint++ def test_prepare_slack_gallery_no_explore_hint_without_integration(self) -> None:+ subscription = self._subscription(post_all_in_main=True)+ asset = ExportedAsset.objects.create(+ team=self.team, insight_id=self.insight.id, export_format="image/png", content=b"PNG"+ )+ assets = list(ExportedAsset.objects.filter(id=asset.id).select_related("insight"))+ gallery = _prepare_slack_gallery(subscription, assets, total_asset_count=1)+ assert "@PostHog" not in gallery.initial_comment++ def test_default_threaded_keeps_only_first_image_in_main(self) -> None:+ assets = [+ ExportedAsset.objects.create(+ team=self.team,+ insight_id=self.insight.id,+ export_format="image/png",+ content_location=f"s3://bucket/test-{i}.png",+ )+ for i in range(3)+ ]+ message = _prepare_slack_message(+ self._subscription(post_all_in_main=False), assets, total_asset_count=len(assets)+ )+ image_blocks = [block for block in message.blocks if block.get("type") == "image"]+ assert len(image_blocks) == 1+ assert len(message.thread_messages) == len(assets) - 1++class TestSlackExploreHint(APIBaseTest):def setUp(self) -> None:self.insight = Insight.objects.create(team=self.team, short_id="123456", name="My Test subscription")@@ -783,3 +1017,10 @@ class TestSlackExploreHint(APIBaseTest):org.is_ai_data_processing_approved = Falseorg.save()assert self._hint_texts(self._make_integration(REQUIRED_SLACK_SCOPES)) == []++[email protected]("error_code", ["missing_scope", "not_allowed_token_type"])+def test_scope_revocation_errors_auto_disable(error_code: str) -> None:+ # Guards the wiring in delivery_common: errors in this set route to auto_disable_and_return,+ # which disables the subscription and notifies the creator when files:write is revoked.+ assert error_code in SLACK_USER_CONFIG_ERRORSdiff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 68972859591f..c53cf39be833 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -510,6 +510,7 @@ export const FEATURE_FLAGS = {SUBSCRIPTION_AI_PROMPT: 'ai-subscriptions', // owner: #team-analytics-platform, gates AI prompt-based subscriptionsSUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE: 'subscription-ai-summary-prompt-guide', // owner: #team-analytics-platform, gates the per-subscription prompt guide textareaSUBSCRIPTION_CREATION_WIZARD: 'subscription-creation-wizard', // owner: #team-analytics-platform, experiment=control,test+ SUBSCRIPTION_SLACK_GALLERY: 'subscription-slack-gallery', // owner: #team-analytics-platform, enables gallery delivery after the worker rollout completesSURVEY_HEADLINE_SUMMARY: 'survey-headline-summary', // owner: @adboio #team-surveysSURVEYS_ERROR_TRACKING_CROSS_SELL: 'surveys-in-error-tracking', // owner: @adboio #team-surveysSURVEYS_FORM_BUILDER: 'surveys-form-builder', // owner: @adboio #team-surveysdiff --git a/frontend/src/lib/integrations/IntegrationScopesWarning.tsx b/frontend/src/lib/integrations/IntegrationScopesWarning.tsxindex b1cc22d5b298..2b669a9234a9 100644--- a/frontend/src/lib/integrations/IntegrationScopesWarning.tsx+++ b/frontend/src/lib/integrations/IntegrationScopesWarning.tsx@@ -2,14 +2,14 @@ import { useActions } from 'kea'import { useMemo } from 'react'import api from 'lib/api'-import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'-import { TeamMembershipLevel } from 'lib/constants'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'import { Link } from 'lib/lemon-ui/Link'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { IntegrationType } from '~/types'+import { useIntegrationManagementRestriction } from './integrationPermissions'+/*** Extract the granted OAuth scopes from an integration's stored config. Tolerates the* various shapes different providers persist: ``config.scope`` vs ``config.scopes``,@@ -54,10 +54,7 @@ export function IntegrationScopesWarning({schema?: { requiredScopes?: string }}): JSX.Element {const { reportIntegrationConnectClicked } = useActions(eventUsageLogic)- const restrictedReason = useRestrictedArea({- scope: RestrictionScope.Project,- minimumAccessLevel: TeamMembershipLevel.Admin,- })+ const restrictedReason = useIntegrationManagementRestriction()const grantedScopes = useMemo(() => getGrantedScopes(integration), [integration.config, integration])const requiredScopes = schema?.requiredScopes?.split(' ') || []const missingScopes = requiredScopes.filter((scope) => !grantedScopes.includes(scope))diff --git a/frontend/src/lib/integrations/integrationPermissions.ts b/frontend/src/lib/integrations/integrationPermissions.tsnew file mode 100644index 000000000000..a162a6a0a5ed--- /dev/null+++ b/frontend/src/lib/integrations/integrationPermissions.ts@@ -0,0 +1,14 @@+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'++// Single source of truth for "can the current user connect/reconnect integrations" on the frontend.+// Mirrors the backend IntegrationViewSet permission (TeamMemberStrictManagementPermission, which+// requires project-admin for writes). Returns a disabledReason string when the user lacks access,+// else null — wire it into the disabledReason of any connect/reconnect affordance so every+// integration gate stays in sync with the backend and with each other.+export function useIntegrationManagementRestriction(): string | null {+ return useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })+}diff --git a/frontend/src/lib/integrations/integrationsLogic.ts b/frontend/src/lib/integrations/integrationsLogic.tsindex 5960260b0ef6..7e3e4c322b0d 100644--- a/frontend/src/lib/integrations/integrationsLogic.ts+++ b/frontend/src/lib/integrations/integrationsLogic.ts@@ -254,6 +254,7 @@ export interface integrationsLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -310,6 +311,7 @@ export interface integrationsLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -383,6 +385,7 @@ export interface integrationsLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -443,6 +446,7 @@ export interface integrationsLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefineddiff --git a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.tsindex c73c0579bd08..b0dcec5510e0 100644--- a/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts+++ b/frontend/src/scenes/settings/organization/organizationIntegrationsLogic.ts@@ -84,6 +84,7 @@ export interface organizationIntegrationsLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -140,6 +141,7 @@ export interface organizationIntegrationsLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefineddiff --git a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts b/frontend/src/scenes/settings/user/personalIntegrationsLogic.tsindex 24726d1c1c1b..a5d8b29b3341 100644--- a/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts+++ b/frontend/src/scenes/settings/user/personalIntegrationsLogic.ts@@ -121,6 +121,7 @@ export interface personalIntegrationsLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -180,6 +181,7 @@ export interface personalIntegrationsLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefineddiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex b61ab1dc4267..c790a887521a 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -90,7 +90,7 @@ import type { ExperimentFeatureFlagInputApi } from 'products/experiments/frontenimport type { IntegrationConfigApi } from 'products/integrations/frontend/generated/api.schemas'import type { CommentSlackThreadRefApi } from 'products/platform_features/frontend/generated/api.schemas'import type { InsightFilterOverrideContextApi } from 'products/product_analytics/frontend/generated/api.schemas'-import type { AIPromptConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'+import type { AIPromptConfigApi, DeliveryConfigApi } from 'products/subscriptions/frontend/generated/api.schemas'import type { RuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'import { CyclotronInputType } from 'products/workflows/frontend/Workflows/hogflows/steps/types'import type { HogFlow } from 'products/workflows/frontend/Workflows/hogflows/types'@@ -5526,6 +5526,7 @@ export interface SubscriptionType {integration_id?: number | nullprompt?: string | nullai_prompt_config?: AIPromptConfigApi | null+ delivery_config?: DeliveryConfigApitarget_type: stringtarget_value: stringfrequency: 'daily' | 'weekly' | 'monthly' | 'yearly'@@ -5663,6 +5664,7 @@ export interface IntegrationType {created_by?: UserBasicType | nullcreated_at: stringerrors?: string+ files_write_requestable?: IntegrationConfigApi['files_write_requestable']/** GitHub only. When false, disconnecting also uninstalls the App from GitHub. */installation_shared?: IntegrationConfigApi['installation_shared']/** GitHub only. `unavailable` once the App was removed or suspended on GitHub. */diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex f7487759ef97..632061b246e0 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -61,6 +61,7 @@ from posthog.models.integration import (POSTHOG_CONNECT_DEFAULT_SCOPES,POSTHOG_CONNECT_GRANTABLE_SCOPES,POSTHOG_CONNECT_KIND,+ POSTHOG_SLACK_SCOPE,SLACK_INTEGRATION_KINDS,AnthropicIntegration,ApplePushIntegration,@@ -552,6 +553,9 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial"""Standard Integration serializer."""created_by = UserBasicSerializer(read_only=True)+ files_write_requestable = serializers.SerializerMethodField(+ help_text="Slack only: whether reconnecting can request the files:write scope."+ )installation_shared = serializers.SerializerMethodField(help_text=("GitHub only, null otherwise. Whether another project's GitHub integration references the same "@@ -576,6 +580,7 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial"created_by","errors","display_name",+ "files_write_requestable","installation_shared","installation_status",]@@ -585,10 +590,15 @@ class IntegrationSerializer(serializers.ModelSerializer, UserAccessControlSerial"created_by","errors","display_name",+ "files_write_requestable","installation_shared","installation_status",]+ @extend_schema_field(serializers.BooleanField())+ def get_files_write_requestable(self, obj: Integration) -> bool:+ return obj.kind == "slack" and "files:write" in POSTHOG_SLACK_SCOPE.split(",")+@extend_schema_field(serializers.BooleanField(allow_null=True))def get_installation_shared(self, obj: Integration) -> bool | None:if obj.kind != "github" or not obj.integration_id:diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.pyindex 9c48defb7d87..eb60748f272d 100644--- a/posthog/api/test/test_integration.py+++ b/posthog/api/test/test_integration.py@@ -6703,3 +6703,31 @@ class TestPosthogConnectionListScoping:def test_creator_still_sees_their_connection(self, client: HttpClient):client.force_login(self.owner)assert self.connection.id in self._list_ids(client)+++class TestIntegrationSerializerFilesWriteRequestable(APIBaseTest):+ @parameterized.expand(+ [+ ("slack_requests_files_write", "slack", "chat:write,files:write", True),+ ("slack_does_not_request_files_write", "slack", "chat:write", False),+ ("non_slack_is_never_requestable", "github", "chat:write,files:write", False),+ ]+ )+ def test_files_write_requestable(self, _name, kind, requested_scope, expected):+ config = {"team": {"name": "Test Workspace"}} if kind == "slack" else {"installation_id": "12345"}+ integration = Integration.objects.create(team=self.team, kind=kind, config=config)+ with (+ patch(+ "posthog.models.integration.oauth.get_instance_settings",+ return_value={+ "SLACK_APP_CLIENT_ID": "test-client-id",+ "SLACK_APP_CLIENT_SECRET": "test-client-secret",+ "SLACK_APP_SIGNING_SECRET": "test-signing-secret",+ },+ ),+ patch("posthog.api.integration.POSTHOG_SLACK_SCOPE", requested_scope),+ ):+ response = self.client.get(f"/api/environments/{self.team.id}/integrations/{integration.id}/")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["files_write_requestable"] is expecteddiff --git a/posthog/constants.py b/posthog/constants.pyindex 8ee564bd6475..b5377356dfe3 100644--- a/posthog/constants.py+++ b/posthog/constants.py@@ -333,6 +333,9 @@ PRODUCT_TOUR_TARGETING_FLAG_PREFIX = "product-tour-targeting-"# Server-side evaluation via posthoganalytics; keep in sync with frontend FEATURE_FLAGS.SUBSCRIPTION_AI_SUMMARY_PROMPT_GUIDE_FEATURE_FLAG_KEY = "subscription-ai-summary-prompt-guide"SUBSCRIPTION_AI_PROMPT_FEATURE_FLAG_KEY = "ai-subscriptions"+# Enable only after every subscriptions worker has deployed the gallery claim boundary. Older workers+# share the v2 activity name and would otherwise send the legacy layout during a rolling deployment.+SUBSCRIPTION_SLACK_GALLERY_FEATURE_FLAG_KEY = "subscription-slack-gallery"EXPERIMENTS_SYNC_QUERIES_FEATURE_FLAG_KEY = "experiments-sync-queries"EXPERIMENTS_RETENTION_METRIC_EVENTS_PREAGGREGATION_FEATURE_FLAG_KEY = ("experiments-retention-metric-events-preaggregation"diff --git a/posthog/egress/slack/async_client.py b/posthog/egress/slack/async_client.pyindex 54382e21e64f..13dc7558feb9 100644--- a/posthog/egress/slack/async_client.py+++ b/posthog/egress/slack/async_client.py@@ -6,7 +6,11 @@ from slack_sdk.http_retry.response import HttpResponsefrom slack_sdk.http_retry.state import RetryStatefrom slack_sdk.web.async_client import AsyncWebClient-from posthog.egress.slack.observability import record_slack_api_exception, record_slack_api_response+from posthog.egress.slack.observability import (+ record_slack_api_exception,+ record_slack_api_response,+ slack_endpoint_from_url,+)class SlackAsyncObservabilityHandler(AsyncRetryHandler):@@ -24,7 +28,7 @@ class SlackAsyncObservabilityHandler(AsyncRetryHandler):response: HttpResponse | None = None,error: Exception | None = None,) -> bool:- endpoint = request.url.rsplit("/", 1)[-1]+ endpoint = slack_endpoint_from_url(request.url)if response is not None:record_slack_api_response(response,diff --git a/posthog/egress/slack/client.py b/posthog/egress/slack/client.pyindex a7c229f48ef7..e0608776ed0a 100644--- a/posthog/egress/slack/client.py+++ b/posthog/egress/slack/client.py@@ -6,7 +6,11 @@ from slack_sdk.http_retry.request import HttpRequestfrom slack_sdk.http_retry.response import HttpResponsefrom slack_sdk.http_retry.state import RetryState-from posthog.egress.slack.observability import record_slack_api_exception, record_slack_api_response+from posthog.egress.slack.observability import (+ record_slack_api_exception,+ record_slack_api_response,+ slack_endpoint_from_url,+)class SlackObservabilityHandler(RetryHandler):@@ -24,7 +28,7 @@ class SlackObservabilityHandler(RetryHandler):response: HttpResponse | None = None,error: Exception | None = None,) -> bool:- endpoint = request.url.rsplit("/", 1)[-1]+ endpoint = slack_endpoint_from_url(request.url)if response is not None:record_slack_api_response(response,diff --git a/posthog/egress/slack/observability.py b/posthog/egress/slack/observability.pyindex 3dcecfd257b5..5b732ae391d5 100644--- a/posthog/egress/slack/observability.py+++ b/posthog/egress/slack/observability.py@@ -1,6 +1,7 @@import timefrom collections.abc import Mappingfrom typing import cast+from urllib.parse import urlparseimport requestsfrom prometheus_client import Counter, Gauge@@ -57,6 +58,13 @@ slack_egress = EgressObservability(SLACK_DOMAIN, _metrics, _parse_slack_rate_limregister_egress_observability(slack_egress)+def slack_endpoint_from_url(url: str) -> str:+ parsed = urlparse(url)+ if parsed.netloc == "files.slack.com" and parsed.path.startswith("/upload/v1/"):+ return "files.uploadExternal.data"+ return parsed.path.rstrip("/").rsplit("/", 1)[-1] or "unknown"++def record_slack_api_response(response: object,*,diff --git a/posthog/egress/test/test_slack_client.py b/posthog/egress/test/test_slack_client.pyindex 34a7a21a617a..7f1bd4ebc2a5 100644--- a/posthog/egress/test/test_slack_client.py+++ b/posthog/egress/test/test_slack_client.py@@ -1,5 +1,6 @@from typing import Any+import pytestfrom unittest.mock import patchfrom prometheus_client import REGISTRY@@ -8,6 +9,7 @@ from slack_sdk.http_retry.request import HttpRequestfrom slack_sdk.http_retry.response import HttpResponsefrom slack_sdk.http_retry.state import RetryState+from posthog.egress.slack.async_client import SlackAsyncObservabilityHandlerfrom posthog.egress.slack.client import SlackWebClient@@ -66,3 +68,19 @@ def test_slack_web_client_records_each_retry_attempt() -> None:)is not None)+++async def test_async_slack_client_normalizes_external_upload_ticket() -> None:+ handler = SlackAsyncObservabilityHandler(source="test", workspace_id="T123", app_id="posthog")+ request = HttpRequest(+ method="POST",+ url="https://files.slack.com/upload/v1/unique-secret-ticket",+ headers={},+ )+ response = HttpResponse(status_code=200, headers={}, body={})++ with patch("posthog.egress.slack.async_client.record_slack_api_response") as record_response:+ assert await handler.can_retry_async(state=RetryState(), request=request, response=response) is False++ assert record_response.call_args.kwargs["endpoint"] == "files.uploadExternal.data"diff --git a/posthog/helpers/slack_subscription_explore.py b/posthog/helpers/slack_subscription_explore.pyindex 3d3f848e8fc7..3d72d61d11cf 100644--- a/posthog/helpers/slack_subscription_explore.py+++ b/posthog/helpers/slack_subscription_explore.py@@ -9,16 +9,26 @@ from posthog.models.integration import IntegrationBOT_SETUP_DOCS_URL = "https://posthog.com/docs/slack-app"-def build_explore_hint(integration: Integration | None, *, utm_tags: str, ai_enabled: bool) -> dict[str, Any] | None:- """Slack context block nudging the channel to @PostHog this report (or to set the bot up).+def build_explore_hint_text(integration: Integration | None, *, utm_tags: str, ai_enabled: bool) -> str | None:+ """mrkdwn nudging the channel to @PostHog this report (or to set the bot up).Returns ``None`` when there's no Slack install or the org hasn't approved AI data processing —- we don't nudge people toward the AI bot when their org hasn't opted into AI.+ we don't nudge people toward the AI bot when their org hasn't opted into AI. Plain-text variant+ used where Slack only accepts mrkdwn (e.g. a gallery upload's ``initial_comment``)."""if integration is None or not ai_enabled:return Noneif bot_is_ready(integration):- text = "💬 Reply in this thread and mention *@PostHog* with a question to dig into this report."- else:- text = f"💬 <{BOT_SETUP_DOCS_URL}?{utm_tags}|Set up the @PostHog bot> to ask follow-up questions about your reports here."+ return "💬 Reply in this thread and mention *@PostHog* with a question to dig into this report."+ return f"💬 <{BOT_SETUP_DOCS_URL}?{utm_tags}|Set up the @PostHog bot> to ask follow-up questions about your reports here."+++def build_explore_hint(integration: Integration | None, *, utm_tags: str, ai_enabled: bool) -> dict[str, Any] | None:+ """Slack context block nudging the channel to @PostHog this report (or to set the bot up).++ Returns ``None`` in the same cases as ``build_explore_hint_text``.+ """+ text = build_explore_hint_text(integration, utm_tags=utm_tags, ai_enabled=ai_enabled)+ if text is None:+ return Nonereturn {"type": "context", "elements": [{"type": "mrkdwn", "text": text}]}diff --git a/posthog/storage/object_storage.py b/posthog/storage/object_storage.pyindex 0014bee350e3..28853c331aaf 100644--- a/posthog/storage/object_storage.py+++ b/posthog/storage/object_storage.py@@ -31,6 +31,10 @@ class ObjectStorageClient(metaclass=abc.ABCMeta):def head_object(self, bucket: str, file_key: str) -> Optional[dict]:pass+ @abc.abstractmethod+ def head_object_strict(self, bucket: str, file_key: str) -> Optional[dict]:+ pass+@abc.abstractmethoddef get_presigned_url(self,@@ -107,6 +111,9 @@ class UnavailableStorage(ObjectStorageClient):def head_object(self, bucket: str, file_key: str):return None+ def head_object_strict(self, bucket: str, file_key: str) -> Optional[dict]:+ raise ObjectStorageError("object storage is unavailable")+def get_presigned_url(self,bucket: str,@@ -178,6 +185,22 @@ class ObjectStorage(ObjectStorageClient):logger.warn("object_storage.head_object_failed", bucket=bucket, file_key=file_key, error=e)return None+ def head_object_strict(self, bucket: str, file_key: str) -> Optional[dict]:+ try:+ return self.aws_client.head_object(Bucket=bucket, Key=file_key)+ except ClientError as e:+ error_code = e.response.get("Error", {}).get("Code")+ status_code = e.response.get("ResponseMetadata", {}).get("HTTPStatusCode")+ if error_code in {"404", "NoSuchKey", "NotFound"} or status_code == 404:+ return None+ logger.exception("object_storage.head_object_failed", bucket=bucket, file_key=file_key, error=e)+ capture_exception(e)+ raise ObjectStorageError("head_object failed") from e+ except Exception as e:+ logger.exception("object_storage.head_object_failed", bucket=bucket, file_key=file_key, error=e)+ capture_exception(e)+ raise ObjectStorageError("head_object failed") from e+def get_presigned_url(self,bucket: str,@@ -644,5 +667,11 @@ def head_object(file_key: str, bucket: str | None = None) -> Optional[dict]:return object_storage_client().head_object(file_key=file_key, bucket=bucket or settings.OBJECT_STORAGE_BUCKET)+def head_object_strict(file_key: str, bucket: str | None = None) -> Optional[dict]:+ return object_storage_client().head_object_strict(+ file_key=file_key, bucket=bucket or settings.OBJECT_STORAGE_BUCKET+ )++def health_check() -> bool:return object_storage_client().head_bucket(bucket=settings.OBJECT_STORAGE_BUCKET)diff --git a/posthog/storage/test/test_object_storage.py b/posthog/storage/test/test_object_storage.pyindex acb9451410bd..b3bff7072644 100644--- a/posthog/storage/test/test_object_storage.py+++ b/posthog/storage/test/test_object_storage.py@@ -237,6 +237,27 @@ class TestStorage(APIBaseTest):assert len(mock_client.delete_objects.call_args_list[1].kwargs["Delete"]["Objects"]) == 1+class TestObjectStorageStrictHead(SimpleTestCase):+ def test_returns_none_only_for_missing_objects(self) -> None:+ mock_client = MagicMock()+ error_response = {+ "Error": {"Code": "NoSuchKey", "Message": "The specified key does not exist."},+ "ResponseMetadata": {"HTTPStatusCode": 404},+ }+ mock_client.head_object.side_effect = ClientError(error_response, "HeadObject") # type: ignore[arg-type]+ storage = ObjectStorage(mock_client)++ assert storage.head_object_strict("test-bucket", "missing-key") is None++ def test_raises_for_transient_errors(self) -> None:+ mock_client = MagicMock()+ mock_client.head_object.side_effect = TimeoutError("object storage timed out")+ storage = ObjectStorage(mock_client)++ with self.assertRaises(ObjectStorageError):+ storage.head_object_strict("test-bucket", "test-key")++class TestObjectStorageClientFactory(SimpleTestCase):def setUp(self) -> None:object_storage_module._client = UnavailableStorage()diff --git a/products/alerts/frontend/logic/alertNotificationLogic.ts b/products/alerts/frontend/logic/alertNotificationLogic.tsindex f9133e4f4b50..ec91ef21e97c 100644--- a/products/alerts/frontend/logic/alertNotificationLogic.ts+++ b/products/alerts/frontend/logic/alertNotificationLogic.ts@@ -73,6 +73,7 @@ export interface alertNotificationLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -132,6 +133,7 @@ export interface alertNotificationLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefineddiff --git a/products/exports/backend/migrations/0009_subscription_delivery_config.py b/products/exports/backend/migrations/0009_subscription_delivery_config.pynew file mode 100644index 000000000000..4f3c1d497d4f--- /dev/null+++ b/products/exports/backend/migrations/0009_subscription_delivery_config.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("exports", "0008_exportedasset_source_authentication"),+ ]++ operations = [+ migrations.AddField(+ model_name="subscription",+ name="delivery_config",+ field=models.JSONField(default=dict),+ ),+ ]diff --git a/products/exports/backend/migrations/max_migration.txt b/products/exports/backend/migrations/max_migration.txtindex 36df3d5c6719..8eb88bb29936 100644--- a/products/exports/backend/migrations/max_migration.txt+++ b/products/exports/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_exportedasset_source_authentication+0009_subscription_delivery_configdiff --git a/products/exports/backend/models/subscription.py b/products/exports/backend/models/subscription.pyindex 304557693b89..c12800c27d45 100644--- a/products/exports/backend/models/subscription.py+++ b/products/exports/backend/models/subscription.py@@ -210,6 +210,7 @@ class Subscription(ModelActivityMixin, models.Model):summary_enabled = models.BooleanField(default=False)summary_prompt_guide = models.CharField(max_length=500, blank=True, default="")+ delivery_config = models.JSONField(default=dict)class Meta:indexes = [@@ -501,6 +502,7 @@ class Subscription(ModelActivityMixin, models.Model):"bysetpos": self.bysetpos,"prompt_length": len(self.prompt or ""),"ai_window_mode": self.ai_window_mode if self.resource_type == self.ResourceType.AI_PROMPT else None,+ "post_all_insights_in_main_message": self.delivery_config.get("post_all_insights_in_main_message", False),}# For insight subscriptions, attribute the subscribed insight's query type (e.g. TrendsQuery,# FunnelsQuery) using the same keys as the "insight created/updated" events, so subscriptionsdiff --git a/products/exports/backend/temporal/subscriptions/activities.py b/products/exports/backend/temporal/subscriptions/activities.pyindex 54a57cafb7c8..0864cbd7dbae 100644--- a/products/exports/backend/temporal/subscriptions/activities.py+++ b/products/exports/backend/temporal/subscriptions/activities.py@@ -462,7 +462,11 @@ async def _deliver_insight_dashboard_subscription(subscription_id=inputs.subscription_id,target_type=subscription.target_type,)- return await auto_disable_and_return(subscription, UNSUPPORTED_TARGET_DISABLE_REASON, recipient_results)+ return await auto_disable_and_return(+ subscription,+ UNSUPPORTED_TARGET_DISABLE_REASON,+ recipient_results,+ )assets_by_id = await database_sync_to_async(lambda: {diff --git a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.pyindex aacb3fc810ef..9cb6e0df70e0 100644--- a/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py+++ b/products/exports/backend/temporal/subscriptions/ai_subscription/activities.py@@ -237,7 +237,11 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Gen# org that revokes AI-data-processing approval later. Auto-disable so it stops re-firing.if not subscription.team.organization.is_ai_data_processing_approved:LOGGER.warning("generate_ai_subscription_report.consent_revoked", subscription_id=subscription.id)- aborted = await auto_disable_and_return(subscription, AI_CONSENT_REVOKED_DISABLE_REASON, [])+ aborted = await auto_disable_and_return(+ subscription,+ AI_CONSENT_REVOKED_DISABLE_REASON,+ [],+ )return GenerateAIReportResult(aborted=True, recipient_results=aborted.recipient_results, target_type=subscription.target_type)@@ -302,7 +306,11 @@ async def generate_ai_subscription_report(inputs: GenerateAIReportInputs) -> Genhuman_readable_error=str(exc),)]- aborted = await auto_disable_and_return(subscription, AI_PROMPT_INVALID_DISABLE_REASON, recipient_results)+ aborted = await auto_disable_and_return(+ subscription,+ AI_PROMPT_INVALID_DISABLE_REASON,+ recipient_results,+ )return GenerateAIReportResult(aborted=True, recipient_results=aborted.recipient_results, target_type=subscription.target_type)diff --git a/products/exports/backend/temporal/subscriptions/delivery_common.py b/products/exports/backend/temporal/subscriptions/delivery_common.pyindex c99f2d8f41ba..30aa9848f485 100644--- a/products/exports/backend/temporal/subscriptions/delivery_common.py+++ b/products/exports/backend/temporal/subscriptions/delivery_common.py@@ -20,6 +20,7 @@ from products.exports.backend.temporal.subscriptions.types import (from ee.tasks.subscriptions import SLACK_USER_CONFIG_ERRORS, _capture_delivery_failed_eventfrom ee.tasks.subscriptions.auto_disable import (SLACK_DISCONNECTED_DISABLE_REASON,+ SLACK_FILE_UPLOAD_PERMISSION_REVOKED_DISABLE_REASON,SLACK_PERMISSION_REVOKED_DISABLE_REASON,DisableReason,disable_invalid_subscription,@@ -199,7 +200,8 @@ async def deliver_slack(except ApplicationError:raiseexcept Exception as exc:- slack_error_code = exc.response.get("error") if isinstance(exc, SlackApiError) else None+ slack_response = exc.response if isinstance(exc, SlackApiError) else {}+ slack_error_code = slack_response.get("error")_capture_delivery_failed_event(subscription, exc)LOGGER.error("deliver_subscription.slack_failed",@@ -212,9 +214,15 @@ async def deliver_slack(capture_exception(exc)if slack_error_code in SLACK_USER_CONFIG_ERRORS:# Won't self-heal without user action — auto-disable so it stops re-firing.- return await auto_disable_and_return(- subscription, SLACK_PERMISSION_REVOKED_DISABLE_REASON, recipient_results+ needed_scopes = {+ scope.strip() for scope in str(slack_response.get("needed") or "").split(",") if scope.strip()+ }+ reason = (+ SLACK_FILE_UPLOAD_PERMISSION_REVOKED_DISABLE_REASON+ if "files:write" in needed_scopes+ else SLACK_PERMISSION_REVOKED_DISABLE_REASON)+ return await auto_disable_and_return(subscription, reason, recipient_results)raise # Transient Slack errors — let Temporal retryif result.is_complete_success:diff --git a/products/exports/backend/temporal/subscriptions/test_delivery_activities.py b/products/exports/backend/temporal/subscriptions/test_delivery_activities.pyindex 0a238569895c..4da517565cf0 100644--- a/products/exports/backend/temporal/subscriptions/test_delivery_activities.py+++ b/products/exports/backend/temporal/subscriptions/test_delivery_activities.py@@ -1,13 +1,16 @@import uuidimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchfrom asgiref.sync import sync_to_async+from slack_sdk.errors import SlackApiError+from slack_sdk.web.async_slack_response import AsyncSlackResponsefrom temporalio.exceptions import ApplicationErrorfrom temporalio.testing import ActivityEnvironmentfrom posthog.email import EmailDeliveryError+from posthog.models.integration import Integrationfrom posthog.slo.types import SloArea, SloConfig, SloOperationfrom posthog.temporal.exports.activities import export_asset_activityfrom posthog.temporal.exports.types import ExportAssetResult@@ -23,6 +26,7 @@ from products.exports.backend.temporal.subscriptions.activities import (validate_subscription_for_delivery,)from products.exports.backend.temporal.subscriptions.ai_subscription.activities import generate_ai_subscription_report+from products.exports.backend.temporal.subscriptions.delivery_common import deliver_slackfrom products.exports.backend.temporal.subscriptions.snapshot_activities import snapshot_subscription_insightsfrom products.exports.backend.temporal.subscriptions.types import (CreateExportAssetsResult,@@ -44,6 +48,40 @@ from ee.tasks.test.subscriptions.subscriptions_test_factory import create_subscrpytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]+async def test_deliver_slack_explains_missing_file_upload_scope(team, user) -> None:+ integration = await sync_to_async(Integration.objects.create)(team=team, kind="slack", config={})+ subscription = await sync_to_async(create_subscription)(+ team=team,+ created_by=user,+ target_type="slack",+ target_value="C123|#general",+ integration=integration,+ )+ response = AsyncSlackResponse(+ client=None,+ http_verb="POST",+ api_url="https://slack.com/api/files.completeUploadExternal",+ req_args={},+ data={"ok": False, "error": "missing_scope", "needed": "files:write"},+ headers={},+ status_code=200,+ )++ with (+ patch("products.exports.backend.temporal.subscriptions.delivery_common._capture_delivery_failed_event"),+ patch("ee.tasks.subscriptions.auto_disable.create_subscription_auto_disabled_notification"),+ patch("ee.tasks.subscriptions.auto_disable.send_notifications_for_disabled_subscription"),+ ):+ result = await deliver_slack(subscription, [], AsyncMock(side_effect=SlackApiError("Error", response)))++ await sync_to_async(subscription.refresh_from_db)()+ assert subscription.enabled is False+ assert result.recipient_results[0].error == {+ "message": "PostHog can no longer upload files to Slack",+ "type": "slack_file_upload_permission_revoked",+ }++# v1 only exists as a Temporal history-compat shim for pre-patch workflows. Both# entry points must hit the shared delivery + EmailDeliveryError -> non-retryable# ApplicationError mapping, so the delivery record keeps per-recipient results.diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 0c7f72cfc7d1..29778f0c9caf 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -273,6 +273,8 @@ export interface IntegrationConfigApi {readonly created_by: UserBasicApireadonly errors: stringreadonly display_name: string+ /** Slack only: whether reconnecting can request the files:write scope. */+ readonly files_write_requestable: boolean/*** GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.* @nullable@@ -329,6 +331,8 @@ export interface PatchedIntegrationConfigApi {readonly created_by?: UserBasicApireadonly errors?: stringreadonly display_name?: string+ /** Slack only: whether reconnecting can request the files:write scope. */+ readonly files_write_requestable?: boolean/*** GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.* @nullablediff --git a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.tsindex d74b7ff3b354..e4411dd5078e 100644--- a/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts+++ b/products/logs/frontend/components/LogsAlerting/logsAlertNotificationLogic.ts@@ -68,6 +68,7 @@ export interface logsAlertNotificationLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -127,6 +128,7 @@ export interface logsAlertNotificationLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefineddiff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.tsindex a520e9cb1a60..b1d3062359e2 100644--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts@@ -166,6 +166,7 @@ export interface taskTrackerSceneLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -225,6 +226,7 @@ export interface taskTrackerSceneLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefineddiff --git a/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.tsindex aaf8a2093659..99c5f2b06785 100644--- a/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerAlertNotificationLogic.ts@@ -65,6 +65,7 @@ export interface scannerAlertNotificationLogicActions {created_by?: null | import('~/types').UserBasicType | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -124,6 +125,7 @@ export interface scannerAlertNotificationLogicActions {created_by?: null | import('~/types').UserBasicType | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefineddiff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.tsindex 3f4f55ee3e88..0573940fc504 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.test.ts@@ -5,6 +5,7 @@ import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'import { ApiError } from 'lib/api'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { getRecentSlackChannelIds } from 'lib/integrations/slackChannel'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { organizationLogic } from 'scenes/organizationLogic'@@ -12,7 +13,7 @@ import { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { InsightShortId, SubscriptionType } from '~/types'+import { InsightShortId, IntegrationType, SubscriptionType } from '~/types'import { subscriptionLogic } from './subscriptionLogic'@@ -770,4 +771,36 @@ describe('subscriptionLogic', () => {await expectLogic(newLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])expect(capturedBody?.prompt).toBeUndefined()})++ it.each([+ ['removes the gallery flag when files:write is missing', 'chat:write,channels:read', false],+ ['keeps the gallery flag when files:write is granted', 'chat:write,files:write', true],+ ] as const)('%s on submit', async (_label, scope, expected) => {+ const integrations = integrationsLogic()+ integrations.mount()+ await expectLogic(integrations).toFinishListeners()+ integrations.actions.loadIntegrationsSuccess([{ id: 7, kind: 'slack', config: { scope } } as IntegrationType])++ let capturedBody: Partial<SubscriptionType> | undefined+ useMocks({+ post: {+ '/api/environments/:team/subscriptions': async ({ request }) => {+ capturedBody = (await request.json()) as Partial<SubscriptionType>+ return [200, { id: 51, ...capturedBody } as SubscriptionType]+ },+ },+ })+ router.actions.push('/insights/123/subscriptions/new')+ await expectLogic(newLogic).toFinishListeners()+ newLogic.actions.setSubscriptionValues({+ target_type: 'slack',+ target_value: 'C123|#general',+ integration_id: 7,+ title: 'Gallery test',+ delivery_config: { post_all_insights_in_main_message: true },+ })+ newLogic.actions.submitSubscription()+ await expectLogic(newLogic).toFinishListeners().toDispatchActions(['submitSubscriptionSuccess'])+ expect(capturedBody?.delivery_config?.post_all_insights_in_main_message).toBe(expected)+ })})diff --git a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.tsindex 8c2a7191a97b..4e281245f4e6 100644--- a/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts+++ b/products/subscriptions/frontend/components/Subscriptions/subscriptionLogic.ts@@ -7,6 +7,7 @@ import posthog from 'posthog-js'import api, { ApiError } from 'lib/api'import { dayjs } from 'lib/dayjs'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { recordRecentSlackChannel, slackChannelId } from 'lib/integrations/slackChannel'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { getCurrentTeamId } from 'lib/utils/getAppContext'@@ -29,10 +30,17 @@ import type { SubscriptionResourceType, UserBasicType, WeekdayType } from '../..import type { OrganizationType, UserType } from '../../../../../frontend/src/types'import type { AIPromptConfigApi } from '../../generated/api.schemas'import type { AIWindowConfigModeEnumApi } from '../../generated/api.schemas'+import type { DeliveryConfigApi } from '../../generated/api.schemas'import { runSubscriptionTestDelivery } from './runSubscriptionTestDelivery'import { SUBSCRIPTION_PREFILL_PARAMS } from './subscriptionNudge'import { subscriptionsLogic } from './subscriptionsLogic'-import { ALL_DAYS, AI_PROMPT_MAX_LENGTH, SubscriptionBaseProps, urlForSubscription } from './utils'+import {+ ALL_DAYS,+ AI_PROMPT_MAX_LENGTH,+ coerceDeliveryConfigForScope,+ SubscriptionBaseProps,+ urlForSubscription,+} from './utils'// Spelled out rather than interpolated, so the event a metric is configured against is greppable.const EXPORT_NUDGE_CLICKED_EVENTS = {@@ -174,6 +182,7 @@ const NEW_SUBSCRIPTION: Partial<SubscriptionType> = {summary_enabled: false,summary_prompt_guide: '',ai_prompt_config: { window: { mode: 'since_last_sent' } },+ delivery_config: { post_all_insights_in_main_message: false },send_test_now: true,}@@ -259,6 +268,7 @@ export interface subscriptionLogicActions {dashboard?: number | undefineddashboard_export_insights?: number[] | undefineddeleted?: boolean | undefined+ delivery_config?: DeliveryConfigApi | undefinedenabled?: boolean | undefinedfrequency?: 'daily' | 'monthly' | 'weekly' | 'yearly' | undefinedid?: number | undefined@@ -291,6 +301,7 @@ export interface subscriptionLogicActions {dashboard?: number | undefineddashboard_export_insights?: number[] | undefineddeleted?: boolean | undefined+ delivery_config?: DeliveryConfigApi | undefinedenabled?: boolean | undefinedfrequency?: 'daily' | 'monthly' | 'weekly' | 'yearly' | undefinedid?: number | undefined@@ -568,6 +579,10 @@ export const subscriptionLogic = kea<subscriptionLogicType>([const payload = {...subscription,bysetpos: subscription.frequency === 'monthly' ? subscription.bysetpos : null,+ delivery_config: coerceDeliveryConfigForScope(+ subscription,+ integrationsLogic.findMounted()?.values.integrations+ ),insight: isAi ? undefined : insightId,dashboard: isAi ? undefined : props.dashboardId,// AI subscriptions have no dashboard, so a carried-over insight selection woulddiff --git a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts b/products/subscriptions/frontend/components/Subscriptions/utils.test.tsindex c591b482dfbc..b26a908a8874 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.test.ts+++ b/products/subscriptions/frontend/components/Subscriptions/utils.test.ts@@ -1,11 +1,14 @@import { SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'+import { IntegrationType, SubscriptionType } from '~/types'import {canNudgeToSubscribe,+ coerceDeliveryConfigForScope,formatSubscriptionSchedule,getAiSubscriptionGate,getNextDeliveryDate,getSubscriptionAdvancedSettings,+ integrationHasFilesWrite,selectedDaysToDayPickerLabel,shouldShowDayPicker,toggleSelectedDay,@@ -67,6 +70,48 @@ describe('getSubscriptionAdvancedSettings', () => {})})+describe('Slack gallery delivery config', () => {+ const slackIntegration = (id: number, scope: string): IntegrationType =>+ ({ id, kind: 'slack', config: { scope } }) as IntegrationType+ const subscription = (args: Partial<SubscriptionType>): SubscriptionType =>+ ({+ target_type: 'slack',+ integration_id: 7,+ delivery_config: { post_all_insights_in_main_message: true },+ ...args,+ }) as SubscriptionType++ it.each([+ ['granted', slackIntegration(7, 'chat:write,files:write,channels:read'), true],+ ['missing', slackIntegration(7, 'chat:write,channels:read'), false],+ ['substring only', slackIntegration(7, 'files:write:advanced'), false],+ ['missing integration', undefined, false],+ ] as const)('detects files:write when it is %s', (_label, integration, expected) => {+ expect(integrationHasFilesWrite(integration)).toBe(expected)+ })++ it.each<[string, SubscriptionType, IntegrationType[] | null | undefined, boolean]>([+ ['removes the flag when files:write is missing', subscription({}), [slackIntegration(7, 'chat:write')], false],+ ['keeps the flag when files:write is granted', subscription({}), [slackIntegration(7, 'files:write')], true],+ [+ 'removes the flag for a non-Slack target',+ subscription({ target_type: 'email' }),+ [slackIntegration(7, 'files:write')],+ false,+ ],+ ['removes the flag when the loaded integration is missing', subscription({}), [], false],+ ['preserves the flag while integrations are unresolved', subscription({}), null, true],+ ])('%s', (_label, value, integrations, expected) => {+ expect(coerceDeliveryConfigForScope(value, integrations)?.post_all_insights_in_main_message).toBe(expected)+ })++ it('returns an already-disabled config unchanged', () => {+ const config = { post_all_insights_in_main_message: false }+ const value = subscription({ delivery_config: config })+ expect(coerceDeliveryConfigForScope(value, [])).toBe(config)+ })+})+describe('getNextDeliveryDate', () => {beforeEach(() => {jest.useFakeTimers()diff --git a/products/subscriptions/frontend/components/Subscriptions/utils.tsx b/products/subscriptions/frontend/components/Subscriptions/utils.tsxindex fbf54eb66a11..56147c997b25 100644--- a/products/subscriptions/frontend/components/Subscriptions/utils.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/utils.tsx@@ -4,13 +4,14 @@ import { IconLetter } from '@posthog/icons'import { LemonSelectOption, LemonSelectOptionLeaf, LemonSelectOptions } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'+import { getGrantedScopes } from 'lib/integrations/IntegrationScopesWarning'import { IconSlack } from 'lib/lemon-ui/icons'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { range } from 'lib/utils/arrays'import { urls } from 'scenes/urls'import { SubscriptionAIPromptMaxLength, SubscriptionFreeTierLimit } from '~/queries/schema/schema-general'-import { InsightShortId, SubscriptionType, WeekdayType } from '~/types'+import { InsightShortId, IntegrationType, SubscriptionType, WeekdayType } from '~/types'export const AI_PROMPT_MAX_LENGTH = SubscriptionAIPromptMaxLength.CHARACTERS@@ -186,6 +187,33 @@ export function getSubscriptionAdvancedSettings(return settings}+export function integrationHasFilesWrite(integration: IntegrationType | null | undefined): boolean {+ return integration ? getGrantedScopes(integration).includes('files:write') : false+}++export function coerceDeliveryConfigForScope(+ subscription: SubscriptionType,+ integrations: IntegrationType[] | null | undefined+): SubscriptionType['delivery_config'] {+ if (!subscription.delivery_config?.post_all_insights_in_main_message) {+ return subscription.delivery_config+ }+ if (subscription.target_type !== 'slack') {+ return { ...subscription.delivery_config, post_all_insights_in_main_message: false }+ }+ if (integrations == null) {+ return subscription.delivery_config+ }++ const selectedIntegration = subscription.integration_id+ ? integrations.find((integration) => integration.id === subscription.integration_id)+ : undefined+ if (!integrationHasFilesWrite(selectedIntegration)) {+ return { ...subscription.delivery_config, post_all_insights_in_main_message: false }+ }+ return subscription.delivery_config+}+function formatSelectedDeliveryDays(selectedDays: WeekdayType[]): string {if (hasSameDays(selectedDays, ALL_DAYS)) {return 'on Monday to Sunday'diff --git a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsxindex 7a341f00f747..8497f61d2ced 100644--- a/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx+++ b/products/subscriptions/frontend/components/Subscriptions/views/EditSubscription.tsx@@ -2,9 +2,10 @@ import { useActions, useValues } from 'kea'import { Form } from 'kea-forms'import { ReactNode } from 'react'-import { IconChevronLeft, IconSend } from '@posthog/icons'+import { IconChevronLeft, IconInfo, IconSend } from '@posthog/icons'import { LemonInput, LemonTextArea, Link } from '@posthog/lemon-ui'+import api from 'lib/api'import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'import { FlaggedFeature } from 'lib/components/FlaggedFeature'import { UsageLimitPaywall } from 'lib/components/PayGateMini/UsageLimitPaywall'@@ -14,6 +15,7 @@ import { usersLemonSelectOptions } from 'lib/components/UserSelectItem'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { useIntegrationManagementRestriction } from 'lib/integrations/integrationPermissions'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'import { LemonBanner } from 'lib/lemon-ui/LemonBanner'@@ -52,6 +54,7 @@ import {frequencyOptionsSingular,getAiSubscriptionGate,getNextDeliveryDate,+ integrationHasFilesWrite,intervalOptions,monthlyWeekdayOptions,shouldShowDayPicker,@@ -278,6 +281,8 @@ function EditSubscriptionForm({const { slackIntegrations, integrations } = useValues(integrationsLogic)const { dataProcessingAccepted } = useValues(maxGlobalLogic)const aiSubscriptionsEnabled = useFeatureFlag('SUBSCRIPTION_AI_PROMPT')+ const slackGalleryEnabled = useFeatureFlag('SUBSCRIPTION_SLACK_GALLERY')+ const slackReconnectRestriction = useIntegrationManagementRestriction()const emailDisabled = !preflight?.email_service_availableconst isAiPrompt = subscription?.resource_type === SubscriptionResourceTypes.AiPrompt@@ -565,6 +570,67 @@ function EditSubscriptionForm({}}</LemonField>)}++ {(slackGalleryEnabled ||+ subscription.delivery_config?.post_all_insights_in_main_message) &&+ subscription.integration_id &&+ subscription.target_value &&+ (() => {+ const selectedIntegration = integrations?.find(+ (integration) => integration.id === subscription.integration_id+ )+ if (!selectedIntegration?.files_write_requestable) {+ return null+ }+ const hasFilesWrite = integrationHasFilesWrite(selectedIntegration)+ return (+ <LemonField+ name={['delivery_config', 'post_all_insights_in_main_message']}+ help="Posts all insight images together in the main Slack message instead of one per threaded reply."+ >+ {({ value, onChange }) => (+ <div className="border rounded">+ <LemonSwitch+ className="py-2"+ checked={Boolean(value && hasFilesWrite)}+ onChange={onChange}+ disabledReason={+ hasFilesWrite+ ? undefined+ : 'Reconnect Slack below to grant the file-upload permission.'+ }+ fullWidth+ label="Post all insights in the main message"+ />+ {!hasFilesWrite && (+ <div className="flex items-center gap-2 border-t px-2 py-2">+ <IconInfo className="text-base text-secondary shrink-0" />+ <span className="flex-1 text-xs text-secondary">+ Posting all insights together needs the+ Slack file-upload permission (+ <code>files:write</code>). Reconnect Slack+ to grant it, then return here.+ </span>+ <LemonButton+ type="secondary"+ size="xsmall"+ to={api.integrations.authorizeUrl({+ kind: selectedIntegration.kind,+ next: window.location.pathname,+ })}+ disableClientSideRouting+ disabledReason={slackReconnectRestriction}+ data-attr="subscription-slack-reconnect"+ >+ Reconnect Slack+ </LemonButton>+ </div>+ )}+ </div>+ )}+ </LemonField>+ )+ })()}</>)}</>diff --git a/products/subscriptions/frontend/generated/api.schemas.ts b/products/subscriptions/frontend/generated/api.schemas.tsindex 03ee60dfa2fd..7c426798fd35 100644--- a/products/subscriptions/frontend/generated/api.schemas.ts+++ b/products/subscriptions/frontend/generated/api.schemas.ts@@ -169,6 +169,14 @@ export interface UserBasicApi {role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null}+/**+ * Typed view over the Subscription.delivery_config JSON blob.+ */+export interface DeliveryConfigApi {+ /** Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false. */+ post_all_insights_in_main_message?: boolean+}+/*** Standard Subscription serializer.*/@@ -284,6 +292,8 @@ export interface SubscriptionApi {* @maxLength 500*/summary_prompt_guide?: string+ /** Per-delivery rendering options. Each option documents which delivery targets it applies to. */+ delivery_config?: DeliveryConfigApi}export interface PaginatedSubscriptionListApi {@@ -432,6 +442,8 @@ export interface PatchedSubscriptionApi {* @maxLength 500*/summary_prompt_guide?: string+ /** Per-delivery rendering options. Each option documents which delivery targets it applies to. */+ delivery_config?: DeliveryConfigApi}/**diff --git a/products/subscriptions/frontend/generated/api.zod.ts b/products/subscriptions/frontend/generated/api.zod.tsindex 09c7461720e5..b31e50cd7982 100644--- a/products/subscriptions/frontend/generated/api.zod.ts+++ b/products/subscriptions/frontend/generated/api.zod.ts@@ -27,6 +27,8 @@ export const subscriptionsCreateBodyTitleMax = 100export const subscriptionsCreateBodySummaryPromptGuideMax = 500+export const subscriptionsCreateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault = false+export const SubscriptionsCreateBody = /* @__PURE__ */ zod.object({dashboard: zod@@ -176,6 +178,18 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.describe('Optional free-text guidance (max 500 chars) steering the AI summary, e.g. which metrics to emphasize. Only settable when AI summary context is enabled for the organization; clearing it (empty string) is always allowed.'),+ delivery_config: zod+ .object({+ post_all_insights_in_main_message: zod+ .boolean()+ .default(subscriptionsCreateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault)+ .describe(+ 'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'+ ),+ })+ .describe('Typed view over the Subscription.delivery_config JSON blob.')+ .optional()+ .describe('Per-delivery rendering options. Each option documents which delivery targets it applies to.'),}).describe('Standard Subscription serializer.')@@ -197,6 +211,8 @@ export const subscriptionsUpdateBodyTitleMax = 100export const subscriptionsUpdateBodySummaryPromptGuideMax = 500+export const subscriptionsUpdateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault = false+export const SubscriptionsUpdateBody = /* @__PURE__ */ zod.object({dashboard: zod@@ -346,6 +362,18 @@ export const SubscriptionsUpdateBody = /* @__PURE__ */ zod.describe('Optional free-text guidance (max 500 chars) steering the AI summary, e.g. which metrics to emphasize. Only settable when AI summary context is enabled for the organization; clearing it (empty string) is always allowed.'),+ delivery_config: zod+ .object({+ post_all_insights_in_main_message: zod+ .boolean()+ .default(subscriptionsUpdateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault)+ .describe(+ 'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'+ ),+ })+ .describe('Typed view over the Subscription.delivery_config JSON blob.')+ .optional()+ .describe('Per-delivery rendering options. Each option documents which delivery targets it applies to.'),}).describe('Standard Subscription serializer.')@@ -367,6 +395,8 @@ export const subscriptionsPartialUpdateBodyTitleMax = 100export const subscriptionsPartialUpdateBodySummaryPromptGuideMax = 500+export const subscriptionsPartialUpdateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault = false+export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.object({dashboard: zod@@ -523,5 +553,17 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.describe('Optional free-text guidance (max 500 chars) steering the AI summary, e.g. which metrics to emphasize. Only settable when AI summary context is enabled for the organization; clearing it (empty string) is always allowed.'),+ delivery_config: zod+ .object({+ post_all_insights_in_main_message: zod+ .boolean()+ .default(subscriptionsPartialUpdateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault)+ .describe(+ 'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'+ ),+ })+ .describe('Typed view over the Subscription.delivery_config JSON blob.')+ .optional()+ .describe('Per-delivery rendering options. Each option documents which delivery targets it applies to.'),}).describe('Standard Subscription serializer.')diff --git a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.tsindex 4abbd065214c..d0a6c4551f71 100644--- a/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewSettingsSceneLogic.ts@@ -57,6 +57,7 @@ export interface visualReviewSettingsSceneLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefined@@ -116,6 +117,7 @@ export interface visualReviewSettingsSceneLogicActions {created_by?: UserBasicType | null | undefineddisplay_name: stringerrors?: string | undefined+ files_write_requestable?: boolean | undefinedicon_url: anyid: numberinstallation_shared?: boolean | null | undefineddiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 0b200a2e25fc..31474613d9f5 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -27084,6 +27084,14 @@ export namespace Schemas {org?: string;}+ /**+ * Typed view over the Subscription.delivery_config JSON blob.+ */+ export interface DeliveryConfig {+ /** Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false. */+ post_all_insights_in_main_message?: boolean;+ }+/*** * `open_to_gate` - OPEN_TO_GATE* * `gate_to_merge` - GATE_TO_MERGE@@ -46390,6 +46398,8 @@ export namespace Schemas {readonly created_by: UserBasic;readonly errors: string;readonly display_name: string;+ /** Slack only: whether reconnecting can request the files:write scope. */+ readonly files_write_requestable: boolean;/*** GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.* @nullable@@ -57087,6 +57097,8 @@ export namespace Schemas {* @maxLength 500*/summary_prompt_guide?: string;+ /** Per-delivery rendering options. Each option documents which delivery targets it applies to. */+ delivery_config?: DeliveryConfig;}export interface PaginatedSubscriptionList {@@ -63138,6 +63150,8 @@ export namespace Schemas {readonly created_by?: UserBasic;readonly errors?: string;readonly display_name?: string;+ /** Slack only: whether reconnecting can request the files:write scope. */+ readonly files_write_requestable?: boolean;/*** GitHub only, null otherwise. Whether another project's GitHub integration references the same App installation. When false, disconnecting this integration also uninstalls the GitHub App from the connected account or organization and removes personal GitHub connections that share it.* @nullable@@ -66046,6 +66060,8 @@ export namespace Schemas {* @maxLength 500*/summary_prompt_guide?: string;+ /** Per-delivery rendering options. Each option documents which delivery targets it applies to. */+ delivery_config?: DeliveryConfig;}/**diff --git a/services/mcp/src/generated/subscriptions/api.ts b/services/mcp/src/generated/subscriptions/api.tsindex c5451471572d..9a07fecc9a5f 100644--- a/services/mcp/src/generated/subscriptions/api.ts+++ b/services/mcp/src/generated/subscriptions/api.ts@@ -62,6 +62,8 @@ export const subscriptionsCreateBodyTitleMax = 100export const subscriptionsCreateBodySummaryPromptGuideMax = 500+export const subscriptionsCreateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault = false+export const SubscriptionsCreateBody = /* @__PURE__ */ zod.object({dashboard: zod@@ -206,6 +208,18 @@ export const SubscriptionsCreateBody = /* @__PURE__ */ zod.describe('Optional free-text guidance (max 500 chars) steering the AI summary, e.g. which metrics to emphasize. Only settable when AI summary context is enabled for the organization; clearing it (empty string) is always allowed.'),+ delivery_config: zod+ .object({+ post_all_insights_in_main_message: zod+ .boolean()+ .default(subscriptionsCreateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault)+ .describe(+ 'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'+ ),+ })+ .describe('Typed view over the Subscription.delivery_config JSON blob.')+ .optional()+ .describe('Per-delivery rendering options. Each option documents which delivery targets it applies to.'),}).describe('Standard Subscription serializer.')@@ -245,6 +259,8 @@ export const subscriptionsPartialUpdateBodyTitleMax = 100export const subscriptionsPartialUpdateBodySummaryPromptGuideMax = 500+export const subscriptionsPartialUpdateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault = false+export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.object({dashboard: zod@@ -390,6 +406,18 @@ export const SubscriptionsPartialUpdateBody = /* @__PURE__ */ zod.describe('Optional free-text guidance (max 500 chars) steering the AI summary, e.g. which metrics to emphasize. Only settable when AI summary context is enabled for the organization; clearing it (empty string) is always allowed.'),+ delivery_config: zod+ .object({+ post_all_insights_in_main_message: zod+ .boolean()+ .default(subscriptionsPartialUpdateBodyDeliveryConfigOnePostAllInsightsInMainMessageDefault)+ .describe(+ 'Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.'+ ),+ })+ .describe('Typed view over the Subscription.delivery_config JSON blob.')+ .optional()+ .describe('Per-delivery rendering options. Each option documents which delivery targets it applies to.'),}).describe('Standard Subscription serializer.')diff --git a/services/mcp/src/tools/generated/subscriptions.ts b/services/mcp/src/tools/generated/subscriptions.tsindex 7f0e1e9f6a10..60b6b216c002 100644--- a/services/mcp/src/tools/generated/subscriptions.ts+++ b/services/mcp/src/tools/generated/subscriptions.ts@@ -86,6 +86,9 @@ const subscriptionsCreate = (): ToolBase<typeof SubscriptionsCreateSchema, Schemif (params.summary_prompt_guide !== undefined) {body['summary_prompt_guide'] = params.summary_prompt_guide}+ if (params.delivery_config !== undefined) {+ body['delivery_config'] = params.delivery_config+ }const result = await context.api.request<Schemas.Subscription>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/`,@@ -286,6 +289,9 @@ const subscriptionsPartialUpdate = (): ToolBase<typeof SubscriptionsPartialUpdatif (params.summary_prompt_guide !== undefined) {body['summary_prompt_guide'] = params.summary_prompt_guide}+ if (params.delivery_config !== undefined) {+ body['delivery_config'] = params.delivery_config+ }const result = await context.api.request<Schemas.Subscription>({method: 'PATCH',path: `/api/projects/${encodeURIComponent(String(projectId))}/subscriptions/${encodeURIComponent(String(params.id))}/`,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.jsonindex 1caa4346754e..b977ef83b6f1 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/subscriptions-create.json@@ -106,6 +106,17 @@},"type": "array"},+ "delivery_config": {+ "description": "Per-delivery rendering options. Each option documents which delivery targets it applies to.",+ "properties": {+ "post_all_insights_in_main_message": {+ "default": false,+ "description": "Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.",+ "type": "boolean"+ }+ },+ "type": "object"+ },"enabled": {"description": "Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.","type": "boolean"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 ecb6aa6d9ba9..19a2ba03eccd 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@@ -105,6 +105,17 @@},"type": "array"},+ "delivery_config": {+ "description": "Per-delivery rendering options. Each option documents which delivery targets it applies to.",+ "properties": {+ "post_all_insights_in_main_message": {+ "default": false,+ "description": "Slack only: when true, upload all insight images together in the main Slack message instead of posting the first image in the main message and the rest as threaded replies. Defaults to false.",+ "type": "boolean"+ }+ },+ "type": "object"+ },"enabled": {"description": "Whether the subscription is active. Set to false to pause delivery without deleting. Auto-set to false when the delivery integration becomes invalid.","type": "boolean"