: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(comments): ingest Slack thread replies back into discussions (inbound) (#66843)
Luke Belton62947c8c8a70
diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex bfa49e471d8d..efcbe9e41765 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -78,8 +78,11 @@ def _require_ticket_editor_access(STALE_SLACK_RESERVATION_GRACE = timedelta(minutes=2)# item_context keys the Slack mirror sync stamps server-side. Stripped from client input so a-# caller can't forge sync state (suppress mirroring of a reply, or spoof Slack attribution).-RESERVED_ITEM_CONTEXT_KEYS = frozenset({"from_slack", "slack_synced_ts"})+# caller can't forge sync state (suppress mirroring of a reply, block ingestion of a real Slack+# message by squatting on its ts, or spoof a Slack author identity in the discussion UI).+RESERVED_ITEM_CONTEXT_KEYS = frozenset(+ {"from_slack", "slack_synced_ts", "slack_message_ts", "slack_author_name", "slack_author_avatar"}+)def _release_slack_reservation(slack_thread: "CommentSlackThread") -> None:diff --git a/posthog/helpers/slack_identity.py b/posthog/helpers/slack_identity.pyindex c2aeb765e818..b086e05730b9 100644--- a/posthog/helpers/slack_identity.py+++ b/posthog/helpers/slack_identity.py@@ -24,7 +24,7 @@ logger = structlog.get_logger(__name__)SLACK_USER_CACHE_TTL = 5 * 60 # 5 minutesSLACK_AVATAR_CACHE_TTL = 5 * 60 # 5 minutes-_UNKNOWN_USER = MappingProxyType({"name": "Unknown", "email": None, "avatar": None})+_UNKNOWN_USER = MappingProxyType({"name": "Unknown", "email": None, "avatar": None, "team_id": None})def _make_cache_key(prefix: str, *args: str) -> str:@@ -106,6 +106,9 @@ def resolve_slack_user(client: WebClient, slack_user_id: str, *, workspace: str)"name": name,"email": profile.get("email"),"avatar": profile.get("image_72"),+ # Slack workspace the user belongs to — lets callers tell workspace members apart+ # from external (Slack Connect) participants before trusting the profile email.+ "team_id": user_data.get("team_id"),}set_cached_slack_user(slack_user_id, result, workspace)return resultdiff --git a/posthog/tasks/comment_slack_sync.py b/posthog/tasks/comment_slack_sync.pyindex 55a8bdae5faf..d9943acaf83c 100644--- a/posthog/tasks/comment_slack_sync.py+++ b/posthog/tasks/comment_slack_sync.py@@ -1,4 +1,5 @@import time+from typing import Any, castimport structlogimport posthoganalytics@@ -6,6 +7,8 @@ from celery import Task, shared_taskfrom slack_sdk import WebClientfrom slack_sdk.errors import SlackApiError+from posthog.comment.formatting import slack_to_content_and_rich_content+from posthog.helpers.slack_identity import resolve_posthog_user_for_slack, resolve_slack_userfrom posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_userfrom posthog.models.comment import Comment, CommentSlackThreadfrom posthog.models.comment.slack_thread import DISCUSSIONS_SLACK_SYNC_FLAG@@ -15,6 +18,10 @@ from posthog.scoping_audit import skip_team_scope_auditlogger = structlog.get_logger(__name__)+# item_context key holding the source Slack message ts of an ingested reply — the+# idempotency key that makes re-processing the same Slack event a no-op.+SLACK_MESSAGE_TS_KEY = "slack_message_ts"+# item_context key holding the Slack ts of a reply's mirrored copy. Its presence is the# idempotency marker that keeps Celery retries and backfill re-runs from double-posting.SLACK_SYNCED_TS_KEY = "slack_synced_ts"@@ -92,6 +99,20 @@ def _log_backfill_reply_failure(comment_slack_thread_id: str, reply: Comment) ->)+def _neutralize_rich_content_images(node: dict[str, Any] | list[Any] | object) -> None:+ """Escape markdown image syntax in every text node of an inbound reply's rich content."""+ if isinstance(node, dict):+ typed_node = cast(dict[str, Any], node)+ text = typed_node.get("text")+ if typed_node.get("type") == "text" and isinstance(text, str):+ typed_node["text"] = text.replace("![", "!\\[")+ for value in typed_node.values():+ _neutralize_rich_content_images(value)+ elif isinstance(node, list):+ for item in node:+ _neutralize_rich_content_images(item)++def _mark_reply_synced(reply: Comment, ts: object) -> None:item_context = dict(reply.item_context) if isinstance(reply.item_context, dict) else {}item_context[SLACK_SYNCED_TS_KEY] = ts if isinstance(ts, str) else ""@@ -158,6 +179,101 @@ def mirror_comment_reply_to_slack(self: Task, comment_id: str) -> None:_mark_reply_synced(comment, posted_ts)+@shared_task(bind=True, ignore_result=True, max_retries=3, default_retry_delay=5)+@skip_team_scope_audit # Comment is on RootTeamManager; queries pin the team via the mirror's integration+def ingest_slack_discussion_reply(+ self: Task,+ comment_slack_thread_id: str,+ slack_user_id: str,+ text: str,+ blocks: list | None,+ message_ts: str,+) -> None:+ """Save a Slack thread reply as a discussion comment (the inbound mirror half).++ Runs off the webhook request thread: Slack expects the events endpoint to ack in ~3+ seconds and this path makes a ``users.info`` call. Idempotent per source Slack message+ ts, so task retries and duplicate event deliveries can't create duplicate comments.+ """+ mirror = (+ CommentSlackThread.objects.unscoped()+ .filter(id=comment_slack_thread_id)+ .select_related("integration__team")+ .first()+ )+ if mirror is None:+ return+ # message_ts is the idempotency key; without it a redelivered event would duplicate the+ # comment (the enqueuing side already refuses these — this is the fail-closed backstop).+ if not message_ts:+ return+ team = mirror.integration.team+ if _sync_killed(team.id):+ return++ if Comment.objects.filter(+ team_id=team.id,+ source_comment_id=mirror.source_comment_id,+ item_context__slack_message_ts=message_ts,+ ).exists():+ return++ content, rich_content = slack_to_content_and_rich_content(text, blocks)+ if not content and not rich_content:+ return+ # Slack text has no markdown image syntax, so neutralizing it is lossless — and keeps an+ # external participant's reply from making the discussion UI load remote images. The UI+ # prefers rich_content (flattened back to markdown), so its text nodes need the same+ # treatment or the escape would be sidestepped whenever the message carries blocks.+ content = content.replace("![", "!\\[")+ _neutralize_rich_content_images(rich_content)++ try:+ client = SlackIntegration(mirror.integration).client+ client.timeout = 10+ # The profile feeds the workspace-membership trust check below — namespace the cache by+ # this integration's workspace so a colliding user id from another workspace (Slack+ # Connect) can't be served from a stale entry.+ user_info = resolve_slack_user(client, slack_user_id, workspace=mirror.integration.integration_id or "")+ except Exception as exc:+ raise self.retry(exc=exc)++ # Only attribute the comment to a PostHog user when Slack confirms the author belongs to+ # this integration's own workspace. In externally-shared (Slack Connect) channels the other+ # workspace's admin controls its users' profile emails, so trusting the email there would+ # let an outsider post as any org member.+ posthog_user = None+ if user_info.get("team_id") and user_info.get("team_id") == mirror.integration.integration_id:+ posthog_user = resolve_posthog_user_for_slack(user_info.get("email"), team)++ Comment.objects.create(+ team=team,+ scope=mirror.scope,+ item_id=mirror.item_id,+ # The reply hangs off the mirrored thread's root comment (None only for whole-item mirrors).+ source_comment_id=mirror.source_comment_id,+ content=content,+ rich_content=rich_content,+ # Slack users without a verified PostHog account stay author-less; their display+ # identity rides in item_context (name + avatar only — no email or Slack user id,+ # which would leak external participants' PII through the comments API).+ created_by=posthog_user,+ item_context={+ "from_slack": True,+ SLACK_MESSAGE_TS_KEY: message_ts,+ "slack_author_name": user_info["name"],+ "slack_author_avatar": user_info.get("avatar"),+ },+ )+ logger.info(+ "slack_discussion_reply_ingested",+ team_id=team.id,+ scope=mirror.scope,+ item_id=mirror.item_id,+ comment_slack_thread_id=comment_slack_thread_id,+ )++@shared_task(ignore_result=True)@skip_team_scope_audit # Comment is on RootTeamManager; the reply query filters by the mirror's team_iddef backfill_comment_slack_thread(comment_slack_thread_id: str) -> None:diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambrindex 9fbedee8ede3..3936ef87cfb4 100644--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr@@ -20,6 +20,7 @@'posthog.tasks.calculate_cohort.insert_cohort_from_query','posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task','posthog.tasks.comment_slack_sync.backfill_comment_slack_thread',+ 'posthog.tasks.comment_slack_sync.ingest_slack_discussion_reply','posthog.tasks.comment_slack_sync.mirror_comment_reply_to_slack','posthog.tasks.demo_create_data.create_data_for_demo_team','posthog.tasks.early_access_feature.create_waitlist_survey_for_concept_feature',diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex a3ae2df33550..71875533815b 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -58,6 +58,7 @@ from posthog.user_permissions import UserPermissionsfrom posthog.utils import get_instance_regionfrom products.slack_app.backend import inbox_channel, onboarding+from products.slack_app.backend.discussion_replies import try_ingest_discussion_replyfrom products.slack_app.backend.feature_flags import (ASSISTANT_REQUIRED_SCOPES,is_slack_app_assistant_enabled,@@ -1943,6 +1944,22 @@ def route_posthog_code_event_to_relevant_region(_report_slack_mention_dropped(event, slack_team_id, reason="no_integration", replied=False)return region_route+ # A reply on a thread that mirrors a PostHog discussion becomes a comment, not agent work.+ if event_type == "message":+ try:+ ingested = try_ingest_discussion_reply(+ event, workspace_result.candidates, channel_str, thread_ts_str, slack_team_id+ )+ except Exception:+ # Never let discussion ingest break the shared event handler — a 500 here would+ # also lose the agent-followup routing, and Slack retries are dropped upstream.+ logger.exception(+ "slack_discussion_reply_ingest_failed", slack_team_id=slack_team_id, channel=channel_str+ )+ ingested = False+ if ingested:+ return ROUTE_HANDLED_LOCALLY+# Threads we don't own (and orgs that haven't opted in) are dropped here# so the rest of the pipeline only runs for actionable messages.untagged_followup_mapping: SlackThreadTaskMapping | None = Nonediff --git a/products/slack_app/backend/discussion_replies.py b/products/slack_app/backend/discussion_replies.pynew file mode 100644index 000000000000..e043811cc79c--- /dev/null+++ b/products/slack_app/backend/discussion_replies.py@@ -0,0 +1,79 @@+"""Ingest Slack thread replies on mirrored discussion threads back into PostHog as comments.++The outbound half (PostHog discussion -> Slack thread) lives in posthog/helpers/slack_thread_mirror.py+and the send_to_slack action. This is the inbound half: when someone replies in a Slack thread that a+discussion is mirrored to, save their message as a reply Comment on that discussion. Only the routing+decision happens here, on the webhook request thread — the Slack profile lookup and comment write run+in a Celery task so the events endpoint can ack within Slack's deadline and failures get retries.+"""++from typing import Any++import structlog++from posthog.models.comment import CommentSlackThread+from posthog.models.integration import Integration+from posthog.tasks.comment_slack_sync import ingest_slack_discussion_reply++from products.slack_app.backend.models import SlackThreadTaskMapping++logger = structlog.get_logger(__name__)+++def try_ingest_discussion_reply(+ event: dict[str, Any],+ candidates: list[Integration],+ channel: str | None,+ thread_ts: str | None,+ slack_team_id: str,+) -> bool:+ """Enqueue a Slack thread reply for ingestion as a discussion comment if the thread is mirrored.++ Returns True when the reply belonged to a mirrored discussion (so the caller stops treating+ it as coding-agent work), False when the thread isn't a mirrored discussion.++ Echo prevention is twofold: the caller's ``_thread_message_ignore_reason`` already drops the+ bot's own posts before we get here, and the comment we create is flagged ``from_slack`` so the+ outbound mirror signal won't bounce it straight back to Slack.+ """+ if not channel or not thread_ts:+ return False++ # candidates are this workspace's integrations in this region; bound the cross-team lookup to them.+ candidate_ids = [c.id for c in candidates]+ mirror = (+ CommentSlackThread.objects.unscoped()+ .filter(integration_id__in=candidate_ids, slack_channel_id=channel, slack_thread_ts=thread_ts)+ .only("id")+ .first()+ )+ if mirror is None:+ return False++ # A thread can be both a mirrored discussion and an agent-task thread (someone @-mentioned the+ # agent in it). The agent followup pipeline takes precedence — claiming the reply here would+ # silently swallow instructions meant for the agent.+ if SlackThreadTaskMapping.objects.filter(+ integration_id__in=candidate_ids, channel=channel, thread_ts=thread_ts+ ).exists():+ return False++ # ts is the ingestion idempotency key — without it, Slack's event redelivery would create+ # duplicate comments. A real message always carries one; claim the event but don't ingest.+ if not event.get("ts"):+ logger.warning("slack_discussion_reply_missing_ts", comment_slack_thread_id=str(mirror.id))+ return True++ ingest_slack_discussion_reply.delay(+ comment_slack_thread_id=str(mirror.id),+ slack_user_id=str(event.get("user") or ""),+ text=str(event.get("text") or ""),+ blocks=event.get("blocks") if isinstance(event.get("blocks"), list) else None,+ message_ts=str(event.get("ts") or ""),+ )+ logger.info(+ "slack_discussion_reply_enqueued",+ comment_slack_thread_id=str(mirror.id),+ slack_team_id=slack_team_id,+ )+ return Truediff --git a/products/slack_app/backend/tests/test_discussion_replies.py b/products/slack_app/backend/tests/test_discussion_replies.pynew file mode 100644index 000000000000..d8b1979da647--- /dev/null+++ b/products/slack_app/backend/tests/test_discussion_replies.py@@ -0,0 +1,145 @@+from posthog.test.base import APIBaseTest+from unittest.mock import patch++from posthog.models.comment import Comment, CommentSlackThread+from posthog.models.integration import Integration++from products.slack_app.backend.discussion_replies import try_ingest_discussion_reply++# The Slack profile lookup happens inside the ingest Celery task (eager in tests).+RESOLVE = "posthog.tasks.comment_slack_sync.resolve_slack_user"+++class TestIngestDiscussionReply(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T1", sensitive_config={"access_token": "t"}+ )+ self.root = Comment.objects.create(team=self.team, scope="Insight", item_id="42", content="root")+ CommentSlackThread.objects.for_team(self.team.id).create(+ team=self.team,+ scope="Insight",+ item_id="42",+ source_comment=self.root,+ integration=self.integration,+ slack_channel_id="C1",+ slack_thread_ts="100.1",+ )++ def _event(self, **kwargs) -> dict:+ event = {+ "type": "message",+ "user": "U1",+ "channel": "C1",+ "thread_ts": "100.1",+ "ts": "100.2",+ "text": "hi from slack",+ }+ event.update(kwargs)+ return event++ def _ingest(self, event: dict) -> bool:+ return try_ingest_discussion_reply(event, [self.integration], event["channel"], event.get("thread_ts"), "T1")++ @patch(+ RESOLVE,+ return_value={"name": "Stranger", "email": "[email protected]", "avatar": "http://a", "team_id": "T_EXT"},+ )+ def test_ingests_reply_anchored_on_thread_root(self, _resolve):+ handled = self._ingest(self._event())++ assert handled is True+ reply = Comment.objects.get(source_comment=self.root)+ assert reply.item_context is not None+ assert reply.content == "hi from slack"+ assert (reply.scope, reply.item_id) == ("Insight", "42")+ assert reply.created_by_id is None # stranger isn't an org member+ assert reply.item_context["from_slack"] is True+ assert reply.item_context["slack_author_name"] == "Stranger"+ # External participants' email / Slack user id must not leak through the comments API.+ assert "slack_author_email" not in reply.item_context+ assert "slack_user_id" not in reply.item_context++ @patch(RESOLVE)+ def test_maps_workspace_member_to_posthog_account_by_email(self, mock_resolve):+ mock_resolve.return_value = {"name": "Member", "email": self.user.email, "avatar": None, "team_id": "T1"}++ self._ingest(self._event())++ reply = Comment.objects.get(source_comment=self.root)+ assert reply.created_by_id == self.user.id++ @patch(RESOLVE)+ def test_external_workspace_author_is_never_attributed(self, mock_resolve):+ # Slack Connect: the author's profile email matches an org member, but they belong to a+ # different workspace whose admin controls that email — attributing would allow+ # impersonation, so the comment stays author-less.+ mock_resolve.return_value = {"name": "Imposter", "email": self.user.email, "avatar": None, "team_id": "T_EXT"}++ self._ingest(self._event())++ reply = Comment.objects.get(source_comment=self.root)+ assert reply.item_context is not None+ assert reply.created_by_id is None+ assert reply.item_context["slack_author_name"] == "Imposter"++ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})+ def test_image_markdown_neutralized_in_content_and_rich_content(self, _resolve):+ # The discussion UI renders rich_content (preferred) or content as markdown without+ # disabling images — inbound Slack text must never carry live image syntax.+ payload = "look "+ blocks = [+ {+ "type": "rich_text",+ "elements": [{"type": "rich_text_section", "elements": [{"type": "text", "text": payload}]}],+ }+ ]+ self._ingest(self._event(text=payload, blocks=blocks))++ reply = Comment.objects.get(source_comment=self.root)+ assert reply.rich_content is not None+ assert "![" not in (reply.content or "")+ text_node = reply.rich_content["content"][0]["content"][0]["text"]+ assert text_node == "look !\\[x](https://attacker.example/pixel)"++ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})+ def test_duplicate_event_delivery_creates_one_comment(self, _resolve):+ # Slack delivers at-least-once; the message ts is the idempotency key.+ assert self._ingest(self._event()) is True+ assert self._ingest(self._event()) is True++ assert Comment.objects.filter(source_comment=self.root).count() == 1++ def test_returns_false_for_unmirrored_thread(self):+ handled = self._ingest(self._event(thread_ts="999.9"))++ assert handled is False+ assert not Comment.objects.filter(source_comment=self.root).exists()++ @patch("products.slack_app.backend.discussion_replies.SlackThreadTaskMapping")+ def test_agent_task_thread_takes_precedence(self, mock_mapping):+ # A mirrored thread where someone also @-mentioned the coding agent: followups belong+ # to the agent pipeline, not the discussion.+ mock_mapping.objects.filter.return_value.exists.return_value = True++ handled = self._ingest(self._event())++ assert handled is False+ assert not Comment.objects.filter(source_comment=self.root).exists()++ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})+ def test_empty_message_handled_without_creating_comment(self, _resolve):+ handled = self._ingest(self._event(text="", blocks=None))++ assert handled is True+ assert not Comment.objects.filter(source_comment=self.root).exists()++ @patch("posthog.tasks.comment_slack_sync.posthoganalytics.feature_enabled", return_value=False)+ @patch(RESOLVE, return_value={"name": "X", "email": None, "avatar": None, "team_id": "T1"})+ def test_kill_switch_stops_ingestion(self, _resolve, _flag):+ # Turning the flag explicitly off halts inbound sync on existing mirrors too.+ handled = self._ingest(self._event())++ assert handled is True # still claimed as a discussion thread — just not written+ assert not Comment.objects.filter(source_comment=self.root).exists()