: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(slack_app): keep the mention in the line the answer opens (#98109)
Vojta Bartošb7999dd0577f
diff --git a/posthog/helpers/slack_markdown.py b/posthog/helpers/slack_markdown.pyindex 1d82050e7ba5..0315f7a94ac0 100644--- a/posthog/helpers/slack_markdown.py+++ b/posthog/helpers/slack_markdown.py@@ -1,15 +1,49 @@-"""Building a Slack `markdown` block, which renders Markdown instead of Slack's own `mrkdwn`.+"""Delivering Markdown to Slack in a `markdown` block, which renders Markdown instead of Slack's+own `mrkdwn`.-Shared by every surface that has Markdown to deliver, so the block's character budget is-stated once rather than per product.+Shared by every surface that has Markdown to deliver, so the block's character budget and the+rules its text must hold to are stated once rather than per product."""from __future__ import annotations+import re+# Slack budgets 12,000 characters across every markdown block in one message. A message carries# one, and the headroom covers the blocks around it.SLACK_MARKDOWN_TEXT_MAX_LEN = 11500+# The constructs Markdown reads only at the start of a line: an ATX heading, a list item, a block+# quote, a fence, a table row, and a thematic break. A list item and a heading need the space that+# separates the marker from the content, which is what keeps `**Bold**` and `#hashtag` out.+_LINE_ANCHORED_OPENING = re.compile(+ r"""+ \#{1,6}(\s|$) # heading+ |[-*+]\s # bullet list item+ |\d{1,9}[.)]\s # ordered list item+ |> # block quote+ |```|~~~ # fenced code+ |\| # table row+ |(-\s*){3,}$|(\*\s*){3,}$|(_\s*){3,}$ # thematic break+ """,+ re.VERBOSE,+)+++def opens_with_line_anchored_markdown(text: str) -> bool:+ """Whether the first line of `text` is a construct Markdown reads only at the start of a line.++ Such a line takes no prefix: anything put in front of it moves the marker off the line start,+ and Slack then renders the markup as literal text instead of the heading, list, or quote it+ stands for. Text that opens with a paragraph has no such constraint.+ """+ first_line = text.partition("\n")[0]+ # An indented code block opens on four spaces or a tab. Up to three leading spaces still count+ # as the start of the line for every other construct.+ if first_line.startswith((" ", "\t")):+ return True+ return bool(_LINE_ANCHORED_OPENING.match(first_line.lstrip(" ")))+def slack_markdown_block(text: str) -> dict:"""The block Slack renders Markdown in. The caller is responsible for `text` being safe todiff --git a/posthog/helpers/tests/test_slack_markdown.py b/posthog/helpers/tests/test_slack_markdown.pynew file mode 100644index 000000000000..ab8f855d7614--- /dev/null+++ b/posthog/helpers/tests/test_slack_markdown.py@@ -0,0 +1,43 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.helpers.slack_markdown import opens_with_line_anchored_markdown+++class TestOpensWithLineAnchoredMarkdown(SimpleTestCase):+ @parameterized.expand(+ [+ ("heading", "## Heading\n\nBody."),+ ("deepest_heading", "###### Heading"),+ ("bullet_list", "- First\n- Second"),+ ("star_bullet_list", "* First"),+ ("ordered_list", "1. First"),+ ("ordered_list_parenthesis", "1) First"),+ ("block_quote", "> Quoted."),+ ("fenced_code", "```python\nprint()\n```"),+ ("tilde_fence", "~~~\ncode\n~~~"),+ ("table", "| Model | Effort |\n| --- | --- |"),+ ("thematic_break", "---\n\nBody."),+ ("indented_code", " print()"),+ ("three_leading_spaces", " ## Heading"),+ ]+ )+ def test_line_anchored_openings(self, _name: str, text: str) -> None:+ assert opens_with_line_anchored_markdown(text)++ @parameterized.expand(+ [+ ("prose", "Done. Your default task model is now Claude Opus 5."),+ # The marker of a heading or a list needs the space that separates it from the content,+ # so these open a paragraph and take a mention in front of them.+ ("bold_opening", "**Done.** Your default task model is now Claude Opus 5."),+ ("emphasis_opening", "*Done.* Your model is set."),+ ("hashtag", "#opus is the default now."),+ ("inline_code", "`opus-5` is the default now."),+ ("heading_later_in_the_answer", "Done.\n\n## What changed"),+ ("empty", ""),+ ]+ )+ def test_openings_that_take_a_prefix(self, _name: str, text: str) -> None:+ assert not opens_with_line_anchored_markdown(text)diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.pyindex e74749cd2bac..23bb30e17187 100644--- a/products/tasks/backend/temporal/slack_relay/activities.py+++ b/products/tasks/backend/temporal/slack_relay/activities.py@@ -5,7 +5,7 @@ from markdown_to_mrkdwn import SlackMarkdownConverterfrom temporalio import activityfrom posthog.dataclasses import frozen-from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, opens_with_line_anchored_markdownfrom posthog.temporal.common.logger import get_loggerfrom posthog.temporal.common.utils import close_db_connections@@ -447,12 +447,13 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:# converting, so the gate is read before the answer is prepared.markdown = handler.renders_markdown()- # Markdown reads a heading, a list, a quote, a table, and a fence only at the start of a- # line, so a mention glued to the front of the answer would turn its first construct into- # literal text. Giving the mention its own line keeps that construct intact and still- # notifies, which is what the streamed replies already do. On the mrkdwn path the mention- # stays inline, because nothing there depends on the line it starts.- mention_separator = "\n\n" if markdown else " "+ # The mention opens the answer, in the same line, so the reply reads as one message. An answer+ # that opens with a heading, a list, a quote, a table, or a fence is the exception: Markdown+ # reads those only at the start of a line, so a mention in front of one would turn it into+ # literal text. Those answers take the mention on a line of its own, which keeps the construct+ # intact and still notifies. On the mrkdwn path nothing depends on the line the answer starts,+ # so the mention is always inline there.+ mention_separator = "\n\n" if markdown and opens_with_line_anchored_markdown(text) else " "mention_prefix = f"<@{target}>{mention_separator}" if target else ""# Pending chart images compose into a single Slack message together with the answer text,diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.pyindex e68629341323..ddc210a63379 100644--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py@@ -168,26 +168,27 @@ class TestRelaySlackMessage(TestCase):@parameterized.expand([# The converter turns the heading into inline bold, which survives an inline mention.- ("mrkdwn", False, "<@U123> *Heading*"),- ("markdown", True, "<@U123>\n\n## Heading"),+ ("mrkdwn_heading", False, "## Heading\n\nBody text.", "<@U123> *Heading*"),+ ("markdown_heading", True, "## Heading\n\nBody text.", "<@U123>\n\n## Heading"),+ ("markdown_prose", True, "Done. Your model is set.", "<@U123> Done."),])@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")- def test_the_mention_keeps_off_the_line_the_answer_opens(- self, _name, markdown, expected_opening, mock_delete_progress, mock_post+ def test_the_mention_leaves_the_answers_opening_line_only_where_markdown_needs_it(+ self, _name, markdown, text, expected_opening, mock_delete_progress, mock_post):- # Markdown reads a heading only at the start of a line, so a mention glued to the front- # of the answer renders the `##` as literal text. That is the formatting the gate exists- # to keep, and it is the opening of every mentioned reply.+ # Markdown reads a heading only at the start of a line, so a mention glued to the front of+ # that answer renders the `##` as literal text. An answer that opens with prose has no such+ # constraint, and reads as one message with the mention in its first line.with patch("products.slack_app.backend.slack_thread.SlackThreadHandler.renders_markdown", return_value=markdown):relay_slack_message(RelaySlackMessageInput(run_id=str(self.task_run.id),- relay_id=f"relay-mention-{markdown}",- text="## Heading\n\nBody text.",+ relay_id=f"relay-mention-{_name}",+ text=text,))