: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(tasks): send Slack DMs for PostHog Code comments (#81230)
Shy Alteref8f21bfd506
diff --git a/posthog/api/comments.py b/posthog/api/comments.pyindex 9237ef4a5a0d..aa4fa7b7eea5 100644--- a/posthog/api/comments.py+++ b/posthog/api/comments.py@@ -1,6 +1,5 @@from datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any, cast-from uuid import UUIDfrom django.core import exceptions as django_exceptionsfrom django.db import transaction@@ -21,6 +20,7 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import ClassicBehaviorBooleanFieldSerializer, action+from posthog.comment.access import task_comment_target_is_accessiblefrom posthog.event_usage import groupsfrom posthog.exceptions import Conflictfrom posthog.helpers.slack_thread_mirror import post_comment_to_slack_thread, slack_author_from_user@@ -238,44 +238,6 @@ def _mentions_allowed_for_comment_target(return task_comment_mentions_allowed(team_id=team_id, task_id=task_id)-def _task_comment_target_is_accessible(- *, team_id: int, user_id: int | None, task_id: str, scope: str, item_id: str | None-) -> bool:- from products.tasks.backend.facade.api import task_comment_target_is_accessible # noqa: PLC0415-- if scope != "desktop_canvas":- return task_comment_target_is_accessible(- team_id=team_id,- user_id=user_id,- task_id=task_id,- scope=scope,- item_id=item_id,- )- if not task_comment_target_is_accessible(- team_id=team_id,- user_id=user_id,- task_id=task_id,- scope="task",- item_id=task_id,- ):- return False-- from products.canvas.backend.comment_access import canvas_belongs_to_task # noqa: PLC0415-- try:- parsed_task_id = UUID(task_id)- except ValueError:- return False- if not item_id:- return False- return canvas_belongs_to_task(- team_id=team_id,- user_id=user_id,- canvas_id=item_id,- task_id=parsed_task_id,- )--class CommentSerializer(serializers.ModelSerializer):def _extract_mentions_from_rich_content(self, rich_content: dict | None) -> list[int]:if not rich_content:@@ -456,7 +418,7 @@ class CommentSerializer(serializers.ModelSerializer):target_context = data.get("item_context", instance.item_context if instance else None) or {}if target_scope in {"task", "task_artifact", "desktop_canvas"}:task_id = target_item_id if target_scope == "task" else target_context.get("taskId")- if not _task_comment_target_is_accessible(+ if not task_comment_target_is_accessible(team_id=self.context["get_team"]().id,user_id=request.user.id,task_id=task_id or "",@@ -881,7 +843,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVreturnitem_context = comment.item_context if isinstance(comment.item_context, dict) else {}task_id = comment.item_id if comment.scope == "task" else item_context.get("taskId")- if not _task_comment_target_is_accessible(+ if not task_comment_target_is_accessible(team_id=self.team_id,user_id=self.request.user.id,task_id=task_id or "",@@ -896,7 +858,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVcomment = get_object_or_404(queryset, **{self.lookup_field: lookup_value})if comment.scope in {"task", "task_artifact", "desktop_canvas"}:task_id = comment.item_id if comment.scope == "task" else (comment.item_context or {}).get("taskId")- if not _task_comment_target_is_accessible(+ if not task_comment_target_is_accessible(team_id=self.team_id,user_id=self.request.user.id,task_id=task_id or "",@@ -952,7 +914,7 @@ class CommentViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVelif scope in {"task", "task_artifact", "desktop_canvas"}:task_id = params.get("task_id")item_id = params.get("item_id")- if not _task_comment_target_is_accessible(+ if not task_comment_target_is_accessible(team_id=self.team_id,user_id=self.request.user.id,task_id=task_id or "",diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.pyindex 4d8d63fefe01..c9fc4e5af44d 100644--- a/posthog/api/test/test_user.py+++ b/posthog/api/test/test_user.py@@ -2010,6 +2010,7 @@ class TestUserAPI(APIBaseTest):{"plugin_disabled": False,"discussions_mentioned": False,+ "task_comments_slack_dm": False,"project_weekly_digest_disabled": {"123": True}, # Note: JSON converts int keys to strings"all_weekly_digest_disabled": True,"error_tracking_issue_assigned": False,@@ -2032,6 +2033,7 @@ class TestUserAPI(APIBaseTest):{"plugin_disabled": False,"discussions_mentioned": False,+ "task_comments_slack_dm": False,"project_weekly_digest_disabled": {"123": True},"all_weekly_digest_disabled": True,"error_tracking_issue_assigned": False,@@ -2302,6 +2304,7 @@ class TestUserAPI(APIBaseTest):{"plugin_disabled": True, # Default value"discussions_mentioned": True, # Default value+ "task_comments_slack_dm": False, # Default value"project_weekly_digest_disabled": {}, # Default value"all_weekly_digest_disabled": True,"error_tracking_issue_assigned": True, # Default valuediff --git a/posthog/comment/access.py b/posthog/comment/access.pynew file mode 100644index 000000000000..61200ca497c9--- /dev/null+++ b/posthog/comment/access.py@@ -0,0 +1,44 @@+from uuid import UUID+++def task_comment_target_is_accessible(+ *, team_id: int, user_id: int | None, task_id: str | UUID, scope: str, item_id: str | None+) -> bool:+ from products.tasks.backend.facade.api import (+ task_comment_target_is_accessible as task_target_is_accessible, # noqa: PLC0415 # Import lazily because generic comment imports must not load product models.+ )++ if scope != "desktop_canvas":+ return task_target_is_accessible(+ team_id=team_id,+ user_id=user_id,+ task_id=task_id,+ scope=scope,+ item_id=item_id,+ )+ if not task_target_is_accessible(+ team_id=team_id,+ user_id=user_id,+ task_id=task_id,+ scope="task",+ item_id=str(task_id),+ ):+ return False++ try:+ parsed_task_id = UUID(str(task_id))+ except ValueError:+ return False+ if not item_id:+ return False++ from products.canvas.backend.comment_access import (+ canvas_belongs_to_task, # noqa: PLC0415 # Import lazily because non-canvas comments do not need Canvas models.+ )++ return canvas_belongs_to_task(+ team_id=team_id,+ user_id=user_id,+ canvas_id=item_id,+ task_id=parsed_task_id,+ )diff --git a/posthog/models/user.py b/posthog/models/user.pyindex b552b308868a..d621f46f0337 100644--- a/posthog/models/user.py+++ b/posthog/models/user.py@@ -40,6 +40,7 @@ class Notifications(TypedDict, total=False):str, Any] # Maps team_id (str) to enabled status (True = included). None/missing = not configured (auto-select on first digest).discussions_mentioned: bool+ task_comments_slack_dm: bool # Slack DM for task comment mentions, replies, and owned itemsproject_weekly_digest_disabled: dict[str, Any] # Maps project ID to disabled status, str is the team_id as a stringall_weekly_digest_disabled: booldata_pipeline_error_threshold: (@@ -67,6 +68,8 @@ NOTIFICATION_DEFAULTS: Notifications = {"error_tracking_issue_assigned": True, # Error tracking issue assignment"error_tracking_weekly_digest": True, # Error tracking weekly digest enabled by default"discussions_mentioned": True, # Mentions in comments enabled by default+ # Off by default: forwarding comment text into Slack is opt-in, not implied by linking Slack.+ "task_comments_slack_dm": False,"project_weekly_digest_disabled": {}, # Empty dict by default - no projects disabled"all_weekly_digest_disabled": False, # Weekly digests enabled by default"data_pipeline_error_threshold": 0.01, # Default: notify when failure rate exceeds 1%diff --git a/posthog/settings/celery.py b/posthog/settings/celery.pyindex 5ca75c7cb678..bdec526944b0 100644--- a/posthog/settings/celery.py+++ b/posthog/settings/celery.py@@ -23,6 +23,9 @@ CELERY_IMPORTS: list[str] = ["posthog.models.product_intent.product_intent","posthog.models.scoping","posthog.scoping_audit",+ # Not a `<app>/tasks.py`, so autodiscovery walks past it — the app package holds a `tasks/`+ # namespace package instead, and importing that doesn't reach the module inside.+ "products.tasks.backend.tasks.tasks",]CELERY_BROKER_URL = REDIS_URL # celery connects to redisCELERY_BEAT_MAX_LOOP_INTERVAL = 30 # sleep max 30sec before checking for new periodic eventsdiff --git a/products/tasks/backend/logic/services/comment_activity.py b/products/tasks/backend/logic/services/comment_activity.pyindex fece49d47486..613344ce69ba 100644--- a/products/tasks/backend/logic/services/comment_activity.py+++ b/products/tasks/backend/logic/services/comment_activity.py@@ -3,13 +3,18 @@ from datetime import datetimefrom uuid import UUIDfrom django.core.exceptions import ValidationError as DjangoValidationError+from django.db import transactionfrom django.db.models import Q+import structlog+from posthog.models import Commentfrom products.tasks.backend.models import Channel, Task, TaskArtifact, TaskCommentActivity, TaskRunfrom products.tasks.backend.visibility import task_visibility_q+logger = structlog.get_logger(__name__)+COMMENT_ACTIVITY_SCOPES = frozenset({"task", "task_artifact", "desktop_canvas"})@@ -128,3 +133,29 @@ def project_comment_activity(root_comment_id=root_comment_id,recipients=recipients,)+ _enqueue_slack_dms(team_id=team_id, comment_id=comment_id, task_id=task_id, recipients=recipients)+++def _enqueue_slack_dms(*, team_id: int, comment_id: UUID, task_id: UUID, recipients: dict[int, str]) -> None:+ """Hand the same recipient map to the Slack DM channel. Never fails the projection: the+ Activity row is the notification that has to land."""+ if not recipients:+ return++ def _enqueue() -> None:+ try:+ from products.tasks.backend.tasks.tasks import ( # noqa: PLC0415 — avoids the service/task circular import+ deliver_comment_slack_dms,+ )++ deliver_comment_slack_dms.delay(+ team_id=team_id,+ comment_id=str(comment_id),+ task_id=str(task_id),+ recipients={str(user_id): kind for user_id, kind in recipients.items()},+ )+ except Exception:+ logger.exception("comment_slack_dm_enqueue_failed", comment_id=str(comment_id))++ # The worker re-reads the comment, so it must not start before the write is visible.+ transaction.on_commit(_enqueue)diff --git a/products/tasks/backend/logic/services/comment_slack_dm.py b/products/tasks/backend/logic/services/comment_slack_dm.pynew file mode 100644index 000000000000..4caa10370457--- /dev/null+++ b/products/tasks/backend/logic/services/comment_slack_dm.py@@ -0,0 +1,280 @@+"""Slack DM delivery for PostHog Code comment notifications.++A second channel for the three recipient kinds the in-app Activity feed already gets: a mention,+a reply to your comment, a comment on something you own. Recipients and the personal-channel+exclusion are decided by ``comment_activity``; this module only decides whether each recipient+wants a DM, may still see the comment, and where to send it.++Delivery is best-effort. The Activity row is the durable notification, so a Slack failure is+logged and dropped rather than retried — which also means a retry can't double-DM someone without+a per-recipient sent marker to store.+"""++from collections.abc import Mapping+from uuid import UUID++from django.conf import settings++import structlog++from posthog.comment.access import task_comment_target_is_accessible+from posthog.comment.formatting import escape_slack_mrkdwn, rich_content_to_slack_payload+from posthog.helpers.slack_identity import resolve_slack_user+from posthog.models.comment import Comment+from posthog.models.integration import Integration, SlackIntegration+from posthog.models.organization import OrganizationMembership+from posthog.models.team import Team+from posthog.models.user import User+from posthog.models.user_integration import UserIntegration+from posthog.user_permissions import UserPermissions++from products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled+from products.slack_app.backend.services.slack_user_info import lookup_slack_user_id_by_email+from products.tasks.backend.models import Task, TaskCommentActivity++logger = structlog.get_logger(__name__)++# Opt-in: having linked a Slack account is not consent to have your comments forwarded into it.+SLACK_DM_SETTING = "task_comments_slack_dm"++# Slack allows 3000 characters per section; a DM that long is unreadable, and the link to the full+# thread is right there in the heading.+_BODY_LIMIT = 800++_HEADINGS: Mapping[str, str] = {+ TaskCommentActivity.Kind.MENTION: "{author} mentioned you on {link}",+ TaskCommentActivity.Kind.THREAD_REPLY: "{author} replied to your comment on {link}",+ TaskCommentActivity.Kind.OWNED_ITEM_COMMENT: "{author} commented on {link}",+}+++def send_comment_slack_dms(*, team_id: int, comment_id: UUID, task_id: UUID, recipients: Mapping[int, str]) -> None:+ """DM each recipient who opted in, can still see the comment, and has linked Slack.++ ``recipients`` is the map ``comment_activity`` just projected: user id to activity kind.+ """+ if not recipients:+ return++ comment = Comment.objects.filter(team_id=team_id, id=comment_id, deleted=False).select_related("created_by").first()+ if comment is None:+ return _skip(comment_id, "comment_missing")+ skip_reason = _skip_reason(comment)+ if skip_reason:+ return _skip(comment_id, skip_reason)++ # Cheapest gate first: most comments have no opted-in recipient, and this keeps the flag call+ # (a network hop) off that path.+ wanted = _recipients_wanting_dms(team_id=team_id, comment=comment, recipients=recipients)+ if not wanted:+ return _skip(comment_id, "no_opted_in_recipient")++ integrations = list(+ Integration.objects.filter(team_id=team_id, kind=Integration.IntegrationKind.SLACK)+ .exclude(integration_id__isnull=True)+ .exclude(integration_id="")+ .order_by("id")+ )+ if not integrations:+ return _skip(comment_id, "no_slack_integration")+ # The flag that gates the Slack identity link itself. Gating delivery on it too means an org+ # that never had the link flow can't receive DMs, and turning it off halts delivery without a+ # deploy. Skipped in local dev, where flags evaluate against the developer's own instance and+ # the gate would otherwise fail closed on every machine — the same default-on-in-dev treatment+ # the desktop flags get.+ task = Task.objects.filter(team_id=team_id, id=task_id).only("id", "team_id", "title").first()+ if task is None:+ return _skip(comment_id, "task_missing")++ team = Team.objects.filter(id=team_id).only("id", "organization_id").first()+ if team is None:+ return _skip(comment_id, "team_missing")+ users = User.objects.in_bulk(list(wanted))+ integration_by_workspace = {integration.integration_id: integration for integration in integrations}+ slack_clients: dict[int, SlackIntegration] = {}+ for user_id, kind in wanted.items():+ recipient = users.get(user_id)+ if recipient is None:+ _skip(comment_id, "recipient_missing", user_id=user_id)+ continue+ if not recipient.is_active:+ _skip(comment_id, "recipient_inactive", user_id=user_id)+ continue+ # Re-checked at send time rather than trusting the projected recipient set: the in-app feed+ # re-checks visibility on every read, and a DM can't be taken back.+ if not OrganizationMembership.objects.filter(organization_id=team.organization_id, user_id=user_id).exists():+ _skip(comment_id, "recipient_left_organization", user_id=user_id)+ continue+ if UserPermissions(user=recipient, team=team).current_team.effective_membership_level is None:+ _skip(comment_id, "recipient_lost_project_access", user_id=user_id)+ continue+ if not task_comment_target_is_accessible(+ team_id=team_id,+ user_id=user_id,+ task_id=task_id,+ scope=comment.scope,+ item_id=comment.item_id,+ ):+ _skip(comment_id, "recipient_lost_access", user_id=user_id)+ continue+ try:+ integration = _integration_for_recipient(+ user_id=user_id, integrations=integrations, integration_by_workspace=integration_by_workspace+ )+ if integration is None:+ _skip(comment_id, "ambiguous_slack_workspace", user_id=user_id)+ continue+ if not settings.DEBUG and not is_slack_app_oauth_enabled(integration, integration.integration_id):+ _skip(comment_id, "slack_app_oauth_disabled", user_id=user_id)+ continue+ slack = slack_clients.setdefault(integration.id, SlackIntegration(integration))+ slack_user_id = _resolve_slack_user_id(+ user_id=user_id, email=recipient.email or "", integration=integration, slack=slack+ )+ if not slack_user_id:+ _skip(comment_id, "recipient_not_found_in_slack", user_id=user_id)+ continue+ fallback, blocks = _message(kind=kind, comment=comment, task=task, organization_id=team.organization_id)+ slack.client.chat_postMessage(channel=slack_user_id, text=fallback, blocks=blocks, unfurl_links=False)+ except Exception as exc:+ logger.warning("comment_slack_dm_failed", comment_id=str(comment_id), user_id=user_id, error=str(exc))+++def _skip(comment_id: UUID, reason: str, user_id: int | None = None) -> None:+ """Every gate here returns silently by design, which makes "why did I get no DM" unanswerable+ without one line per exit."""+ logger.info("comment_slack_dm_skipped", comment_id=str(comment_id), reason=reason, user_id=user_id)+++def _skip_reason(comment: Comment) -> str | None:+ """Replies that aren't messages. Reactions and resolve/reopen are both stored as reply+ comments, so without this a thumbs-up would DM everyone in the thread."""+ context = comment.item_context if isinstance(comment.item_context, dict) else {}+ if context.get("is_emoji"):+ return "emoji"+ if context.get("threadState"):+ return "thread_state"+ if context.get("from_slack"):+ return "from_slack"+ return None+++def _recipients_wanting_dms(*, team_id: int, comment: Comment, recipients: Mapping[int, str]) -> dict[int, str]:+ """Narrow the Activity recipients to the ones who asked to be DMed.++ ``THREAD_REPLY`` narrows further: the Activity feed notifies every thread participant, but the+ DM says "replied to your comment", so only the thread's author gets one.+ """+ # Read the raw partial settings rather than the merged `notification_settings` property: the+ # setting is opt-in, so an absent key means off and there's no default to merge in.+ opted_in = {+ user_id+ for user_id, partial in User.objects.filter(id__in=list(recipients), is_active=True).values_list(+ "id", "partial_notification_settings"+ )+ if isinstance(partial, dict) and partial.get(SLACK_DM_SETTING) is True+ }+ if not opted_in:+ return {}++ root_author_id: int | None = None+ if any(kind == TaskCommentActivity.Kind.THREAD_REPLY for uid, kind in recipients.items() if uid in opted_in):+ root_author_id = (+ Comment.objects.filter(team_id=team_id, id=comment.source_comment_id or comment.id)+ .values_list("created_by_id", flat=True)+ .first()+ )++ wanted: dict[int, str] = {}+ for user_id, kind in recipients.items():+ if user_id not in opted_in:+ continue+ if kind == TaskCommentActivity.Kind.THREAD_REPLY and user_id != root_author_id:+ continue+ wanted[user_id] = kind+ return wanted+++def _resolve_slack_user_id(+ *, user_id: int, email: str, integration: Integration, slack: SlackIntegration+) -> str | None:+ """Who to DM, preferring the identity the user authenticated over the one we inferred."""+ link = (+ UserIntegration.objects.filter(+ user_id=user_id,+ kind=UserIntegration.IntegrationKind.SLACK,+ config__slack_team_id=integration.integration_id,+ )+ .order_by("-created_at")+ .first()+ )+ if link:+ return link.integration_id+ return _slack_user_id_by_email(email=email, integration=integration, slack=slack)+++def _integration_for_recipient(+ *, user_id: int, integrations: list[Integration], integration_by_workspace: Mapping[str | None, Integration]+) -> Integration | None:+ """Use a recipient's linked workspace; email lookup is safe only with one destination."""+ linked_workspace = (+ UserIntegration.objects.filter(user_id=user_id, kind=UserIntegration.IntegrationKind.SLACK)+ .order_by("-created_at")+ .values_list("config__slack_team_id", flat=True)+ .first()+ )+ if isinstance(linked_workspace, str):+ return integration_by_workspace.get(linked_workspace)+ return integrations[0] if len(integrations) == 1 else None+++def _slack_user_id_by_email(*, email: str, integration: Integration, slack: SlackIntegration) -> str | None:+ """Match a PostHog email against the workspace's own Slack directory.++ This is what makes the feature work without every person linking an account first. It asks the+ customer's own directory a question about our own user's email, which is the opposite direction+ from the inbound path (where a Slack-supplied email would decide who a PostHog user is, and so+ can't be trusted).+ """+ workspace = integration.integration_id or ""+ if not email or not workspace:+ return None+ slack_user_id = lookup_slack_user_id_by_email(slack, integration, email)+ if not slack_user_id:+ return None+ profile = resolve_slack_user(slack.client, slack_user_id, workspace=workspace)+ # `users.lookupByEmail` also returns external Slack Connect members, whose profile emails are+ # controlled by their own workspace's admin. Without this check an outsider could claim a+ # teammate's address and receive their comment text.+ if profile.get("team_id") != workspace:+ logger.warning("comment_slack_dm_email_match_outside_workspace", integration_id=integration.id)+ return None+ return slack_user_id+++def _author_name(comment: Comment) -> str:+ author = comment.created_by+ if author is None:+ return "Someone"+ return f"{author.first_name} {author.last_name}".strip() or author.email or "Someone"+++def _message(*, kind: str, comment: Comment, task: Task, organization_id: str | UUID | None) -> tuple[str, list[dict]]:+ url = f"{settings.SITE_URL}/project/{task.team_id}/tasks/{task.id}"+ title = task.title or "a task"+ author = _author_name(comment)+ template = _HEADINGS.get(kind, _HEADINGS[TaskCommentActivity.Kind.MENTION])+ # A pipe in the title would end the link label early, so it can't survive into the label.+ label = escape_slack_mrkdwn(title).replace("|", "-")+ heading = template.format(author=f"*{escape_slack_mrkdwn(author)}*", link=f"<{url}|{label}>")+ # Plain-text twin for the notification preview and older clients.+ fallback = template.format(author=escape_slack_mrkdwn(author), link=escape_slack_mrkdwn(title))++ body, _ = rich_content_to_slack_payload(+ comment.rich_content, comment.content or "", include_images=False, organization_id=organization_id+ )+ body = body.strip()+ if len(body) > _BODY_LIMIT:+ body = body[: _BODY_LIMIT - 1] + "…"+ text = f"{heading}\n\n> " + body.replace("\n", "\n> ") if body else heading+ return fallback, [{"type": "section", "text": {"type": "mrkdwn", "text": text}}]diff --git a/products/tasks/backend/tasks/tasks.py b/products/tasks/backend/tasks/tasks.pyindex 39dd726badf7..ac54d62ae44f 100644--- a/products/tasks/backend/tasks/tasks.py+++ b/products/tasks/backend/tasks/tasks.py@@ -4,6 +4,7 @@ from uuid import UUIDfrom celery import shared_taskfrom products.tasks.backend.facade.api import record_comment_activity+from products.tasks.backend.logic.services.comment_slack_dm import send_comment_slack_dms@shared_task(ignore_result=True, autoretry_for=(Exception,), retry_backoff=True, max_retries=5)@@ -24,3 +25,21 @@ def project_task_comment_activity(target_owner_id=target_owner_id,activity_at=datetime.fromisoformat(activity_at) if activity_at else None,)+++# No retries: the Activity row already carries the notification, so a dropped DM is recoverable+# while a re-sent one is not.+@shared_task(ignore_result=True)+def deliver_comment_slack_dms(+ *,+ team_id: int,+ comment_id: str,+ task_id: str,+ recipients: dict[str, str],+) -> None:+ send_comment_slack_dms(+ team_id=team_id,+ comment_id=UUID(comment_id),+ task_id=UUID(task_id),+ recipients={int(user_id): kind for user_id, kind in recipients.items()},+ )diff --git a/products/tasks/backend/tests/test_comment_slack_dm.py b/products/tasks/backend/tests/test_comment_slack_dm.pynew file mode 100644index 000000000000..bdabe639e567--- /dev/null+++ b/products/tasks/backend/tests/test_comment_slack_dm.py@@ -0,0 +1,283 @@+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.models import Comment, OrganizationMembership, User+from posthog.models.integration import Integration+from posthog.models.user_integration import UserIntegration++from products.canvas.backend.models import Canvas+from products.tasks.backend.logic.services.comment_slack_dm import send_comment_slack_dms+from products.tasks.backend.models import Channel, TaskCommentActivity+from products.tasks.backend.tests.test_comment_activity import CommentActivityTestCase++from ee.models.rbac.access_control import AccessControl++SLACK_WORKSPACE_ID = "T123"+++class TestCommentSlackDm(CommentActivityTestCase):+ def setUp(self) -> None:+ super().setUp()+ Integration.objects.create(+ team=self.team, kind="slack", integration_id=SLACK_WORKSPACE_ID, config={"scope": "chat:write"}+ )+ self._link_slack(self.author, "U-author")+ self._opt_in(self.author)++ flag_patch = patch(+ "products.tasks.backend.logic.services.comment_slack_dm.is_slack_app_oauth_enabled", return_value=True+ )+ client_patch = patch("products.tasks.backend.logic.services.comment_slack_dm.SlackIntegration")+ self.addCleanup(flag_patch.stop)+ self.addCleanup(client_patch.stop)+ flag_patch.start()+ self.slack_client = MagicMock()+ client_patch.start().return_value.client = self.slack_client++ def _link_slack(self, user, slack_user_id: str, workspace_id: str = SLACK_WORKSPACE_ID) -> None:+ UserIntegration.objects.create(+ user=user,+ kind=UserIntegration.IntegrationKind.SLACK,+ integration_id=slack_user_id,+ config={"slack_team_id": workspace_id},+ )++ def _opt_in(self, user, enabled: bool = True) -> None:+ user.partial_notification_settings = {"task_comments_slack_dm": enabled}+ user.save()++ def _record_activity(self, comment: Comment, user_ids: list[int] | None = None) -> None:+ # Delivery is enqueued on commit, which a TestCase never reaches on its own.+ with self.captureOnCommitCallbacks(execute=True):+ super()._record_activity(comment, user_ids)++ def _dm_channels(self) -> list[str]:+ return [call.kwargs["channel"] for call in self.slack_client.chat_postMessage.call_args_list]++ def test_mention_dms_the_mentioned_user(self):+ comment = self._comment()++ self._record_activity(comment, [self.author.id])++ assert self._dm_channels() == ["U-author"]+ text = self.slack_client.chat_postMessage.call_args.kwargs["blocks"][0]["text"]["text"]+ assert "mentioned you" in text+ assert "this needs a guard" in text++ def test_fallback_text_escapes_user_controlled_slack_markup(self):+ self.peer.first_name = "<@U-ATTACKER>"+ self.peer.last_name = ""+ self.peer.save(update_fields=["first_name", "last_name"])+ self.task.title = "<https://example.com|click me>"+ self.task.save(update_fields=["title"])++ self._record_activity(self._comment(), [self.author.id])++ fallback = self.slack_client.chat_postMessage.call_args.kwargs["text"]+ assert fallback == "<@U-ATTACKER> mentioned you on <https://example.com|click me>"++ def test_no_dm_when_the_user_opted_out(self):+ self._opt_in(self.author, False)++ self._record_activity(self._comment(), [self.author.id])++ assert self._dm_channels() == []++ def test_deleted_comment_is_not_sent_after_delivery_is_enqueued(self):+ comment = self._comment()+ comment.deleted = True+ comment.save(update_fields=["deleted"])++ send_comment_slack_dms(+ team_id=self.team.id,+ comment_id=comment.id,+ task_id=self.task.id,+ recipients={self.author.id: TaskCommentActivity.Kind.MENTION},+ )++ assert self._dm_channels() == []++ def test_removed_organization_member_does_not_receive_a_dm(self):+ OrganizationMembership.objects.filter(user=self.author, organization=self.organization).delete()++ self._record_activity(self._comment(), [self.author.id])++ assert self._dm_channels() == []++ def test_inactive_user_does_not_receive_a_dm(self):+ self.author.is_active = False+ self.author.save(update_fields=["is_active"])+ comment = self._comment()++ send_comment_slack_dms(+ team_id=self.team.id,+ comment_id=comment.id,+ task_id=self.task.id,+ recipients={self.author.id: TaskCommentActivity.Kind.MENTION},+ )++ assert self._dm_channels() == []++ def test_project_member_without_access_does_not_receive_a_dm(self):+ self.organization.available_product_features = [+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save(update_fields=["available_product_features"])+ OrganizationMembership.objects.filter(user=self.author, organization=self.organization).update(+ level=OrganizationMembership.Level.MEMBER+ )+ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ access_level="none",+ )++ self._record_activity(self._comment(), [self.author.id])++ assert self._dm_channels() == []++ def test_canvas_comment_dms_a_recipient_who_can_access_its_task(self):+ canvas = Canvas.objects.create(+ team=self.team,+ channel=self.channel,+ name="Launch canvas",+ created_by=self.peer,+ generation_task_id=self.task.id,+ )+ comment = self._comment(scope="desktop_canvas", item_id=str(canvas.id))++ self._record_activity(comment, [self.author.id])++ assert self._dm_channels() == ["U-author"]++ def test_canvas_comment_does_not_dm_a_recipient_without_canvas_access(self):+ personal_channel = Channel.objects.unscoped().create(+ team=self.team,+ name="private",+ channel_type=Channel.ChannelType.PERSONAL,+ created_by=self.peer,+ )+ canvas = Canvas.objects.create(+ team=self.team,+ channel=personal_channel,+ name="Launch canvas",+ created_by=self.peer,+ generation_task_id=self.task.id,+ )+ comment = self._comment(scope="desktop_canvas", item_id=str(canvas.id))++ self._record_activity(comment, [self.author.id])++ assert self._dm_channels() == []++ @parameterized.expand(+ [+ # Same workspace as the integration: the directory match is trustworthy.+ ("same_workspace", SLACK_WORKSPACE_ID, ["U-by-email"]),+ # A Slack Connect guest whose profile email its own admin controls.+ ("external_workspace", "T-OTHER", []),+ ]+ )+ def test_unlinked_user_is_matched_by_email_only_inside_the_workspace(+ self, _name: str, profile_team_id: str, expected: list[str]+ ):+ UserIntegration.objects.filter(user=self.author).delete()++ with (+ patch(+ "products.tasks.backend.logic.services.comment_slack_dm.lookup_slack_user_id_by_email",+ return_value="U-by-email",+ ),+ patch(+ "products.tasks.backend.logic.services.comment_slack_dm.resolve_slack_user",+ return_value={"name": "Ann", "team_id": profile_team_id},+ ),+ ):+ self._record_activity(self._comment(), [self.author.id])++ assert self._dm_channels() == expected++ def test_the_linked_account_wins_over_an_email_match(self):+ with patch(+ "products.tasks.backend.logic.services.comment_slack_dm.lookup_slack_user_id_by_email",+ return_value="U-by-email",+ ) as lookup:+ self._record_activity(self._comment(), [self.author.id])++ assert self._dm_channels() == ["U-author"]+ lookup.assert_not_called()++ def test_linked_workspace_selects_the_matching_slack_integration(self):+ second_workspace = "T456"+ Integration.objects.create(+ team=self.team, kind="slack", integration_id=second_workspace, config={"scope": "chat:write"}+ )+ self._link_slack(self.author, "U-author-second-workspace", second_workspace)++ self._record_activity(self._comment(), [self.author.id])++ assert self._dm_channels() == ["U-author-second-workspace"]++ @parameterized.expand(+ [+ ("reaction", {"is_emoji": True}),+ ("resolve", {"threadState": "resolved"}),+ ]+ )+ def test_reactions_and_thread_state_changes_do_not_dm(self, _name: str, extra_context: dict):+ root = self._comment(created_by=self.author)+ reply = self._comment(+ created_by=self.peer,+ source_comment=root,+ item_context={"anchor": {"kind": "document"}, "taskId": str(self.task.id), **extra_context},+ )++ self._record_activity(reply)++ assert self._dm_channels() == []++ def test_reply_dms_the_thread_author_only(self):+ third = User.objects.create_user(email="[email protected]", first_name="Carol", password="password")+ self.organization.members.add(third)+ OrganizationMembership.objects.filter(user=third, organization=self.organization).update(+ level=OrganizationMembership.Level.ADMIN+ )+ self._link_slack(third, "U-carol")+ self._opt_in(third)+ root = self._comment(created_by=self.author)+ Comment.objects.create(+ team=self.team,+ scope=root.scope,+ item_id=root.item_id,+ item_context=root.item_context,+ source_comment=root,+ content="chiming in",+ created_by=third,+ )+ latest_reply = self._comment(created_by=self.peer, source_comment=root, content="on it")++ self._record_activity(latest_reply)++ assert self._dm_channels() == ["U-author"]++ def test_slack_failure_does_not_break_activity_projection(self):+ self.slack_client.chat_postMessage.side_effect = Exception("slack down")+ comment = self._comment()++ self._record_activity(comment, [self.author.id])++ assert TaskCommentActivity.objects.filter(team=self.team, user=self.author, comment=comment).exists()++ def test_a_slack_failure_for_one_recipient_does_not_skip_the_next_recipient(self):+ third = User.objects.create_user(email="[email protected]", first_name="Carol", password="password")+ self.organization.members.add(third)+ self._link_slack(third, "U-carol")+ self._opt_in(third)+ self.slack_client.chat_postMessage.side_effect = [Exception("slack down"), None]++ self._record_activity(self._comment(), [self.author.id, third.id])++ assert self._dm_channels() == ["U-author", "U-carol"]