: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
refactor(comments): extract shared Slack/comment primitives into core (#66841)
Luke Beltonfc4addf2f370
diff --git a/posthog/comment/__init__.py b/posthog/comment/__init__.pynew file mode 100644index 000000000000..c7ab1b55ecc5--- /dev/null+++ b/posthog/comment/__init__.py@@ -0,0 +1,6 @@+"""Cross-channel logic shared by anything that mirrors comment threads to external surfaces.++Sits alongside the ``posthog.models.comment`` data layer: this package holds the+channel-agnostic content conversion and Slack identity helpers reused by the+conversations (support) product and core discussions.+"""diff --git a/products/conversations/backend/formatting.py b/posthog/comment/formatting.pysimilarity index 94%rename from products/conversations/backend/formatting.pyrename to posthog/comment/formatting.pyindex 69bdd8b4043a..57f4dc25704b 100644--- a/products/conversations/backend/formatting.py+++ b/posthog/comment/formatting.py@@ -5,6 +5,7 @@ import html as html_modimport unicodedatafrom collections.abc import Iterablefrom typing import Any+from uuid import UUIDJSON = dict[str, Any]@@ -31,6 +32,18 @@ _RE_MD_ESCAPE = re.compile(r"([\\`*_{}\[\]()#+\-.!|])")_RE_MD_ESCAPED_CHAR = re.compile(r"\\([\\`*_{}\[\]()#+\-.!|])")_RE_ALT_ESCAPE = re.compile(r"([\\\]])")_RE_SLACK_EMOJI = re.compile(r":([a-z0-9_+\-]+):")+_RE_MRKDWN_BLOCKQUOTE_UNESCAPE = re.compile(r"^>", re.MULTILINE)+++def escape_slack_mrkdwn(text: str) -> str:+ """Escape Slack mrkdwn control characters in user-supplied text.++ Unescaped `<...>` sequences are live in mrkdwn: `<!channel>` broadcasts,+ `<@U…>` pings a user, and `<url|label>` renders a disguised link.+ """+ if not text:+ return ""+ return text.replace("&", "&").replace("<", "<").replace(">", ">")def _slack_unicode_to_char(unicode_hex: str) -> str | None:@@ -161,18 +174,28 @@ def strip_slack_user_mentions(text: str) -> str:return _RE_SLACK_USER_MENTION.sub("", text)-def content_to_slack_mrkdwn(content: str) -> str:+def content_to_slack_mrkdwn(content: str, organization_id: str | UUID | None = None) -> str:"""Convert markdown comment content to Slack mrkdwn text.Backslash-escaped characters are unescaped: mrkdwn has no escape syntax, so amarkdown ``\\.`` would otherwise reach Slack as a literal backslash. They aremasked before the syntax conversions below so an escaped ``*`` is not mistakenfor emphasis.++ ``organization_id`` scopes ``@member:<uuid>`` resolution. The marker is author-controlled and+ the rendered text lands in someone's Slack workspace, so an unscoped lookup would let a comment+ pull a name or email out of another organization. Without an organization every marker falls+ back to the generic "@teammate"."""if not content:return ""- text = content+ # Escape mrkdwn control chars up front so user content can't inject links,+ # user mentions, or <!channel>-style broadcasts. The conversions below+ # generate their own <url|label> constructs on top of the escaped text.+ text = escape_slack_mrkdwn(content)+ # Markdown blockquote markers double as (inert) mrkdwn quotes — keep them.+ text = _RE_MRKDWN_BLOCKQUOTE_UNESCAPE.sub(">", text)escaped_chars: list[str] = []@@ -211,10 +234,12 @@ def content_to_slack_mrkdwn(content: str) -> str:def resolve_mention(match: re.Match) -> str:uuid_str = match.group(1)+ if organization_id is None:+ return "@teammate"try:from posthog.models import User- user = User.objects.filter(uuid=uuid_str).first()+ user = User.objects.filter(uuid=uuid_str, organization_membership__organization_id=organization_id).first()if user:name = f"{user.first_name} {user.last_name}".strip() or user.emailreturn f"@{name}"@@ -899,11 +924,16 @@ def rich_content_to_html(rich_content: JSON | None) -> str:def rich_content_to_slack_payload(- rich_content: JSON | None, fallback_content: str, include_images: bool = True+ rich_content: JSON | None,+ fallback_content: str,+ include_images: bool = True,+ organization_id: str | UUID | None = None,) -> tuple[str, list[JSON] | None]:"""Convert outbound app message to Slack payload fields.+ ``organization_id`` scopes mention resolution — see content_to_slack_mrkdwn.+Returns:- text (always present, used as fallback for notifications/older clients)- blocks (Slack rich_text blocks when rich_content is available)@@ -912,6 +942,6 @@ def rich_content_to_slack_payload(blocks = rich_content_to_slack_blocks(rich_content, include_images=include_images)markdown_text = rich_content_to_markdown(rich_content, include_images=include_images)source_content = markdown_text or fallback_content- return content_to_slack_mrkdwn(source_content), blocks+ return content_to_slack_mrkdwn(source_content, organization_id), blocks- return content_to_slack_mrkdwn(fallback_content), None+ return content_to_slack_mrkdwn(fallback_content, organization_id), Nonediff --git a/posthog/helpers/slack_identity.py b/posthog/helpers/slack_identity.pynew file mode 100644index 000000000000..c2aeb765e818--- /dev/null+++ b/posthog/helpers/slack_identity.py@@ -0,0 +1,159 @@+"""Slack identity resolution shared by anything that mirrors comment threads to/from Slack.++Token-agnostic: every function takes a ``slack_sdk.WebClient`` so the caller supplies the+workspace'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.+"""++from types import MappingProxyType++from django.core.cache import cache++import structlog+from slack_sdk import WebClient++from posthog.models.organization import OrganizationMembership+from posthog.models.team.team import Team+from posthog.models.user import User++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++_UNKNOWN_USER = MappingProxyType({"name": "Unknown", "email": None, "avatar": None})+++def _make_cache_key(prefix: str, *args: str) -> str:+ """Create a namespaced cache key."""+ key_parts = ":".join(str(arg) for arg in args)+ return f"slack_identity:{prefix}:{key_parts}"+++def get_cached_slack_user(slack_user_id: str, workspace: str) -> dict | None:+ """Get cached Slack user profile."""+ key = _make_cache_key("slack_user", workspace, slack_user_id)+ try:+ return cache.get(key)+ except Exception:+ logger.warning("slack_identity_cache_get_error", key=key)+ return None+++def set_cached_slack_user(slack_user_id: str, user_info: dict, workspace: str) -> None:+ """Cache a Slack user profile."""+ key = _make_cache_key("slack_user", workspace, slack_user_id)+ try:+ cache.set(key, user_info, timeout=SLACK_USER_CACHE_TTL)+ except Exception:+ 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())+ try:+ return cache.get(key)+ except Exception:+ logger.warning("slack_identity_cache_get_error", key=key)+ 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())+ try:+ cache.set(key, avatar_url, timeout=SLACK_AVATAR_CACHE_TTL)+ except Exception:+ logger.warning("slack_identity_cache_set_error", key=key)+++def resolve_slack_user(client: WebClient, slack_user_id: str, *, workspace: str) -> dict:+ """Resolve a Slack user ID to name, email, and avatar. Cached in Redis for 5 minutes.++ Slack user ids are only unique per workspace, so ``workspace`` (the Slack team id the+ event or integration is scoped to) namespaces the cache — a colliding id from another+ workspace can't be served from this one's cache.+ """+ if not slack_user_id:+ logger.warning("slack_user_resolve_empty_id")+ return dict(_UNKNOWN_USER)++ cached = get_cached_slack_user(slack_user_id, workspace)+ if cached is not None:+ return cached++ try:+ response = client.users_info(user=slack_user_id)+ raw_data = response.data if hasattr(response, "data") else None+ data: dict = raw_data if isinstance(raw_data, dict) else {}++ if not data.get("ok"):+ logger.warning(+ "slack_user_resolve_not_ok",+ slack_user_id=slack_user_id,+ error=data.get("error"),+ )+ return dict(_UNKNOWN_USER)++ user_data = data.get("user") or {}+ profile = user_data.get("profile") or {}+ name = profile.get("display_name") or profile.get("real_name") or "Unknown"+ result = {+ "name": name,+ "email": profile.get("email"),+ "avatar": profile.get("image_72"),+ }+ set_cached_slack_user(slack_user_id, result, workspace)+ return result+ except Exception as e:+ logger.warning("slack_user_resolve_failed", slack_user_id=slack_user_id, error=str(e))+ 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."""+ if not email:+ return None++ cached = get_cached_slack_avatar(email)+ if cached is not None:+ return cached or None # empty string = negative cache++ try:+ response = client.users_lookupByEmail(email=email)+ raw_data = response.data if hasattr(response, "data") else None+ data: dict = raw_data if isinstance(raw_data, dict) else {}++ if not data.get("ok"):+ set_cached_slack_avatar(email, "")+ return None++ profile = (data.get("user") or {}).get("profile") or {}+ avatar = profile.get("image_72") or ""+ set_cached_slack_avatar(email, avatar)+ return avatar or None+ except 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)+ return 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:+ return None+ membership = (+ OrganizationMembership.objects.filter(+ organization_id=team.organization_id,+ # Slack profile emails often differ in case from the stored PostHog email (IdP casing).+ user__email__iexact=email,+ )+ .select_related("user")+ .first()+ )+ return membership.user if membership else Nonediff --git a/posthog/helpers/tests/test_slack_identity.py b/posthog/helpers/tests/test_slack_identity.pynew file mode 100644index 000000000000..e4a633f9fd77--- /dev/null+++ b/posthog/helpers/tests/test_slack_identity.py@@ -0,0 +1,35 @@+from unittest.mock import MagicMock++from django.core.cache import cache+from django.test import SimpleTestCase++from posthog.helpers.slack_identity import resolve_slack_user+++def _client_returning(name: str, email: str) -> MagicMock:+ client = MagicMock()+ client.users_info.return_value.data = {+ "ok": True,+ "user": {"profile": {"display_name": name, "email": email, "image_72": None}},+ }+ return client+++class TestSlackIdentityWorkspaceNamespacing(SimpleTestCase):+ def setUp(self) -> None:+ cache.clear()++ def test_colliding_user_ids_in_different_workspaces_do_not_share_cache(self) -> None:+ workspace_a_client = _client_returning("Alice Internal", "[email protected]")+ workspace_b_client = _client_returning("Mallory External", "[email protected]")++ resolved_a = resolve_slack_user(workspace_a_client, "U12345", workspace="T_WORKSPACE_A")+ resolved_b = resolve_slack_user(workspace_b_client, "U12345", workspace="T_WORKSPACE_B")++ assert resolved_a["email"] == "[email protected]"+ assert resolved_b["email"] == "[email protected]"+ workspace_b_client.users_info.assert_called_once_with(user="U12345")++ # 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")diff --git a/products/conversations/backend/api/tests/test_formatting.py b/products/conversations/backend/api/tests/test_formatting.pyindex 08a08e5c902b..67666569ed92 100644--- a/products/conversations/backend/api/tests/test_formatting.py+++ b/products/conversations/backend/api/tests/test_formatting.py@@ -1,8 +1,10 @@+from posthog.test.base import BaseTest+from django.test import SimpleTestCasefrom parameterized import parameterized-from products.conversations.backend.formatting import (+from posthog.comment.formatting import (_slack_emoji_name_to_char,_slack_unicode_to_char,content_to_slack_mrkdwn,@@ -13,6 +15,7 @@ from products.conversations.backend.formatting import (rich_content_to_slack_payload,slack_to_content_and_rich_content,)+from posthog.models import Organization, Userdef _paragraph(text: str) -> dict:@@ -37,6 +40,19 @@ class TestSlackFormatting(SimpleTestCase):assert content == expectedassert rich_content is None+ @parameterized.expand(+ [+ ("channel_broadcast", "hey <!channel> look", "hey <!channel> look"),+ ("user_mention", "ping <@U12345>", "ping <@U12345>"),+ ("disguised_link", "<https://evil.com|posthog.com>", "<https://evil.com|posthog.com>"),+ ("ampersand", "a & b", "a & b"),+ ("md_link_still_converts", "[docs](https://posthog.com)", "<https://posthog.com|docs>"),+ ("blockquote_preserved", "> quoted", "> quoted"),+ ]+ )+ def test_outbound_mrkdwn_escapes_control_sequences(self, _name: str, content: str, expected: str) -> None:+ assert content_to_slack_mrkdwn(content) == expected+@parameterized.expand([("alias_thumbsup", ":+1:", "\U0001f44d"),@@ -462,6 +478,10 @@ class TestSlackFormatting(SimpleTestCase):assert "<@UXYZ999>" in contentassert rich_content is not None+ def test_mention_without_an_organization_stays_generic(self) -> None:+ # No organization means no scope to resolve within, so don't touch the database at all.+ assert content_to_slack_mrkdwn("hi @member:00000000-0000-0000-0000-000000000001") == "hi @teammate"+class TestRichContentBlockNodes(SimpleTestCase):@parameterized.expand(@@ -742,3 +762,21 @@ class TestRichContentBlockNodes(SimpleTestCase):}html = rich_content_to_html(doc)assert "<blockquote>see<br><ul><li>one</li></ul></blockquote>" in html+++class TestSlackMentionScoping(BaseTest):+ def test_mention_resolves_only_within_the_organization(self) -> None:+ # The @member marker is author-controlled and the rendered name lands in a Slack workspace,+ # so a UUID from another organization must not pull that person's name or email across.+ other_org = Organization.objects.create(name="other org")+ outsider = User.objects.create_and_join(other_org, "[email protected]", "password")+ self.user.first_name = "Insider"+ self.user.last_name = ""+ self.user.save()++ rendered = content_to_slack_mrkdwn(+ f"@member:{self.user.uuid} and @member:{outsider.uuid}", self.organization.id+ )++ assert rendered == "@Insider and @teammate"+ assert outsider.email not in rendereddiff --git a/products/conversations/backend/api/tests/test_reaction_backfill.py b/products/conversations/backend/api/tests/test_reaction_backfill.pyindex fd46036fcd67..b49619b0a699 100644--- a/products/conversations/backend/api/tests/test_reaction_backfill.py+++ b/products/conversations/backend/api/tests/test_reaction_backfill.py@@ -61,7 +61,7 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")comments = Comment.objects.filter(item_id=str(self.ticket.id)).order_by("created_at")assert comments.count() == 2@@ -81,7 +81,7 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")client.conversations_replies.assert_called_once_with(channel=CHANNEL, ts=PARENT_TS, limit=200)@@ -102,7 +102,7 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")comments = Comment.objects.filter(item_id=str(self.ticket.id))assert comments.count() == 1@@ -124,7 +124,7 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")comments = Comment.objects.filter(item_id=str(self.ticket.id))assert comments.count() == 1@@ -141,7 +141,7 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")comments = Comment.objects.filter(item_id=str(self.ticket.id))assert comments.count() == 1@@ -158,7 +158,7 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")comments = Comment.objects.filter(item_id=str(self.ticket.id))assert comments.count() == 1@@ -178,7 +178,7 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")comments = Comment.objects.filter(item_id=str(self.ticket.id))assert comments.count() == 1@@ -197,10 +197,12 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")assert mock_user.call_count == 2- mock_user.assert_has_calls([call(client, "U_SAME"), call(client, "U_OTHER")], any_order=True)+ mock_user.assert_has_calls(+ [call(client, "U_SAME", workspace="T123"), call(client, "U_OTHER", workspace="T123")], any_order=True+ )@patch(f"{MODULE}.get_bot_user_id", return_value="U_OWN_BOT")@patch(f"{MODULE}.resolve_slack_user", return_value={"name": "Alice", "email": None, "avatar": None})@@ -214,7 +216,9 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, after_ts="1700000000.000300")+ _backfill_thread_replies(+ client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123", after_ts="1700000000.000300"+ )comments = Comment.objects.filter(item_id=str(self.ticket.id)).order_by("created_at")assert comments.count() == 1@@ -224,7 +228,7 @@ class TestBackfillThreadReplies(BaseTest):replies = [_make_slack_reply(PARENT_TS, text="parent")]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")assert Comment.objects.filter(item_id=str(self.ticket.id)).count() == 0self.ticket.refresh_from_db()@@ -233,7 +237,7 @@ class TestBackfillThreadReplies(BaseTest):def test_no_op_when_api_returns_empty_messages(self):client = self._mock_client([])- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")assert Comment.objects.filter(item_id=str(self.ticket.id)).count() == 0self.ticket.refresh_from_db()@@ -243,7 +247,7 @@ class TestBackfillThreadReplies(BaseTest):client = MagicMock()client.conversations_replies.side_effect = Exception("Slack API error")- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")assert Comment.objects.filter(item_id=str(self.ticket.id)).count() == 0self.ticket.refresh_from_db()@@ -259,7 +263,7 @@ class TestBackfillThreadReplies(BaseTest):]client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL, PARENT_TS, slack_team_id="T123")comment = Comment.objects.get(item_id=str(self.ticket.id))assert comment.item_context == {@@ -307,7 +311,13 @@ class TestHandleSupportReactionBackfill(BaseTest):assert mock_create.call_args.kwargs["is_thread_reply"] is Falseassert mock_create.call_args.kwargs["thread_ts"] == PARENT_TSmock_backfill.assert_called_once_with(- client, self.team, mock_create.return_value, CHANNEL, PARENT_TS, after_ts=PARENT_TS+ client,+ self.team,+ mock_create.return_value,+ CHANNEL,+ PARENT_TS,+ slack_team_id=SLACK_TEAM,+ after_ts=PARENT_TS,)@patch(f"{MODULE}._backfill_thread_replies")@@ -334,7 +344,7 @@ class TestHandleSupportReactionBackfill(BaseTest):assert mock_create.call_args.kwargs["slack_user_id"] == "U_CUSTOMER"# Backfill only replies posted after the reacted message.mock_backfill.assert_called_once_with(- client, self.team, mock_create.return_value, CHANNEL, PARENT_TS, after_ts=reply_ts+ client, self.team, mock_create.return_value, CHANNEL, PARENT_TS, slack_team_id=SLACK_TEAM, after_ts=reply_ts)# We must never fetch via conversations.history (it can't see thread replies).client.conversations_history.assert_not_called()@@ -362,7 +372,7 @@ class TestHandleSupportReactionBackfill(BaseTest):assert mock_create.call_args.kwargs["thread_ts"] == PARENT_TSassert mock_create.call_args.kwargs["text"] == "screenshots"mock_backfill.assert_called_once_with(- client, self.team, mock_create.return_value, CHANNEL, PARENT_TS, after_ts=reply_ts+ client, self.team, mock_create.return_value, CHANNEL, PARENT_TS, slack_team_id=SLACK_TEAM, after_ts=reply_ts)@patch(f"{MODULE}._backfill_thread_replies")@@ -382,7 +392,13 @@ class TestHandleSupportReactionBackfill(BaseTest):)assert mock_create.call_args.kwargs["thread_ts"] == PARENT_TSmock_backfill.assert_called_once_with(- client, self.team, mock_create.return_value, CHANNEL, PARENT_TS, after_ts=PARENT_TS+ client,+ self.team,+ mock_create.return_value,+ CHANNEL,+ PARENT_TS,+ slack_team_id=SLACK_TEAM,+ after_ts=PARENT_TS,)@patch(f"{MODULE}._backfill_thread_replies")@@ -556,7 +572,9 @@ class TestSlackTicketCreateLockDedup(BaseTest):for _ in range(2):ticket = create_or_update_slack_ticket(**kwargs)if ticket:- _backfill_thread_replies(client, self.team, ticket, CHANNEL, PARENT_TS, after_ts=PARENT_TS)+ _backfill_thread_replies(+ client, self.team, ticket, CHANNEL, PARENT_TS, slack_team_id="T123", after_ts=PARENT_TS+ )tickets = Ticket.objects.filter(team=self.team, slack_channel_id=CHANNEL, slack_thread_ts=PARENT_TS)assert tickets.count() == 1diff --git a/products/conversations/backend/api/tests/test_slack_team_member_detection.py b/products/conversations/backend/api/tests/test_slack_team_member_detection.pyindex 4cf3a15e565e..c3b591bfb284 100644--- a/products/conversations/backend/api/tests/test_slack_team_member_detection.py+++ b/products/conversations/backend/api/tests/test_slack_team_member_detection.py@@ -205,7 +205,7 @@ class TestBackfillTeamMemberDetection(BaseTest):_files,mock_resolve,):- def resolve_side_effect(client, slack_user_id):+ def resolve_side_effect(client, slack_user_id, *, workspace=""):if slack_user_id == "U_TEAM":return _team_member_user_info(self.user.email)return _customer_user_info()@@ -217,7 +217,7 @@ class TestBackfillTeamMemberDetection(BaseTest):replies.append({"ts": f"1700000000.000{200 + i * 100}", "user": user, "text": f"reply {i}"})client = self._mock_client(replies)- _backfill_thread_replies(client, self.team, self.ticket, CHANNEL_ID, PARENT_TS)+ _backfill_thread_replies(client, self.team, self.ticket, CHANNEL_ID, PARENT_TS, slack_team_id="T123")self.ticket.refresh_from_db()assert self.ticket.unread_team_count == expected_unread_teamdiff --git a/products/conversations/backend/cache.py b/products/conversations/backend/cache.pyindex addedb0e3884..3a7690066ee5 100644--- a/products/conversations/backend/cache.py+++ b/products/conversations/backend/cache.py@@ -25,7 +25,6 @@ logger = structlog.get_logger(__name__)MESSAGES_CACHE_TTL = 15 # Short TTL - messages need to appear quicklyTICKETS_CACHE_TTL = 30 # Slightly longer - ticket list changes less frequentlyUNREAD_COUNT_CACHE_TTL = 30 # For dashboard polling - invalidated on changes-SLACK_AVATAR_CACHE_TTL = 5 * 60 # 5 minutes for slack avatar lookup# All possible status filter values for tickets cache invalidation_TICKETS_STATUS_VARIANTS: list[str | None] = [None, *[s.value for s in Status]]@@ -150,24 +149,6 @@ def invalidate_tickets_cache(team_id: int, widget_session_id: str) -> None:logger.warning("conversations_cache_invalidate_error", keys=keys)-# Slack User Cache-# Caches Slack user profile lookups (name, email, avatar) to reduce-# Slack API calls. Keyed by slack_user_id — IDs are functionally unique-# across workspaces. Short TTL keeps profiles reasonably fresh.--SLACK_USER_CACHE_TTL = 5 * 60 # 5 minutes---def get_cached_slack_user(slack_user_id: str) -> dict | None:- """Get cached Slack user profile."""- key = _make_cache_key("slack_user", slack_user_id)- try:- return cache.get(key)- except Exception:- logger.warning("conversations_cache_get_error", key=key)- return None--PERSON_DISTINCT_IDS_CACHE_TTL = 30 # seconds@@ -199,40 +180,6 @@ def get_person_distinct_ids(team_id: int, distinct_id: str) -> list[str]:return all_ids-def set_cached_slack_user(slack_user_id: str, user_info: dict) -> None:- """Cache a Slack user profile."""- key = _make_cache_key("slack_user", slack_user_id)- try:- cache.set(key, user_info, timeout=SLACK_USER_CACHE_TTL)- except Exception:- logger.warning("conversations_cache_set_error", key=key)---# Slack Avatar-by-Email Cache-# Caches the result of users.lookupByEmail so outbound replies can show-# the replying user's Slack profile picture. Empty string = negative cache-# (user not found in the Slack workspace for that email).---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())- try:- return cache.get(key)- except Exception:- logger.warning("conversations_cache_get_error", key=key)- 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())- try:- cache.set(key, avatar_url, timeout=SLACK_AVATAR_CACHE_TTL)- except Exception:- logger.warning("conversations_cache_set_error", key=key)--# Slack Bot User ID Cache# Caches the bot's own user_id (from auth.test) so member join/leave handlers# don't burn Slack's Tier-1 rate-limit budget with a round-trip per event.diff --git a/products/conversations/backend/slack.py b/products/conversations/backend/slack.pyindex 93998a2156cb..eccdb4bdf557 100644--- a/products/conversations/backend/slack.py+++ b/products/conversations/backend/slack.py@@ -12,7 +12,6 @@ All three converge to create_or_update_slack_ticket().import reimport jsonfrom datetime import UTC, datetime-from types import MappingProxyTypefrom typing import Any, Literal, NamedTuplefrom urllib.parse import urljoin, urlparsefrom urllib.request import HTTPRedirectHandler, Request, build_opener@@ -24,10 +23,15 @@ import structlogimport posthoganalyticsfrom slack_sdk import WebClient+from posthog.comment.formatting import (+ extract_slack_user_ids,+ slack_to_content_and_rich_content,+ strip_slack_user_mentions,+)from posthog.event_usage import groups, report_team_actionfrom posthog.exceptions_capture import capture_exception+from posthog.helpers.slack_identity import resolve_posthog_user_for_slack, resolve_slack_userfrom posthog.models.comment import Comment-from posthog.models.organization import OrganizationMembershipfrom posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.ph_client import ph_scoped_capture@@ -35,16 +39,11 @@ from posthog.ph_client import ph_scoped_capturefrom .cache import (NUDGE_COOLDOWN_TTL,get_cached_bot_user_id,- get_cached_slack_avatar,- get_cached_slack_user,is_nudge_suppressed,set_cached_bot_user_id,- set_cached_slack_avatar,- set_cached_slack_user,slack_ticket_create_lock,suppress_nudge,)-from .formatting import extract_slack_user_ids, slack_to_content_and_rich_content, strip_slack_user_mentionsfrom .models import Ticketfrom .models.constants import Channel, ChannelDetail, Statusfrom .services.attachments import (@@ -148,91 +147,6 @@ def get_slack_client(team: Team) -> WebClient:raise ValueError("Support Slack bot token is not configured")-_UNKNOWN_USER = MappingProxyType({"name": "Unknown", "email": None, "avatar": None})---def resolve_slack_user(client: WebClient, slack_user_id: str) -> dict:- """Resolve a Slack user ID to name, email, and avatar. Cached in Redis for 5 minutes."""- if not slack_user_id:- logger.warning("slack_support_user_resolve_empty_id")- return dict(_UNKNOWN_USER)-- cached = get_cached_slack_user(slack_user_id)- if cached is not None:- return cached-- try:- response = client.users_info(user=slack_user_id)- raw_data = response.data if hasattr(response, "data") else None- data: dict = raw_data if isinstance(raw_data, dict) else {}-- if not data.get("ok"):- logger.warning(- "slack_support_user_resolve_not_ok",- slack_user_id=slack_user_id,- error=data.get("error"),- )- return dict(_UNKNOWN_USER)-- user_data = data.get("user") or {}- profile = user_data.get("profile") or {}- name = profile.get("display_name") or profile.get("real_name") or "Unknown"- result = {- "name": name,- "email": profile.get("email"),- "avatar": profile.get("image_72"),- }- set_cached_slack_user(slack_user_id, result)- return result- except Exception as e:- logger.warning("slack_support_user_resolve_failed", slack_user_id=slack_user_id, error=str(e))- 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."""- if not email:- return None-- cached = get_cached_slack_avatar(email)- if cached is not None:- return cached or None # empty string = negative cache-- try:- response = client.users_lookupByEmail(email=email)- raw_data = response.data if hasattr(response, "data") else None- data: dict = raw_data if isinstance(raw_data, dict) else {}-- if not data.get("ok"):- set_cached_slack_avatar(email, "")- return None-- profile = (data.get("user") or {}).get("profile") or {}- avatar = profile.get("image_72") or ""- set_cached_slack_avatar(email, avatar)- return avatar or None- except 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)- return 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:- return None- membership = (- OrganizationMembership.objects.filter(- organization_id=team.organization_id,- user__email=email,- )- .select_related("user")- .first()- )- return membership.user if membership else None--def get_bot_user_id(client: WebClient) -> str | None:"""Get the bot's own user ID to filter out self-messages."""try:@@ -501,7 +415,7 @@ def create_or_update_slack_ticket(images, file_attachments = split_slack_attachments(extract_slack_files(files, team, client))# Resolve Slack user info for this message author- user_info = resolve_slack_user(client, slack_user_id)+ user_info = resolve_slack_user(client, slack_user_id, workspace=slack_team_id or "")# Check if this Slack user is a PostHog team memberposthog_user = resolve_posthog_user_for_slack(user_info.get("email"), team)@@ -514,7 +428,7 @@ def create_or_update_slack_ticket(if uid == slack_user_id and user_info["name"] != "Unknown":user_names[uid] = user_info["name"]elif uid not in user_names:- info = resolve_slack_user(client, uid)+ info = resolve_slack_user(client, uid, workspace=slack_team_id or "")if info["name"] != "Unknown":user_names[uid] = info["name"]@@ -700,7 +614,7 @@ def _configured_support_channels(settings: dict) -> set[str]:def _record_last_slack_message(- team: Team, *, channel: str, slack_user_id: str, message_ts: str | None, is_bot: bool+ team: Team, *, channel: str, slack_user_id: str, message_ts: str | None, is_bot: bool, slack_team_id: str) -> None:"""Record the message time on the customer analytics account bound to `channel`.@@ -719,7 +633,7 @@ def _record_last_slack_message(account = customer_analytics.get_account_ref_by_slack_channel_id(team_id, channel)if account is None:return- slack_user = resolve_slack_user(get_slack_client(team), slack_user_id)+ slack_user = resolve_slack_user(get_slack_client(team), slack_user_id, workspace=slack_team_id)# An unresolved email may belong to a teammate, so treat it as one.email = slack_user.get("email")if not email or resolve_posthog_user_for_slack(email, team):@@ -766,7 +680,14 @@ def handle_support_message(event: dict, team: Team, slack_team_id: str) -> None:thread_ts = event.get("thread_ts")message_ts = event.get("ts")- _record_last_slack_message(team, channel=channel, slack_user_id=slack_user_id, message_ts=message_ts, is_bot=is_bot)+ _record_last_slack_message(+ team,+ channel=channel,+ slack_user_id=slack_user_id,+ message_ts=message_ts,+ is_bot=is_bot,+ slack_team_id=slack_team_id,+ )if thread_ts:if is_bot:@@ -810,7 +731,9 @@ def handle_support_message(event: dict, team: Team, slack_team_id: str) -> None:# click "Open ticket" (handled by the interactivity endpoint). Heuristics# keep us from pestering the whole channel.if settings_dict.get("slack_nudge_enabled", True):- decision = _should_send_nudge(team, channel, slack_user_id, text, blocks, files, message_ts or "")+ decision = _should_send_nudge(+ team, channel, slack_user_id, text, blocks, files, message_ts or "", slack_team_id+ )if decision.send:post_ticket_confirmation_prompt(team=team,@@ -1021,6 +944,7 @@ def _should_send_nudge(blocks: list[dict] | None,files: list[dict] | None,message_ts: str,+ slack_team_id: str,) -> NudgeDecision:"""Heuristics to avoid pestering the channel: nudge only external users on substantivemessages, skipping anyone recently nudged/dismissed or who @mentioned the bot (which@@ -1044,7 +968,7 @@ def _should_send_nudge(# External users only — internal teammates don't need nudging. Skipped in local# dev, where the tester's own account is the only org member and would never nudge.if not settings.DEBUG:- user_info = resolve_slack_user(client, slack_user_id)+ user_info = resolve_slack_user(client, slack_user_id, workspace=slack_team_id)if resolve_posthog_user_for_slack(user_info.get("email"), team):return NudgeDecision(send=False, classifier_verdict="skipped")@@ -1173,7 +1097,9 @@ def _create_ticket_and_backfill(post_confirmation=post_confirmation,)if ticket:- _backfill_thread_replies(client, team, ticket, slack_channel_id, thread_ts, after_ts=after_ts)+ _backfill_thread_replies(+ client, team, ticket, slack_channel_id, thread_ts, slack_team_id=slack_team_id, after_ts=after_ts+ )return ticket@@ -1343,6 +1269,8 @@ def _backfill_thread_replies(ticket: Ticket,channel: str,thread_ts: str,+ *,+ slack_team_id: str | None,after_ts: str | None = None,) -> None:"""Fetch existing thread replies and add them as comments on the ticket.@@ -1400,7 +1328,7 @@ def _backfill_thread_replies(images, file_attachments = split_slack_attachments(extract_slack_files(reply_files, team, client))if reply_user not in user_cache:- user_cache[reply_user] = resolve_slack_user(client, reply_user)+ user_cache[reply_user] = resolve_slack_user(client, reply_user, workspace=slack_team_id or "")user_info = user_cache[reply_user]if reply_user not in posthog_user_cache:@@ -1413,7 +1341,7 @@ def _backfill_thread_replies(reply_user_names: dict[str, str] = {}for uid in mentioned_ids:if uid not in user_cache:- user_cache[uid] = resolve_slack_user(client, uid)+ user_cache[uid] = resolve_slack_user(client, uid, workspace=slack_team_id or "")if user_cache[uid]["name"] != "Unknown":reply_user_names[uid] = user_cache[uid]["name"]@@ -1624,6 +1552,7 @@ def _handle_member_event(team: Team,*,joined: bool,+ slack_team_id: str,client: WebClient | None = None,own_bot_user_id: str | None = None,) -> None:@@ -1673,7 +1602,7 @@ def _handle_member_event(# Members of the team's own organization are internal teammates, not the external# participants these alerts surface — skip them.- slack_user = resolve_slack_user(client, user)+ slack_user = resolve_slack_user(client, user, workspace=slack_team_id)if resolve_posthog_user_for_slack(slack_user.get("email"), team):return@@ -1707,9 +1636,11 @@ def handle_member_joined_channel(event: dict, team: Team, slack_team_id: str) ->client = get_slack_client(team)own_bot_user_id = get_bot_user_id_cached(team, client)_track_bot_joined_channel(event, team, slack_team_id, own_bot_user_id=own_bot_user_id)- _handle_member_event(event, team, joined=True, client=client, own_bot_user_id=own_bot_user_id)+ _handle_member_event(+ event, team, joined=True, slack_team_id=slack_team_id, client=client, own_bot_user_id=own_bot_user_id+ )def handle_member_left_channel(event: dict, team: Team, slack_team_id: str) -> None:"""Handle a Slack 'member_left_channel' event by alerting the configured channel."""- _handle_member_event(event, team, joined=False)+ _handle_member_event(event, team, joined=False, slack_team_id=slack_team_id)diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex fcb4bf96c0e5..566d77425c9e 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -21,7 +21,14 @@ import structlogfrom celery import shared_taskfrom celery.exceptions import MaxRetriesExceededError, Retry+from posthog.comment.formatting import (+ extract_images_from_rich_content,+ rich_content_to_html,+ rich_content_to_markdown,+ rich_content_to_slack_payload,+)from posthog.egress.github.transport import GitHubRateLimitError+from posthog.helpers.slack_identity import resolve_slack_avatar_by_emailfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activityfrom posthog.models.comment import Comment as CommentModelfrom posthog.models.github_integration_base import GitHubIntegrationError@@ -32,12 +39,6 @@ from posthog.storage import object_storagefrom products.conversations.backend.cache import NUDGE_DISMISS_TTL, suppress_nudgefrom products.conversations.backend.events import capture_ticket_status_changed-from products.conversations.backend.formatting import (- extract_images_from_rich_content,- rich_content_to_html,- rich_content_to_markdown,- rich_content_to_slack_payload,-)from products.conversations.backend.mailgun import (MailgunDomainNotRegistered,MailgunNotConfigured,@@ -72,7 +73,6 @@ from products.conversations.backend.slack import (handle_support_message,handle_support_reaction,nudge_event_properties,- resolve_slack_avatar_by_email,ticket_created_text,)from products.conversations.backend.support_teams import (@@ -390,7 +390,9 @@ def post_reply_to_slack()return- slack_text, slack_blocks = rich_content_to_slack_payload(rich_content, content, include_images=False)+ slack_text, slack_blocks = rich_content_to_slack_payload(+ rich_content, content, include_images=False, organization_id=team.organization_id+ )rich_images = extract_images_from_rich_content(rich_content)logger.info("🧵 slack_reply_payload_prepared",diff --git a/products/signals/backend/emission/fetchers/conversations.py b/products/signals/backend/emission/fetchers/conversations.pyindex 5e0e6e69073b..9ec58ca1436e 100644--- a/products/signals/backend/emission/fetchers/conversations.py+++ b/products/signals/backend/emission/fetchers/conversations.py@@ -7,10 +7,10 @@ from django.utils import timezoneimport structlog+from posthog.comment.formatting import extract_images_from_rich_contentfrom posthog.models import Teamfrom posthog.models.comment import Comment-from products.conversations.backend.formatting import extract_images_from_rich_contentfrom products.conversations.backend.models import Ticketfrom products.signals.backend.emission.registry import SignalSourceTableConfigfrom products.signals.backend.models import SignalEmissionRecord