Skip to content

: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.

feat(comments): mirror discussion threads to Slack (outbound) (#66842)

Luke Belton5451f2c54d2a
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index d853c0d810a6..4821c3a29555 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -155,6 +155,11 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"BatchExportRun",
"CodeInvite",
"CodeInviteRedemption",
+ # Comment↔Slack-thread mirror mapping — looked up by source_comment FK or
+ # (scope, item_id) within team scope, and by internally-generated task-arg id;
+ # never by user-supplied CommentSlackThread id through an API. Fail-closed via
+ # TeamScopedManager (TeamScopedRootMixin) on top.
+ "CommentSlackThread",
"EndpointVersion",
"ErrorTrackingIssueAssignment",
"StreamlitAppVersion",
diff --git a/posthog/api/comments.py b/posthog/api/comments.py
index 23f7ed7b1d43..bfa49e471d8d 100644
--- a/posthog/api/comments.py
+++ b/posthog/api/comments.py
@@ -1,3 +1,4 @@
+from datetime import timedelta
from typing import TYPE_CHECKING, Any, cast
from django.core import exceptions as django_exceptions
@@ -5,26 +6,41 @@ from django.db import transaction
from django.db.models import Q, QuerySet
from django.utils import timezone
-from drf_spectacular.utils import extend_schema
+import structlog
+import posthoganalytics
+from drf_spectacular.utils import extend_schema, extend_schema_field
from rest_framework import exceptions, pagination, serializers, viewsets
from rest_framework.request import Request
from rest_framework.response import Response
+from slack_sdk.errors import SlackApiError
from posthog.api.forbid_destroy_model import ForbidDestroyModel
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.shared import UserBasicSerializer
from posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, action
+from posthog.exceptions import Conflict
+from posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_user
from posthog.models import User
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.activity_logging.model_activity import get_was_impersonated
-from posthog.models.comment import Comment
+from posthog.models.comment import Comment, CommentSlackThread
from posthog.models.comment.comment import TICKET_COMMENT_SCOPES, activity_log_scope_for
-from posthog.models.comment.utils import produce_discussion_mention_events, send_mention_notifications
+from posthog.models.comment.slack_thread import DISCUSSIONS_SLACK_SYNC_FLAG
+from posthog.models.comment.utils import (
+ build_comment_item_url,
+ comment_scope_display_name,
+ produce_discussion_mention_events,
+ send_mention_notifications,
+)
+from posthog.models.integration import Integration, SlackIntegration
+from posthog.tasks.comment_slack_sync import backfill_comment_slack_thread
from posthog.tasks.email import send_discussions_mentioned
if TYPE_CHECKING:
from posthog.rbac.user_access_control import UserAccessControl
+logger = structlog.get_logger(__name__)
+
def _normalize_scope(scope: Any) -> Any:
"""Match how the serializer will store a submitted scope.
@@ -58,6 +74,40 @@ def _require_ticket_editor_access(
raise exceptions.PermissionDenied("You do not have access to this ticket")
+# A reservation with no posted root older than this is a crashed send — safe to retry.
+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"})
+
+
+def _release_slack_reservation(slack_thread: "CommentSlackThread") -> None:
+ """Best-effort release so a later send can retry; must not mask the Slack error being raised."""
+ try:
+ slack_thread.delete()
+ except Exception:
+ # The stale-reservation grace period will unblock a retry even if this row lingers.
+ logger.exception("comment_slack_reservation_release_failed", slack_thread_id=str(slack_thread.id))
+
+
+def _slack_thread_url(thread: CommentSlackThread) -> str:
+ """Permalink that opens the mirrored Slack thread.
+
+ Uses the standard `/archives/<channel>/p<ts>` permalink form (ts with the dot removed); Slack
+ resolves the workspace from the channel. Falls back to the channel if the root isn't posted yet.
+ """
+ base = f"https://app.slack.com/archives/{thread.slack_channel_id}"
+ if not thread.slack_thread_ts:
+ return base
+ return f"{base}/p{thread.slack_thread_ts.replace('.', '')}"
+
+
+class CommentSlackThreadRefSerializer(serializers.Serializer):
+ channel_id = serializers.CharField(help_text="Slack channel ID this discussion is mirrored to.")
+ url = serializers.CharField(help_text="Deep link that opens the mirrored Slack thread.")
+
+
class CommentSerializer(serializers.ModelSerializer):
def _extract_mentions_from_rich_content(self, rich_content: dict | None) -> list[int]:
if not rich_content:
@@ -99,6 +149,22 @@ class CommentSerializer(serializers.ModelSerializer):
allow_null=True,
help_text="The user who marked this task complete. Null for open tasks and non-task comments.",
)
+ slack_thread = serializers.SerializerMethodField(
+ help_text=(
+ "The Slack thread this comment's discussion is mirrored to, or null. Set only on a "
+ "tracked thread-root comment; used to surface an 'Open in Slack' link and hide re-sending."
+ )
+ )
+
+ @extend_schema_field(CommentSlackThreadRefSerializer(allow_null=True))
+ def get_slack_thread(self, comment: Comment) -> dict | None:
+ by_comment = self.context.get("slack_thread_by_comment") or {}
+ thread = by_comment.get(str(comment.id))
+ # A reservation with no posted root isn't a live mirror — report null so the UI
+ # keeps offering "send to Slack" rather than a dead "Open in Slack" link.
+ if thread is None or not thread.slack_thread_ts:
+ return None
+ return {"channel_id": thread.slack_channel_id, "url": _slack_thread_url(thread)}
class Meta:
model = Comment
@@ -186,6 +252,11 @@ class CommentSerializer(serializers.ModelSerializer):
if not content.strip() and (not rich_content or self.has_empty_paragraph(rich_content)):
raise exceptions.ValidationError("A comment must have content")
+ if isinstance(data.get("item_context"), dict):
+ data["item_context"] = {
+ k: v for k, v in data["item_context"].items() if k not in RESERVED_ITEM_CONTEXT_KEYS
+ }
+
if not instance:
data["created_by"] = request.user
if data.get("is_task"):
@@ -294,6 +365,47 @@ class CommentListQueryParamsSerializer(serializers.Serializer):
)
+class CommentSlackThreadSerializer(serializers.ModelSerializer):
+ created_by = UserBasicSerializer(
+ read_only=True, allow_null=True, help_text="User who mirrored the discussion. Null if since deleted."
+ )
+
+ class Meta:
+ model = CommentSlackThread
+ fields = [
+ "id",
+ "scope",
+ "item_id",
+ "source_comment",
+ "integration",
+ "slack_channel_id",
+ "slack_thread_ts",
+ "slack_team_id",
+ "created_at",
+ "created_by",
+ ]
+ read_only_fields = fields
+ extra_kwargs = {
+ "scope": {"help_text": "Resource type of the mirrored discussion (e.g. Insight)."},
+ "item_id": {"help_text": "ID of the resource the discussion is attached to."},
+ "source_comment": {"help_text": "The thread-root comment whose replies mirror to the Slack thread."},
+ "integration": {"help_text": "Slack integration used to post to and read from the thread."},
+ "slack_channel_id": {"help_text": "Slack channel the mirrored thread lives in."},
+ "slack_thread_ts": {"help_text": "Slack thread timestamp anchoring the mirrored thread."},
+ "slack_team_id": {"help_text": "Slack workspace ID, used to route inbound replies back."},
+ }
+
+
+class SendCommentToSlackSerializer(serializers.Serializer):
+ integration_id = serializers.IntegerField(
+ help_text="ID of the Slack integration (kind='slack') whose bot posts the thread."
+ )
+ channel_id = serializers.CharField(
+ max_length=255,
+ help_text="Slack channel ID to create the mirrored thread in. The bot must be a member of the channel.",
+ )
+
+
@extend_schema(extensions={"x-product": "platform_features"})
class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet):
queryset = Comment.objects.all()
@@ -351,9 +463,47 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
def list(self, request, *args, **kwargs):
return super().list(request, *args, **kwargs)
+ def _slack_mirror_flag_enabled(self) -> bool:
+ """Whether discussions↔Slack sync is on for this user/team.
+
+ Keyed on the requesting user (plus org/project groups) so the gate agrees with the
+ frontend's per-user flag evaluation during partial rollouts.
+ """
+ team = self.team
+ flag_distinct_id = str(getattr(self.request.user, "distinct_id", None) or team.uuid)
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ DISCUSSIONS_SLACK_SYNC_FLAG,
+ flag_distinct_id,
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ )
+ )
+ except Exception:
+ return False
+
def get_serializer_context(self) -> dict[str, Any]:
context = super().get_serializer_context()
context["get_user_access_control"] = lambda: self.user_access_control
+ # Prefetch the discussion's Slack mirrors once (keyed by thread-root comment, 1:1) so the
+ # serializer's slack_thread field doesn't do a query per comment. Skipped entirely while
+ # the feature flag is off, so unflagged teams don't pay the lookup on a hot endpoint.
+ scope = self.request.GET.get("scope")
+ item_id = self.request.GET.get("item_id")
+ pk = self.kwargs.get("pk")
+ thread_by_comment: dict[str, CommentSlackThread] = {}
+ if ((scope and item_id) or pk) and self._slack_mirror_flag_enabled():
+ if scope and item_id:
+ for thread in CommentSlackThread.objects.for_team(self.team.id).filter(scope=scope, item_id=item_id):
+ if thread.source_comment_id:
+ thread_by_comment[str(thread.source_comment_id)] = thread
+ else:
+ # Detail responses (retrieve/update/complete/reopen) have no scope/item_id params; fetch
+ # the one possible mirror so slack_thread doesn't silently null out — the frontend
+ # replaces list entries with these responses, which would drop the Slack state.
+ for thread in CommentSlackThread.objects.for_team(self.team.id).filter(source_comment_id=pk):
+ thread_by_comment[str(thread.source_comment_id)] = thread
+ context["slack_thread_by_comment"] = thread_by_comment
return context
def _require_ticket_viewer_access_for_pk(self) -> None:
@@ -538,6 +688,115 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelV
serializer = CommentSerializer(comment, context=self.get_serializer_context())
return Response(serializer.data)
+ @extend_schema(
+ request=SendCommentToSlackSerializer,
+ responses=CommentSlackThreadSerializer,
+ description=(
+ "Mirror this discussion thread to a Slack channel. Posts the comment (and its existing "
+ "replies) as a new Slack thread; later replies on either side sync across. A discussion "
+ "mirrors to exactly one Slack thread: re-calling with the same channel returns the "
+ "existing mirror; a different channel is a 400 naming the existing one. 409 while a "
+ "concurrent send is in flight. 404 when the feature is not enabled for the team."
+ ),
+ )
+ @action(methods=["POST"], detail=True)
+ def send_to_slack(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ team = self.team
+ if not self._slack_mirror_flag_enabled():
+ raise exceptions.NotFound()
+
+ comment = self.get_object()
+ if comment.source_comment_id is not None:
+ raise exceptions.ValidationError("Only a top-level comment (a thread root) can be sent to Slack")
+ if comment.scope == "conversations_ticket":
+ raise exceptions.ValidationError("Conversations tickets sync to Slack through the support product")
+
+ params = SendCommentToSlackSerializer(data=request.data)
+ params.is_valid(raise_exception=True)
+ integration_id = params.validated_data["integration_id"]
+ channel_id = params.validated_data["channel_id"]
+
+ integration = Integration.objects.filter(team=team, id=integration_id, kind="slack").first()
+ if integration is None:
+ raise exceptions.ValidationError("Slack integration not found")
+
+ # Reserve the mapping before posting: a discussion mirrors to exactly one Slack thread (1:1),
+ # and the source_comment OneToOne makes this get_or_create race-safe — a double-click can't
+ # post two root messages.
+ slack_thread, created = CommentSlackThread.objects.for_team(team.id).get_or_create(
+ team=team,
+ source_comment=comment,
+ defaults={
+ "scope": comment.scope,
+ "item_id": comment.item_id,
+ "integration": integration,
+ "slack_channel_id": channel_id,
+ "slack_team_id": integration.integration_id,
+ "created_by": cast(User, request.user),
+ },
+ )
+ if not created:
+ if slack_thread.slack_thread_ts:
+ if slack_thread.slack_channel_id != channel_id:
+ raise exceptions.ValidationError(
+ "This discussion is already mirrored to Slack channel "
+ f"{slack_thread.slack_channel_id} — a discussion can only sync to one thread"
+ )
+ # Idempotent: already mirrored to this channel — return the mapping, no re-post.
+ return Response(CommentSlackThreadSerializer(slack_thread).data)
+ if timezone.now() - slack_thread.created_at < STALE_SLACK_RESERVATION_GRACE:
+ # Another request holds the reservation and its root post is still in flight.
+ raise Conflict("This discussion is already being sent to Slack — try again shortly")
+ # A reservation this old with no root message is a crashed send that would otherwise
+ # block the discussion forever. Adopt it and retry the post; resetting created_at
+ # re-bounds the reply backfill to this attempt.
+ slack_thread.integration = integration
+ slack_thread.slack_channel_id = channel_id
+ slack_thread.slack_team_id = integration.integration_id
+ slack_thread.created_by = cast(User, request.user)
+ slack_thread.created_at = timezone.now()
+ slack_thread.save(
+ update_fields=["integration", "slack_channel_id", "slack_team_id", "created_by", "created_at"]
+ )
+
+ author_name, author_email = slack_author_from_user(comment.created_by)
+ client = SlackIntegration(integration).client
+ client.timeout = 10 # keep a slow Slack workspace from pinning the request worker
+ try:
+ thread_ts = post_comment_to_slack_thread(
+ client=client,
+ channel=channel_id,
+ content=comment.content or "",
+ rich_content=comment.rich_content,
+ author_name=author_name,
+ author_email=author_email,
+ 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,
+ )
+ except Exception as e:
+ _release_slack_reservation(slack_thread)
+ # Surface Slack's error code (not_in_channel, channel_not_found, ...) — it's the
+ # actionable part for the user; the full exception is chained for error tracking.
+ slack_error = e.response.get("error") if isinstance(e, SlackApiError) and e.response else None
+ detail = (
+ f"Failed to post the discussion to Slack ({slack_error})"
+ if slack_error
+ else ("Failed to post the discussion to Slack")
+ )
+ raise exceptions.ValidationError(detail) from e
+ if not thread_ts:
+ _release_slack_reservation(slack_thread)
+ raise exceptions.ValidationError("Cannot send an empty comment to Slack")
+
+ slack_thread.slack_thread_ts = thread_ts
+ slack_thread.save(update_fields=["slack_thread_ts"])
+
+ # Backfill existing replies asynchronously so the request isn't blocked on N Slack posts.
+ backfill_comment_slack_thread.delay(comment_slack_thread_id=str(slack_thread.id))
+
+ return Response(CommentSlackThreadSerializer(slack_thread).data)
+
@staticmethod
def _log_task_state_change(comment: Comment, request: Request, *, completed: bool) -> None:
log_activity(
diff --git a/posthog/api/test/test_comment_slack_sync.py b/posthog/api/test/test_comment_slack_sync.py
new file mode 100644
index 000000000000..73d5cc35b14a
--- /dev/null
+++ b/posthog/api/test/test_comment_slack_sync.py
@@ -0,0 +1,508 @@
+from datetime import timedelta
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from celery.exceptions import Retry
+from parameterized import parameterized
+from rest_framework import status
+from slack_sdk.errors import SlackApiError
+
+from posthog.api.comments import _slack_thread_url
+from posthog.helpers.slack_thread_mirror import escape_slack_mrkdwn
+from posthog.models.comment import Comment, CommentSlackThread
+from posthog.models.integration import Integration
+from posthog.tasks.comment_slack_sync import (
+ BACKFILL_BATCH_SIZE,
+ BACKFILL_RESCHEDULE_COUNTDOWN_SECONDS,
+ SLACK_SYNCED_TS_KEY,
+ backfill_comment_slack_thread,
+ mirror_comment_reply_to_slack,
+)
+
+
+class TestSendCommentToSlack(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T123",
+ config={"authed_user": {"id": "u"}},
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+ def _comment(self, **kwargs) -> Comment:
+ defaults: dict = {
+ "team": self.team,
+ "scope": "Insight",
+ "item_id": "42",
+ "content": "hello",
+ "created_by": self.user,
+ }
+ defaults.update(kwargs)
+ return Comment.objects.create(**defaults)
+
+ @parameterized.expand(
+ [
+ # ts dot stripped, archives permalink form
+ ("with_ts", "1700.1", "https://app.slack.com/archives/C1/p17001"),
+ # not yet posted: link to the channel
+ ("no_ts", "", "https://app.slack.com/archives/C1"),
+ ]
+ )
+ def test_slack_thread_url(self, _name, ts, expected):
+ thread = CommentSlackThread(slack_channel_id="C1", slack_thread_ts=ts, slack_team_id="T123")
+ assert _slack_thread_url(thread) == expected
+
+ def _send(self, comment_id, channel_id: str = "C1", integration_id: int | None = None):
+ return self.client.post(
+ f"/api/projects/{self.team.id}/comments/{comment_id}/send_to_slack/",
+ {"integration_id": integration_id or self.integration.id, "channel_id": channel_id},
+ )
+
+ @patch("posthog.api.comments.backfill_comment_slack_thread.delay")
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.comments.SlackIntegration")
+ def test_creates_mirror_posts_root_and_enqueues_backfill(self, mock_slack, _flag, mock_backfill):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "1700.1"}
+ comment = self._comment()
+
+ res = self._send(comment.id)
+
+ assert res.status_code == status.HTTP_200_OK, res.json()
+ mirror = CommentSlackThread.objects.for_team(self.team.id).get()
+ assert mirror.source_comment_id == comment.id
+ assert mirror.slack_thread_ts == "1700.1"
+ assert (mirror.slack_channel_id, mirror.slack_team_id) == ("C1", "T123")
+ # Only the root is posted synchronously; replies are backfilled out-of-band.
+ assert mock_slack.return_value.client.chat_postMessage.call_count == 1
+ mock_backfill.assert_called_once_with(comment_slack_thread_id=str(mirror.id))
+
+ @patch("posthog.api.comments.backfill_comment_slack_thread.delay")
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.comments.SlackIntegration")
+ def test_idempotent_does_not_repost(self, mock_slack, _flag, _backfill):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "1700.1"}
+ comment = self._comment()
+
+ first = self._send(comment.id)
+ second = self._send(comment.id)
+
+ assert first.status_code == status.HTTP_200_OK
+ assert second.status_code == status.HTTP_200_OK
+ assert CommentSlackThread.objects.for_team(self.team.id).count() == 1
+ assert mock_slack.return_value.client.chat_postMessage.call_count == 1
+
+ @patch("posthog.api.comments.backfill_comment_slack_thread.delay")
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.comments.SlackIntegration")
+ def test_failed_post_releases_reservation(self, mock_slack, _flag, _backfill):
+ mock_slack.return_value.client.chat_postMessage.side_effect = Exception("slack down")
+ comment = self._comment()
+
+ res = self._send(comment.id)
+
+ assert res.status_code == status.HTTP_400_BAD_REQUEST
+ # The reserved row is rolled back so a later attempt isn't blocked by the idempotency check.
+ assert not CommentSlackThread.objects.for_team(self.team.id).exists()
+
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=False)
+ def test_404_when_flag_disabled(self, _flag):
+ comment = self._comment()
+
+ res = self._send(comment.id)
+
+ assert res.status_code == status.HTTP_404_NOT_FOUND
+ assert not CommentSlackThread.objects.for_team(self.team.id).exists()
+
+ @patch("posthog.api.comments.backfill_comment_slack_thread.delay")
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.comments.SlackIntegration")
+ def test_resend_to_different_channel_names_existing_one(self, mock_slack, _flag, _backfill):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "1700.1"}
+ comment = self._comment()
+ self._send(comment.id, channel_id="C1")
+
+ res = self._send(comment.id, channel_id="C2")
+
+ assert res.status_code == status.HTTP_400_BAD_REQUEST
+ assert "C1" in str(res.json())
+ # No second root post, mapping unchanged.
+ assert mock_slack.return_value.client.chat_postMessage.call_count == 1
+ assert CommentSlackThread.objects.for_team(self.team.id).get().slack_channel_id == "C1"
+
+ @patch("posthog.api.comments.backfill_comment_slack_thread.delay")
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.comments.SlackIntegration")
+ def test_in_flight_reservation_returns_409(self, mock_slack, _flag, _backfill):
+ comment = self._comment()
+ # A fresh reservation with no posted root — another request is mid-send.
+ CommentSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ scope="Insight",
+ item_id="42",
+ source_comment=comment,
+ integration=self.integration,
+ slack_channel_id="C1",
+ )
+
+ res = self._send(comment.id)
+
+ assert res.status_code == status.HTTP_409_CONFLICT
+ mock_slack.return_value.client.chat_postMessage.assert_not_called()
+
+ @patch("posthog.api.comments.backfill_comment_slack_thread.delay")
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.api.comments.SlackIntegration")
+ def test_stale_reservation_is_adopted_and_retried(self, mock_slack, _flag, mock_backfill):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "1700.9"}
+ comment = self._comment()
+ # A crashed send left an old reservation with no root message.
+ stale = CommentSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ scope="Insight",
+ item_id="42",
+ source_comment=comment,
+ integration=self.integration,
+ slack_channel_id="C1",
+ )
+ CommentSlackThread.objects.for_team(self.team.id).filter(id=stale.id).update(
+ created_at=timezone.now() - timedelta(minutes=10)
+ )
+
+ res = self._send(comment.id, channel_id="C2")
+
+ assert res.status_code == status.HTTP_200_OK, res.json()
+ mirror = CommentSlackThread.objects.for_team(self.team.id).get()
+ assert (mirror.slack_thread_ts, mirror.slack_channel_id) == ("1700.9", "C2")
+ mock_backfill.assert_called_once_with(comment_slack_thread_id=str(mirror.id))
+
+ @parameterized.expand([("reply", "source_comment"), ("unknown_integration", "integration")])
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ def test_rejects_invalid_target(self, _name, bad, _flag):
+ if bad == "source_comment":
+ parent = self._comment()
+ res = self._send(self._comment(source_comment=parent).id)
+ else:
+ res = self._send(self._comment().id, integration_id=999999)
+
+ assert res.status_code == status.HTTP_400_BAD_REQUEST
+ assert not CommentSlackThread.objects.for_team(self.team.id).exists()
+
+
+class TestCommentReplySlackSignal(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.parent = Comment.objects.create(team=self.team, scope="Insight", item_id="42", content="root")
+ self.other_parent = Comment.objects.create(team=self.team, scope="Insight", item_id="99", content="root2")
+ CommentSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ scope="Insight",
+ item_id="42",
+ source_comment=self.parent,
+ integration=self.integration,
+ slack_channel_id="C1",
+ slack_thread_ts="1700.1",
+ )
+
+ @parameterized.expand(
+ [
+ ("mirrored_reply", "parent", "Insight", None, True),
+ ("non_mirrored_reply", "other_parent", "Insight", None, False),
+ ("from_slack_reply_not_echoed", "parent", "Insight", {"from_slack": True}, False),
+ ("emoji_reaction_not_mirrored", "parent", "Insight", {"is_emoji": True}, False),
+ ("conversations_ticket_excluded", "parent", "conversations_ticket", None, False),
+ ("top_level_comment", None, "Insight", None, False),
+ ]
+ )
+ @patch("posthog.tasks.comment_slack_sync.mirror_comment_reply_to_slack.delay")
+ def test_reply_enqueues_only_when_it_should(
+ self, _name, parent_attr, scope, item_context, expected_called, mock_delay
+ ):
+ source = getattr(self, parent_attr) if parent_attr else None
+ # A valid-UUID item_id keeps the conversations product's own ticket signals (which parse
+ # item_id as a Ticket UUID for the conversations_ticket scope) from choking on this case.
+ item_id = "00000000-0000-0000-0000-000000000042"
+ with self.captureOnCommitCallbacks(execute=True):
+ Comment.objects.create(
+ team=self.team,
+ scope=scope,
+ item_id=item_id,
+ content="reply",
+ source_comment=source,
+ item_context=item_context,
+ created_by=self.user,
+ )
+
+ assert mock_delay.called is expected_called
+
+
+class TestReplyMirror(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.parent = Comment.objects.create(team=self.team, scope="Insight", item_id="42", content="root")
+
+ def _mirror(self) -> CommentSlackThread:
+ return CommentSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ scope="Insight",
+ item_id="42",
+ source_comment=self.parent,
+ integration=self.integration,
+ slack_channel_id="C1",
+ slack_thread_ts="100.1",
+ )
+
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_posts_reply_to_the_mirrored_thread(self, mock_slack):
+ self._mirror()
+ reply = Comment.objects.create(
+ team=self.team, scope="Insight", item_id="42", content="reply", source_comment=self.parent
+ )
+
+ mirror_comment_reply_to_slack.apply(kwargs={"comment_id": str(reply.id)})
+
+ client = mock_slack.return_value.client
+ assert client.chat_postMessage.call_count == 1
+ assert client.chat_postMessage.call_args.kwargs["thread_ts"] == "100.1"
+
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_noop_when_thread_has_no_mirror(self, mock_slack):
+ reply = Comment.objects.create(
+ team=self.team, scope="Insight", item_id="42", content="reply", source_comment=self.parent
+ )
+
+ mirror_comment_reply_to_slack.apply(kwargs={"comment_id": str(reply.id)})
+
+ mock_slack.assert_not_called()
+
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_reply_posts_once_across_task_reruns(self, mock_slack):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "100.2"}
+ self._mirror()
+ reply = Comment.objects.create(
+ team=self.team, scope="Insight", item_id="42", content="reply", source_comment=self.parent
+ )
+
+ # A Celery retry after a successful post re-runs the whole task; the synced marker
+ # stamped on the first run must prevent a duplicate Slack message.
+ mirror_comment_reply_to_slack.apply(kwargs={"comment_id": str(reply.id)})
+ mirror_comment_reply_to_slack.apply(kwargs={"comment_id": str(reply.id)})
+
+ assert mock_slack.return_value.client.chat_postMessage.call_count == 1
+ reply.refresh_from_db()
+ assert reply.item_context is not None
+ assert reply.item_context[SLACK_SYNCED_TS_KEY] == "100.2"
+
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_reply_retries_while_root_post_pending(self, mock_slack):
+ # Reservation exists but the root hasn't posted yet (send_to_slack mid-flight):
+ # the reply must be retried, not dropped and not posted out of order.
+ mirror = self._mirror()
+ CommentSlackThread.objects.for_team(self.team.id).filter(id=mirror.id).update(slack_thread_ts="")
+ reply = Comment.objects.create(
+ team=self.team, scope="Insight", item_id="42", content="reply", source_comment=self.parent
+ )
+
+ with self.assertRaises(Retry):
+ mirror_comment_reply_to_slack(comment_id=str(reply.id))
+
+ mock_slack.return_value.client.chat_postMessage.assert_not_called()
+
+ @patch("posthog.tasks.comment_slack_sync.posthoganalytics.feature_enabled", return_value=False)
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_kill_switch_stops_reply_sync(self, mock_slack, _flag):
+ self._mirror()
+ reply = Comment.objects.create(
+ team=self.team, scope="Insight", item_id="42", content="reply", source_comment=self.parent
+ )
+
+ mirror_comment_reply_to_slack.apply(kwargs={"comment_id": str(reply.id)})
+
+ mock_slack.assert_not_called()
+
+
+class TestBackfill(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.parent = Comment.objects.create(team=self.team, scope="Insight", item_id="42", content="root")
+
+ def _reply(self, content: str, **kwargs) -> Comment:
+ return Comment.objects.create(
+ team=self.team, scope="Insight", item_id="42", content=content, source_comment=self.parent, **kwargs
+ )
+
+ def _mirror(self) -> CommentSlackThread:
+ # Matches the real flow: replies exist first, then send_to_slack creates the mirror.
+ return CommentSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ scope="Insight",
+ item_id="42",
+ source_comment=self.parent,
+ integration=self.integration,
+ slack_channel_id="C1",
+ slack_thread_ts="100.1",
+ )
+
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_backfills_replies_and_skips_from_slack_and_emoji(self, mock_slack):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "100.2"}
+ self._reply("r1")
+ self._reply("r2")
+ # A reply that came in from Slack must not be echoed back; reactions aren't messages.
+ self._reply("from slack", item_context={"from_slack": True})
+ self._reply("👍", item_context={"is_emoji": True})
+ mirror = self._mirror()
+
+ backfill_comment_slack_thread(str(mirror.id))
+
+ # r1 + r2 only — from_slack and emoji replies are skipped, and the root isn't a reply.
+ assert mock_slack.return_value.client.chat_postMessage.call_count == 2
+
+ @patch("posthog.tasks.comment_slack_sync.time.sleep")
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_backfill_retries_once_after_slack_rate_limit(self, mock_slack, mock_sleep):
+ rate_limited = MagicMock()
+ rate_limited.get.side_effect = lambda key, default=None: {"error": "ratelimited"}.get(key, default)
+ rate_limited.headers = {"Retry-After": "2"}
+ mock_slack.return_value.client.chat_postMessage.side_effect = [
+ SlackApiError("ratelimited", rate_limited),
+ {"ts": "100.2"},
+ ]
+ reply = self._reply("r1")
+ mirror = self._mirror()
+
+ backfill_comment_slack_thread(str(mirror.id))
+
+ # The rate-limited post is retried after Slack's Retry-After instead of dropping the reply.
+ assert mock_slack.return_value.client.chat_postMessage.call_count == 2
+ mock_sleep.assert_called_once_with(2)
+ reply.refresh_from_db()
+ assert reply.item_context is not None
+ assert reply.item_context[SLACK_SYNCED_TS_KEY] == "100.2"
+
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_backfill_owns_only_replies_that_predate_the_mirror(self, mock_slack):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "100.2"}
+ self._reply("before")
+ mirror = self._mirror()
+ # Created after the mirror: the live post_save signal owns it — backfill posting it
+ # too is the double-post race.
+ self._reply("after")
+
+ backfill_comment_slack_thread(str(mirror.id))
+
+ assert mock_slack.return_value.client.chat_postMessage.call_count == 1
+
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_backfill_rerun_does_not_double_post(self, mock_slack):
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "100.2"}
+ self._reply("r1")
+ mirror = self._mirror()
+
+ backfill_comment_slack_thread(str(mirror.id))
+ backfill_comment_slack_thread(str(mirror.id))
+
+ assert mock_slack.return_value.client.chat_postMessage.call_count == 1
+
+ @patch("posthog.tasks.comment_slack_sync.backfill_comment_slack_thread.apply_async")
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_backfill_stops_at_the_batch_size_and_reschedules(self, mock_slack, mock_apply_async):
+ # Reply history is caller-controlled, so one run must not walk an unbounded thread while
+ # holding a shared worker.
+ mock_slack.return_value.client.chat_postMessage.return_value = {"ts": "100.2"}
+ for index in range(BACKFILL_BATCH_SIZE + 3):
+ self._reply(f"r{index}")
+ mirror = self._mirror()
+
+ backfill_comment_slack_thread(str(mirror.id))
+
+ assert mock_slack.return_value.client.chat_postMessage.call_count == BACKFILL_BATCH_SIZE
+ mock_apply_async.assert_called_once_with((str(mirror.id),), countdown=BACKFILL_RESCHEDULE_COUNTDOWN_SECONDS)
+
+ @patch("posthog.tasks.comment_slack_sync.backfill_comment_slack_thread.apply_async")
+ @patch("posthog.tasks.comment_slack_sync.SlackIntegration")
+ def test_backfill_does_not_reschedule_when_the_batch_posted_nothing(self, mock_slack, mock_apply_async):
+ # A failed post leaves the reply unstamped, so it stays in the next batch — rescheduling on
+ # "work remains" alone would requeue the same doomed batch forever.
+ mock_slack.return_value.client.chat_postMessage.side_effect = Exception("slack is down")
+ for index in range(BACKFILL_BATCH_SIZE + 3):
+ self._reply(f"r{index}")
+ mirror = self._mirror()
+
+ backfill_comment_slack_thread(str(mirror.id))
+
+ mock_apply_async.assert_not_called()
+
+
+class TestSlackThreadSerialization(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.parent = Comment.objects.create(team=self.team, scope="Insight", item_id="42", content="root")
+ self.mirror = CommentSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ scope="Insight",
+ item_id="42",
+ source_comment=self.parent,
+ integration=self.integration,
+ slack_channel_id="C1",
+ slack_thread_ts="1700.1",
+ )
+
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ def test_detail_response_includes_slack_thread(self, _mock_flag):
+ # Detail responses replace list entries client-side — dropping slack_thread there
+ # made the "Open in Slack" state vanish after an edit/complete.
+ res = self.client.get(f"/api/projects/{self.team.id}/comments/{self.parent.id}/")
+
+ assert res.status_code == status.HTTP_200_OK
+ assert res.json()["slack_thread"] == {
+ "channel_id": "C1",
+ "url": "https://app.slack.com/archives/C1/p17001",
+ }
+
+ @patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=True)
+ def test_unposted_reservation_serializes_as_null(self, _mock_flag):
+ # A reservation with no root message isn't a live mirror; reporting it would show a
+ # dead "Open in Slack" link and hide re-sending.
+ CommentSlackThread.objects.for_team(self.team.id).filter(id=self.mirror.id).update(slack_thread_ts="")
+
+ res = self.client.get(f"/api/projects/{self.team.id}/comments/?scope=Insight&item_id=42")
+
+ assert res.status_code == status.HTTP_200_OK
+ results = {r["id"]: r for r in res.json()["results"]}
+ assert results[str(self.parent.id)]["slack_thread"] is None
+
+ def test_slack_thread_lookup_skipped_when_flag_off(self):
+ # Unflagged teams must not pay the mirror lookup on the hot comments endpoint.
+ with patch("posthog.api.comments.posthoganalytics.feature_enabled", return_value=False):
+ res = self.client.get(f"/api/projects/{self.team.id}/comments/{self.parent.id}/")
+ assert res.status_code == status.HTTP_200_OK
+ assert res.json()["slack_thread"] is None
+
+
+class TestEscapeSlackMrkdwn(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("link_injection", "<https://evil|click>", "&lt;https://evil|click&gt;"),
+ ("ampersand", "Tom & Jerry", "Tom &amp; Jerry"),
+ ("plain", "Alice", "Alice"),
+ ]
+ )
+ def test_escapes_slack_control_chars(self, _name, raw, expected):
+ assert escape_slack_mrkdwn(raw) == expected
diff --git a/posthog/api/test/test_comments.py b/posthog/api/test/test_comments.py
index 5ed55eb4a6da..d17597435514 100644
--- a/posthog/api/test/test_comments.py
+++ b/posthog/api/test/test_comments.py
@@ -75,6 +75,7 @@ class TestComments(APIBaseTest, QueryMatchingTest):
"is_task": False,
"completed_at": None,
"completed_by": None,
+ "slack_thread": None,
}
def test_updates_content_and_increments_version(self) -> None:
@@ -106,6 +107,7 @@ class TestComments(APIBaseTest, QueryMatchingTest):
"is_task": False,
"completed_at": None,
"completed_by": None,
+ "slack_thread": None,
}
def test_empty_comments_list(self) -> None:
@@ -661,6 +663,13 @@ class TestComments(APIBaseTest, QueryMatchingTest):
)
assert response.status_code == status.HTTP_403_FORBIDDEN
+ def test_reserved_slack_sync_item_context_keys_are_stripped(self) -> None:
+ # Forged sync state would let a caller suppress mirroring or spoof Slack attribution.
+ created = self._create_comment(
+ {"item_context": {"from_slack": True, "slack_synced_ts": "123.456", "is_emoji": False}}
+ )
+ assert created["item_context"] == {"is_emoji": False}
+
def test_ticket_scope_key_cannot_write_non_ticket_comment_via_body_scope(self) -> None:
comment = Comment.objects.create(
team=self.team, scope="Notebook", item_id="n1", content="note", created_by=self.user
@@ -1156,6 +1165,14 @@ class TestCommentHelperFunctions(APIBaseTest):
("without_slug_replay", "Replay", "rec_123", "", "/replay/rec_123#panel=discussion"),
("without_slug_feature_flag", "FeatureFlag", "10", "", "/feature_flags/10#panel=discussion"),
("unknown_scope_fallback", "UnknownScope", "123", "", "#panel=discussion"),
+ # item_id is client-supplied free text — mrkdwn/URL control chars must be encoded.
+ (
+ "item_id_with_mrkdwn_chars",
+ "Notebook",
+ "x|<!channel>y",
+ "",
+ "/notebooks/x%7C%3C%21channel%3Ey#panel=discussion",
+ ),
]
)
def test_build_comment_item_url(self, name: str, scope: str, item_id: str, slug: str, expected_suffix: str) -> None:
diff --git a/posthog/helpers/slack_thread_mirror.py b/posthog/helpers/slack_thread_mirror.py
new file mode 100644
index 000000000000..ecafad0603fe
--- /dev/null
+++ b/posthog/helpers/slack_thread_mirror.py
@@ -0,0 +1,123 @@
+"""Post PostHog comment content into a Slack thread.
+
+Token-agnostic: the caller supplies a ``slack_sdk.WebClient`` built from whichever workspace
+bot token applies (the generic Slack ``Integration``, the conversations SupportHog bot, ...).
+The inbound counterpart — ingesting Slack replies back as comments — is wired separately where
+the Slack event webhook lives.
+"""
+
+from uuid import UUID
+
+import structlog
+from slack_sdk import WebClient
+
+from posthog.comment.formatting import escape_slack_mrkdwn, rich_content_to_slack_payload
+from posthog.helpers.slack_identity import resolve_slack_avatar_by_email
+
+logger = structlog.get_logger(__name__)
+
+
+def slack_author_from_user(user: object | None) -> tuple[str, str]:
+ """Resolve a comment author to (display_name, email) for the Slack post.
+
+ ``user`` is a ``User`` (typed loosely to avoid importing the model here). Falls back to a
+ neutral "PostHog" name with no email for system/AI-authored comments.
+ """
+ if user is not None:
+ name = f"{getattr(user, 'first_name', '')} {getattr(user, 'last_name', '')}".strip() or getattr(
+ user, "email", ""
+ )
+ return name or "PostHog", getattr(user, "email", "") or ""
+ return "PostHog", ""
+
+
+def _mrkdwn_safe_url(url: str) -> str:
+ """Percent-encode the characters that terminate or split a mrkdwn ``<url|label>`` link."""
+ return url.replace("<", "%3C").replace(">", "%3E").replace("|", "%7C")
+
+
+def _discussion_card_blocks(*, body_mrkdwn: str, author_name: str, item_url: str, item_label: str) -> list[dict]:
+ """A Block Kit card for the thread root: 'New comment on <link> from <author>', the comment
+ body, and an 'Open in PostHog' button. Replies stay plain text since they're threaded under it.
+ """
+ return [
+ {
+ "type": "section",
+ "text": {
+ "type": "mrkdwn",
+ "text": f":speech_balloon: New comment on <{_mrkdwn_safe_url(item_url)}|{escape_slack_mrkdwn(item_label)}>",
+ },
+ },
+ {"type": "context", "elements": [{"type": "mrkdwn", "text": f"From *{escape_slack_mrkdwn(author_name)}*"}]},
+ {"type": "section", "text": {"type": "mrkdwn", "text": body_mrkdwn or "_(no text)_"}},
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Open in PostHog", "emoji": True},
+ "url": item_url,
+ }
+ ],
+ },
+ ]
+
+
+def post_comment_to_slack_thread(
+ *,
+ client: WebClient,
+ channel: str,
+ content: str,
+ rich_content: dict | None,
+ author_name: str,
+ author_email: str = "",
+ thread_ts: str | None = None,
+ item_url: str | None = None,
+ item_label: str | None = None,
+ organization_id: str | UUID | None = None,
+) -> str | None:
+ """Post a comment's content to a Slack channel, optionally threaded under ``thread_ts``.
+
+ When ``item_url`` is given (the thread root), the message renders as a card linking back to the
+ discussion; otherwise (replies) it's a plain threaded message. ``organization_id`` scopes
+ @-mention resolution — without it every mention renders as a generic teammate. Returns the
+ posted message's ``ts`` so the caller can anchor a mirror on the first post, or ``None`` when
+ there was nothing to post. Raises on a Slack API failure so callers can react (the API action
+ surfaces an error; the Celery tasks retry) instead of silently dropping the message.
+ """
+ slack_text, slack_blocks = rich_content_to_slack_payload(
+ rich_content, content, include_images=False, organization_id=organization_id
+ )
+ if not slack_text.strip() and not slack_blocks:
+ 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
+
+ message_kwargs: dict = {
+ "channel": channel,
+ "text": slack_text,
+ "username": author_name or "PostHog",
+ }
+ if thread_ts:
+ message_kwargs["thread_ts"] = thread_ts
+ if icon_url:
+ message_kwargs["icon_url"] = icon_url
+
+ if item_url:
+ message_kwargs["blocks"] = _discussion_card_blocks(
+ body_mrkdwn=slack_text,
+ author_name=author_name,
+ item_url=item_url,
+ item_label=item_label or "the discussion",
+ )
+ # text stays as the plain body for notification previews / fallback clients.
+ elif slack_blocks:
+ message_kwargs["blocks"] = slack_blocks
+
+ try:
+ response = client.chat_postMessage(**message_kwargs)
+ except Exception as e:
+ logger.warning("slack_thread_mirror_post_failed", channel=channel, thread_ts=thread_ts, error=str(e))
+ raise
+ return response.get("ts")
diff --git a/posthog/migrations/1291_commentslackthread.py b/posthog/migrations/1291_commentslackthread.py
new file mode 100644
index 000000000000..bd8164dba601
--- /dev/null
+++ b/posthog/migrations/1291_commentslackthread.py
@@ -0,0 +1,89 @@
+# Generated by Django 5.2.14 on 2026-07-03 08:40
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1290_backfill_identity_provider_config_identifiers"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CommentSlackThread",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("scope", models.CharField(max_length=79)),
+ ("item_id", models.CharField(blank=True, max_length=72, null=True)),
+ ("slack_channel_id", models.CharField(max_length=255)),
+ (
+ "slack_thread_ts",
+ models.CharField(blank=True, default="", max_length=255),
+ ),
+ (
+ "slack_team_id",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "created_by",
+ models.ForeignKey(
+ blank=True,
+ db_constraint=False,
+ db_index=False,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ (
+ "integration",
+ models.ForeignKey(
+ help_text="Slack integration whose bot token posts to and reads from the mirrored thread",
+ limit_choices_to={"kind": "slack"},
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.integration",
+ ),
+ ),
+ (
+ "source_comment",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.comment",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["team_id", "scope", "item_id"],
+ name="posthog_com_team_id_5c412f_idx",
+ ),
+ models.Index(
+ fields=["slack_channel_id", "slack_thread_ts"],
+ name="posthog_com_slack_c_7add63_idx",
+ ),
+ ],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index f2d211f6cee0..3fe81b0351dc 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1290_backfill_identity_provider_config_identifiers
+1291_commentslackthread
diff --git a/posthog/models/__init__.py b/posthog/models/__init__.py
index 0a67ab5cce99..b9b2aee743ef 100644
--- a/posthog/models/__init__.py
+++ b/posthog/models/__init__.py
@@ -11,7 +11,7 @@ from .activity_logging.notification_viewed import NotificationViewed
from .async_deletion import AsyncDeletion, DeletionType
from .async_migration import AsyncMigration, AsyncMigrationError, MigrationStatus
from .column_configuration import ColumnConfiguration
-from .comment import Comment
+from .comment import Comment, CommentSlackThread
from .core_event import CoreEvent
from .data_deletion_request import DataDeletionRequest
from .data_color_theme import DataColorTheme
@@ -185,6 +185,7 @@ __all__ = [
"WebAnalyticsFilterPreset",
"ScheduledChange",
"Comment",
+ "CommentSlackThread",
# Deprecated models here for backwards compatibility
"Prompt",
"PromptSequence",
diff --git a/posthog/models/comment/__init__.py b/posthog/models/comment/__init__.py
index 2db964fcf3f0..0e7b9cd29204 100644
--- a/posthog/models/comment/__init__.py
+++ b/posthog/models/comment/__init__.py
@@ -1,3 +1,4 @@
from .comment import Comment
+from .slack_thread import CommentSlackThread
-__all__ = ["Comment"]
+__all__ = ["Comment", "CommentSlackThread"]
diff --git a/posthog/models/comment/slack_thread.py b/posthog/models/comment/slack_thread.py
new file mode 100644
index 000000000000..8514ee04a09a
--- /dev/null
+++ b/posthog/models/comment/slack_thread.py
@@ -0,0 +1,92 @@
+from django.db import models, transaction
+
+from posthog.models.comment.comment import Comment
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.signals import mutable_receiver
+from posthog.models.utils import UUIDModel
+
+# Gates creating new mirrors (fail-closed, in the send_to_slack action) and doubles as the
+# kill switch for syncing on existing mirrors (explicit-off, in the Celery tasks and the
+# inbound ingest) — flipping it off during an incident halts all mirror traffic.
+DISCUSSIONS_SLACK_SYNC_FLAG = "discussions-slack-sync"
+
+
+class CommentSlackThread(TeamScopedRootMixin, UUIDModel):
+ """Maps a discussion thread to a mirrored Slack thread so replies sync both ways.
+
+ Keyed on the thread-root comment (``source_comment``), so a single item — e.g. an
+ insight — can have many independently-synced threads, each to its own Slack channel.
+ ``scope`` / ``item_id`` are denormalized from the thread root so a discussion's synced
+ threads can be listed without loading every comment.
+ """
+
+ # db_constraint=False: posthog_team is a hot table; a real FK constraint would lock it on
+ # CREATE TABLE. Tenant isolation is enforced by the fail-closed TeamScopedManager, not the DB FK.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+
+ scope = models.CharField(max_length=79)
+ item_id = models.CharField(max_length=72, null=True, blank=True)
+ # The thread-root comment this Slack thread mirrors. One Slack thread per discussion (1:1):
+ # the OneToOne is the uniqueness guard that makes send_to_slack's get_or_create race-safe.
+ source_comment = models.OneToOneField("posthog.Comment", on_delete=models.CASCADE)
+
+ integration = models.ForeignKey(
+ "posthog.Integration",
+ on_delete=models.CASCADE,
+ limit_choices_to={"kind": "slack"},
+ help_text="Slack integration whose bot token posts to and reads from the mirrored thread",
+ )
+ slack_channel_id = models.CharField(max_length=255)
+ # Empty until the root message is posted — the row is reserved first to win the race for this
+ # (team, source_comment, channel) before any Slack call, then the ts is filled in.
+ slack_thread_ts = models.CharField(max_length=255, blank=True, default="")
+ # Slack workspace id, used to route inbound thread replies back to this mapping.
+ slack_team_id = models.CharField(max_length=255, null=True, blank=True)
+
+ created_at = models.DateTimeField(auto_now_add=True)
+ # db_constraint=False: posthog_user is a hot table (see team above).
+ created_by = models.ForeignKey(
+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_index=False, db_constraint=False
+ )
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["team_id", "scope", "item_id"]),
+ # The inbound Slack webhook resolves every threaded message via
+ # (integration, slack_channel_id, slack_thread_ts) — keep that lookup off a seq scan.
+ models.Index(fields=["slack_channel_id", "slack_thread_ts"]),
+ ]
+
+
+@mutable_receiver(models.signals.post_save, sender=Comment)
+def mirror_comment_reply_to_slack_on_create(sender, instance: Comment, created: bool, **kwargs) -> None:
+ """Sync a newly-created discussion reply out to any mirrored Slack threads.
+
+ Only replies (``source_comment`` set) sync — the thread root is posted by the send_to_slack
+ action. Conversations tickets are excluded (that product has its own Slack sync),
+ Slack-originated replies (``item_context.from_slack``) are skipped to avoid echo loops, and
+ emoji reactions (``item_context.is_emoji`` — stored as reply comments) don't post as messages.
+ """
+ if not created or not instance.source_comment_id:
+ return
+ if instance.scope == "conversations_ticket":
+ return
+ item_context = instance.item_context
+ if isinstance(item_context, dict) and (item_context.get("from_slack") or item_context.get("is_emoji")):
+ return
+ if (
+ not CommentSlackThread.objects.for_team(instance.team_id)
+ .filter(source_comment_id=instance.source_comment_id)
+ .exists()
+ ):
+ return
+
+ comment_id = str(instance.id)
+
+ def _enqueue() -> None:
+ # Deferred import: this module loads at django.setup(); keep the Slack/Celery deps off that path.
+ from posthog.tasks.comment_slack_sync import mirror_comment_reply_to_slack # noqa: PLC0415
+
+ mirror_comment_reply_to_slack.delay(comment_id=comment_id)
+
+ transaction.on_commit(_enqueue)
diff --git a/posthog/models/comment/utils.py b/posthog/models/comment/utils.py
index 4f72b3449a8f..9f905149967f 100644
--- a/posthog/models/comment/utils.py
+++ b/posthog/models/comment/utils.py
@@ -1,4 +1,5 @@
from typing import TYPE_CHECKING, Any, Optional
+from urllib.parse import quote
from django.conf import settings
@@ -43,12 +44,33 @@ SCOPE_TO_PATH_MAPPING: dict[str, str] = {
"Ticket": "/support/tickets/{item_id}",
}
+# Human-readable scope names for user-facing surfaces (e.g. the mirrored Slack card) —
+# raw scope values are internal CamelCase enums and read as jargon.
+SCOPE_DISPLAY_NAMES: dict[str, str] = {
+ "Replay": "a session recording",
+ "Notebook": "a notebook",
+ "Insight": "an insight",
+ "FeatureFlag": "a feature flag",
+ "Dashboard": "a dashboard",
+ "Survey": "a survey",
+ "Experiment": "an experiment",
+ "ErrorTracking": "an error tracking issue",
+ "Ticket": "a support ticket",
+}
+
+
+def comment_scope_display_name(scope: str) -> str:
+ return SCOPE_DISPLAY_NAMES.get(scope, "the discussion")
+
def build_comment_item_url(scope: str, item_id: Optional[str], slug: Optional[str] = None) -> str:
if slug:
url = f"{settings.SITE_URL}{slug}"
elif scope in SCOPE_TO_PATH_MAPPING and item_id:
- path = SCOPE_TO_PATH_MAPPING[scope].format(item_id=item_id)
+ # item_id is a free-form client-supplied CharField — percent-encode it so characters
+ # with meaning downstream (Slack mrkdwn `|`/`>` in links, URL delimiters) can't break
+ # or redirect the rendered link.
+ path = SCOPE_TO_PATH_MAPPING[scope].format(item_id=quote(str(item_id), safe=""))
url = f"{settings.SITE_URL}{path}"
else:
url = settings.SITE_URL
diff --git a/posthog/tasks/__init__.py b/posthog/tasks/__init__.py
index 78860776c846..6a32db638d04 100644
--- a/posthog/tasks/__init__.py
+++ b/posthog/tasks/__init__.py
@@ -4,6 +4,7 @@ from . import (
activity_log,
async_migrations,
calculate_cohort,
+ comment_slack_sync,
demo_create_data,
demo_reset_master_team,
early_access_feature,
@@ -30,6 +31,7 @@ __all__ = [
"activity_log",
"async_migrations",
"calculate_cohort",
+ "comment_slack_sync",
"demo_create_data",
"demo_reset_master_team",
"early_access_feature",
diff --git a/posthog/tasks/comment_slack_sync.py b/posthog/tasks/comment_slack_sync.py
new file mode 100644
index 000000000000..55a8bdae5faf
--- /dev/null
+++ b/posthog/tasks/comment_slack_sync.py
@@ -0,0 +1,241 @@
+import time
+
+import structlog
+import posthoganalytics
+from celery import Task, shared_task
+from slack_sdk import WebClient
+from slack_sdk.errors import SlackApiError
+
+from posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_user
+from posthog.models.comment import Comment, CommentSlackThread
+from posthog.models.comment.slack_thread import DISCUSSIONS_SLACK_SYNC_FLAG
+from posthog.models.integration import SlackIntegration
+from posthog.models.team import Team
+from posthog.scoping_audit import skip_team_scope_audit
+
+logger = structlog.get_logger(__name__)
+
+# 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"
+
+# A discussion's reply history is caller-controlled and unbounded, and each post can block on a
+# rate-limit wait, so one backfill run takes a bounded slice and reschedules the rest. Without
+# this, mirroring a few large discussions could hold shared workers for a long time.
+BACKFILL_BATCH_SIZE = 25
+BACKFILL_SLEEP_BUDGET_SECONDS = 60
+BACKFILL_RESCHEDULE_COUNTDOWN_SECONDS = 60
+
+
+def _organization_id_for_team(team_id: int) -> str | None:
+ return Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()
+
+
+def _sync_killed(team_id: int) -> bool:
+ """Kill switch for syncing on existing mirrors: only an explicit flag *off* halts it.
+
+ The fail-closed creation gate is send_to_slack; here a flag-evaluation error or missing
+ flag (None) must not silently drop user replies, so only False stops the sync. Evaluated
+ with the same org/project groups as the request path, so a project-targeted disable also
+ stops sync on mirrors that already exist.
+ """
+ try:
+ team_ref = Team.objects.filter(id=team_id).values_list("uuid", "organization_id").first()
+ if team_ref is None:
+ return False
+ team_uuid, organization_id = team_ref
+ return (
+ posthoganalytics.feature_enabled(
+ DISCUSSIONS_SLACK_SYNC_FLAG,
+ str(team_uuid),
+ groups={"organization": str(organization_id), "project": str(team_id)},
+ )
+ is False
+ )
+ except Exception:
+ return False
+
+
+def _slack_retry_after(exc: Exception) -> int | None:
+ """Seconds Slack asked us to wait when the failure is a rate limit; None for other errors."""
+ if not isinstance(exc, SlackApiError) or exc.response is None:
+ return None
+ if exc.response.get("error") != "ratelimited":
+ return None
+ try:
+ return min(int(exc.response.headers.get("Retry-After", "1")), 30)
+ except (AttributeError, TypeError, ValueError):
+ return 1
+
+
+def _post_backfill_reply(
+ client: WebClient, mirror: CommentSlackThread, reply: Comment, organization_id: str | None
+) -> str | None:
+ author_name, author_email = slack_author_from_user(reply.created_by)
+ return post_comment_to_slack_thread(
+ client=client,
+ channel=mirror.slack_channel_id,
+ content=reply.content or "",
+ rich_content=reply.rich_content,
+ author_name=author_name,
+ author_email=author_email,
+ thread_ts=mirror.slack_thread_ts,
+ organization_id=organization_id,
+ )
+
+
+def _log_backfill_reply_failure(comment_slack_thread_id: str, reply: Comment) -> None:
+ logger.warning(
+ "comment_slack_backfill_reply_failed",
+ comment_slack_thread_id=comment_slack_thread_id,
+ comment_id=str(reply.id),
+ )
+
+
+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 ""
+ Comment.objects.filter(id=reply.id).update(item_context=item_context)
+
+
+def _reply_skip_reason(reply: Comment) -> str | None:
+ item_context = reply.item_context if isinstance(reply.item_context, dict) else {}
+ if item_context.get("from_slack"):
+ return "from_slack" # came in from Slack — echoing it back would loop
+ if item_context.get("is_emoji"):
+ return "emoji" # reactions are stored as reply comments but aren't messages
+ if SLACK_SYNCED_TS_KEY in item_context:
+ return "already_synced"
+ return None
+
+
+# Retry budget must outlast a slow root post in send_to_slack (up to two 10s Slack calls),
+# or a reply created mid-send would exhaust retries and never reach the thread.
+@shared_task(bind=True, ignore_result=True, max_retries=6, default_retry_delay=10)
+@skip_team_scope_audit # Comment is on RootTeamManager; queries pin the team via the comment/mirror rows
+def mirror_comment_reply_to_slack(self: Task, comment_id: str) -> None:
+ """Post a newly-created discussion reply into its parent's mirrored Slack thread.
+
+ A discussion mirrors to exactly one Slack thread (1:1). Retries on a Slack failure rather
+ than silently dropping the reply, and stamps the posted ts onto the reply so a retry after
+ a successful post (e.g. worker death between the Slack ack and the task ack) can't re-post.
+ """
+ comment = Comment.objects.filter(id=comment_id).select_related("created_by").first()
+ if comment is None or not comment.source_comment_id or _reply_skip_reason(comment):
+ return
+ if _sync_killed(comment.team_id):
+ return
+
+ mirror = (
+ CommentSlackThread.objects.for_team(comment.team_id)
+ .filter(source_comment_id=comment.source_comment_id)
+ .select_related("integration")
+ .first()
+ )
+ if mirror is None:
+ return
+ if not mirror.slack_thread_ts:
+ # Reserved but the root post hasn't landed yet (send_to_slack mid-flight) — retry rather
+ # than dropping the reply. A failed root post deletes the reservation, so the retry then
+ # exits on mirror is None.
+ raise self.retry()
+
+ author_name, author_email = slack_author_from_user(comment.created_by)
+ try:
+ client = SlackIntegration(mirror.integration).client
+ posted_ts = post_comment_to_slack_thread(
+ client=client,
+ channel=mirror.slack_channel_id,
+ content=comment.content or "",
+ rich_content=comment.rich_content,
+ author_name=author_name,
+ author_email=author_email,
+ thread_ts=mirror.slack_thread_ts,
+ organization_id=_organization_id_for_team(comment.team_id),
+ )
+ except Exception as exc:
+ raise self.retry(exc=exc)
+ _mark_reply_synced(comment, posted_ts)
+
+
+@shared_task(ignore_result=True)
+@skip_team_scope_audit # Comment is on RootTeamManager; the reply query filters by the mirror's team_id
+def backfill_comment_slack_thread(comment_slack_thread_id: str) -> None:
+ """Post a discussion's pre-existing replies into a freshly-mirrored Slack thread.
+
+ Runs asynchronously after send_to_slack — so the request isn't blocked on N sequential Slack
+ posts. Bounded to replies created before the mirror: later replies belong exclusively to the
+ live post_save signal, so the two paths can't both post the same reply. Best-effort per reply —
+ a failure on one is logged and skipped — and each success is stamped with its posted ts, so a
+ re-run never double-posts.
+
+ Each run takes at most BACKFILL_BATCH_SIZE replies and spends at most
+ BACKFILL_SLEEP_BUDGET_SECONDS waiting out rate limits, then reschedules itself for the rest.
+ That keeps one big discussion from occupying a shared worker for an unbounded stretch.
+ """
+ mirror = (
+ CommentSlackThread.objects.unscoped().filter(id=comment_slack_thread_id).select_related("integration").first()
+ )
+ if mirror is None or not mirror.source_comment_id or not mirror.slack_thread_ts:
+ return
+ if _sync_killed(mirror.team_id):
+ return
+
+ try:
+ client = SlackIntegration(mirror.integration).client
+ except Exception:
+ logger.warning("comment_slack_backfill_client_failed", comment_slack_thread_id=comment_slack_thread_id)
+ return
+
+ organization_id = _organization_id_for_team(mirror.team_id)
+
+ # source_comment_id matches the thread root, so this returns its replies (not the root itself).
+ # Already-stamped replies are excluded in SQL rather than skipped in Python, so each run's
+ # batch is fresh work and a rescheduled run makes progress instead of re-walking the tail.
+ replies = (
+ Comment.objects.filter(
+ team_id=mirror.team_id,
+ source_comment_id=mirror.source_comment_id,
+ deleted=False,
+ created_at__lt=mirror.created_at,
+ )
+ .exclude(item_context__has_key=SLACK_SYNCED_TS_KEY)
+ .select_related("created_by")
+ .order_by("created_at")
+ )
+ batch = list(replies[: BACKFILL_BATCH_SIZE + 1])
+ remaining = len(batch) > BACKFILL_BATCH_SIZE
+ slept_seconds = 0
+ synced_any = False
+ for reply in batch[:BACKFILL_BATCH_SIZE]:
+ if slept_seconds >= BACKFILL_SLEEP_BUDGET_SECONDS:
+ remaining = True
+ break
+ if _reply_skip_reason(reply):
+ continue
+ try:
+ posted_ts = _post_backfill_reply(client, mirror, reply, organization_id)
+ except Exception as exc:
+ # chat.postMessage allows ~1 msg/sec per channel, so a long backfill will get rate
+ # limited; honoring Retry-After once keeps the whole thread mirroring instead of
+ # silently dropping its tail.
+ retry_after = _slack_retry_after(exc)
+ if retry_after is None:
+ _log_backfill_reply_failure(comment_slack_thread_id, reply)
+ continue
+ time.sleep(retry_after)
+ slept_seconds += retry_after
+ try:
+ posted_ts = _post_backfill_reply(client, mirror, reply, organization_id)
+ except Exception:
+ _log_backfill_reply_failure(comment_slack_thread_id, reply)
+ continue
+ _mark_reply_synced(reply, posted_ts)
+ synced_any = True
+
+ # Only continue while the run is actually draining the queue. A batch where every post failed
+ # leaves the same rows unstamped, so rescheduling on `remaining` alone would loop forever.
+ if remaining and synced_any:
+ backfill_comment_slack_thread.apply_async(
+ (comment_slack_thread_id,), countdown=BACKFILL_RESCHEDULE_COUNTDOWN_SECONDS
+ )
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index dfb7ebb56a03..9fbedee8ede3 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -19,6 +19,8 @@
'posthog.tasks.calculate_cohort.insert_cohort_from_filters',
'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.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',
'posthog.tasks.early_access_feature.send_events_for_early_access_feature_stage_change',
diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txt
index acc11544cd3b..73996450869d 100644
--- a/posthog/test/setup_receivers_baseline.txt
+++ b/posthog/test/setup_receivers_baseline.txt
@@ -108,6 +108,7 @@ post_save:ee.vercel.integration.sync_feature_flag_experimentation_item
post_save:posthog.caching.organization_serializer_cache._connect_invalidation.<locals>.receiver_fn
post_save:posthog.models.activity_logging.activity_log.activity_log_created
post_save:posthog.models.comment.comment.log_comment_activity
+post_save:posthog.models.comment.slack_thread.mirror_comment_reply_to_slack_on_create
post_save:posthog.models.event_ingestion_restriction_config.update_redis_cache_with_config
post_save:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__init_subclass__.<locals>._file_system_post_save
post_save:posthog.models.file_system.user_product_list.access_control_created
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 0a750fb452eb..a584043c931c 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -760,6 +760,13 @@ export interface ChangeRequestRejectApi {
reason: string
}
+export interface CommentSlackThreadRefApi {
+ /** Slack channel ID this discussion is mirrored to. */
+ channel_id: string
+ /** Deep link that opens the mirrored Slack thread. */
+ url: string
+}
+
export interface CommentApi {
readonly id: string
readonly created_by: UserBasicApi
@@ -771,6 +778,8 @@ export interface CommentApi {
is_task?: boolean
/** The user who marked this task complete. Null for open tasks and non-task comments. */
readonly completed_by: UserBasicApi | null
+ /** The Slack thread this comment's discussion is mirrored to, or null. Set only on a tracked thread-root comment; used to surface an 'Open in Slack' link and hide re-sending. */
+ readonly slack_thread: CommentSlackThreadRefApi | null
/** @nullable */
content?: string | null
rich_content?: unknown
@@ -812,6 +821,8 @@ export interface PatchedCommentApi {
is_task?: boolean
/** The user who marked this task complete. Null for open tasks and non-task comments. */
readonly completed_by?: UserBasicApi | null
+ /** The Slack thread this comment's discussion is mirrored to, or null. Set only on a tracked thread-root comment; used to surface an 'Open in Slack' link and hide re-sending. */
+ readonly slack_thread?: CommentSlackThreadRefApi | null
/** @nullable */
content?: string | null
rich_content?: unknown
@@ -834,6 +845,43 @@ export interface PatchedCommentApi {
source_comment?: string | null
}
+export interface SendCommentToSlackApi {
+ /** ID of the Slack integration (kind='slack') whose bot posts the thread. */
+ integration_id: number
+ /**
+ * Slack channel ID to create the mirrored thread in. The bot must be a member of the channel.
+ * @maxLength 255
+ */
+ channel_id: string
+}
+
+export interface CommentSlackThreadApi {
+ readonly id: string
+ /** Resource type of the mirrored discussion (e.g. Insight). */
+ readonly scope: string
+ /**
+ * ID of the resource the discussion is attached to.
+ * @nullable
+ */
+ readonly item_id: string | null
+ /** The thread-root comment whose replies mirror to the Slack thread. */
+ readonly source_comment: string
+ /** Slack integration used to post to and read from the thread. */
+ readonly integration: number
+ /** Slack channel the mirrored thread lives in. */
+ readonly slack_channel_id: string
+ /** Slack thread timestamp anchoring the mirrored thread. */
+ readonly slack_thread_ts: string
+ /**
+ * Slack workspace ID, used to route inbound replies back.
+ * @nullable
+ */
+ readonly slack_team_id: string | null
+ readonly created_at: string
+ /** User who mirrored the discussion. Null if since deleted. */
+ readonly created_by: UserBasicApi | null
+}
+
export interface PinnedSceneTabApi {
/** Stable identifier for the tab. Generated client-side; safe to omit on create. */
id?: string
diff --git a/products/platform_features/frontend/generated/api.ts b/products/platform_features/frontend/generated/api.ts
index 07fa3907ec7b..3c2573ca0547 100644
--- a/products/platform_features/frontend/generated/api.ts
+++ b/products/platform_features/frontend/generated/api.ts
@@ -21,6 +21,7 @@ import type {
ChangeRequestRejectApi,
ChangeRequestsListParams,
CommentApi,
+ CommentSlackThreadApi,
CommentsListParams,
ListParams,
MembersListParams,
@@ -49,6 +50,7 @@ import type {
RoleMembershipApi,
RolesListParams,
RolesRoleMembershipsListParams,
+ SendCommentToSlackApi,
WelcomeResponseApi,
} from './api.schemas'
@@ -994,6 +996,27 @@ export const commentsReopenCreate = async (
})
}
+export const getCommentsSendToSlackCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/comments/${id}/send_to_slack/`
+}
+
+/**
+ * Mirror this discussion thread to a Slack channel. Posts the comment (and its existing replies) as a new Slack thread; later replies on either side sync across. A discussion mirrors to exactly one Slack thread: re-calling with the same channel returns the existing mirror; a different channel is a 400 naming the existing one. 409 while a concurrent send is in flight. 404 when the feature is not enabled for the team.
+ */
+export const commentsSendToSlackCreate = async (
+ projectId: string,
+ id: string,
+ sendCommentToSlackApi: SendCommentToSlackApi,
+ options?: RequestInit
+): Promise<CommentSlackThreadApi> => {
+ return apiMutator<CommentSlackThreadApi>(getCommentsSendToSlackCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(sendCommentToSlackApi),
+ })
+}
+
export const getCommentsThreadRetrieveUrl = (projectId: string, id: string) => {
return `/api/projects/${projectId}/comments/${id}/thread/`
}
diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.ts
index 5e8b54ac1a7e..ab3064766e55 100644
--- a/products/platform_features/frontend/generated/api.zod.ts
+++ b/products/platform_features/frontend/generated/api.zod.ts
@@ -418,6 +418,19 @@ export const CommentsPartialUpdateBody = /* @__PURE__ */ zod.object({
source_comment: zod.uuid().nullish(),
})
+/**
+ * Mirror this discussion thread to a Slack channel. Posts the comment (and its existing replies) as a new Slack thread; later replies on either side sync across. A discussion mirrors to exactly one Slack thread: re-calling with the same channel returns the existing mirror; a different channel is a 400 naming the existing one. 409 while a concurrent send is in flight. 404 when the feature is not enabled for the team.
+ */
+export const commentsSendToSlackCreateBodyChannelIdMax = 255
+
+export const CommentsSendToSlackCreateBody = /* @__PURE__ */ zod.object({
+ integration_id: zod.number().describe("ID of the Slack integration (kind='slack') whose bot posts the thread."),
+ channel_id: zod
+ .string()
+ .max(commentsSendToSlackCreateBodyChannelIdMax)
+ .describe('Slack channel ID to create the mirrored thread in. The bot must be a member of the channel.'),
+})
+
/**
* Update the authenticated user's pinned sidebar tabs and/or homepage for the current team. Pass `@me` as the UUID. Send `tabs` to replace the pinned tab list, `homepage` to set the home destination (any PostHog URL — dashboard, insight, search results, scene). Either field may be omitted to leave it unchanged; sending `homepage: null` or `{}` clears the homepage.
*/
diff --git a/products/platform_features/mcp/tools.yaml b/products/platform_features/mcp/tools.yaml
index 83166f2bbef7..19be6debf1ec 100644
--- a/products/platform_features/mcp/tools.yaml
+++ b/products/platform_features/mcp/tools.yaml
@@ -324,6 +324,9 @@ tools:
comments-reopen-create:
operation: comments_reopen_create
enabled: false
+ comments-send-to-slack-create:
+ operation: comments_send_to_slack_create
+ enabled: false
comments-update:
operation: comments_update
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 9d6086cfe16e..3a1dbed26e0e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -15320,6 +15320,13 @@ export namespace Schemas {
readonly updated_at: string;
}
+ export interface CommentSlackThreadRef {
+ /** Slack channel ID this discussion is mirrored to. */
+ channel_id: string;
+ /** Deep link that opens the mirrored Slack thread. */
+ url: string;
+ }
+
export interface Comment {
readonly id: string;
readonly created_by: UserBasic;
@@ -15331,6 +15338,8 @@ export namespace Schemas {
is_task?: boolean;
/** The user who marked this task complete. Null for open tasks and non-task comments. */
readonly completed_by: UserBasic | null;
+ /** The Slack thread this comment's discussion is mirrored to, or null. Set only on a tracked thread-root comment; used to surface an 'Open in Slack' link and hide re-sending. */
+ readonly slack_thread: CommentSlackThreadRef | null;
/** @nullable */
content?: string | null;
rich_content?: unknown;
@@ -15353,6 +15362,33 @@ export namespace Schemas {
source_comment?: string | null;
}
+ export interface CommentSlackThread {
+ readonly id: string;
+ /** Resource type of the mirrored discussion (e.g. Insight). */
+ readonly scope: string;
+ /**
+ * ID of the resource the discussion is attached to.
+ * @nullable
+ */
+ readonly item_id: string | null;
+ /** The thread-root comment whose replies mirror to the Slack thread. */
+ readonly source_comment: string;
+ /** Slack integration used to post to and read from the thread. */
+ readonly integration: number;
+ /** Slack channel the mirrored thread lives in. */
+ readonly slack_channel_id: string;
+ /** Slack thread timestamp anchoring the mirrored thread. */
+ readonly slack_thread_ts: string;
+ /**
+ * Slack workspace ID, used to route inbound replies back.
+ * @nullable
+ */
+ readonly slack_team_id: string | null;
+ readonly created_at: string;
+ /** User who mirrored the discussion. Null if since deleted. */
+ readonly created_by: UserBasic | null;
+ }
+
/**
* * `conversation` - conversation
* * `review` - review
@@ -51559,6 +51595,8 @@ export namespace Schemas {
is_task?: boolean;
/** The user who marked this task complete. Null for open tasks and non-task comments. */
readonly completed_by?: UserBasic | null;
+ /** The Slack thread this comment's discussion is mirrored to, or null. Set only on a tracked thread-root comment; used to surface an 'Open in Slack' link and hide re-sending. */
+ readonly slack_thread?: CommentSlackThreadRef | null;
/** @nullable */
content?: string | null;
rich_content?: unknown;
@@ -66303,6 +66341,16 @@ export namespace Schemas {
sdks: SdkAssessment[];
}
+ export interface SendCommentToSlack {
+ /** ID of the Slack integration (kind='slack') whose bot posts the thread. */
+ integration_id: number;
+ /**
+ * Slack channel ID to create the mirrored thread in. The bot must be a member of the channel.
+ * @maxLength 255
+ */
+ channel_id: string;
+ }
+
export interface SendInvitesRequest {
/**
* Override the email subject line for this send. Plain text only — URLs, angle brackets, and control characters are rejected. Falls back to the topic's saved subject, then a default.