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(slack_app): post echoed mentions in the bare form so they notify (#72658)

Vojta Bartoš581117736de6
diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.py
index 44f002b81a89..ecbd6b4b024f 100644
--- a/posthog/temporal/ai/slack_app/activities/task_creation.py
+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py
@@ -125,11 +125,12 @@ def _max_ts(*candidates: str | None) -> str:
def _format_author_token(user_id: str | None, display_name: str | None) -> str:
"""Render a message author as a labeled Slack mention when we have the raw id.
- `<@U…|displayname>` is the wire-format token Slack accepts on both inbound and
- outbound messages; including it here means the agent sees who wrote each line
- *and* can echo the token verbatim to ping that participant back. When the raw
- id is missing (bots, app-posted messages, unresolved users), fall back to the
- plain display name so the line still reads naturally.
+ `<@U…|displayname>` is the form Slack uses to deliver mentions inbound; rendering
+ it here means the agent sees who wrote each line *and* can echo the token verbatim
+ to ping that participant back (the Slack relay rewrites echoed tokens to the bare
+ `<@U…>` on the way out, which is what actually notifies). When the raw id is missing
+ (bots, app-posted messages, unresolved users), fall back to the plain display name
+ so the line still reads naturally.
"""
name = (display_name or "").strip() or "user"
uid = (user_id or "").strip()
diff --git a/products/slack_app/backend/services/slack_messages.py b/products/slack_app/backend/services/slack_messages.py
index 2513c111f25e..a9203665ca04 100644
--- a/products/slack_app/backend/services/slack_messages.py
+++ b/products/slack_app/backend/services/slack_messages.py
@@ -1,11 +1,12 @@
"""Slack message text processing helpers.
The bot strips its own self-mention and enriches every other `<@U…>` reference
-with a `|displayname` label before handing the text to the agent. Slack accepts
-the labeled form `<@U_ID|displayname>` on both inbound and outbound messages —
-the agent gets a human-readable name to reason about *and* a wire-format token
-it can echo verbatim to ping the user back, so no outbound transformation is
-needed.
+with a `|displayname` label before handing the text to the agent — the agent
+gets a human-readable name to reason about *and* a token it can echo verbatim to
+ping the user back. The labeled form is how Slack delivers mentions inbound, but
+it does not reliably notify when a bot posts it outbound, so the Slack relay
+rewrites echoed `<@U_ID|displayname>` tokens back to the bare `<@U_ID>` on the
+way out (see `products/tasks/backend/temporal/slack_relay/activities.py`).
Also houses ``collect_thread_messages`` (and its cached wrapper) — fetching the
full thread shape used by the agent context block lives next to the text logic
@@ -48,9 +49,10 @@ def resolve_user_mentions_text(
Slack delivers events with bare `<@U_ID>` references — opaque to an LLM,
and easily paraphrased away into plain prose. For real users we enrich to
Slack's labeled form `<@U_ID|displayname>`: the agent gets both a
- human-readable handle to reason about *and* the exact wire-format token it
- can echo verbatim to ping the user back. Slack accepts the labeled form on
- the way out, so no outbound transformation is needed.
+ human-readable handle to reason about *and* the exact token it can echo
+ verbatim to ping the user back. The labeled form does not reliably notify
+ when a bot posts it outbound, so the Slack relay rewrites echoed tokens back
+ to the bare `<@U_ID>` before posting.
Bot users (our own, plus any other workspace bot — Grafana, GitHub, etc.)
are stripped entirely. There's nothing useful for the agent to do with a
@@ -118,6 +120,22 @@ def labeled_mentions_to_display_names(text: str) -> str:
return re.sub(r"<@[A-Z0-9]+\|([^>]+)>", r"@\1", text)
+_RE_LABELED_USER_MENTION = re.compile(r"<@([A-Z0-9]+)\|[^>]*>")
+
+
+def normalize_labeled_mentions_to_bare(text: str) -> str:
+ """Rewrite labeled `<@U_ID|display name>` mentions to the bare `<@U_ID>` for outbound posts.
+
+ We feed the agent the labeled form so it can echo a token to ping a participant back, but
+ that form only reliably notifies inbound: when a bot posts it, Slack does not consistently
+ linkify it, so a display name containing a space renders as inert text and the user is never
+ notified. The bare `<@U_ID>` is the canonical outbound mention — Slack resolves the current
+ name itself. Only `<@…>` user mentions are rewritten; channel links (`<#C…|name>`),
+ broadcast/subteam refs (`<!…>`), and URL links (`<https://…|label>`) keep their labels.
+ """
+ return _RE_LABELED_USER_MENTION.sub(r"<@\1>", text)
+
+
def flatten_block_text(node: Any) -> list[str]:
"""Best-effort plain-text extraction from a Slack block-kit subtree.
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index f9c9c0d171a6..a8748c3adb37 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -7,6 +7,8 @@ from slack_sdk import WebClient
from posthog.models.integration import Integration, SlackIntegration
+from products.slack_app.backend.services.slack_messages import normalize_labeled_mentions_to_bare
+
logger = structlog.get_logger(__name__)
PROGRESS_MESSAGE_MARKER = "Working on task..."
@@ -193,7 +195,7 @@ class SlackThreadHandler:
if first_task_id and first_task_title:
chunks.append(_task_update_chunk(first_task_id, first_task_title, "in_progress", first_task_details))
if first_markdown_text:
- for piece in _split_markdown_text(first_markdown_text):
+ for piece in _split_markdown_text(normalize_labeled_mentions_to_bare(first_markdown_text)):
chunks.append({"type": "markdown_text", "text": piece})
if not chunks:
return None
@@ -230,7 +232,7 @@ class SlackThreadHandler:
continue
chunks.append(_task_update_chunk(str(task_id), str(title), str(status), t.get("details")))
if markdown_text:
- for piece in _split_markdown_text(markdown_text):
+ for piece in _split_markdown_text(normalize_labeled_mentions_to_bare(markdown_text)):
chunks.append({"type": "markdown_text", "text": piece})
if not chunks:
return
@@ -260,7 +262,7 @@ class SlackThreadHandler:
_task_update_chunk(complete_task_id, complete_task_title, "complete", complete_task_details)
)
if final_markdown:
- for piece in _split_markdown_text(final_markdown):
+ for piece in _split_markdown_text(normalize_labeled_mentions_to_bare(final_markdown)):
final_chunks.append({"type": "markdown_text", "text": piece})
if self.context.mentioning_slack_user_id:
# Newlines keep the mention off the tail of the last streamed prose chunk.
diff --git a/products/slack_app/backend/tests/services/slack_messages/test_normalize_labeled_mentions_to_bare.py b/products/slack_app/backend/tests/services/slack_messages/test_normalize_labeled_mentions_to_bare.py
new file mode 100644
index 000000000000..68c5e1cd99a9
--- /dev/null
+++ b/products/slack_app/backend/tests/services/slack_messages/test_normalize_labeled_mentions_to_bare.py
@@ -0,0 +1,21 @@
+import unittest
+
+from parameterized import parameterized
+
+from products.slack_app.backend.services.slack_messages import normalize_labeled_mentions_to_bare
+
+
+class TestNormalizeLabeledMentionsToBare(unittest.TestCase):
+ @parameterized.expand(
+ [
+ ("single_word_name", "hi <@U123|vojta>", "hi <@U123>"),
+ ("name_with_space", "hi <@U123|Radu Raicea>", "hi <@U123>"),
+ ("multiple_mentions", "<@U1|A B> and <@U2|C>", "<@U1> and <@U2>"),
+ ("already_bare_untouched", "hi <@U123>", "hi <@U123>"),
+ ("channel_link_kept", "see <#C123|general>", "see <#C123|general>"),
+ ("url_link_kept", "<https://x.com|label>", "<https://x.com|label>"),
+ ("broadcast_kept", "<!here>", "<!here>"),
+ ]
+ )
+ def test_normalize(self, _name, text, expected):
+ assert normalize_labeled_mentions_to_bare(text) == expected
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index 4010d720879a..4ea2e744d128 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -27,6 +27,29 @@ class TestSlackThreadHandler(SimpleTestCase):
def test_format_task_error(self, _name: str, error: str, expected: str) -> None:
assert _format_task_error(error) == expected
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_stop_status_stream_posts_labeled_mention_as_bare(self, mock_get_client):
+ # The streaming path posts the agent's final answer, which can echo a participant in
+ # the labeled `<@U…|display name>` form. A name with a space renders as inert text when
+ # a bot posts it, so it must be normalized to the bare `<@U…>` that actually notifies.
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+
+ context = SlackThreadContext(
+ integration_id=1,
+ channel="C001",
+ thread_ts="1234.5678",
+ mentioning_slack_user_id="U123",
+ )
+ handler = SlackThreadHandler(context)
+
+ handler.stop_status_stream(ts="1234.9999", final_markdown="Answering <@U094TR1E59V|Radu Raicea> now.")
+
+ chunks = mock_client.chat_appendStream.call_args.kwargs["chunks"]
+ streamed = "".join(chunk.get("text", "") for chunk in chunks)
+ assert "<@U094TR1E59V>" in streamed
+ assert "Radu Raicea" not in streamed
+
@patch.object(SlackThreadHandler, "_find_progress_message_ts", return_value=None)
@patch.object(SlackThreadHandler, "_get_client")
def test_progress_message_has_no_terminate_button(self, mock_get_client, _mock_find_progress):
diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.py
index 699bb9fa6888..a92918efa9bc 100644
--- a/products/tasks/backend/temporal/slack_relay/activities.py
+++ b/products/tasks/backend/temporal/slack_relay/activities.py
@@ -360,6 +360,7 @@ class RelaySlackMessageInput:
@close_db_connections
def relay_slack_message(input: RelaySlackMessageInput) -> None:
from products.slack_app.backend.models import SlackThreadTaskMapping
+ from products.slack_app.backend.services.slack_messages import normalize_labeled_mentions_to_bare
from products.slack_app.backend.slack_thread import SlackThreadContext, SlackThreadHandler
from products.tasks.backend.models import TaskRun
from products.tasks.backend.temporal.process_task.utils import get_message_actor
@@ -386,6 +387,11 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
logger.info("slack_relay_empty_text", run_id=input.run_id, relay_id=input.relay_id)
return
+ # Rewrite echoed ``<@U…|name>`` tokens to the bare ``<@U…>`` so the mentions the agent
+ # composed actually notify their targets. Done before splitting/conversion: the bare form
+ # is shorter (never enlarges a chunk) and the mrkdwn converter passes it through untouched.
+ text = normalize_labeled_mentions_to_bare(text)
+
# Living-artifacts gating lives in the service: has_pending_slack_file_artifacts
# (and deliver_pending_slack_file_artifacts below) return falsy when the
# workspace's living-artifacts flag is off. Run-manifest artifacts are internal
diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
index 8c310198beaf..13a16cdccd8a 100644
--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
@@ -152,6 +152,32 @@ class TestRelaySlackMessage(TestCase):
mock_post.assert_called_once()
assert mock_post.call_args.args[0].startswith(expected_prefix)
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
+ def test_labeled_mention_echoed_in_body_is_posted_as_bare(
+ self,
+ _mock_delete_progress,
+ mock_post,
+ _mock_update,
+ ):
+ # The agent echoes participants in the labeled ``<@U…|display name>`` form fed to it.
+ # That form does not reliably notify when the bot posts it, so the relay must rewrite
+ # it to the bare ``<@U…>`` — otherwise a display name with a space (here "Radu Raicea")
+ # renders as inert text and the mentioned user is never pinged.
+ relay_slack_message(
+ RelaySlackMessageInput(
+ run_id=str(self.task_run.id),
+ relay_id="relay-labeled-mention",
+ text="Answering <@U094TR1E59V|Radu Raicea> now.",
+ )
+ )
+
+ mock_post.assert_called_once()
+ posted = mock_post.call_args.args[0]
+ assert "<@U094TR1E59V>" in posted
+ assert "Radu Raicea" not in posted
+
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")