: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(customer-analytics): send announcements under your own Slack name (#102862)
Christophe Eynius Tranbergb9fe142d580c
diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 81a82b0e69c3..79c607d88fa9 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -1215,6 +1215,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVrich_content=comment.rich_content,author_name=author_name,author_email=author_email,+ workspace=integration.integration_id,item_url=build_comment_item_url(comment.scope, comment.item_id),item_label=comment_scope_display_name(comment.scope),organization_id=self.team.organization_id,diff --git a/posthog/egress/slack/client.py b/posthog/egress/slack/client.pyindex 033898cb7487..a26859617e2f 100644--- a/posthog/egress/slack/client.py+++ b/posthog/egress/slack/client.py@@ -45,6 +45,9 @@ class SlackWebClient(WebClient):**kwargs: Any,) -> None:super().__init__(token=token, **kwargs)+ # Kept on the client so callers that need the workspace this token belongs to (e.g. to+ # namespace a per-workspace cache) can read it back instead of re-resolving it.+ self.workspace_id = workspace_id or Noneself.retry_handlers.insert(0,SlackObservabilityHandler(source=source, workspace_id=workspace_id, app_id=app_id),diff --git a/posthog/helpers/slack_thread_mirror.py b/posthog/helpers/slack_thread_mirror.pyindex a138e9ffe97c..c8ac2345c87c 100644--- a/posthog/helpers/slack_thread_mirror.py+++ b/posthog/helpers/slack_thread_mirror.py@@ -94,6 +94,7 @@ def post_comment_to_slack_thread(rich_content: dict | None,author_name: str,author_email: str = "",+ workspace: str | None = None,thread_ts: str | None = None,item_url: str | None = None,item_label: str | None = None,@@ -103,7 +104,9 @@ def post_comment_to_slack_thread(When ``item_url`` is given (the thread root), the message renders as a card linking back to thediscussion; otherwise (replies) it's a plain threaded message. ``organization_id`` scopes- @-mention resolution — without it every mention renders as a generic teammate. Returns the+ @-mention resolution — without it every mention renders as a generic teammate. ``workspace``+ (the Slack team id behind ``client``) scopes the author's avatar lookup, so one workspace's+ cached profile is never served for another's. Returns theposted message's ``ts`` so the caller can anchor a mirror on the first post, or ``None`` whenthere was nothing to post. Raises on a Slack API failure so callers can react (the API actionsurfaces an error; the Celery tasks retry) instead of silently dropping the message.@@ -115,7 +118,7 @@ def post_comment_to_slack_thread(return None# Show the author's Slack avatar when we can match them by email (needs chat:write.customize).- icon_url = resolve_slack_avatar_by_email(client, author_email) if author_email else None+ icon_url = resolve_slack_avatar_by_email(client, author_email, workspace=workspace) if author_email else Nonemessage_kwargs: dict = {"channel": channel,diff --git a/posthog/slack/identity.py b/posthog/slack/identity.pyindex b086e05730b9..9a9b9af8a86e 100644--- a/posthog/slack/identity.py+++ b/posthog/slack/identity.py@@ -2,9 +2,10 @@Token-agnostic: every function takes a ``slack_sdk.WebClient`` so the caller supplies theworkspace's bot token (the conversations SupportHog bot, the generic Slack ``Integration``,-etc.). Profile and avatar lookups are cached in Redis. Slack user ids are only guaranteed-unique per workspace, so profile cache keys are namespaced by the required ``workspace``-(the Slack team id); email keys are globally unique already.+etc.). Profile and avatar lookups are cached in Redis. Neither a Slack user id nor an email+address identifies the same person across workspaces — an id is only unique within one, and+one address can belong to different people in two — so every cache key is namespaced by+``workspace`` (the Slack team id the client's token points at)."""from types import MappingProxyType@@ -22,7 +23,7 @@ logger = structlog.get_logger(__name__)# Short TTLs keep cached Slack profiles/avatars reasonably fresh.SLACK_USER_CACHE_TTL = 5 * 60 # 5 minutes-SLACK_AVATAR_CACHE_TTL = 5 * 60 # 5 minutes+SLACK_PROFILE_CACHE_TTL = 5 * 60 # 5 minutes_UNKNOWN_USER = MappingProxyType({"name": "Unknown", "email": None, "avatar": None, "team_id": None})@@ -52,9 +53,10 @@ def set_cached_slack_user(slack_user_id: str, user_info: dict, workspace: str) -logger.warning("slack_identity_cache_set_error", key=key)-def get_cached_slack_avatar(email: str) -> str | None:- """Get cached Slack avatar URL for an email. Returns None on cache miss, empty string for negative cache."""- key = _make_cache_key("slack_avatar", email.lower())+def get_cached_slack_profile(email: str, workspace: str) -> dict | None:+ """Get the cached Slack profile for an email in this workspace. Returns None on cache miss,+ an empty dict for negative cache."""+ key = _make_cache_key("slack_profile", workspace, email.lower())try:return cache.get(key)except Exception:@@ -62,11 +64,11 @@ def get_cached_slack_avatar(email: str) -> str | None:return None-def set_cached_slack_avatar(email: str, avatar_url: str) -> None:- """Cache a Slack avatar URL (or empty string for negative cache)."""- key = _make_cache_key("slack_avatar", email.lower())+def set_cached_slack_profile(email: str, profile: dict, workspace: str) -> None:+ """Cache a Slack profile (or an empty dict for negative cache)."""+ key = _make_cache_key("slack_profile", workspace, email.lower())try:- cache.set(key, avatar_url, timeout=SLACK_AVATAR_CACHE_TTL)+ cache.set(key, profile, timeout=SLACK_PROFILE_CACHE_TTL)except Exception:logger.warning("slack_identity_cache_set_error", key=key)@@ -117,14 +119,26 @@ def resolve_slack_user(client: WebClient, slack_user_id: str, *, workspace: str)return dict(_UNKNOWN_USER)-def resolve_slack_avatar_by_email(client: WebClient, email: str) -> str | None:- """Look up a Slack user by email and return their profile image URL. Cached in Redis."""+def resolve_slack_profile_by_email(client: WebClient, email: str, *, workspace: str | None) -> dict | None:+ """Look up a Slack user by email and return ``{"name", "avatar"}``. Cached in Redis.++ ``None`` when the email matches no Slack user (or the lookup failed), so callers can+ tell "no Slack identity" apart from "matched, but no avatar set". Needs the+ ``users:read.email`` scope on the token.++ The profile belongs to whichever workspace ``client``'s token points at, and the same+ email can resolve to different people in two of them, so ``workspace`` (the Slack team+ id) namespaces the cache. Pass ``None`` when the caller can't identify the workspace:+ the lookup then bypasses the cache entirely rather than sharing one unkeyed entry+ between workspaces.+ """if not email:return None- cached = get_cached_slack_avatar(email)- if cached is not None:- return cached or None # empty string = negative cache+ if workspace:+ cached = get_cached_slack_profile(email, workspace)+ if cached is not None:+ return cached or None # empty dict = negative cachetry:response = client.users_lookupByEmail(email=email)@@ -132,20 +146,31 @@ def resolve_slack_avatar_by_email(client: WebClient, email: str) -> str | None:data: dict = raw_data if isinstance(raw_data, dict) else {}if not data.get("ok"):- set_cached_slack_avatar(email, "")+ if workspace:+ set_cached_slack_profile(email, {}, workspace)return Noneprofile = (data.get("user") or {}).get("profile") or {}- avatar = profile.get("image_72") or ""- set_cached_slack_avatar(email, avatar)- return avatar or None+ resolved = {+ "name": profile.get("display_name") or profile.get("real_name") or "",+ "avatar": profile.get("image_72") or "",+ }+ if workspace:+ set_cached_slack_profile(email, resolved, workspace)+ return resolvedexcept Exception:# Don't negative-cache on transient errors (rate limits, network)# so the next reply retries the lookup.- logger.warning("slack_avatar_lookup_failed", email=email)+ logger.warning("slack_profile_lookup_failed", email=email)return None+def resolve_slack_avatar_by_email(client: WebClient, email: str, *, workspace: str | None) -> str | None:+ """Look up a Slack user by email and return their profile image URL. Cached in Redis."""+ profile = resolve_slack_profile_by_email(client, email, workspace=workspace)+ return (profile or {}).get("avatar") or None++def resolve_posthog_user_for_slack(email: str | None, team: Team) -> User | None:"""Match a Slack user's email to a PostHog user within the team's organization."""if not email:diff --git a/posthog/slack/test/test_identity.py b/posthog/slack/test/test_identity.pyindex 30ab29c829f1..65131250cca6 100644--- a/posthog/slack/test/test_identity.py+++ b/posthog/slack/test/test_identity.py@@ -3,7 +3,7 @@ from unittest.mock import MagicMockfrom django.core.cache import cachefrom django.test import SimpleTestCase-from posthog.slack.identity import resolve_slack_user+from posthog.slack.identity import resolve_slack_profile_by_email, resolve_slack_userdef _client_returning(name: str, email: str) -> MagicMock:@@ -33,3 +33,53 @@ class TestSlackIdentityWorkspaceNamespacing(SimpleTestCase):# Same workspace does hit the cache: no second API call.resolve_slack_user(workspace_a_client, "U12345", workspace="T_WORKSPACE_A")workspace_a_client.users_info.assert_called_once_with(user="U12345")+++def _client_resolving_email(name: str, avatar: str) -> MagicMock:+ client = MagicMock()+ client.users_lookupByEmail.return_value.data = {+ "ok": True,+ "user": {"profile": {"display_name": name, "image_72": avatar}},+ }+ return client+++class TestSlackProfileByEmailWorkspaceNamespacing(SimpleTestCase):+ def setUp(self) -> None:+ cache.clear()++ def test_same_email_in_different_workspaces_does_not_share_cache(self) -> None:+ # One address can belong to different people in two workspaces, and the resolved profile+ # decides whose name a message is posted under — so a shared entry posts as the wrong person.+ workspace_a_client = _client_resolving_email("Alice Internal", "https://example.com/alice.png")+ workspace_b_client = _client_resolving_email("Mallory External", "https://evil.example.com/mallory.png")++ resolved_a = resolve_slack_profile_by_email(workspace_a_client, "[email protected]", workspace="T_A")+ resolved_b = resolve_slack_profile_by_email(workspace_b_client, "[email protected]", workspace="T_B")++ assert resolved_a == {"name": "Alice Internal", "avatar": "https://example.com/alice.png"}+ assert resolved_b == {"name": "Mallory External", "avatar": "https://evil.example.com/mallory.png"}++ # Same workspace does hit the cache: no second API call.+ resolve_slack_profile_by_email(workspace_a_client, "[email protected]", workspace="T_A")+ workspace_a_client.users_lookupByEmail.assert_called_once_with(email="[email protected]")++ def test_unknown_workspace_bypasses_the_cache_instead_of_sharing_one_entry(self) -> None:+ client = _client_resolving_email("Ada", "https://example.com/ada.png")++ assert resolve_slack_profile_by_email(client, "[email protected]", workspace=None) is not None+ resolve_slack_profile_by_email(client, "[email protected]", workspace=None)++ # An unkeyed entry would be readable from every workspace, so nothing is cached at all.+ assert client.users_lookupByEmail.call_count == 2++ def test_unmatched_email_is_negative_cached_per_workspace(self) -> None:+ client = MagicMock()+ client.users_lookupByEmail.return_value.data = {"ok": False, "error": "users_not_found"}++ assert resolve_slack_profile_by_email(client, "[email protected]", workspace="T_A") is None+ assert resolve_slack_profile_by_email(client, "[email protected]", workspace="T_A") is None+ client.users_lookupByEmail.assert_called_once_with(email="[email protected]")++ assert resolve_slack_profile_by_email(client, "[email protected]", workspace="T_B") is None+ assert client.users_lookupByEmail.call_count == 2diff --git a/posthog/tasks/comment_slack_sync.py b/posthog/tasks/comment_slack_sync.pyindex 4a11939c516d..859ea20b5d2d 100644--- a/posthog/tasks/comment_slack_sync.py+++ b/posthog/tasks/comment_slack_sync.py@@ -87,6 +87,7 @@ def _post_backfill_reply(rich_content=reply.rich_content,author_name=author_name,author_email=author_email,+ workspace=mirror.slack_team_id,thread_ts=mirror.slack_thread_ts,organization_id=organization_id,)@@ -174,6 +175,7 @@ def mirror_comment_reply_to_slack(self: Task, comment_id: str) -> None:rich_content=comment.rich_content,author_name=author_name,author_email=author_email,+ workspace=mirror.slack_team_id,thread_ts=mirror.slack_thread_ts,organization_id=_organization_id_for_team(comment.team_id),)diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex 485568431b65..b17bb7e63b1c 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -27,6 +27,7 @@ from posthog.ingress.contracts import DeliveryOwnership, WebhookDeliveryfrom posthog.models.comment import Commentfrom posthog.models.integration import Integrationfrom posthog.models.team import Team+from posthog.slack.identity import resolve_slack_profile_by_emailfrom posthog.temporal.common.client import sync_connectfrom products.conversations.backend.channel_summary_ids import build_channel_summary_workflow_id@@ -42,6 +43,7 @@ from products.conversations.backend.facade.types import (PublicHumanReplies as PublicHumanReplies,ResolvedTicketRevision as ResolvedTicketRevision,SupportChannel as SupportChannel,+ SupportSlackSender as SupportSlackSender,SupportTicketMessage as SupportTicketMessage,TicketSummary as TicketSummary,)@@ -58,7 +60,10 @@ from products.conversations.backend.models import (from products.conversations.backend.models.constants import WORKFLOW_AUTHOR_TYPEfrom products.conversations.backend.services.messages import public_human_ticket_repliesfrom products.conversations.backend.slack import get_slack_client-from products.conversations.backend.support_slack import get_support_slack_bot_token+from products.conversations.backend.support_slack import (+ get_support_slack_bot_token,+ supporthog_lacks_custom_identity_scope,+)from products.conversations.backend.support_slack_channels import (SupportSlackChannelsUnavailable as SupportSlackChannelsUnavailable,SupportSlackNotConfigured as SupportSlackNotConfigured,@@ -107,6 +112,14 @@ class SupportMessageSendError(Exception):self.retry_after = retry_after+class SupportSenderIdentityUnavailable(Exception):+ """This SupportHog install can't post under a name and avatar other than the bot's own.++ Slack only grants scopes at install time, so an install authorized before+ ``chat:write.customize`` was requested needs an admin to reconnect.+ """++def accept_github_event(delivery: WebhookDelivery) -> None:"""The inbound GitHub App webhook enters conversations here, so its consumer needs no internal import."""# Deferred to keep the Celery task module off the facade import path.@@ -305,10 +318,62 @@ def list_support_bot_channels(team_id: int, *, members_only: bool = False) -> lireturn [SupportChannel(id=c["id"], name=c["name"], is_member=c["is_member"]) for c in channels]-def post_support_message(team_id: int, channel_id: str, text: str) -> str:+def _message_identity_kwargs(team: Team, sender: SupportSlackSender | None) -> dict[str, Any]:+ """``chat.postMessage`` overrides for the name and avatar a message appears under."""+ if sender is not None:+ # The bot icon next to a person's name would contradict it, so it is not a fallback.+ return {"username": sender.name, **({"icon_url": sender.icon_url} if sender.icon_url else {})}++ kwargs: dict[str, Any] = {}+ support_settings = team.conversations_settings or {}+ if bot_display_name := support_settings.get("slack_bot_display_name"):+ kwargs["username"] = bot_display_name+ if bot_icon_url := support_settings.get("slack_bot_icon_url"):+ kwargs["icon_url"] = bot_icon_url+ return kwargs+++def resolve_support_slack_sender(team_id: int, email: str) -> SupportSlackSender | None:+ """The Slack name and avatar of the workspace member with this email, or ``None`` when+ the email matches no Slack user.++ Lets a caller post as a teammate's profile rather than the bot's; the message is still+ a bot message, Slack only renders it under that name and avatar.++ Raises :class:`SupportSlackNotConfigured` when the bot isn't connected, and+ :class:`SupportSenderIdentityUnavailable` when the install can't post under a custom+ identity at all — resolving a profile it could never post under only produces messages+ Slack rejects one channel at a time.+ """+ try:+ team = Team.objects.get(id=team_id)+ client = get_slack_client(team)+ except (Team.DoesNotExist, ValueError):+ raise SupportSlackNotConfigured()++ if supporthog_lacks_custom_identity_scope(team):+ raise SupportSenderIdentityUnavailable()++ profile = resolve_slack_profile_by_email(client, email, workspace=client.workspace_id)+ if not profile or not profile.get("name"):+ return None+ return SupportSlackSender(name=str(profile["name"]), icon_url=str(profile.get("avatar") or ""))+++def post_support_message(+ team_id: int,+ channel_id: str,+ text: str,+ *,+ sender: SupportSlackSender | None = None,+) -> str:"""Post ``text`` to a Slack channel as the SupportHog bot, applying the team'sconfigured bot display name and icon. Returns the posted message's Slack ts.+ ``sender`` overrides that identity for this message only — Slack renders it under the+ given name and avatar (needs the ``chat:write.customize`` scope), which is how a+ message can look like it comes from a teammate instead of the bot.+Raises :class:`SupportSlackNotConfigured` when the bot isn't connected and:class:`SupportMessageSendError` when the post fails."""@@ -318,12 +383,7 @@ def post_support_message(team_id: int, channel_id: str, text: str) -> str:except (Team.DoesNotExist, ValueError):raise SupportSlackNotConfigured()- message_kwargs: dict[str, Any] = {}- support_settings = team.conversations_settings or {}- if bot_display_name := support_settings.get("slack_bot_display_name"):- message_kwargs["username"] = bot_display_name- if bot_icon_url := support_settings.get("slack_bot_icon_url"):- message_kwargs["icon_url"] = bot_icon_url+ message_kwargs = _message_identity_kwargs(team, sender)try:response = client.chat_postMessage(channel=channel_id, text=text, **message_kwargs)diff --git a/products/conversations/backend/facade/types.py b/products/conversations/backend/facade/types.pyindex 2ef1d0d4a5b9..ec739f669a56 100644--- a/products/conversations/backend/facade/types.py+++ b/products/conversations/backend/facade/types.py@@ -22,6 +22,14 @@ class SupportChannel:is_member: bool+@dataclass(frozen=True)+class SupportSlackSender:+ """The Slack profile a SupportHog message can be posted under."""++ name: str+ icon_url: str++@dataclass(frozen=True)class ConversationMessageSender:name: strdiff --git a/products/conversations/backend/support_slack.py b/products/conversations/backend/support_slack.pyindex 19aea3130b98..24b2ba02d8d8 100644--- a/products/conversations/backend/support_slack.py+++ b/products/conversations/backend/support_slack.py@@ -21,6 +21,9 @@ SUPPORT_SLACK_FILE_READ_SCOPE = "files:read"SUPPORT_SLACK_FILE_WRITE_SCOPE = "files:write"SUPPORT_SLACK_FILE_SCOPES = frozenset({SUPPORT_SLACK_FILE_READ_SCOPE, SUPPORT_SLACK_FILE_WRITE_SCOPE})+# Posting under a name and avatar other than the bot's own needs this.+SUPPORT_SLACK_CUSTOM_IDENTITY_SCOPE = "chat:write.customize"+def get_support_slack_settings() -> dict:return get_instance_settings(@@ -47,6 +50,20 @@ def supporthog_missing_file_scopes(team: "Team") -> list[str]:return sorted(SUPPORT_SLACK_FILE_SCOPES.difference(granted or []))+def supporthog_lacks_custom_identity_scope(team: "Team") -> bool:+ """Whether this install is *known* to be unable to post under a custom name and avatar.++ False when scopes were never recorded: the scope has been requested for as long as we've+ recorded them, so an unrecorded install most likely has it, and refusing on that guess+ would block installs that work. Slack still rejects the post if it really is missing.+ """+ settings = team.conversations_settings+ granted = settings.get("slack_scopes") if isinstance(settings, dict) else None+ if not granted:+ return False+ return SUPPORT_SLACK_CUSTOM_IDENTITY_SCOPE not in granted++def get_support_slack_bot_token(team: "Team") -> str:config = get_or_create_team_extension(team, TeamConversationsSlackConfig)return str(config.slack_bot_token or "")diff --git a/products/conversations/backend/tasks/slack.py b/products/conversations/backend/tasks/slack.pyindex fdd44507fca5..6e6d30774cf5 100644--- a/products/conversations/backend/tasks/slack.py+++ b/products/conversations/backend/tasks/slack.py@@ -814,7 +814,7 @@ def _slack_sender(*, client: Any, team: Team, payload: dict[str, Any], ticket_idauthor_icon_url: str | None = Noneif author_email:try:- author_icon_url = resolve_slack_avatar_by_email(client, author_email)+ author_icon_url = resolve_slack_avatar_by_email(client, author_email, workspace=client.workspace_id)except Exception:logger.warning("slack_delivery_avatar_lookup_failed", ticket_id=ticket_id, exc_info=True)return SlackSender(@@ -1172,7 +1172,7 @@ def post_reply_to_slack(# Resolve the replying user's Slack profile pictureauthor_icon_url: str | None = Noneif author_email:- author_icon_url = resolve_slack_avatar_by_email(client, author_email)+ author_icon_url = resolve_slack_avatar_by_email(client, author_email, workspace=client.workspace_id)icon_url = author_icon_url or bot_icon_urlmessage_kwargs: dict = {diff --git a/products/conversations/backend/tests/test_facade.py b/products/conversations/backend/tests/test_facade.pyindex 23303502c161..ee172c9b2feb 100644--- a/products/conversations/backend/tests/test_facade.py+++ b/products/conversations/backend/tests/test_facade.py@@ -6,6 +6,7 @@ from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.conf import settings+from django.core.cache import cachefrom django.utils import timezonefrom parameterized import parameterized@@ -17,11 +18,14 @@ from posthog.models.comment import Commentfrom products.conversations.backend.channel_summary_ids import build_channel_summary_workflow_idfrom products.conversations.backend.facade.api import (SupportMessageSendError,+ SupportSenderIdentityUnavailable,+ SupportSlackSender,get_public_human_replies,list_account_ticket_messages,list_account_tickets,list_resolved_ticket_revisions,post_support_message,+ resolve_support_slack_sender,trigger_immediate_channel_summary,)from products.conversations.backend.models.constants import Status@@ -59,6 +63,43 @@ class TestPostSupportMessage(BaseTest):assert kwargs["username"] == "SupportBot"assert kwargs["icon_url"] == "https://example.com/icon.png"+ @patch(CLIENT)+ def test_sender_overrides_the_bot_identity(self, mock_get_client: MagicMock):+ self.team.conversations_settings = {+ "slack_bot_display_name": "SupportBot",+ "slack_bot_icon_url": "https://example.com/bot.png",+ }+ self.team.save()+ client = MagicMock()+ client.chat_postMessage.return_value = {"ts": "111.222"}+ mock_get_client.return_value = client++ post_support_message(+ self.team.pk,+ "C1",+ "hello team",+ sender=SupportSlackSender(name="Ada", icon_url="https://example.com/ada.png"),+ )++ kwargs = client.chat_postMessage.call_args.kwargs+ assert kwargs["username"] == "Ada"+ assert kwargs["icon_url"] == "https://example.com/ada.png"++ @patch(CLIENT)+ def test_sender_without_avatar_keeps_the_name_only(self, mock_get_client: MagicMock):+ self.team.conversations_settings = {"slack_bot_icon_url": "https://example.com/bot.png"}+ self.team.save()+ client = MagicMock()+ client.chat_postMessage.return_value = {"ts": "111.222"}+ mock_get_client.return_value = client++ post_support_message(self.team.pk, "C1", "hi", sender=SupportSlackSender(name="Ada", icon_url=""))++ kwargs = client.chat_postMessage.call_args.kwargs+ assert kwargs["username"] == "Ada"+ # The bot icon would contradict the name, so it is not applied.+ assert "icon_url" not in kwargs+@parameterized.expand([(@@ -98,6 +139,59 @@ class TestPostSupportMessage(BaseTest):assert ctx.exception.retry_after == expected_retry_after+class TestResolveSupportSlackSender(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ cache.clear()++ def _client_returning(self, data: dict) -> MagicMock:+ client = MagicMock()+ client.users_lookupByEmail.return_value.data = data+ return client++ @patch(CLIENT)+ def test_resolves_workspace_member_by_email(self, mock_get_client: MagicMock):+ mock_get_client.return_value = self._client_returning(+ {"ok": True, "user": {"profile": {"display_name": "Ada", "image_72": "https://example.com/ada.png"}}}+ )++ sender = resolve_support_slack_sender(self.team.pk, "[email protected]")++ assert sender == SupportSlackSender(name="Ada", icon_url="https://example.com/ada.png")++ @patch(CLIENT)+ def test_returns_none_when_no_slack_user_has_the_email(self, mock_get_client: MagicMock):+ mock_get_client.return_value = self._client_returning({"ok": False, "error": "users_not_found"})++ assert resolve_support_slack_sender(self.team.pk, "[email protected]") is None++ @patch(CLIENT)+ def test_refuses_when_the_install_cannot_post_a_custom_identity(self, mock_get_client: MagicMock):+ # Slack would reject every such post, so fail before resolving a profile we can't use.+ self.team.conversations_settings = {"slack_scopes": ["chat:write", "users:read.email"]}+ self.team.save()+ client = self._client_returning({"ok": True, "user": {"profile": {"display_name": "Ada"}}})+ mock_get_client.return_value = client++ with self.assertRaises(SupportSenderIdentityUnavailable):+ resolve_support_slack_sender(self.team.pk, "[email protected]")+ client.users_lookupByEmail.assert_not_called()++ @patch(CLIENT)+ def test_allows_an_install_whose_scopes_were_never_recorded(self, mock_get_client: MagicMock):+ # Predates scope recording, and the scope has been requested for longer than that — so an+ # empty list is "unknown", not "missing", and refusing would block a working install.+ self.team.conversations_settings = {"slack_enabled": True}+ self.team.save()+ mock_get_client.return_value = self._client_returning(+ {"ok": True, "user": {"profile": {"display_name": "Ada"}}}+ )++ assert resolve_support_slack_sender(self.team.pk, "[email protected]") == SupportSlackSender(+ name="Ada", icon_url=""+ )++class TestListAccountTickets(BaseTest):def setUp(self) -> None:super().setUp()diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 9a27cfa6add7..46226970a41a 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -5667,6 +5667,8 @@ def _to_announcement_view(announcement) -> contracts.AnnouncementView:short_id=announcement.short_id,message=announcement.message,status=announcement.status,+ send_as=announcement.send_as,+ sender_display_name=announcement.sender_display_name,total_channels=announcement.total_channels,sent_count=announcement.sent_count,failed_count=announcement.failed_count,@@ -5698,9 +5700,11 @@ def get_announcement(team_id: int, short_id: str) -> contracts.AnnouncementViewreturn _to_announcement_view(announcement) if announcement is not None else None-def create_announcement(*, team_id: int, user: "User", message: str, channels: list[str]) -> contracts.AnnouncementView:+def create_announcement(+ *, team_id: int, user: "User", message: str, channels: list[str], send_as: str = "bot"+) -> contracts.AnnouncementView:team = Team.objects.get(id=team_id)- announcement = _announcements_logic.create_announcement(team, user, message, channels)+ announcement = _announcements_logic.create_announcement(team, user, message, channels, send_as)# Dispatch only after the delivery rows commit; a rollback must not leave a phantom task.transaction.on_commit(lambda: send_announcement.delay(str(announcement.id), team_id))return _to_announcement_view(announcement)diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 0a0d782c393d..021c7542b4d2 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -1369,6 +1369,8 @@ class AnnouncementView:short_id: str = ""message: str = ""status: str = ""+ send_as: str = "bot"+ sender_display_name: str = ""total_channels: int = 0sent_count: int = 0failed_count: int = 0diff --git a/products/customer_analytics/backend/logic/announcements.py b/products/customer_analytics/backend/logic/announcements.pyindex 79f11971acb6..4c0022f2d3d7 100644--- a/products/customer_analytics/backend/logic/announcements.py+++ b/products/customer_analytics/backend/logic/announcements.py@@ -9,10 +9,13 @@ import structlogfrom products.conversations.backend.facade.api import (SupportMessageSendError,+ SupportSenderIdentityUnavailable,SupportSlackChannelsUnavailable,SupportSlackNotConfigured,+ SupportSlackSender,list_support_bot_channels,post_support_message,+ resolve_support_slack_sender,)from products.customer_analytics.backend.constants import (DELIVERY_IN_FLIGHT_ERROR,@@ -33,7 +36,61 @@ class AnnouncementRateLimited(Exception):pass-def create_announcement(team: Team, created_by: User, message: str, channel_ids: list[str]) -> Announcement:+def _resolve_user_sender(team_id: int, user: User) -> SupportSlackSender:+ """The Slack profile to post under when someone sends an announcement as themselves.++ Matches by email, so a user whose Slack email differs from their PostHog one has no+ identity to post under — say so instead of quietly falling back to the bot, which is+ the exact outcome the option exists to avoid.+ """+ email = (user.email or "").strip()+ if not email:+ raise AnnouncementValidationError(+ {"send_as": "Your PostHog account has no email address, so we cannot find your Slack profile."}+ )+ # The email address is the only thing binding this person to the Slack profile we post under,+ # and on an instance with no email delivery an address change is written straight to the+ # account with no proof of ownership (see the `is_email_available()` branch in+ # `UserSerializer.update`). Unverified, it would let someone send to customer channels under a+ # colleague's name and avatar, so require the same bar the support widget uses before it+ # attests an email across systems: verified, not merely present.+ if user.is_email_verified is not True:+ raise AnnouncementValidationError(+ {+ "send_as": "Verify your email address before sending as yourself — until then PostHog "+ "cannot confirm that Slack profile is yours. Send as SupportHog instead."+ }+ )+ try:+ sender = resolve_support_slack_sender(team_id, email)+ except SupportSlackNotConfigured:+ raise AnnouncementValidationError("The SupportHog Slack bot is not connected.")+ except SupportSenderIdentityUnavailable:+ # Every channel would fail the same way at post time, so stop before the first one.+ raise AnnouncementValidationError(+ {+ "send_as": "This Slack workspace was connected before PostHog could post under your "+ "name, so reconnect the SupportHog bot in Support settings — or send as SupportHog."+ }+ )+ if sender is None:+ raise AnnouncementValidationError(+ {+ "send_as": f"No Slack user has the email {email}, so we cannot send as you. "+ "Send as SupportHog instead, or sign in to Slack with this email."+ }+ )+ return sender+++def create_announcement(+ team: Team,+ created_by: User,+ message: str,+ channel_ids: list[str],+ send_as: str = Announcement.SendAs.BOT,+) -> Announcement:+ sender = _resolve_user_sender(team.pk, created_by) if send_as == Announcement.SendAs.USER else Nonetry:allowed = {c.id: c for c in list_support_bot_channels(team.pk, members_only=True)}except SupportSlackNotConfigured:@@ -51,6 +108,9 @@ def create_announcement(team: Team, created_by: User, message: str, channel_ids:created_by=created_by,total_channels=len(channel_ids),status=Announcement.Status.PENDING,+ send_as=send_as,+ sender_display_name=sender.name if sender else "",+ sender_icon_url=sender.icon_url if sender else "",)AnnouncementDelivery.objects.bulk_create([@@ -123,10 +183,11 @@ def send_pending_deliveries(announcement_id: str, team_id: int) -> None:announcement.status = Announcement.Status.SENDINGannouncement.save(update_fields=["status", "updated_at"])+ sender = _announcement_sender(announcement)deferred = 0for delivery in pending:try:- if not _deliver_to_channel(team_id, delivery, announcement.message):+ if not _deliver_to_channel(team_id, delivery, announcement.message, sender):deferred += 1except SupportSlackNotConfigured:logger.warning("announcement_no_slack_credentials", announcement_id=announcement_id, team_id=team_id)@@ -154,14 +215,23 @@ def send_pending_deliveries(announcement_id: str, team_id: int) -> None:raise AnnouncementRateLimited(f"{deferred} channel(s) rate limited")-def _deliver_to_channel(team_id: int, delivery: AnnouncementDelivery, message: str) -> bool:+def _announcement_sender(announcement: Announcement) -> SupportSlackSender | None:+ """The Slack identity to post under, or ``None`` to post as the SupportHog bot."""+ if announcement.send_as != Announcement.SendAs.USER or not announcement.sender_display_name:+ return None+ return SupportSlackSender(name=announcement.sender_display_name, icon_url=announcement.sender_icon_url)+++def _deliver_to_channel(+ team_id: int, delivery: AnnouncementDelivery, message: str, sender: SupportSlackSender | None = None+) -> bool:was_rate_limit_deferred = delivery.error == DELIVERY_RATE_LIMIT_DEFERRED_ERROR# Claim the row before posting so a crash between the Slack post and the outcome save# can never lead to a double post on retry.delivery.error = DELIVERY_IN_FLIGHT_ERRORdelivery.save(update_fields=["error", "updated_at"])try:- delivery.slack_message_ts = post_support_message(team_id, delivery.slack_channel_id, message)+ delivery.slack_message_ts = post_support_message(team_id, delivery.slack_channel_id, message, sender=sender)delivery.status = AnnouncementDelivery.Status.SENTdelivery.sent_at = timezone.now()delivery.error = ""diff --git a/products/customer_analytics/backend/migrations/0061_announcement_send_as.py b/products/customer_analytics/backend/migrations/0061_announcement_send_as.pynew file mode 100644index 000000000000..bff10d174579--- /dev/null+++ b/products/customer_analytics/backend/migrations/0061_announcement_send_as.py@@ -0,0 +1,31 @@+# Generated by Django 5.2.17 on 2026-09-18 10:30++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("customer_analytics", "0060_teamcustomeranalyticsconfig_default_pinned_properties"),+ ]++ operations = [+ migrations.AddField(+ model_name="announcement",+ name="send_as",+ field=models.CharField(+ choices=[("bot", "SupportHog"), ("user", "The person who created it")],+ default="bot",+ max_length=20,+ ),+ ),+ migrations.AddField(+ model_name="announcement",+ name="sender_display_name",+ field=models.CharField(blank=True, default="", max_length=200),+ ),+ migrations.AddField(+ model_name="announcement",+ name="sender_icon_url",+ field=models.TextField(blank=True, default=""),+ ),+ ]diff --git a/products/customer_analytics/backend/migrations/max_migration.txt b/products/customer_analytics/backend/migrations/max_migration.txtindex db8c804c4757..e575e1ba50bb 100644--- a/products/customer_analytics/backend/migrations/max_migration.txt+++ b/products/customer_analytics/backend/migrations/max_migration.txt@@ -1 +1 @@-0060_teamcustomeranalyticsconfig_default_pinned_properties+0061_announcement_send_asdiff --git a/products/customer_analytics/backend/models/announcement.py b/products/customer_analytics/backend/models/announcement.pyindex 92282d2ab874..2cc25ceb1164 100644--- a/products/customer_analytics/backend/models/announcement.py+++ b/products/customer_analytics/backend/models/announcement.py@@ -15,6 +15,10 @@ class Announcement(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetPARTIALLY_FAILED = "partially_failed", "Partially failed"FAILED = "failed", "Failed"+ class SendAs(models.TextChoices):+ BOT = "bot", "SupportHog"+ USER = "user", "The person who created it"+all_teams = models.Manager() # noqa: DJ012team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")@@ -25,6 +29,12 @@ class Announcement(TeamScopedRootMixin, UUIDModel, CreatedMetaFields, UpdatedMetshort_id = models.CharField(max_length=12, blank=True, default=generate_short_id)message = models.TextField()status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)+ send_as = models.CharField(max_length=20, choices=SendAs.choices, default=SendAs.BOT)+ # Slack name and avatar resolved from created_by when send_as is USER. Snapshotted at+ # create time so every channel gets the same identity, even if the Slack profile+ # changes (or becomes unresolvable) while the send task runs.+ sender_display_name = models.CharField(max_length=200, blank=True, default="")+ sender_icon_url = models.TextField(blank=True, default="")total_channels = models.PositiveIntegerField(default=0)sent_count = models.PositiveIntegerField(default=0)failed_count = models.PositiveIntegerField(default=0)diff --git a/products/customer_analytics/backend/presentation/views/announcements.py b/products/customer_analytics/backend/presentation/views/announcements.pyindex 2dab0561a9eb..be56d6719b87 100644--- a/products/customer_analytics/backend/presentation/views/announcements.py+++ b/products/customer_analytics/backend/presentation/views/announcements.py@@ -33,6 +33,11 @@ _ANNOUNCEMENT_STATUS_CHOICES = [("failed", "Failed"),]+_ANNOUNCEMENT_SEND_AS_CHOICES = [+ ("bot", "SupportHog"),+ ("user", "The person who created it"),+]+_DELIVERY_STATUS_CHOICES = [("pending", "Pending"),("sent", "Sent"),@@ -88,6 +93,16 @@ class AnnouncementSerializer(DataclassSerializer):choices=_ANNOUNCEMENT_STATUS_CHOICES,help_text="Overall status: pending, sending, sent, partially_failed, or failed.",)+ send_as = serializers.ChoiceField(+ choices=_ANNOUNCEMENT_SEND_AS_CHOICES,+ default="bot",+ help_text="Slack identity the message is posted under: 'bot' posts as SupportHog, 'user' posts under the "+ "Slack name and avatar of the person sending it (matched by their PostHog email).",+ )+ sender_display_name = serializers.CharField(+ read_only=True,+ help_text="Slack display name the message was posted under when send_as is 'user'; empty otherwise.",+ )total_channels = serializers.IntegerField(read_only=True, help_text="Number of channels this announcement targets.")sent_count = serializers.IntegerField(read_only=True, help_text="Number of channels the message was successfully delivered to."@@ -118,6 +133,8 @@ class AnnouncementSerializer(DataclassSerializer):"short_id","message","status",+ "send_as",+ "sender_display_name","total_channels","sent_count","failed_count",@@ -178,13 +195,18 @@ class AnnouncementViewSet(user=cast(User, request.user),message=data.message,channels=data.channels,+ send_as=data.send_as,)except AnnouncementValidationError as e:raise serializers.ValidationError(e.detail)report_user_action(request.user,"customer analytics announcement created",- {"id": str(announcement.id), "channel_count": announcement.total_channels},+ {+ "id": str(announcement.id),+ "channel_count": announcement.total_channels,+ "send_as": announcement.send_as,+ },team=self.team,request=request,)diff --git a/products/customer_analytics/backend/test/test_announcements.py b/products/customer_analytics/backend/test/test_announcements.pyindex 2f7be5feb20b..a0e8c63877a4 100644--- a/products/customer_analytics/backend/test/test_announcements.py+++ b/products/customer_analytics/backend/test/test_announcements.py@@ -8,17 +8,27 @@ from rest_framework import statusfrom posthog.models.team import Team-from products.conversations.backend.facade.api import SupportChannel, SupportSlackNotConfigured+from products.conversations.backend.facade.api import (+ SupportChannel,+ SupportSenderIdentityUnavailable,+ SupportSlackNotConfigured,+ SupportSlackSender,+)from products.customer_analytics.backend.models import Announcement, AnnouncementDeliveryfrom products.customer_analytics.backend.test.factories import create_account as create_account_rowHELPER = "products.customer_analytics.backend.logic.announcements.list_support_bot_channels"+SENDER = "products.customer_analytics.backend.logic.announcements.resolve_support_slack_sender"class TestAnnouncementAPI(APIBaseTest):def setUp(self):super().setUp()self.base_url = f"/api/projects/{self.team.pk}/announcements/"+ # Sending as yourself requires a verified address; the signed-in-and-verified user is the+ # normal case, so the unverified one gets its own test rather than this default.+ self.user.is_email_verified = True+ self.user.save()def _member_channels(self):return [@@ -78,6 +88,115 @@ class TestAnnouncementAPI(APIBaseTest):assert by_channel["D_secret_dm"].error == "not_in_channel"assert by_channel["C1"].status == AnnouncementDelivery.Status.SENT+ @patch("products.customer_analytics.backend.presentation.views.announcements.report_user_action")+ @patch(HELPER)+ def test_create_defaults_to_sending_as_the_bot(self, mock_channels, _mock_report):+ mock_channels.return_value = self._member_channels()++ response = self.client.post(self.base_url, {"message": "hi", "channels": ["C1"]}, format="json")++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["send_as"] == "bot"+ assert response.json()["sender_display_name"] == ""++ @patch("products.customer_analytics.backend.logic.announcements.post_support_message")+ @patch(SENDER)+ @patch(HELPER)+ def test_create_as_user_snapshots_the_slack_profile_and_posts_under_it(self, mock_channels, mock_sender, mock_post):+ mock_channels.return_value = self._member_channels()+ mock_sender.return_value = SupportSlackSender(name="Ada", icon_url="https://example.com/ada.png")+ mock_post.return_value = "1.0"++ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(+ self.base_url, {"message": "hi", "channels": ["C1"], "send_as": "user"}, format="json"+ )++ assert response.status_code == status.HTTP_201_CREATED, response.json()+ assert response.json()["send_as"] == "user"+ assert response.json()["sender_display_name"] == "Ada"+ mock_sender.assert_called_once_with(self.team.pk, self.user.email)+ assert mock_post.call_args.kwargs["sender"] == SupportSlackSender(+ name="Ada", icon_url="https://example.com/ada.png"+ )++ @patch(SENDER)+ @patch(HELPER)+ def test_create_as_user_rejects_when_no_slack_user_matches_the_email(self, mock_channels, mock_sender):+ mock_channels.return_value = self._member_channels()+ mock_sender.return_value = None++ response = self.client.post(+ self.base_url, {"message": "hi", "channels": ["C1"], "send_as": "user"}, format="json"+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ # Field-keyed errors flatten to detail + attr, which is what the composer reads to tell+ # the sender why this failed rather than showing a generic toast.+ assert self.user.email in response.json()["detail"]+ assert response.json()["attr"] == "send_as"+ # Nothing is sent as SupportHog behind the user's back.+ assert Announcement.all_teams.count() == 0++ @patch(SENDER)+ @patch(HELPER)+ def test_create_as_user_rejects_an_install_that_cannot_post_a_custom_identity(self, mock_channels, mock_sender):+ mock_channels.return_value = self._member_channels()+ mock_sender.side_effect = SupportSenderIdentityUnavailable()++ response = self.client.post(+ self.base_url, {"message": "hi", "channels": ["C1"], "send_as": "user"}, format="json"+ )++ # Otherwise every channel gets a delivery row that Slack rejects one at a time.+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert "reconnect" in response.json()["detail"]+ assert response.json()["attr"] == "send_as"+ assert Announcement.all_teams.count() == 0++ @patch(SENDER)+ @patch(HELPER)+ def test_create_as_user_rejects_an_unverified_email(self, mock_channels, mock_sender):+ mock_channels.return_value = self._member_channels()+ self.user.is_email_verified = None # never confirmed, e.g. an instance with no email delivery+ self.user.save()++ response = self.client.post(+ self.base_url, {"message": "hi", "channels": ["C1"], "send_as": "user"}, format="json"+ )++ # Otherwise a self-asserted address decides whose name and avatar reach the customer.+ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.json()["attr"] == "send_as"+ mock_sender.assert_not_called()+ assert Announcement.all_teams.count() == 0++ @patch(SENDER)+ @patch(HELPER)+ def test_create_as_bot_does_not_require_a_verified_email(self, mock_channels, mock_sender):+ mock_channels.return_value = self._member_channels()+ self.user.is_email_verified = False+ self.user.save()++ response = self.client.post(self.base_url, {"message": "hi", "channels": ["C1"]}, format="json")++ # The bot posts under its own identity, so the sender's address is irrelevant to it.+ assert response.status_code == status.HTTP_201_CREATED, response.json()+ mock_sender.assert_not_called()++ @patch(SENDER)+ @patch(HELPER)+ def test_create_rejects_an_unknown_sender(self, mock_channels, mock_sender):+ mock_channels.return_value = self._member_channels()++ response = self.client.post(+ self.base_url, {"message": "hi", "channels": ["C1"], "send_as": "someone_else"}, format="json"+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ mock_sender.assert_not_called()+ assert Announcement.all_teams.count() == 0+@patch(HELPER)def test_create_rejects_when_slack_not_connected(self, mock_channels):mock_channels.side_effect = SupportSlackNotConfigured()diff --git a/products/customer_analytics/backend/test/test_send_announcement.py b/products/customer_analytics/backend/test/test_send_announcement.pyindex 36240c2cd5ad..3d5c0f249f86 100644--- a/products/customer_analytics/backend/test/test_send_announcement.py+++ b/products/customer_analytics/backend/test/test_send_announcement.py@@ -1,7 +1,11 @@from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch-from products.conversations.backend.facade.api import SupportMessageSendError, SupportSlackNotConfigured+from products.conversations.backend.facade.api import (+ SupportMessageSendError,+ SupportSlackNotConfigured,+ SupportSlackSender,+)from products.customer_analytics.backend.constants import DELIVERY_IN_FLIGHT_ERROR, DELIVERY_INTERRUPTED_ERRORfrom products.customer_analytics.backend.logic.announcements import AnnouncementRateLimitedfrom products.customer_analytics.backend.models import Announcement, AnnouncementDelivery@@ -11,9 +15,13 @@ POST = "products.customer_analytics.backend.logic.announcements.post_support_mesclass TestSendAnnouncement(BaseTest):- def _make(self, channel_ids: list[str], message: str = "hi") -> Announcement:+ def _make(self, channel_ids: list[str], message: str = "hi", **fields) -> Announcement:announcement = Announcement.all_teams.create(- team=self.team, message=message, total_channels=len(channel_ids), status=Announcement.Status.PENDING+ team=self.team,+ message=message,+ total_channels=len(channel_ids),+ status=Announcement.Status.PENDING,+ **fields,)for channel_id in channel_ids:AnnouncementDelivery.all_teams.create(@@ -38,9 +46,43 @@ class TestSendAnnouncement(BaseTest):assert mock_post.call_count == 2assert self._delivery(announcement, "C1").slack_message_ts == "111.222"+ @patch(POST)+ def test_posts_as_the_creator_when_send_as_is_user(self, mock_post: MagicMock):+ mock_post.return_value = "1.0"++ announcement = self._make(+ ["C1"],+ send_as=Announcement.SendAs.USER,+ sender_display_name="Ada",+ sender_icon_url="https://example.com/ada.png",+ )+ send_announcement(str(announcement.id), self.team.pk)++ assert mock_post.call_args.kwargs["sender"] == SupportSlackSender(+ name="Ada", icon_url="https://example.com/ada.png"+ )++ @patch(POST)+ def test_posts_as_the_bot_by_default(self, mock_post: MagicMock):+ mock_post.return_value = "1.0"++ send_announcement(str(self._make(["C1"]).id), self.team.pk)++ assert mock_post.call_args.kwargs["sender"] is None++ @patch(POST)+ def test_falls_back_to_the_bot_when_no_sender_was_snapshotted(self, mock_post: MagicMock):+ mock_post.return_value = "1.0"++ # Nothing resolved the Slack profile, so there is no identity to post under.+ announcement = self._make(["C1"], send_as=Announcement.SendAs.USER)+ send_announcement(str(announcement.id), self.team.pk)++ assert mock_post.call_args.kwargs["sender"] is None+@patch(POST)def test_one_channel_failure_is_isolated(self, mock_post: MagicMock):- def fake_post(team_id: int, channel_id: str, text: str) -> str:+ def fake_post(team_id: int, channel_id: str, text: str, **kwargs) -> str:if channel_id == "Cfail":raise SupportMessageSendError("not_in_channel")return "1.0"diff --git a/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.test.tsx b/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.test.tsxindex 1a210a212d85..a2120f3073cd 100644--- a/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.test.tsx+++ b/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.test.tsx@@ -5,8 +5,11 @@ import '@testing-library/jest-dom'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { Provider } from 'kea'+import { userLogic } from 'scenes/userLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import type { UserType } from '~/types'import { announcementsLogic } from './announcementsLogic'import { AnnouncementsTabContent } from './AnnouncementsTabContent'@@ -45,6 +48,12 @@ describe('AnnouncementsTabContent', () => {})function renderComposer(): void {+ userLogic.actions.loadUserSuccess({+ id: 7,+ first_name: 'Ada',+ email: '[email protected]',+ is_email_verified: true,+ } as UserType)logic.actions.setMessage('Offsite this week')logic.actions.setSelectedChannelIds(['C1', 'C2'])render(@@ -79,6 +88,49 @@ describe('AnnouncementsTabContent', () => {await waitFor(() => expect(document.querySelector('[data-attr="confirm-send-announcement"]')).not.toBeNull())fireEvent.click(document.querySelector('[data-attr="confirm-send-announcement"]')!)- await waitFor(() => expect(postedBodies).toEqual([{ message: 'Offsite this week', channels: ['C1', 'C2'] }]))+ await waitFor(() =>+ expect(postedBodies).toEqual([{ message: 'Offsite this week', channels: ['C1', 'C2'], send_as: 'bot' }])+ )+ })++ // An unverified address cannot be shown to prove the Slack profile is theirs, so the option is+ // closed off here rather than failing after they have written the message and picked channels.+ it('disables sending as yourself until the email address is verified', async () => {+ renderComposer()+ userLogic.actions.loadUserSuccess({+ id: 7,+ first_name: 'Ada',+ email: '[email protected]',+ is_email_verified: null,+ } as UserType)++ // LemonButton marks a disabledReason button aria-disabled, keeping it focusable so the+ // tooltip can explain why.+ await waitFor(() =>+ expect(document.querySelector('[data-attr="announcement-send-as-user"]')).toHaveAttribute(+ 'aria-disabled',+ 'true'+ )+ )+ expect(document.querySelector('[data-attr="announcement-send-as-bot"]')).toHaveAttribute(+ 'aria-disabled',+ 'false'+ )+ })++ // The sender is what the customer sees, so the confirmation has to name it — the mistake+ // this option fixes is realising after the fact that the message went out as SupportHog.+ it('sends as the current user once their name is picked, and names them in the confirmation', async () => {+ renderComposer()++ fireEvent.click(document.querySelector('[data-attr="announcement-send-as-user"]')!)+ clickSend()++ await waitFor(() => expect(screen.getByText('Ada', { selector: 'strong' })).toBeInTheDocument())+ fireEvent.click(document.querySelector('[data-attr="confirm-send-announcement"]')!)++ await waitFor(() =>+ expect(postedBodies).toEqual([{ message: 'Offsite this week', channels: ['C1', 'C2'], send_as: 'user' }])+ )})})diff --git a/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.tsx b/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.tsxindex a258477da748..c130014be324 100644--- a/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.tsx+++ b/products/customer_analytics/frontend/components/Announcements/AnnouncementsTabContent.tsx@@ -5,6 +5,7 @@ import {LemonButton,LemonDialog,LemonInputSelect,+ LemonSegmentedButton,LemonSnack,LemonTable,LemonTableColumns,@@ -17,6 +18,7 @@ import { TZLabel } from 'lib/components/TZLabel'import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'+import { AnnouncementSendAsEnumApi } from '../../generated/api.schemas'import type { AnnouncementApi, AnnouncementDeliveryApi } from '../../generated/api.schemas'import { AnnouncementAccountFilters } from './AnnouncementAccountFilters'import { announcementsLogic } from './announcementsLogic'@@ -38,12 +40,20 @@ function announcementStatusTag(status: AnnouncementApi['status']): { type: TagTy}}-function ConfirmSendContent({ message, channelLabels }: { message: string; channelLabels: string[] }): JSX.Element {+function ConfirmSendContent({+ message,+ channelLabels,+ senderLabel,+}: {+ message: string+ channelLabels: string[]+ senderLabel: string+}): JSX.Element {return (<div className="flex flex-col gap-2 max-w-[500px]"><p className="m-0">- This message will be posted to {pluralize(channelLabels.length, 'customer channel')}. Sending cannot be- undone.+ This message will be posted to {pluralize(channelLabels.length, 'customer channel')} as{' '}+ <strong>{senderLabel}</strong>. Sending cannot be undone.</p><div className="border rounded p-2 bg-surface-secondary whitespace-pre-wrap max-h-40 overflow-y-auto">{message}@@ -66,13 +76,25 @@ function AnnouncementComposer(): JSX.Element {memberChannelsLoading,submitting,submitDisabledReason,+ sendAs,+ senderName,+ senderDisabledReason,} = useValues(announcementsLogic)- const { setMessage, setSelectedChannelIds, submitAnnouncement, loadMemberChannels } = useActions(announcementsLogic)+ const { setMessage, setSelectedChannelIds, setSendAs, submitAnnouncement, loadMemberChannels } =+ useActions(announcementsLogic)++ const senderLabel = sendAs === AnnouncementSendAsEnumApi.User ? senderName : 'SupportHog'const confirmSend = (): void => {LemonDialog.open({title: `Send this announcement to ${pluralize(selectedChannelLabels.length, 'channel')}?`,- content: <ConfirmSendContent message={messageDraft.trim()} channelLabels={selectedChannelLabels} />,+ content: (+ <ConfirmSendContent+ message={messageDraft.trim()}+ channelLabels={selectedChannelLabels}+ senderLabel={senderLabel}+ />+ ),primaryButton: {children: 'Send',onClick: submitAnnouncement,@@ -86,6 +108,29 @@ function AnnouncementComposer(): JSX.Element {return (<div className="flex flex-col gap-2 max-w-[800px]">+ <div className="flex items-center gap-2">+ <span className="text-secondary">Send as</span>+ <LemonSegmentedButton+ size="small"+ value={sendAs}+ onChange={setSendAs}+ options={[+ {+ value: AnnouncementSendAsEnumApi.Bot,+ label: 'SupportHog',+ 'data-attr': 'announcement-send-as-bot',+ },+ {+ value: AnnouncementSendAsEnumApi.User,+ label: senderName,+ disabledReason: senderDisabledReason,+ tooltip:+ 'Posts under your Slack name and photo, matched by your PostHog email. Slack still marks the message as an app.',+ 'data-attr': 'announcement-send-as-user',+ },+ ]}+ />+ </div><LemonTextAreavalue={messageDraft}onChange={setMessage}@@ -194,6 +239,14 @@ function AnnouncementHistory(): JSX.Element {key: 'created_by',render: (_, announcement) => announcement.created_by?.first_name || announcement.created_by?.email || '—',},+ {+ title: 'Sent as',+ key: 'send_as',+ render: (_, announcement) =>+ announcement.send_as === AnnouncementSendAsEnumApi.User+ ? announcement.sender_display_name || '—'+ : 'SupportHog',+ },]return (diff --git a/products/customer_analytics/frontend/components/Announcements/announcementsLogic.test.ts b/products/customer_analytics/frontend/components/Announcements/announcementsLogic.test.tsindex c9f4997742e1..0e3c92e5a25a 100644--- a/products/customer_analytics/frontend/components/Announcements/announcementsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Announcements/announcementsLogic.test.ts@@ -107,6 +107,32 @@ describe('announcementsLogic', () => {expect(logic.values.submitting).toBe(false)})+ it('labels the sender option with the current user and defaults to the bot', async () => {+ logic = announcementsLogic()+ logic.mount()+ await expectLogic(logic).toMatchValues({ sendAs: 'bot' })++ userLogic.actions.loadUserSuccess({+ id: 7,+ first_name: 'Ada',+ email: '[email protected]',+ is_email_verified: true,+ } as UserType)+ await expectLogic(logic).toMatchValues({ senderName: 'Ada', senderDisabledReason: undefined })++ // A legacy account that never confirmed its address reads as unverified, same as the backend.+ userLogic.actions.loadUserSuccess({ id: 7, first_name: 'Ada', is_email_verified: null } as UserType)+ await expectLogic(logic).toMatchValues({+ senderDisabledReason: 'Verify your email address to send announcements as yourself',+ })++ userLogic.actions.loadUserSuccess({ id: 7, first_name: '', email: '' } as UserType)+ await expectLogic(logic).toMatchValues({ senderName: 'you' })++ logic.actions.setSendAs('user')+ await expectLogic(logic).toMatchValues({ sendAs: 'user' })+ })+it('narrows the channel picker to filtered accounts and bulk-selects them', async () => {useMocks({get: {diff --git a/products/customer_analytics/frontend/components/Announcements/announcementsLogic.ts b/products/customer_analytics/frontend/components/Announcements/announcementsLogic.tsindex c73c8694920f..ff9e6231ca71 100644--- a/products/customer_analytics/frontend/components/Announcements/announcementsLogic.ts+++ b/products/customer_analytics/frontend/components/Announcements/announcementsLogic.ts@@ -12,6 +12,7 @@ import { AccountsQuery, NodeKind } from '~/queries/schema/schema-general'import type { TeamPublicType, TeamType, UserType } from '../../../../../frontend/src/types'import { CUSTOMER_ANALYTICS_DEFAULT_QUERY_TAGS } from '../../constants'import { announcementsChannelsList, announcementsCreate, announcementsList } from '../../generated/api'+import { AnnouncementSendAsEnumApi } from '../../generated/api.schemas'import type { AnnouncementApi, AnnouncementChannelApi } from '../../generated/api.schemas'// The account channel id lives in the account's JSON properties, not a top-level@@ -56,6 +57,9 @@ export interface announcementsLogicValues {messageDraft: stringselectedChannelIds: string[]selectedChannelLabels: string[]+ sendAs: AnnouncementSendAsEnumApi+ senderDisabledReason: string | undefined+ senderName: stringslackConnected: booleansubmitDisabledReason: string | undefinedsubmitting: boolean@@ -142,6 +146,9 @@ export interface announcementsLogicActions {setSelectedChannelIds: (channelIds: string[]) => {channelIds: string[]}+ setSendAs: (sendAs: AnnouncementSendAsEnumApi) => {+ sendAs: AnnouncementSendAsEnumApi+ }setSubmitting: (submitting: boolean) => {submitting: boolean}@@ -158,6 +165,8 @@ export interface announcementsLogicMeta {__keaTypeGenInternalSelectorTypes: {slackConnected: (currentTeam: TeamPublicType | TeamType | null) => booleancurrentUserId: (user: UserType | null) => number | null+ senderName: (user: UserType | null) => string+ senderDisabledReason: (user: UserType | null) => string | undefinedfiltersActive: (accountSearch: string, accountTags: string[], assignmentStatus: AssignmentStatus) => booleanassignedToCurrentUser: (assignedTo: number[], currentUserId: number | null) => booleanfilteredChannels: (@@ -207,6 +216,7 @@ export const announcementsLogic = kea<announcementsLogicType>([actions({setMessage: (message: string) => ({ message }),setSelectedChannelIds: (channelIds: string[]) => ({ channelIds }),+ setSendAs: (sendAs: AnnouncementSendAsEnumApi) => ({ sendAs }),submitAnnouncement: true,setSubmitting: (submitting: boolean) => ({ submitting }),setAccountSearch: (search: string) => ({ search }),@@ -297,6 +307,10 @@ export const announcementsLogic = kea<announcementsLogicType>([reducers({messageDraft: ['', { setMessage: (_state, { message }) => message }],selectedChannelIds: [[] as string[], { setSelectedChannelIds: (_state, { channelIds }) => channelIds }],+ sendAs: [+ AnnouncementSendAsEnumApi.Bot as AnnouncementSendAsEnumApi,+ { setSendAs: (_state, { sendAs }) => sendAs },+ ],submitting: [false, { setSubmitting: (_state, { submitting }) => submitting }],accountSearch: ['', { setAccountSearch: (_state, { search }) => search }],accountTags: [[] as string[], { setAccountTags: (_state, { tags }) => tags }],@@ -310,6 +324,18 @@ export const announcementsLogic = kea<announcementsLogicType>([!!currentTeam?.conversations_settings?.slack_enabled,],currentUserId: [(s) => [s.user], (user: UserType | null): number | null => user?.id ?? null],+ // Label for the "send as me" option. The name Slack renders comes from the user's Slack+ // profile, which the backend resolves by email at send time, so this is only a label.+ senderName: [(s) => [s.user], (user: UserType | null): string => user?.first_name || user?.email || 'you'],+ // The backend refuses an unverified address, so say so on the option instead of letting the+ // send fail: it is the email that decides whose name and avatar the customer sees.+ senderDisabledReason: [+ (s) => [s.user],+ (user: UserType | null): string | undefined =>+ user?.is_email_verified === true+ ? undefined+ : 'Verify your email address to send announcements as yourself',+ ],filtersActive: [(s) => [s.accountSearch, s.accountTags, s.assignmentStatus],(accountSearch: string, accountTags: string[], assignmentStatus: AssignmentStatus): boolean =>@@ -433,13 +459,15 @@ export const announcementsLogic = kea<announcementsLogicType>([await announcementsCreate(String(values.currentTeam?.id), {message: values.messageDraft.trim(),channels: values.selectedChannelIds,+ send_as: values.sendAs,})lemonToast.success('Announcement sent')actions.setMessage('')actions.setSelectedChannelIds([])actions.loadAnnouncements()- } catch {- lemonToast.error('Failed to send announcement')+ } catch (error) {+ const detail = (error as { detail?: string } | null)?.detail+ lemonToast.error(detail || 'Failed to send announcement')} finally {actions.setSubmitting(false)}diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 1323e6c9eab0..bd783386e41e 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -2577,6 +2577,17 @@ export const AnnouncementStatusEnumApi = {Failed: 'failed',} as const+/**+ * * `bot` - SupportHog+ * * `user` - The person who created it+ */+export type AnnouncementSendAsEnumApi = (typeof AnnouncementSendAsEnumApi)[keyof typeof AnnouncementSendAsEnumApi]++export const AnnouncementSendAsEnumApi = {+ Bot: 'bot',+ User: 'user',+} as const+/*** * `pending` - Pending* * `sent` - Sent@@ -2628,6 +2639,13 @@ export interface AnnouncementApi {* * `partially_failed` - Partially failed* * `failed` - Failed */readonly status: AnnouncementStatusEnumApi+ /** Slack identity the message is posted under: 'bot' posts as SupportHog, 'user' posts under the Slack name and avatar of the person sending it (matched by their PostHog email).+ *+ * * `bot` - SupportHog+ * * `user` - The person who created it */+ send_as?: AnnouncementSendAsEnumApi+ /** Slack display name the message was posted under when send_as is 'user'; empty otherwise. */+ readonly sender_display_name: string/** Number of channels this announcement targets. */readonly total_channels: number/** Number of channels the message was successfully delivered to. */diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 9fd05a7fb4da..eaab9845a741 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -576,8 +576,17 @@ export const CustomerAnalyticsAccountsTableQueryCreateBody = /* @__PURE__ */ zod.record(zod.string(), zod.unknown()).describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')+export const announcementsCreateBodySendAsDefault = `bot`+export const AnnouncementsCreateBody = /* @__PURE__ */ zod.object({message: zod.string().describe('Message body to send, rendered as Slack mrkdwn.'),+ send_as: zod+ .enum(['bot', 'user'])+ .describe('\* `bot` - SupportHog\n\* `user` - The person who created it')+ .default(announcementsCreateBodySendAsDefault)+ .describe(+ "Slack identity the message is posted under: 'bot' posts as SupportHog, 'user' posts under the Slack name and avatar of the person sending it (matched by their PostHog email).\n\n\* `bot` - SupportHog\n\* `user` - The person who created it"+ ),channels: zod.array(zod.string()).describe(diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f51b8b20ab0a..6d8d167f8d4f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12215,6 +12215,18 @@ export namespace Schemas {Failed: 'failed',} as const;+ /**+ * * `bot` - SupportHog+ * * `user` - The person who created it+ */+ export type AnnouncementSendAsEnum = typeof AnnouncementSendAsEnum[keyof typeof AnnouncementSendAsEnum];+++ export const AnnouncementSendAsEnum = {+ Bot: 'bot',+ User: 'user',+ } as const;+/*** * `pending` - Pending* * `sent` - Sent@@ -12266,6 +12278,13 @@ export namespace Schemas {* * `partially_failed` - Partially failed* * `failed` - Failed */readonly status: AnnouncementStatusEnum;+ /** Slack identity the message is posted under: 'bot' posts as SupportHog, 'user' posts under the Slack name and avatar of the person sending it (matched by their PostHog email).+ *+ * * `bot` - SupportHog+ * * `user` - The person who created it */+ send_as?: AnnouncementSendAsEnum;+ /** Slack display name the message was posted under when send_as is 'user'; empty otherwise. */+ readonly sender_display_name: string;/** Number of channels this announcement targets. */readonly total_channels: number;/** Number of channels the message was successfully delivered to. */diff --git a/services/mcp/src/generated/customer_analytics/api.ts b/services/mcp/src/generated/customer_analytics/api.tsindex 3006cae96ca0..d1d84895718f 100644--- a/services/mcp/src/generated/customer_analytics/api.ts+++ b/services/mcp/src/generated/customer_analytics/api.ts@@ -496,8 +496,17 @@ export const AnnouncementsCreateParams = () => zod.object({),})+export const announcementsCreateBodySendAsDefault = `bot`+export const AnnouncementsCreateBody = () => zod.object({message: zod.string().describe('Message body to send, rendered as Slack mrkdwn.'),+ send_as: zod+ .enum(['bot', 'user'])+ .describe('\* `bot` - SupportHog\n\* `user` - The person who created it')+ .default(announcementsCreateBodySendAsDefault)+ .describe(+ "Slack identity the message is posted under: 'bot' posts as SupportHog, 'user' posts under the Slack name and avatar of the person sending it (matched by their PostHog email).\n\n\* `bot` - SupportHog\n\* `user` - The person who created it"+ ),channels: zod.array(zod.string()).describe(diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.tsindex 2cf564e555db..946921a7c4b0 100644--- a/services/mcp/src/tools/generated/customer_analytics.ts+++ b/services/mcp/src/tools/generated/customer_analytics.ts@@ -716,6 +716,9 @@ const announcementsCreateExecute = (): ToolBase<typeof AnnouncementsCreateSchemaif (params.message !== undefined) {body['message'] = params.message}+ if (params.send_as !== undefined) {+ body['send_as'] = params.send_as+ }if (params.channels !== undefined) {body['channels'] = params.channels}