Skip to content

The agent that grows with you

fix(slack): render mentions as rich_text elements in rich_blocks

Muneeb Anjuma0f9c92bd7a7
diff --git a/plugins/platforms/slack/block_kit.py b/plugins/platforms/slack/block_kit.py
index 540a2f76598..83bcce8169a 100644
--- a/plugins/platforms/slack/block_kit.py
+++ b/plugins/platforms/slack/block_kit.py
@@ -76,15 +76,39 @@ def _indent_level(spaces: str) -> int:
_INLINE_CODE_RE = re.compile(r"`([^`]+)`")
_LINK_RE = re.compile(r"(?<!!)\[([^\]]+)\]\(([^()\s]+(?:\([^()]*\)[^()\s]*)*)\)")
# Slack mrkdwn autolink: <scheme:target> or <scheme:target|label>.
-# Mentions (<@U…>, <#C…>, <!here>) have no scheme: and stay as text.
_SLACK_LINK_RE = re.compile(
r"<([a-zA-Z][a-zA-Z0-9+.\-]*:[^>|]+)(?:\|([^>]+))?>"
)
+# Slack mention tokens carry no scheme: <@U…> (user), <#C…> (channel, with an
+# optional |name label), <!subteam^S…> (usergroup) and <!here|!channel|!everyone>
+# (broadcast). rich_text does not interpret mrkdwn, so these must become
+# user/channel/broadcast/usergroup elements — as plain text Slack renders the
+# token literally.
+_SLACK_MENTION_RE = re.compile(
+ r"<(@[A-Z0-9]+|#[A-Z0-9]+|!subteam\^[A-Z0-9]+|!(?:here|channel|everyone))(?:\|[^>]*)?>"
+)
_BOLD_RE = re.compile(r"(?:\*\*|__)(.+?)(?:\*\*|__)")
_ITALIC_RE = re.compile(r"(?<![\*_])(?:\*|_)(?![\*_\s])(.+?)(?<![\*_\s])(?:\*|_)(?![\*_])")
_STRIKE_RE = re.compile(r"~~(.+?)~~")
+def _mention_element(body: str) -> Optional[dict[str, Any]]:
+ """Map a Slack mention token body (without the angle brackets) to a rich_text element.
+
+ ``@U…`` -> user, ``#C…`` -> channel, ``!subteam^S…`` -> usergroup,
+ ``!here``/``!channel``/``!everyone`` -> broadcast.
+ Returns None for anything else, so the caller can emit the raw token as text."""
+ if body.startswith("@"):
+ return {"type": "user", "user_id": body[1:]}
+ if body.startswith("#"):
+ return {"type": "channel", "channel_id": body[1:]}
+ if body.startswith("!subteam^"):
+ return {"type": "usergroup", "usergroup_id": body[len("!subteam^"):]}
+ if body.startswith("!"):
+ return {"type": "broadcast", "range": body[1:]}
+ return None
+
+
def _inline_elements(text: str) -> list[dict[str, Any]]:
"""Parse a run of inline markdown into rich_text section child elements.
Produces ``text`` elements (optionally styled bold/italic/strike/code) and ``link`` elements.
@@ -147,7 +171,19 @@ def _inline_elements(text: str) -> list[dict[str, Any]]:
_walk_emphasis(m.group(1), inner_style)
_walk_emphasis(s[m.end() :], style)
return
- emit_text(s, dict(style) if style else None)
+ # Base case: split on mention tokens at the leaf so emphasis spans
+ # wrapping a mention are kept intact, while mentions themselves
+ # remain unstyled (Slack rejects styled mention elements).
+ pos = 0
+ for m in _SLACK_MENTION_RE.finditer(s):
+ emit_text(s[pos : m.start()], dict(style) if style else None)
+ element = _mention_element(m.group(1))
+ if element is not None:
+ elements.append(element)
+ else:
+ emit_text(m.group(0), dict(style) if style else None)
+ pos = m.end()
+ emit_text(s[pos:], dict(style) if style else None)
walk(text, {})
return elements or [{"type": "text", "text": text}]
diff --git a/tests/gateway/test_slack_block_kit.py b/tests/gateway/test_slack_block_kit.py
index ddc00e5da0a..c87412a94de 100644
--- a/tests/gateway/test_slack_block_kit.py
+++ b/tests/gateway/test_slack_block_kit.py
@@ -59,13 +59,18 @@ class TestInlineFormatting:
assert any(e.get("style", {}).get("code") for e in els)
def test_slack_mentions_in_bullet_are_not_links(self):
+ """Mentions must become mention elements, never link elements.
+
+ rich_text does not interpret mrkdwn, so a token left as a text element
+ renders literally in Slack (see #133315).
+ """
blocks = render_blocks("- ping <@U123> in <#C456>")
assert blocks is not None
els = blocks[0]["elements"][0]["elements"][0]["elements"]
assert all(e.get("type") != "link" for e in els)
- blob = "".join(e.get("text") or "" for e in els)
- assert "<@U123>" in blob
- assert "<#C456>" in blob
+ assert {"type": "user", "user_id": "U123"} in els
+ assert {"type": "channel", "channel_id": "C456"} in els
+ assert not any("<@" in (e.get("text") or "") or "<#" in (e.get("text") or "") for e in els)
def test_blank_line_separated_ordered_items_stay_in_one_list(self):
@@ -85,6 +90,90 @@ class TestInlineFormatting:
assert len(items) == 3
+class TestSlackMentions:
+ """Mention tokens must become rich_text user/channel/broadcast elements.
+
+ Regression coverage for #133315: mentions inside rich_text (lists, quotes,
+ table cells) were emitted as text elements, so Slack showed the raw token
+ literally instead of a mention.
+ """
+
+ @staticmethod
+ def _item_elements(blocks):
+ rich = next(b for b in blocks if b["type"] == "rich_text")
+ return rich["elements"][0]["elements"][0]["elements"]
+
+ def test_channel_mention_with_label_keeps_only_the_id(self):
+ blocks = render_blocks("- see <#C0C6N2RF5HS|general>")
+ assert blocks is not None
+ els = self._item_elements(blocks)
+ assert {"type": "channel", "channel_id": "C0C6N2RF5HS"} in els
+ assert not any("general" in (e.get("text") or "") for e in els)
+
+ def test_broadcast_mentions_map_to_range(self):
+ blocks = render_blocks("- <!here> <!channel> <!everyone>")
+ assert blocks is not None
+ els = self._item_elements(blocks)
+ assert [e["range"] for e in els if e.get("type") == "broadcast"] == [
+ "here",
+ "channel",
+ "everyone",
+ ]
+
+ def test_usergroup_mention_becomes_usergroup_element(self):
+ blocks = render_blocks("- notify <!subteam^S0123ABC|@marketing> and <!subteam^S987XYZ>")
+ assert blocks is not None
+ els = self._item_elements(blocks)
+ assert {"type": "usergroup", "usergroup_id": "S0123ABC"} in els
+ assert {"type": "usergroup", "usergroup_id": "S987XYZ"} in els
+ assert not any("marketing" in (e.get("text") or "") for e in els)
+
+ def test_mention_in_quote_becomes_mention_element(self):
+ blocks = render_blocks("> ping <@U123> now")
+ assert blocks is not None
+ quote = blocks[0]["elements"][0]
+ assert quote["type"] == "rich_text_quote"
+ assert {"type": "user", "user_id": "U123"} in quote["elements"]
+
+ def test_mention_in_table_cell_becomes_mention_element(self):
+ blocks = render_blocks("| who | note |\n| --- | --- |\n| <@U123> | ok |")
+ assert blocks is not None
+ assert blocks[0]["type"] == "table"
+ cell = blocks[0]["rows"][1][0]
+ assert {"type": "user", "user_id": "U123"} in cell["elements"][0]["elements"]
+
+ def test_unmatched_angle_token_is_preserved_as_text(self):
+ # Not a mention and not an autolink: must survive verbatim, not vanish.
+ blocks = render_blocks("- a <b> c")
+ assert blocks is not None
+ els = self._item_elements(blocks)
+ assert "a <b> c" in "".join(e.get("text") or "" for e in els)
+
+ def test_mention_inside_emphasis_preserves_styling_and_mention(self):
+ # Regression: emphasis wrapping a mention must not be destroyed into literal delimiters
+ blocks = render_blocks("- **ping <@U123> now**")
+ assert blocks is not None
+ els = self._item_elements(blocks)
+ assert not any("**" in (e.get("text") or "") for e in els)
+ assert {"type": "user", "user_id": "U123"} in els
+ assert any(e.get("text") == "ping " and e.get("style", {}).get("bold") for e in els)
+ assert any(e.get("text") == " now" and e.get("style", {}).get("bold") for e in els)
+
+ # Italic
+ blocks = render_blocks("- *ping <#C456>*")
+ els = self._item_elements(blocks)
+ assert not any("*" in (e.get("text") or "") for e in els)
+ assert {"type": "channel", "channel_id": "C456"} in els
+ assert any(e.get("text") == "ping " and e.get("style", {}).get("italic") for e in els)
+
+ # Strike
+ blocks = render_blocks("- ~~hi <!here>~~")
+ els = self._item_elements(blocks)
+ assert not any("~~" in (e.get("text") or "") for e in els)
+ assert {"type": "broadcast", "range": "here"} in els
+ assert any(e.get("text") == "hi " and e.get("style", {}).get("strike") for e in els)
+
+
class TestTables:
def test_pipe_table_renders_native_table_block(self):
md = (