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.

fix(signals): show owners in shared Slack reports (#129695)

Dylan Martinccd0f949b157
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index c52d502fc0fd..c0b22bc77cb8 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -337,7 +337,12 @@ When a project member adds a reviewer, the report shows "Added by" and that memb
Slack notifications for a ready report include only reviewers who have access to the report's project when delivery starts.
The same access rule applies when a reviewer is added later.
-If no suggested reviewer has access, the ready report still goes to the configured team channel without reviewer mentions.
+The team channel shows eligible suggested owners within Slack's text limit.
+When the labels exceed that limit, the notification shows complete labels and a count of the remaining owners.
+It pings only owners routed to that channel, so owners with a personal notification target appear as plain text.
+Slack keeps plain-text owner names literal instead of converting them into mentions.
+Report text also escapes incomplete mention prefixes and nested tokens while it keeps valid HTTP links.
+If no suggested reviewer has access, the ready report still goes to the configured team channel without an owner label.
If the latest actionability judgment marks the report as already addressed, the system does not assign a fallback owner or send a reviewer push notification.
Slack still sends the report to the configured team channel without reviewer mentions.
The notification activity retries transient ClickHouse reads before it claims the report for delivery.
diff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.py
index 17ed7f54d564..ff662ad10496 100644
--- a/products/signals/backend/slack_formatting.py
+++ b/products/signals/backend/slack_formatting.py
@@ -70,7 +70,7 @@ def strip_chart_references(text: str) -> str:
# (`<@U…>`, `<#C…>`, `<!here>`, `<!subteam^S…>`) and the labelled link form, whose `<dest|label>`
# shape lets the label say one thing while the link goes somewhere else. A bare `<https://…>` is
# neither — it links to exactly what it displays — so it is left for Slack to render.
-_SLACK_TOKEN_RE = re.compile(r"<(?:[@#!][^<>]*|[^<>|]*\|[^<>]*)>")
+_SLACK_TOKEN_RE = re.compile(r"<(?:[@#!][^<>]*|[^<>|]*\|[^<>]*)>|<(?=[@#!])")
def defuse_slack_tokens(text: str) -> str:
@@ -81,6 +81,7 @@ def defuse_slack_tokens(text: str) -> str:
label hides its destination. Escaping the angle brackets stops all three, and Slack renders the
escaped form back as the literal characters.
+ Incomplete mention prefixes must also be escaped because conversion can add a closing bracket.
Only a token is rewritten. Escaping every `<` instead corrupts the three things that carry
angle brackets innocently: a code span (`Vec<T>`), a CommonMark autolink, and an angle-bracket
link destination, none of which decode the entity back.
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 2d4e0ee0def6..1c36b264fc35 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -63,6 +63,7 @@ from products.signals.backend.slack_formatting import (
first_sentence as _first_sentence,
is_safe_slack_http_url,
prepare_slack_markdown as _prepare_markdown,
+ slack_text_length,
strip_chart_references as _strip_chart_references,
truncate_slack_text,
)
@@ -83,6 +84,7 @@ logger = logging.getLogger(__name__)
_SUMMARY_EXCERPT_MAX_LEN = 280
_SLACK_HEADER_MAX_LEN = 150
+_SLACK_CONTEXT_MAX_LEN = 3000
_INBOX_INVITE_UTM_TAGS = "utm_source=posthog&utm_campaign=signals_inbox&utm_medium=slack"
# Bound message size / avoid pinging a crowd.
_MAX_REVIEWER_MENTIONS = 5
@@ -393,18 +395,35 @@ def _display_title(title: str | None) -> str:
def _section_body(markdown: str) -> str:
def safe_token(match: re.Match[str]) -> str:
- destination = match.group(1).partition("|")[0]
+ destination = match.group(0)[1:-1].partition("|")[0]
return match.group(0) if is_safe_slack_http_url(destination) else _escape_mrkdwn(match.group(0))
# Conversion creates Slack tokens, so only HTTP links may survive in the untrusted body.
converted = SlackMarkdownConverter().convert(markdown)
- return truncate_slack_text(re.sub(r"<([^<>]*)>", safe_token, converted), 3000)
+ return truncate_slack_text(re.sub(r"<[^<>]*>|[<>]", safe_token, converted), 3000)
+
+
+def _owner_context_text(reviewer_labels: list[str], *, max_length: int = _SLACK_CONTEXT_MAX_LEN) -> str:
+ owner_label = "Suggested owner" if len(reviewer_labels) == 1 else "Suggested owners"
+ prefix = f"👤 {owner_label}:"
+ text = f"{prefix} {' '.join(reviewer_labels)}"
+ if slack_text_length(text) <= max_length:
+ return text
+
+ text = prefix
+ for index, label in enumerate(reviewer_labels):
+ remaining = len(reviewer_labels) - index - 1
+ suffix = f" (+{remaining} more)" if remaining else ""
+ if slack_text_length(text) + 1 + slack_text_length(label) + len(suffix) > max_length:
+ return f"{text} (+{remaining + 1} more)"
+ text += f" {label}"
+ return text
def _build_message_blocks(
report: SignalReport,
*,
- reviewer_mentions: list[str],
+ reviewer_labels: list[str],
use_section_blocks: bool = False,
priority: str | None = None,
offer_implementation: bool = False,
@@ -446,11 +465,13 @@ def _build_message_blocks(
if priority_emoji := _PRIORITY_EMOJI.get(priority or ""):
context_parts.append(f"{priority_emoji} *{priority}*")
# Plain-text blocks would show the raw mention token instead of resolving the user.
- if reviewer_mentions:
- owner_label = "Suggested owner" if len(reviewer_mentions) == 1 else "Suggested owners"
- context_parts.append(f"👤 {owner_label}: {' '.join(reviewer_mentions)}")
+ if reviewer_labels:
+ prefix_length = slack_text_length(" · ".join(context_parts) + " · ") if context_parts else 0
+ context_parts.append(_owner_context_text(reviewer_labels, max_length=_SLACK_CONTEXT_MAX_LEN - prefix_length))
if context_parts:
- blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": " · ".join(context_parts)}]})
+ blocks.append(
+ {"type": "context", "elements": [{"type": "mrkdwn", "text": " · ".join(context_parts), "verbatim": True}]}
+ )
action_elements: list[dict] = []
# A link, not an interactive button: the inbox runs its own access, quota and repository checks.
@@ -476,7 +497,7 @@ def _build_message_blocks(
class _ChannelRoute:
- """One Slack destination and the reviewers routed to it (mentioned only there).
+ """One Slack destination and the reviewers notified or shown there.
The destination is a channel, or a member whose id Slack turns into a direct message.
"""
@@ -487,6 +508,7 @@ class _ChannelRoute:
self.is_team_channel = is_team_channel
self.is_direct_message = is_slack_member_target(channel)
self.users: list[User] = []
+ self.owner_users: dict[int, User] = {}
@frozen
@@ -497,7 +519,7 @@ class _Destination:
class _RouteTable:
- """The destinations one report is posted to, each collecting the reviewers it mentions.
+ """The destinations one report is posted to, with reviewers to notify and display.
Keyed by (integration_id, channel_id) so a reviewer's own channel and the team default
collapse into one post when they resolve to the same Slack channel.
@@ -506,7 +528,7 @@ class _RouteTable:
def __init__(self) -> None:
self._routes: dict[tuple[int, str], _ChannelRoute] = {}
- def add(self, destination: _Destination, *, user: User | None = None) -> None:
+ def add(self, destination: _Destination, *, user: User | None = None, owner_users: Iterable[User] = ()) -> None:
key = (destination.integration.id, _channel_id_from_target(destination.channel))
route = self._routes.get(key)
if route is None:
@@ -518,6 +540,9 @@ class _RouteTable:
route.is_team_channel = True
if user is not None:
route.users.append(user)
+ route.owner_users[user.id] = user
+ for owner_user in owner_users:
+ route.owner_users[owner_user.id] = owner_user
def routes(self) -> list[_ChannelRoute]:
return list(self._routes.values())
@@ -557,13 +582,12 @@ def _build_reviewer_routes(
team_integration: IntegrationRecord | None,
team_channel: str | None,
) -> list[_ChannelRoute]:
- """Route resolvable suggested reviewers to a destination, mentioning them there.
+ """Route resolvable suggested reviewers to a destination.
Own target (filtered by the reviewer's min-priority) if set, else the team default. A reviewer
- filtered out of their own target is not mentioned in the team channel — that was their choice.
- Reviewers sharing a destination are grouped so each channel is posted to once, mentioning only
- its own reviewers. The team-default channel (if configured) receives every report, with no
- mentions when no reviewer is routed there.
+ filtered out of their own target is not pinged. Reviewers sharing a destination are grouped so
+ each channel is posted to once. The team-default channel receives every report and shows every
+ suggested owner. It pings only the reviewers routed there.
"""
reviewer_user_ids = (
set() if report.latest_already_addressed is True else resolve_suggested_reviewer_user_ids(report)
@@ -586,10 +610,11 @@ def _build_reviewer_routes(
continue
table.add(destination, user=user)
- # The team channel gets every report. It mentions only the reviewers routed there, so a reviewer
- # with their own target is not pinged twice.
if team_integration is not None and team_channel:
- table.add(_Destination(integration=team_integration, channel=team_channel, is_team_channel=True))
+ table.add(
+ _Destination(integration=team_integration, channel=team_channel, is_team_channel=True),
+ owner_users=(reviewer_users[user_id] for user_id in sorted(reviewer_users)),
+ )
return table.routes()
@@ -623,11 +648,19 @@ def _deliver_route_notification(
logger.warning("Skipping signals inbox-item Slack DM to an ineligible member", extra=log_context)
_capture_notification_delivered(report, route, trigger=trigger, delivered=False)
return False
- # The only reviewer a direct message could mention is the person already reading it.
- mentions = [] if route.is_direct_message else _resolve_reviewer_mentions(slack, route.users)
+ if route.is_direct_message:
+ reviewer_labels: list[str] = []
+ else:
+ reviewer_labels = _resolve_reviewer_mentions(slack, route.users)
+ mentioned_user_ids = {user.id for user in route.users}
+ reviewer_labels.extend(
+ _escape_mrkdwn(_posthog_user_display_name(user))
+ for user_id, user in route.owner_users.items()
+ if user_id not in mentioned_user_ids
+ )
blocks, text = _build_message_blocks(
report,
- reviewer_mentions=mentions,
+ reviewer_labels=reviewer_labels,
use_section_blocks=organization_inbox_slack_section_blocks_enabled(report.team.organization_id),
priority=priority,
offer_implementation=offer_implementation,
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index 00d69a912bad..ec90d15a1ce0 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -141,7 +141,7 @@ def test_build_message_blocks_includes_recipient_and_open_in_posthog_button(use_
)
blocks, text = _build_message_blocks(
report,
- reviewer_mentions=["<@U123>"],
+ reviewer_labels=["<@U123>"],
use_section_blocks=use_section_blocks,
priority=AutonomyPriority.P1,
offer_implementation=True,
@@ -186,7 +186,7 @@ def test_build_message_blocks_includes_recipient_and_open_in_posthog_button(use_
)
def test_build_message_blocks_shows_only_the_impact_section(summary: str, expected: str) -> None:
report = SignalReport(id="report-uuid", title="Impact test", summary=summary)
- blocks, _ = _build_message_blocks(report, reviewer_mentions=[])
+ blocks, _ = _build_message_blocks(report, reviewer_labels=[])
body = blocks[1]["text"]
if expected:
@@ -195,17 +195,58 @@ def test_build_message_blocks_shows_only_the_impact_section(summary: str, expect
assert "Impact" not in body
-def test_build_message_blocks_mentions_every_routed_reviewer() -> None:
[email protected]("use_section_blocks", [False, True])
+ ("reviewer_labels", "expected", "priority"),
+ [
+ (["<@U1>", "<@U2>"], "👤 Suggested owners: <@U1> <@U2>", None),
+ (["<@U1>", "@here @channel"], "👤 Suggested owners: <@U1> @here @channel", None),
+ (["a" * 2980], "👤 Suggested owner: " + "a" * 2980, None),
+ (["a" * 2981], "👤 Suggested owner: (+1 more)", None),
+ (["🚀" * 1490], "👤 Suggested owner: " + "🚀" * 1490, None),
+ (["🚀" * 1491], "👤 Suggested owner: (+1 more)", None),
+ (
+ ["<@U1>"] + ["Owner" * 200] * 100,
+ "👤 Suggested owners: <@U1> " + "Owner" * 200 + " " + "Owner" * 200 + " (+98 more)",
+ None,
+ ),
+ (["a" * 2966, "<@U1234567890>"], "👤 Suggested owners: " + "a" * 2966 + " (+1 more)", None),
+ (["<@U1>", "&amp;" * 595], "👤 Suggested owners: <@U1> (+1 more)", None),
+ (["a" * 2970], "🟠 *P1* · 👤 Suggested owner: " + "a" * 2970, AutonomyPriority.P1),
+ (["a" * 2971], "🟠 *P1* · 👤 Suggested owner: (+1 more)", AutonomyPriority.P1),
+ ],
+ ids=[
+ "mentions",
+ "literal_names",
+ "at_limit",
+ "long_name",
+ "unicode_at_limit",
+ "long_unicode_name",
+ "many_names",
+ "whole_mention",
+ "escaped_name",
+ "priority_at_limit",
+ "priority_over_limit",
+ ],
+)
+def test_build_message_blocks_bounds_owner_labels(
+ reviewer_labels: list[str], expected: str, priority: str | None, use_section_blocks: bool
+) -> None:
report = SignalReport(id="report-uuid", title="Shared channel")
- blocks, _ = _build_message_blocks(report, reviewer_mentions=["<@U1>", "<@U2>"])
+ blocks, _ = _build_message_blocks(
+ report, reviewer_labels=reviewer_labels, use_section_blocks=use_section_blocks, priority=priority
+ )
- assert blocks[1]["text"] == "**Shared channel**"
- assert blocks[2]["elements"][0]["text"] == "👤 Suggested owners: <@U1> <@U2>"
+ body = blocks[1]["text"]["text"] if use_section_blocks else blocks[1]["text"]
+ assert body == ("*Shared channel*" if use_section_blocks else "**Shared channel**")
+ assert blocks[2]["elements"][0]["text"] == expected
+ assert blocks[2]["elements"][0].get("verbatim") is True
+ assert len(blocks[2]["elements"][0]["text"].encode("utf-16-le")) // 2 <= 3000
def test_build_message_blocks_caps_section_body_without_truncating_mentions() -> None:
report = SignalReport(id="report-uuid", title="🚀" * 2000)
- blocks, _ = _build_message_blocks(report, reviewer_mentions=["<@U123>"], use_section_blocks=True)
+ blocks, _ = _build_message_blocks(report, reviewer_labels=["<@U123>"], use_section_blocks=True)
body = blocks[1]["text"]["text"]
assert len(body.encode("utf-16-le")) // 2 <= 3000
@@ -221,6 +262,9 @@ def test_build_message_blocks_caps_section_body_without_truncating_mentions() ->
"![notify](!here) everyone & ![owner](@U999) look\n\n## Impact\n\n![team](!channel) is affected",
"[notify](!here) everyone & [owner](@U999) look\n\n## Impact\n\n[team](!channel) is affected",
"![notify](!here) everyone & [channel](#C999) [group](!subteam^S999) [link](javascript:alert)",
+ "<!here [details](https://example.com/report?a=1&b=2) everyone & <@U999",
+ "<!here [details](https://example.com/report) everyone & <#C999 [more](https://example.com)",
+ "![notify](!here[details](https://example.com)) everyone & ![owner](@U999[more](https://example.com))",
],
)
def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields(use_section_blocks: bool, summary: str) -> None:
@@ -231,7 +275,7 @@ def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields(use_section_b
summary=summary,
signal_count=1,
)
- blocks, _ = _build_message_blocks(report, reviewer_mentions=["<@U123>"], use_section_blocks=use_section_blocks)
+ blocks, _ = _build_message_blocks(report, reviewer_labels=["<@U123>"], use_section_blocks=use_section_blocks)
section_text = blocks[1]["text"]["text"] if use_section_blocks else blocks[1]["text"]
assert "<!" not in section_text
@@ -250,12 +294,12 @@ def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields(use_section_b
def test_build_message_blocks_does_not_share_conversion_state_between_reports() -> None:
_build_message_blocks(
SignalReport(id="first-report", summary="```python\nexample()\n```"),
- reviewer_mentions=[],
+ reviewer_labels=[],
use_section_blocks=True,
)
blocks, _ = _build_message_blocks(
SignalReport(id="second-report", summary="**Details** are [here](https://example.com)."),
- reviewer_mentions=[],
+ reviewer_labels=[],
use_section_blocks=True,
)
@@ -887,8 +931,6 @@ def test_dispatch_groups_own_and_fallback_reviewers_sharing_a_channel(org_and_te
@pytest.mark.django_db
def test_dispatch_posts_team_channel_when_reviewer_has_own_channel(org_and_team):
- # The only reviewer has their own channel. The team channel still gets the report, without
- # mentioning that reviewer a second time.
org, team = org_and_team
user = _make_reviewer_user(org, "[email protected]", "own-only-bot")
integration = _make_slack_integration(team, user)
@@ -905,7 +947,7 @@ def test_dispatch_posts_team_channel_when_reviewer_has_own_channel(org_and_team)
patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,
patch(
"products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
- return_value=None,
+ return_value="U_OWN",
),
):
slack_cls.return_value.client = fake_client
@@ -914,7 +956,8 @@ def test_dispatch_posts_team_channel_when_reviewer_has_own_channel(org_and_team)
assert sent == 2
posts = {c.kwargs["channel"]: c.kwargs["blocks"] for c in fake_client.chat_postMessage.call_args_list}
assert set(posts) == {"CUSER", "CTEAM"}
- assert "Suggested" not in json.dumps(posts["CTEAM"])
+ assert posts["CUSER"][2]["elements"][0]["text"] == "🟡 *P2* · 👤 Suggested owner: <@U_OWN>"
+ assert posts["CTEAM"][2]["elements"][0]["text"] == "🟡 *P2* · 👤 Suggested owner: Reviewer Bot"
@pytest.mark.django_db
@@ -955,6 +998,7 @@ def test_dispatch_team_channel_tags_only_fallback_reviewers(org_and_team):
assert set(by_channel) == {"CUSER", "CTEAM"}
assert "<@U_OWN>" in by_channel["CUSER"] and "<@U_FALLBACK>" not in by_channel["CUSER"]
assert "<@U_FALLBACK>" in by_channel["CTEAM"] and "<@U_OWN>" not in by_channel["CTEAM"]
+ assert "Reviewer Bot" in by_channel["CTEAM"]
@pytest.mark.django_db
@@ -981,9 +1025,7 @@ def test_dispatch_respects_per_user_min_priority_filter(org_and_team):
@pytest.mark.django_db
-def test_dispatch_filtered_own_channel_reviewer_is_not_mentioned_in_team_channel(org_and_team):
- # A reviewer whose own channel is filtered out by their min-priority chose that
- # threshold, so the team channel gets the report without mentioning them.
+def test_dispatch_filtered_own_channel_reviewer_is_shown_without_a_mention_in_team_channel(org_and_team):
org, team = org_and_team
user = _make_reviewer_user(org, "[email protected]", "low-bot")
integration = _make_slack_integration(team, user)
@@ -1011,7 +1053,7 @@ def test_dispatch_filtered_own_channel_reviewer_is_not_mentioned_in_team_channel
assert sent == 1
call_kwargs = fake_client.chat_postMessage.call_args.kwargs
assert call_kwargs["channel"] == "CTEAM"
- assert "Suggested" not in json.dumps(call_kwargs["blocks"])
+ assert call_kwargs["blocks"][2]["elements"][0]["text"] == "🔵 *P3* · 👤 Suggested owner: Reviewer Bot"
@pytest.mark.django_db