: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
fix(tasks): render mentions and long bodies in comment DMs (#81648)
Shy Altere317a0c72163
diff --git a/posthog/comment/formatting.py b/posthog/comment/formatting.pyindex 876fe6492568..38d591070428 100644--- a/posthog/comment/formatting.py+++ b/posthog/comment/formatting.py@@ -3,7 +3,7 @@import reimport html as html_modimport unicodedata-from collections.abc import Iterable+from collections.abc import Callable, Iterablefrom typing import Anyfrom urllib.parse import urlparsefrom uuid import UUID@@ -28,6 +28,7 @@ _RE_MD_ITALIC = re.compile(r"(?<!\*)\*([^*]+?)\*(?!\*)")_RE_MD_STRIKE = re.compile(r"~~(.+?)~~")_RE_MD_LINK = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")_RE_MD_MENTION = re.compile(r"@member:([a-f0-9-]+)")+_RE_INLINE_MENTION = re.compile(r"@\[([^\][\n]+)\]\(([^\s()@]+@[^\s()@]+)\)")_RE_SINGLE_NEWLINE = re.compile(r"(?<!\n)\n(?!\n)")_RE_MD_ESCAPE = re.compile(r"([\\`*_{}\[\]()#+\-.!|])")_RE_MD_ESCAPED_CHAR = re.compile(r"\\([\\`*_{}\[\]()#+\-.!|])")@@ -175,7 +176,11 @@ def strip_slack_user_mentions(text: str) -> str:return _RE_SLACK_USER_MENTION.sub("", text)-def content_to_slack_mrkdwn(content: str, organization_id: str | UUID | None = None) -> str:+def content_to_slack_mrkdwn(+ content: str,+ organization_id: str | UUID | None = None,+ slack_user_id_by_email: Callable[[str], str | None] | None = None,+) -> str:"""Convert markdown comment content to Slack mrkdwn text.Backslash-escaped characters are unescaped: mrkdwn has no escape syntax, so a@@ -187,6 +192,10 @@ def content_to_slack_mrkdwn(content: str, organization_id: str | UUID | None = Nthe rendered text lands in someone's Slack workspace, so an unscoped lookup would let a commentpull a name or email out of another organization. Without an organization every marker fallsback to the generic "@teammate".++ ``slack_user_id_by_email`` renders ``@[Name](email)`` mentions as native Slack mentions when the+ caller can map the address to a member of the destination workspace. Callers without a workspace+ to resolve against get the plain display name."""if not content:return ""@@ -225,6 +234,19 @@ def content_to_slack_mrkdwn(content: str, organization_id: str | UUID | None = Ntext = _RE_MD_BOLD.sub(capture_bold, text)text = _RE_MD_ITALIC.sub(r"_\1_", text)text = _RE_MD_STRIKE.sub(r"~\1~", text)++ def render_inline_mention(match: re.Match) -> str:+ name, email = match.group(1), match.group(2)+ if slack_user_id_by_email:+ try:+ slack_user_id = slack_user_id_by_email(email)+ except Exception:+ slack_user_id = None+ if slack_user_id:+ return f"<@{slack_user_id}>"+ return f"@{name}"++ text = _RE_INLINE_MENTION.sub(render_inline_mention, text)text = _RE_MD_LINK.sub(r"<\2|\1>", text)for index, value in enumerate(bold_matches):@@ -1002,11 +1024,13 @@ def rich_content_to_slack_payload(fallback_content: str,include_images: bool = True,organization_id: str | UUID | None = None,+ slack_user_id_by_email: Callable[[str], str | None] | None = None,) -> tuple[str, list[JSON] | None]:"""Convert outbound app message to Slack payload fields.- ``organization_id`` scopes mention resolution — see content_to_slack_mrkdwn.+ ``organization_id`` and ``slack_user_id_by_email`` scope mention resolution — see+ content_to_slack_mrkdwn.Returns:- text (always present, used as fallback for notifications/older clients)@@ -1016,6 +1040,6 @@ def rich_content_to_slack_payload(blocks = rich_content_to_slack_blocks(rich_content, include_images=include_images)markdown_text = rich_content_to_markdown(rich_content, include_images=include_images)source_content = markdown_text or fallback_content- return content_to_slack_mrkdwn(source_content, organization_id), blocks+ return content_to_slack_mrkdwn(source_content, organization_id, slack_user_id_by_email), blocks- return content_to_slack_mrkdwn(fallback_content, organization_id), None+ return content_to_slack_mrkdwn(fallback_content, organization_id, slack_user_id_by_email), Nonediff --git a/products/conversations/backend/api/tests/test_formatting.py b/products/conversations/backend/api/tests/test_formatting.pyindex 67666569ed92..24f65e0ab041 100644--- a/products/conversations/backend/api/tests/test_formatting.py+++ b/products/conversations/backend/api/tests/test_formatting.py@@ -48,11 +48,28 @@ class TestSlackFormatting(SimpleTestCase):("ampersand", "a & b", "a & b"),("md_link_still_converts", "[docs](https://posthog.com)", "<https://posthog.com|docs>"),("blockquote_preserved", "> quoted", "> quoted"),+ ("inline_mention", "@[Ann Lee]([email protected]) hi", "@Ann Lee hi"),+ ("inline_mention_repeated", "@[Ann Lee]([email protected]) @[Bo]([email protected])", "@Ann Lee @Bo"),+ ("inline_mention_needs_email", "@[Ann Lee](https://posthog.com)", "@<https://posthog.com|Ann Lee>"),])def test_outbound_mrkdwn_escapes_control_sequences(self, _name: str, content: str, expected: str) -> None:assert content_to_slack_mrkdwn(content) == expected+ def test_inline_mention_uses_slack_member_when_the_address_resolves(self) -> None:+ content = "@[Ann Lee]([email protected]) and @[Bo]([email protected])"++ def resolve(email: str) -> str | None:+ return "U123" if email == "[email protected]" else None++ assert content_to_slack_mrkdwn(content, None, resolve) == "<@U123> and @Bo"++ def test_inline_mention_falls_back_to_the_name_when_lookup_fails(self) -> None:+ def resolve(email: str) -> str | None:+ raise RuntimeError("slack is down")++ assert content_to_slack_mrkdwn("@[Ann Lee]([email protected]) hi", None, resolve) == "@Ann Lee hi"+@parameterized.expand([("alias_thumbsup", ":+1:", "\U0001f44d"),diff --git a/products/tasks/backend/logic/services/comment_slack_dm.py b/products/tasks/backend/logic/services/comment_slack_dm.pyindex 4caa10370457..6db1aad50554 100644--- a/products/tasks/backend/logic/services/comment_slack_dm.py+++ b/products/tasks/backend/logic/services/comment_slack_dm.py@@ -10,7 +10,7 @@ logged and dropped rather than retried — which also means a retry can't doublea per-recipient sent marker to store."""-from collections.abc import Mapping+from collections.abc import Callable, Mappingfrom uuid import UUIDfrom django.conf import settings@@ -40,6 +40,16 @@ 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+_MAX_MENTION_LOOKUPS_PER_SLACK_WORKSPACE = 20++# Slack resolves its own palette keyword per client, where a hex would be a fixed choice that+# can't follow the reader's theme.+_ACCENT = "good"++_LOCATIONS: Mapping[str, str] = {+ "desktop_canvas": "On a canvas",+ "task_artifact": "On an artifact",+}_HEADINGS: Mapping[str, str] = {TaskCommentActivity.Kind.MENTION: "{author} mentioned you on {link}",@@ -92,6 +102,10 @@ def send_comment_slack_dms(*, team_id: int, comment_id: UUID, task_id: UUID, recusers = User.objects.in_bulk(list(wanted))integration_by_workspace = {integration.integration_id: integration for integration in integrations}slack_clients: dict[int, SlackIntegration] = {}+ mention_cache: dict[tuple[int, str], str | None] = {}+ mention_lookup_allowances = {+ integration.id: _MAX_MENTION_LOOKUPS_PER_SLACK_WORKSPACE for integration in integrations+ }for user_id, kind in wanted.items():recipient = users.get(user_id)if recipient is None:@@ -134,8 +148,25 @@ def send_comment_slack_dms(*, team_id: int, comment_id: UUID, task_id: UUID, recif 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)+ fallback, blocks = _message(+ kind=kind,+ comment=comment,+ task=task,+ organization_id=team.organization_id,+ slack_user_id_by_email=_mention_resolver(+ organization_id=team.organization_id,+ integration=integration,+ slack=slack,+ cache=mention_cache,+ lookup_allowances=mention_lookup_allowances,+ ),+ )+ slack.client.chat_postMessage(+ channel=slack_user_id,+ text=fallback,+ attachments=[{"color": _ACCENT, "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))@@ -252,6 +283,53 @@ def _slack_user_id_by_email(*, email: str, integration: Integration, slack: Slacreturn slack_user_id+def _mention_resolver(+ *,+ organization_id: str | UUID,+ integration: Integration,+ slack: SlackIntegration,+ cache: dict[tuple[int, str], str | None],+ lookup_allowances: dict[int, int],+) -> Callable[[str], str | None]:+ """Map a mentioned teammate's email to a Slack member of this workspace.++ Comment content is author-controlled, so only current organization members can reach Slack's+ email lookup. Unresolvable or untrusted addresses stay as plain display names.+ """++ def resolve(email: str) -> str | None:+ normalized_email = email.strip().lower()+ key = (integration.id, normalized_email)+ if key in cache:+ return cache[key]+ if lookup_allowances.get(integration.id, 0) <= 0:+ return None+ lookup_allowances[integration.id] -= 1+ if not OrganizationMembership.objects.filter(+ organization_id=organization_id,+ user__email__iexact=normalized_email,+ user__is_active=True,+ ).exists():+ cache[key] = None+ return None+ cache[key] = _slack_user_id_by_email(email=normalized_email, integration=integration, slack=slack)+ return cache[key]++ return resolve+++def _truncate_body(body: str) -> str:+ """Cutting mid-``<…>`` leaves a link or mention token Slack renders as raw text, so a long+ comment ending in one would show `<https://posthog.com/do…` to the reader."""+ if len(body) <= _BODY_LIMIT:+ return body+ cut = body[: _BODY_LIMIT - 1]+ unclosed = cut.rfind("<")+ if unclosed > cut.rfind(">"):+ cut = cut[:unclosed]+ return cut.rstrip() + "…"++def _author_name(comment: Comment) -> str:author = comment.created_byif author is None:@@ -259,7 +337,14 @@ def _author_name(comment: Comment) -> str: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]]:+def _message(+ *,+ kind: str,+ comment: Comment,+ task: Task,+ organization_id: str | UUID | None,+ slack_user_id_by_email: Callable[[str], str | None] | None = 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)@@ -271,10 +356,17 @@ def _message(*, kind: str, comment: Comment, task: Task, organization_id: str |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+ comment.rich_content,+ comment.content or "",+ include_images=False,+ organization_id=organization_id,+ slack_user_id_by_email=slack_user_id_by_email,)- 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}}]+ body = _truncate_body(body.strip())+ text = f"{heading}\n\n{body}" if body else heading+ blocks: list[dict] = [{"type": "section", "text": {"type": "mrkdwn", "text": text}}]+ # Three canvases in one task otherwise produce three identical headings.+ location = _LOCATIONS.get(comment.scope)+ if location:+ blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": location}]})+ return fallback, blocksdiff --git a/products/tasks/backend/tests/test_comment_slack_dm.py b/products/tasks/backend/tests/test_comment_slack_dm.pyindex bdabe639e567..ba07fd98bfc0 100644--- a/products/tasks/backend/tests/test_comment_slack_dm.py+++ b/products/tasks/backend/tests/test_comment_slack_dm.py@@ -53,6 +53,10 @@ class TestCommentSlackDm(CommentActivityTestCase):with self.captureOnCommitCallbacks(execute=True):super()._record_activity(comment, user_ids)+ def _dm_text(self) -> str:+ attachment = self.slack_client.chat_postMessage.call_args.kwargs["attachments"][0]+ return attachment["blocks"][0]["text"]["text"]+def _dm_channels(self) -> list[str]:return [call.kwargs["channel"] for call in self.slack_client.chat_postMessage.call_args_list]@@ -62,10 +66,62 @@ class TestCommentSlackDm(CommentActivityTestCase):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"]+ text = self._dm_text()assert "mentioned you" in textassert "this needs a guard" in text+ def test_an_overlong_comment_is_not_cut_inside_a_link(self):+ filler = "x" * 790+ comment = self._comment(content=f"{filler} see [the docs](https://posthog.com/docs/reference)")++ self._record_activity(comment, [self.author.id])++ text = self._dm_text()+ assert text.endswith("…")+ assert text.rfind("<") < text.rfind(">")++ def test_inline_mention_lookups_are_bounded(self) -> None:+ third = User.objects.create_user(email="[email protected]", first_name="Carol", password="password")+ self.organization.members.add(third)+ emails = [self.author.email, self.peer.email, third.email]+ comment = self._comment(content=" ".join(f"@[Member {index}]({email})" for index, email in enumerate(emails)))++ with (+ patch("products.tasks.backend.logic.services.comment_slack_dm._MAX_MENTION_LOOKUPS_PER_SLACK_WORKSPACE", 2),+ patch(+ "products.tasks.backend.logic.services.comment_slack_dm.lookup_slack_user_id_by_email",+ side_effect=["U-one", "U-two"],+ ) as lookup,+ patch(+ "products.tasks.backend.logic.services.comment_slack_dm.resolve_slack_user",+ return_value={"team_id": SLACK_WORKSPACE_ID},+ ),+ ):+ self._record_activity(comment, [self.author.id])++ assert lookup.call_count == 2+ text = self._dm_text()+ assert "<@U-one> <@U-two> @Member 2" in text++ def test_inline_mentions_only_query_slack_for_current_organization_members(self) -> None:+ comment = self._comment(content="@[Member]([email protected]) and @[Outsider]([email protected])")++ with (+ patch(+ "products.tasks.backend.logic.services.comment_slack_dm.lookup_slack_user_id_by_email",+ return_value="U-member",+ ) as lookup,+ patch(+ "products.tasks.backend.logic.services.comment_slack_dm.resolve_slack_user",+ return_value={"team_id": SLACK_WORKSPACE_ID},+ ),+ ):+ self._record_activity(comment, [self.author.id])++ lookup.assert_called_once()+ assert lookup.call_args.args[2] == "[email protected]"+ assert "<@U-member> and @Outsider" in self._dm_text()+def test_fallback_text_escapes_user_controlled_slack_markup(self):self.peer.first_name = "<@U-ATTACKER>"self.peer.last_name = ""