: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
chore(slack_app): remove the slack-app-markdown flag and its mrkdwn path (#99006)
Vojta Bartoš4bddf8e09148
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex ca22044fc6aa..b06b65b7d3f6 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -46,7 +46,6 @@ logger = structlog.get_logger(__name__)SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"SLACK_APP_FORKING_FLAG = "slack-app-forking"-SLACK_APP_MARKDOWN_FLAG = "slack-app-markdown"# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.@@ -125,22 +124,6 @@ def is_slack_app_agent_design_enabled(integration: Integration, distinct_id: str)-def is_slack_app_markdown_enabled(integration: Integration) -> bool:- """Gate for delivering an agent answer as a Slack ``markdown`` block instead of converting- it to ``mrkdwn`` first. Posts through the ``chat:write`` the mention flow already requires,- so this is the flag alone.-- Keyed on the Slack workspace rather than the person: how an answer is formatted is a- property of the thread everybody reads, not of whoever asked, and a run's answer can be- posted for a reader the run was not created by.- """- return _workspace_flag_enabled(- SLACK_APP_MARKDOWN_FLAG,- integration,- failure_log_key="slack_app_markdown_feature_flag_check_failed",- )--def is_slack_app_assistant_enabled(integration: Integration) -> bool:"""Gate for the DM assistant: the install must hold the scopes the DM surfacecalls — ``im:history`` in particular, without which the assistant would answerdiff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.pyindex b289fd4439ea..37bae67f0605 100644--- a/products/slack_app/backend/slack_thread.py+++ b/products/slack_app/backend/slack_thread.py@@ -9,7 +9,7 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_blockfrom posthog.models.integration import Integration, SlackIntegration-from products.slack_app.backend.feature_flags import is_slack_app_forking_enabled, is_slack_app_markdown_enabled+from products.slack_app.backend.feature_flags import is_slack_app_forking_enabledfrom products.slack_app.backend.services.model_catalogue import describe_run_modelfrom products.slack_app.backend.services.slack_messages import (RunFooter,@@ -159,7 +159,6 @@ class SlackThreadHandler:self._client: WebClient | None = Noneself._bot_user_id: str | None = Noneself._fork_flag: bool | None = None- self._markdown_flag: bool | None = Noneself._code_access: bool | None = Nonedef _get_integration(self) -> Integration:@@ -181,24 +180,6 @@ class SlackThreadHandler:self._code_access = viewer_has_code_access(self._get_integration(), self.actor_slack_user_id)return bool(self._code_access)- def renders_markdown(self) -> bool:- """Whether an answer is delivered as a Slack `markdown` block rather than converted to- `mrkdwn` first. Memoized like the sibling gates, because the flag is evaluated remotely.-- The one place the gate is read. The relay asks before it prepares the answer, because- the conversion it runs and the size it chunks to both depend on the block the answer- lands in, and then passes the result to `post_thread_message`. That call sits outside- the try blocks the posting methods wrap themselves in, so a failed integration lookup- is answered here rather than left to fail the relay.- """- if self._markdown_flag is None:- try:- self._markdown_flag = is_slack_app_markdown_enabled(self._get_integration())- except Exception as e:- logger.warning("slack_app_markdown_gate_failed", error=str(e))- self._markdown_flag = False- return bool(self._markdown_flag)-def reader_footer(self) -> RunFooter:"""`run_footer` with the desktop link withheld where this reply's reader can'topen it.@@ -654,9 +635,9 @@ class SlackThreadHandler:chunk of a non-streamed answer — the streamed path appends its own instead.`_answer_blocks` decides what the answer is carried in.- ``markdown`` says the text is the agent's Markdown, for a caller that already read- `renders_markdown`. It defaults off so a message of our own wording, which carries no- Markdown worth rendering, never reaches the flag lookup behind that gate.+ ``markdown`` says the text is the agent's Markdown, which the relay passes on as+ written. It defaults off for a message of our own wording, which is already Slack+ ``mrkdwn`` and carries no Markdown worth rendering."""# Text past the block's character cap can only be posted as plain text, which carries# no blocks at all. Dropping the footer there costs a line of provenance, while keepingdiff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.pyindex f1db11dfa0eb..f3f583eff407 100644--- a/products/slack_app/backend/tests/test_slack_thread.py+++ b/products/slack_app/backend/tests/test_slack_thread.py@@ -660,8 +660,8 @@ class TestMarkdownAnswerBlocks(SimpleTestCase):def test_a_rejected_markdown_block_falls_back_to_plain_text_without_looping(self, error_code: str, mock_get_client, mock_get_integration) -> None:- # Under the gate every answer carries a block, and the relay has already claimed the- # message, so a rejection code this branch does not know loses the answer for good.+ # Every answer carries a block, and the relay has already claimed the message, so a+ # rejection code this branch does not know loses the answer for good.# Recovering by calling post_thread_message again would rebuild the same markdown# block, so a rejection Slack repeats would recurse until the stack ran out.mock_client = MagicMock()@@ -675,9 +675,3 @@ class TestMarkdownAnswerBlocks(SimpleTestCase):retry = mock_client.chat_postMessage.call_args_list[1].kwargsassert retry["text"] == "the answer"assert not retry.get("blocks")-- @patch.object(SlackThreadHandler, "_get_integration", side_effect=Integration.DoesNotExist)- def test_the_gate_closes_rather_than_raising_when_the_integration_is_gone(self, _mock_get_integration) -> None:- # The relay reads this gate outside any try block of its own, so a raise here would fail- # the activity and make Temporal replay a relay that can never succeed.- assert self._handler().renders_markdown() is Falsediff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.pyindex 1ddd8c903cce..d48cbb1b1954 100644--- a/products/tasks/backend/logic/services/living_artifacts.py+++ b/products/tasks/backend/logic/services/living_artifacts.py@@ -853,13 +853,10 @@ def has_pending_slack_image_artifacts(run: TaskRun) -> bool:def deliver_pending_slack_file_artifacts(- run: TaskRun, *, answer_sections: list[str] | None = None, answer_is_markdown: bool = False+ run: TaskRun, *, answer_sections: list[str] | None = None) -> SlackFileDeliveryResult:"""Deliver pending slack_file artifacts to the mapped thread.- ``answer_is_markdown`` says the relay left the answer as Markdown for a ``markdown``- block rather than converting it to ``mrkdwn`` for a ``section``.-Images compose into a single chat message together with ``answer_sections``(the relay's answer text): text sections first, then one card perchart (title, image block, "Open in PostHog" button). Chart images reference a@@ -970,7 +967,6 @@ def deliver_pending_slack_file_artifacts(mapping=mapping,image_cards=image_cards,answer_sections=answer_sections or [],- answer_is_markdown=answer_is_markdown,mark_delivered=_mark_card_delivered,deadline=deadline,)@@ -980,7 +976,7 @@ def deliver_pending_slack_file_artifacts(elif answer_sections is not None:# Compose was requested but every image upload failed: the answer text must# still land — and before the non-image shares below, to keep thread order.- blocks = _answer_text_blocks(answer_sections, markdown=answer_is_markdown)+ blocks = _answer_text_blocks(answer_sections)posted = [_post_answer_block(slack, mapping=mapping, block=block) for block in blocks]result.answer_posted = bool(blocks) and all(posted)@@ -1111,7 +1107,6 @@ def _post_composed_answer_message(mapping: Any,image_cards: list[_SlackImageCard],answer_sections: list[str],- answer_is_markdown: bool,mark_delivered: Callable[[_SlackImageCard], None],deadline: float,) -> bool:@@ -1123,32 +1118,27 @@ def _post_composed_answer_message(post succeeds, so an activity that dies part-way through doesn't replay the cardsthat already landed."""sections = [section for section in answer_sections if section.strip()]- section_blocks = _answer_text_blocks(sections, markdown=answer_is_markdown)+ section_blocks = _answer_text_blocks(sections)card_blocks: list[dict[str, Any]] = []for card in image_cards:card_blocks.extend(_chart_card_blocks(card))- if answer_is_markdown:- # A composed message carries a single answer block, because the budget the block's- # character cap comes from is spent across every markdown block in one payload. The- # ones before it go out on their own. The relay chunks under that cap, so most answers- # are one block and nothing spills.- keep_count = 1- else:- keep_count = max(_SLACK_MESSAGE_BLOCK_LIMIT - len(card_blocks), 0)- spill_count = max(len(section_blocks) - keep_count, 0)+ # A composed message carries a single answer block, because the budget the block's+ # character cap comes from is spent across every markdown block in one payload. The+ # ones before it go out on their own. The relay chunks under that cap, so most answers+ # are one block and nothing spills.+ spilled, kept = section_blocks[:-1], section_blocks[-1:]posted_blocks = 0- for block in section_blocks[:spill_count]:+ for block in spilled:# A spilled block is one post each, and a long answer spills several, so this loop# answers to the same budget as the posts below it.if time.monotonic() >= deadline:# The caller reposts the whole answer once this reports it unsent, so stop here# rather than adding a composed message that the repost would duplicate. The cards# stay pending and the next relay delivers them.- logger.warning("task_artifact.slack_post_budget_exhausted", spilled=posted_blocks, of=spill_count)+ logger.warning("task_artifact.slack_post_budget_exhausted", spilled=posted_blocks, of=len(spilled))return Falseposted_blocks += 1 if _post_answer_block(slack, mapping=mapping, block=block) else 0- kept = section_blocks[spill_count:]# Cards alone can exceed the block cap (17+ charts) — composing would then fail# deterministically as invalid_blocks, so go straight to the per-card path.@@ -1157,7 +1147,7 @@ def _post_composed_answer_message(# answer's first chunk. Slack reads it for the notification, the screen reader, and the# mentions it pings, so naming a spilled chunk would preview the wrong text and could# ping its mention a second time.- fallback_text = _answer_block_text(kept[0]) if kept else _artifact_fallback_text(image_cards[0].artifact)+ fallback_text = kept[0]["text"] if kept else _artifact_fallback_text(image_cards[0].artifact)try:if _post_blocks_with_processing_retry(slack,@@ -1195,43 +1185,32 @@ def _post_composed_answer_message(return bool(section_blocks) and posted_blocks == len(section_blocks)-# Section blocks hard-cap at 3000 chars and markdown blocks at 12,000. The relay pre-splits-# under both, but the mention prefix and, on the mrkdwn path, the conversion itself (table-# column padding, escapes) can push a block past its cap — re-split here, preferring-# whitespace so the cut doesn't land inside an entity like `<url|text>` or a Markdown link.-# A cut inside a fenced block is closed and reopened to keep each block self-contained.-_SLACK_SECTION_BLOCK_CHAR_LIMIT = 3000_SLACK_CODE_FENCE = "```"-def _answer_text_blocks(sections: list[str], *, markdown: bool) -> list[dict[str, Any]]:- """One block per piece of answer text, sized to the cap of the block type it lands in."""- limit = SLACK_MARKDOWN_TEXT_MAX_LEN if markdown else _SLACK_SECTION_BLOCK_CHAR_LIMIT+def _answer_text_blocks(sections: list[str]) -> list[dict[str, Any]]:+ """One `markdown` block per section, re-split to the block's character cap.++ The relay is the only producer of sections and already reserves the mention prefix out+ of that cap, so the re-split is a guard for a section that arrives oversized rather than+ a step the answer normally goes through. It prefers whitespace so a cut doesn't land+ inside an entity like `<url|text>` or a Markdown link, and closes and reopens a fenced+ block it has to cut so each block stays self-contained.+ """blocks: list[dict[str, Any]] = []for section in sections:- for piece in _split_section_text(section, limit_chars=limit):- blocks.append(slack_markdown_block(piece) if markdown else _mrkdwn_section_block(piece))+ for piece in _split_section_text(section, limit_chars=SLACK_MARKDOWN_TEXT_MAX_LEN):+ blocks.append(slack_markdown_block(piece))return blocks-def _mrkdwn_section_block(text: str) -> dict[str, Any]:- return {"type": "section", "text": {"type": "mrkdwn", "text": text}}---def _answer_block_text(block: dict[str, Any]) -> str:- """The text a block carries, whichever of the two shapes it is."""- return block["text"] if block["type"] == "markdown" else block["text"]["text"]--def _post_answer_block(slack: Any, *, mapping: Any, block: dict[str, Any]) -> bool:"""Post one answer block as its own message, reporting whether it landed.- A `markdown` block has to go out as a block, because a plain-text message would show- the Markdown source instead of rendering it. An `mrkdwn` section carries the same text- either way, so it posts plainly, which is what these messages have always been.+ The block goes out as a block, because a plain-text message would show the Markdown+ source instead of rendering it."""- blocks = [block] if block["type"] == "markdown" else None- return _post_thread_text(slack, mapping=mapping, text=_answer_block_text(block), blocks=blocks)+ return _post_thread_text(slack, mapping=mapping, text=block["text"], blocks=[block])def _split_section_text(section: str, *, limit_chars: int) -> list[str]:diff --git a/products/tasks/backend/logic/services/tests/test_living_artifacts.py b/products/tasks/backend/logic/services/tests/test_living_artifacts.pyindex 2454bf526318..b095477a29db 100644--- a/products/tasks/backend/logic/services/tests/test_living_artifacts.py+++ b/products/tasks/backend/logic/services/tests/test_living_artifacts.py@@ -23,7 +23,6 @@ from products.tasks.backend.logic.services.living_artifacts import (DEFAULT_DOCUMENT_CONTENT_TYPE,ArtifactCommit,DocumentConnectorUnavailable,- _answer_block_text,_answer_text_blocks,_chart_card_blocks,_post_composed_answer_message,@@ -710,41 +709,32 @@ class TestChartCardBlockBuilders(SimpleTestCase):blocks = _chart_card_blocks(_SlackImageCard(artifact, {}, file_id="F123"))self.assertEqual([b["type"] for b in blocks], expected_block_types)- @parameterized.expand(- [- ("mrkdwn", False, "section", 3000, [3000, 3000, 500, 5]),- ("markdown", True, "markdown", SLACK_MARKDOWN_TEXT_MAX_LEN, [6500, 5]),- ]- )- def test_sections_split_below_the_cap_of_the_block_they_land_in(- self, _name, markdown, block_type, cap, expected_lengths- ):- blocks = _answer_text_blocks(["a" * 6500, "short"], markdown=markdown)- self.assertEqual([b["type"] for b in blocks], [block_type] * len(expected_lengths))- self.assertEqual([len(_answer_block_text(b)) for b in blocks], expected_lengths)- self.assertTrue(all(len(_answer_block_text(b)) <= cap for b in blocks))- self.assertEqual(_answer_block_text(blocks[-1]), "short")-- def test_oversized_sections_split_at_whitespace_so_mrkdwn_entities_survive(self):- # A hard character slice can cut a converted entity like `<url|text>` in half;- # the split must land on whitespace when any is available in the window.- words = "word " * 1300 # 6500 chars of 5-char words- blocks = _answer_text_blocks([words.strip()], markdown=False)+ def test_sections_split_below_the_markdown_block_cap(self):+ blocks = _answer_text_blocks(["a" * 14000, "short"])+ self.assertEqual([b["type"] for b in blocks], ["markdown"] * 3)+ self.assertEqual([len(b["text"]) for b in blocks], [SLACK_MARKDOWN_TEXT_MAX_LEN, 2500, 5])+ self.assertEqual(blocks[-1]["text"], "short")++ def test_oversized_sections_split_at_whitespace_so_slack_entities_survive(self):+ # A hard character slice can cut an entity like `<url|text>` in half; the split must+ # land on whitespace when any is available in the window.+ words = "word " * 3000 # 15,000 chars of 5-char words+ blocks = _answer_text_blocks([words.strip()])self.assertGreater(len(blocks), 1)for block in blocks:- text = block["text"]["text"]- self.assertLessEqual(len(text), 3000)+ text = block["text"]+ self.assertLessEqual(len(text), SLACK_MARKDOWN_TEXT_MAX_LEN)self.assertEqual(set(text.split(" ")), {"word"})def test_oversized_fenced_section_is_closed_and_reopened_around_the_split(self):- # Tables convert to fenced blocks before this re-split, so a cut inside one would- # leave an unclosed fence in one block and a stray closer in the next.- table = "| cell | cell |\n" * 250- blocks = _answer_text_blocks([f"{_SLACK_CODE_FENCE}\n{table}{_SLACK_CODE_FENCE}"], markdown=False)+ # A cut inside a fenced block would leave it unclosed in one block and drop a stray+ # closer in the next.+ table = "| cell | cell |\n" * 1000+ blocks = _answer_text_blocks([f"{_SLACK_CODE_FENCE}\n{table}{_SLACK_CODE_FENCE}"])self.assertGreater(len(blocks), 1)for block in blocks:- text = block["text"]["text"]- self.assertLessEqual(len(text), 3000)+ text = block["text"]+ self.assertLessEqual(len(text), SLACK_MARKDOWN_TEXT_MAX_LEN)self.assertEqual(text.count(_SLACK_CODE_FENCE) % 2, 0)self.assertTrue(text.startswith(_SLACK_CODE_FENCE))self.assertTrue(text.endswith(_SLACK_CODE_FENCE))@@ -752,16 +742,16 @@ class TestChartCardBlockBuilders(SimpleTestCase):def test_fenced_whitespace_free_content_terminates_and_stays_balanced(self):# After a fence is closed and reopened, the only whitespace in the window can be# the reopen prefix's own newline — cutting there consumes nothing of the content.- section = f"{_SLACK_CODE_FENCE}\n{'x' * 8000}\n{_SLACK_CODE_FENCE}"- blocks = _answer_text_blocks([section], markdown=False)+ section = f"{_SLACK_CODE_FENCE}\n{'x' * 30000}\n{_SLACK_CODE_FENCE}"+ blocks = _answer_text_blocks([section])self.assertGreater(len(blocks), 1)for block in blocks:- text = block["text"]["text"]- self.assertLessEqual(len(text), 3000)+ text = block["text"]+ self.assertLessEqual(len(text), SLACK_MARKDOWN_TEXT_MAX_LEN)self.assertEqual(text.count(_SLACK_CODE_FENCE) % 2, 0)self.assertIn(- "x" * 8000,- "".join(b["text"]["text"] for b in blocks)+ "x" * 30000,+ "".join(b["text"] for b in blocks).replace(f"\n{_SLACK_CODE_FENCE}", "").replace(f"{_SLACK_CODE_FENCE}\n", ""),)@@ -799,7 +789,6 @@ class TestChartCardBlockBuilders(SimpleTestCase):mapping=MagicMock(channel="C123", thread_ts="1111.1"),image_cards=cards,answer_sections=[],- answer_is_markdown=False,mark_delivered=lambda card: None,deadline=time.monotonic() + 30,)@@ -821,7 +810,6 @@ class TestChartCardBlockBuilders(SimpleTestCase):mapping=MagicMock(channel="C123", thread_ts="1111.1"),image_cards=cards,answer_sections=["## First", "## Second", "## Third"],- answer_is_markdown=True,mark_delivered=lambda card: None,deadline=time.monotonic() + 30,)@@ -851,7 +839,6 @@ class TestChartCardBlockBuilders(SimpleTestCase):mapping=MagicMock(channel="C123", thread_ts="1111.1"),image_cards=cards,answer_sections=["## First", "## Second", "## Third"],- answer_is_markdown=True,mark_delivered=lambda card: None,deadline=time.monotonic() - 1, # already spent)@@ -879,7 +866,6 @@ class TestChartCardBlockBuilders(SimpleTestCase):mapping=MagicMock(channel="C_DELETED", thread_ts="8888.1"),image_cards=cards,answer_sections=[],- answer_is_markdown=False,mark_delivered=delivered.append,deadline=time.monotonic() + 30,)diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.pyindex 23bb30e17187..716981f13c01 100644--- a/products/tasks/backend/temporal/slack_relay/activities.py+++ b/products/tasks/backend/temporal/slack_relay/activities.py@@ -1,7 +1,6 @@import refrom typing import Any-from markdown_to_mrkdwn import SlackMarkdownConverterfrom temporalio import activityfrom posthog.dataclasses import frozen@@ -18,13 +17,6 @@ from products.tasks.backend.temporal.slack_relay.object_tags import rewrite_objelogger = get_logger(__name__)-_CONVERTER = SlackMarkdownConverter()--_RE_TABLE_ROW = re.compile(r"^\s*\|.*\|\s*$")-_RE_TABLE_SEPARATOR_CELL = re.compile(r"^:?-{2,}:?$")-_RE_FENCE = re.compile(r"^\s*(```|~~~)")-_RE_INLINE_MARKDOWN_MARKERS = re.compile(r"\*\*|__|\*|_|~~|`")-_RE_MD_LINK = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")_RE_DELIVERY_CLAIM = re.compile(r"\b(?:attached|uploaded|shared)\b", re.IGNORECASE)_RE_DELIVERY_NEGATION = re.compile(r"\b(?:not|never|cannot|can't|could not|couldn't|unable to|no file was)\s+"@@ -37,69 +29,11 @@ _RE_LOCAL_DELIVERABLE_REFERENCE = re.compile()_UNCONFIRMED_ATTACHMENT_NOTICE = "\n\n_Note: I can relay text here, but no file was attached to Slack for this run._"-# Repair pattern: bold/italic markers placed *inside* the close of a Slack-style-# angle-bracket link, e.g. ``**<https://example.com**>`` instead of-# ``**<https://example.com>**``. The agent hand-rolls Slack mrkdwn occasionally-# and types the closing marker before ``>``; the standard converter has no way-# to recover, so the asterisks end up adjacent to ``>`` in the final output and-# Slack renders neither the bold nor the link. The flanking lookbehind/lookahead-# require the opening and closing marker runs to be balanced — they refuse to-# half-match a longer asterisk run, so unbalanced edge cases like ``**<url*>``-# are left alone rather than silently rewritten into a different broken shape.-_RE_LINK_TRAILING_MARKER = re.compile(r"(?<![*_~])(\*+|_+|~+)<([^<>]+?)\1>(?![*_~])")--# Repair pattern: a bare ``http(s)`` URL wrapped directly in emphasis markers,-# e.g. ``**https://example.com**``. The converter halves the markers in place-# and emits ``*https://example.com*``; Slack then auto-links the URL but-# renders the surrounding ``*`` as literal text because there is no whitespace-# flanking the markers. Pre-wrapping the URL in ``<>`` lets the converter emit-# the well-formed ``*<https://example.com>*`` — a clean bolded clickable link.-# The URL group excludes whitespace and angle brackets so already well-formed-# links (``**<url>**``) and bracketed markdown links (``**[text](url)**``) are-# left alone.-_RE_BARE_URL_IN_EMPHASIS = re.compile(r"(?<![*_~])(\*+|_+|~+)(https?://[^\s<>]+?)\1(?![*_~])")--# A ``~`` on a word boundary directly in front of a quantity (``~$36k``, ``~2pm``, ``~10%``)-# is the agent writing "approximately". In Markdown a single tilde is a literal character, but-# Slack mrkdwn uses a single tilde as its strikethrough delimiter, so two such approximations-# on one line pair up and strike through everything between them. The lookbehind requires a-# non-word, non-tilde char before the tilde so a git ref (``HEAD~1``), a range (``5~10``), and-# the first ``~`` of a ``~~strikethrough~~`` run are left alone; the lookahead leaves paths-# (``~/dir``) and standalone tildes alone.-_RE_APPROX_TILDE = re.compile(r"(?<![\w~])~(?=[$€£¥₹]?\d)")--# Unicode "tilde operator" — visually a tilde, but not the ASCII strikethrough delimiter, so-# Slack renders it literally.-_APPROX_TILDE = "∼"--# Fenced blocks and inline code spans, kept whole so the tilde substitution skips them: inside-# a code span Slack has no strikethrough semantics anyway, and rewriting ``~`` there would alter-# literal content (``HEAD~1``, npm ranges like ``~1.2.0``). Triple backticks are matched before-# the single-backtick form so a fence isn't split at its inner backticks.-_RE_CODE_SEGMENT = re.compile(r"(```[\s\S]*?```|`[^`\n]*`)")-class _RelayAlreadyRecorded(Exception):"""Raised when a relay was already recorded while holding the row lock."""-def _markdown_to_slack_mrkdwn(text: str) -> str:- """Convert markdown to Slack ``mrkdwn`` via ``markdown_to_mrkdwn``.-- Tables are pre-converted to fenced code blocks before the library runs because- Slack ``mrkdwn`` is rendered in a proportional font — pipe-separated rows do- not line up. A fenced code block forces monospace and the columns align.-- Misplaced link markers (e.g. ``**<url**>``), bare URLs wrapped in emphasis- (e.g. ``**https://example.com**``), and "approximately" tildes (e.g. ``~$36k``)- are normalized first so the converter sees well-formed input.- """- if not text:- return text- repaired = _neutralize_approx_tildes(_wrap_bare_urls_in_emphasis(_repair_link_trailing_markers(text)))- return _CONVERTER.convert(_tables_to_fenced_code_blocks(repaired))--def _append_unconfirmed_attachment_notice(text: str,*,@@ -119,147 +53,17 @@ def _append_unconfirmed_attachment_notice(return f"{text.rstrip()}{_UNCONFIRMED_ATTACHMENT_NOTICE}"-def _repair_link_trailing_markers(text: str) -> str:- """Move emphasis markers from inside a Slack-style link close to outside.-- Handles ``**<url**>``/``*<url*>``/``_<url_>`` (and the ``<url|label>``- variants) by relocating the closing marker after ``>``. The negated- character class stops the match at the next ``<`` or ``>``, so adjacent- links don't cross-contaminate.- """- return _RE_LINK_TRAILING_MARKER.sub(r"\1<\2>\1", text)---def _wrap_bare_urls_in_emphasis(text: str) -> str:- """Wrap bare ``http(s)`` URLs adjacent to emphasis markers with angle brackets.-- ``**https://example.com**`` becomes ``**<https://example.com>**`` so the- downstream converter produces a properly formatted Slack link. Already- bracketed URLs (``**<url>**``) and markdown links (``**[label](url)**``)- are left untouched because the URL group rejects ``<`` and ``[``.- """- return _RE_BARE_URL_IN_EMPHASIS.sub(r"\1<\2>\1", text)---def _neutralize_approx_tildes(text: str) -> str:- """Replace "approximately" tildes in front of a quantity with the tilde operator.-- ``~$36k`` / ``~2pm`` / ``~10%`` becomes ``∼$36k`` / ``∼2pm`` / ``∼10%``. The agent- means "approximately", but Slack mrkdwn reads a single ``~`` as a strikethrough- delimiter, so two of them on one line strike through the text in between. The tilde- operator looks the same and carries no formatting meaning. ``~~strikethrough~~``,- git refs (``HEAD~1``), paths (``~/dir``), and standalone tildes are left alone, and- code spans/fences are skipped so literal code is never rewritten.- """- # ``re.split`` with a capturing group yields alternating text/code segments; the odd- # (code) segments pass through untouched.- return "".join(- segment if index % 2 else _RE_APPROX_TILDE.sub(_APPROX_TILDE, segment)- for index, segment in enumerate(_RE_CODE_SEGMENT.split(text))- )---def _tables_to_fenced_code_blocks(text: str) -> str:- """Replace pipe-syntax markdown tables with fenced code blocks of padded columns.-- A run of consecutive ``|…|`` lines surrounding a ``---`` separator row is- treated as a table; runs without a separator are left untouched. Lines inside- an existing fenced code block are skipped entirely so we don't mis-detect a- pipe-shaped line of source code as a table.- """- lines = text.split("\n")- out: list[str] = []- run: list[str] = []- in_fence = False-- def _flush() -> None:- if not run:- return- rendered = _render_table(run)- out.extend(run if rendered is None else [rendered])- run.clear()-- for line in lines:- if _RE_FENCE.match(line):- _flush()- in_fence = not in_fence- out.append(line)- continue- if not in_fence and _RE_TABLE_ROW.match(line):- run.append(line)- else:- _flush()- out.append(line)- _flush()-- return "\n".join(out)---def _render_table(rows_raw: list[str]) -> str | None:- """Render a candidate table block to a fenced code block, or ``None`` if invalid.-- A separator row of all-dashes cells (``---``, ``:---:``) is required — without- it the pipes are likely incidental rather than a table.- """- parsed: list[list[str]] = []- has_separator = False- for line in rows_raw:- cells = [c.strip() for c in line.strip().strip("|").split("|")]- if cells and all(_RE_TABLE_SEPARATOR_CELL.match(c) for c in cells):- has_separator = True- continue- parsed.append([_strip_inline_markdown(c) for c in cells])-- if not has_separator or not parsed:- return None-- col_count = max(len(r) for r in parsed)- widths = [0] * col_count- for row in parsed:- for i, cell in enumerate(row):- widths[i] = max(widths[i], len(cell))-- body_lines = [- " ".join((row[i] if i < len(row) else "").ljust(widths[i]) for i in range(col_count)).rstrip()- for row in parsed- ]- return "```\n" + "\n".join(body_lines) + "\n```"---def _strip_inline_markdown(cell: str) -> str:- """Strip emphasis markers and unwrap links inside a cell.-- The cell ends up inside a fenced code block where ``*bold*`` and ``[text](url)``- are not interpreted, so leaving the markers in just shifts column widths and- adds visual noise.- """- cell = _RE_MD_LINK.sub(r"\1", cell)- cell = _RE_INLINE_MARKDOWN_MARKERS.sub("", cell)- return cell.strip()---# Slack renders text above ~4000 characters as a "Show more" affordance and silently truncates;-# splitting at 3500 leaves comfortable headroom for the mention prefix and code-fence overhead.-SLACK_MESSAGE_TEXT_LIMIT = 3500--# Section blocks in a composed answer+charts message cap at 3000 characters — tighter-# than plain message text; headroom for the mention prefix.-SLACK_SECTION_TEXT_LIMIT = 2900-_FENCED_CODE_RE = re.compile(r"```([^\n]*)\n([\s\S]*?)\n```")-def _split_markdown_for_slack(text: str, limit: int = SLACK_MESSAGE_TEXT_LIMIT) -> list[str]:+def _split_markdown_for_slack(text: str, limit: int) -> list[str]:"""Split raw markdown into Slack-sized chunks at safe structural boundaries.Splits prefer paragraph (``\\n\\n``) and line (``\\n``) boundaries, then a hardcharacter break as a last resort. Fenced code blocks that cross a chunkboundary are closed at the end of one chunk and reopened (with the samelanguage hint) at the start of the next so each chunk is a self-contained- markdown document. Callers convert each chunk to Slack mrkdwn independently;- that ordering means a hard char break inside an inline span like ``**bold**``- or ``[text](url)`` leaves the broken halves as literal text rather than- producing dangling unbalanced markers in the rendered output.+ markdown document."""if len(text) <= limit:return [text]@@ -402,8 +206,8 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None: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.+ # composed actually notify their targets. Done before splitting: the bare form is shorter,+ # so it never enlarges a chunk.text = normalize_labeled_mentions_to_bare(text)# Object tags (``<insight id="…">``, ``<hogql display="block">``) are what the desktop renders@@ -443,41 +247,19 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:handler = SlackThreadHandler(context, actor_slack_user_id=target, turn_trace_id=input.trace_id)handler.run_footer = load_run_footer(task_run.id)- # The block the answer lands in decides both how much of it fits and whether it needs- # converting, so the gate is read before the answer is prepared.- markdown = handler.renders_markdown()-# 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 " "+ # intact and still notifies.+ mention_separator = "\n\n" if 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,- # whose blocks are tighter than a plain message, so pick the chunk limit before splitting.compose_with_charts = has_pending_slack_files and has_pending_slack_image_artifacts(task_run)- if markdown:- # One `markdown` block per message either way, so composing costs the answer nothing.- # The mention rides on the first chunk, so it comes out of the same budget: without- # that the chunk it lands on overflows the block and posts as Markdown source.- chunk_limit = SLACK_MARKDOWN_TEXT_MAX_LEN - len(mention_prefix)- else:- chunk_limit = SLACK_SECTION_TEXT_LIMIT if compose_with_charts else SLACK_MESSAGE_TEXT_LIMIT-- # Split the raw markdown first, then convert each chunk independently. Converting- # per-chunk means an inline span broken by a hard char split (e.g. ``**bold**``- # halved) stays literal in the output instead of leaving dangling Slack-mrkdwn- # markers that would garble the rendering of surrounding text.- #- # A `markdown` block takes the agent's Markdown as written, so the conversion is skipped- # wholesale: its repairs all exist to survive Slack's own `mrkdwn`, and applying them- # would flatten headings, tables, and task lists the block renders on its own.- chunks = _split_markdown_for_slack(text, limit=chunk_limit)- if not markdown:- chunks = [_markdown_to_slack_mrkdwn(chunk) for chunk in chunks]++ # The mention rides on the first chunk, so it comes out of the same budget: without that+ # allowance the chunk it lands on overflows the block and posts as Markdown source.+ chunks = _split_markdown_for_slack(text, limit=SLACK_MARKDOWN_TEXT_MAX_LEN - len(mention_prefix))def _record_sent_relay(state: dict[str, Any]) -> None:sent_relay_ids = state.get("slack_sent_relay_ids") or []@@ -506,9 +288,7 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:sections = list(chunks)if sections:sections[0] = f"{mention_prefix}{sections[0]}"- answer_posted = deliver_pending_slack_file_artifacts(- task_run, answer_sections=sections, answer_is_markdown=markdown- ).answer_posted+ answer_posted = deliver_pending_slack_file_artifacts(task_run, answer_sections=sections).answer_postedif answer_posted:# The answer went out inside the composed message, whose blocks are the text# sections and the chart cards, so the footer follows it as its own message.@@ -519,7 +299,7 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:prefix = mention_prefix if index == 0 else ""# This relay carries one agent answer, split only to fit Slack's length cap, so# the last chunk is where the turn ends and the footer belongs.- handler.post_thread_message(f"{prefix}{chunk}", with_footer=index == len(chunks) - 1, markdown=markdown)+ handler.post_thread_message(f"{prefix}{chunk}", with_footer=index == len(chunks) - 1, markdown=True)if has_pending_slack_files and not compose_with_charts:deliver_pending_slack_file_artifacts(task_run)diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.pyindex ddc210a63379..558a5e7e8016 100644--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py@@ -20,14 +20,9 @@ from products.slack_app.backend.models import SlackThreadTaskMappingfrom products.tasks.backend.logic.services.living_artifacts import SlackFileDeliveryResultfrom products.tasks.backend.models import Task, TaskArtifact, TaskRunfrom products.tasks.backend.temporal.slack_relay.activities import (- SLACK_MESSAGE_TEXT_LIMIT,RelaySlackMessageInput,_append_unconfirmed_attachment_notice,- _markdown_to_slack_mrkdwn,- _neutralize_approx_tildes,- _repair_link_trailing_markers,_split_markdown_for_slack,- _wrap_bare_urls_in_emphasis,relay_slack_message,)@@ -138,59 +133,42 @@ class TestRelaySlackMessage(TestCase):_RICH_ANSWER = "## Heading\n\n| a | b |\n| --- | --- |\n| 1 | 2 |\n\n- [ ] todo"- @parameterized.expand(- [- ("mrkdwn", False, "*Heading*\n\n```\na b\n1 2\n```\n\n\u2022 \u2610 todo"),- ("markdown", True, _RICH_ANSWER),- ]- )@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")- def test_the_gate_decides_whether_the_answer_is_converted(- self, _name, markdown, expected, mock_delete_progress, mock_post- ):- # The conversion exists to survive Slack's own mrkdwn, and it costs the answer its- # headings, its tables, and its task lists. A markdown block renders all three, so- # running the conversion under the gate would throw away what the gate is for.- 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-conversion-{markdown}",- text=self._RICH_ANSWER,- )+ def test_the_answer_reaches_slack_as_the_agent_wrote_it(self, mock_delete_progress, mock_post):+ # A markdown block renders headings, tables, and task lists on its own, so the answer+ # goes out untouched. Rewriting any of it here would flatten what the block renders.+ relay_slack_message(+ RelaySlackMessageInput(+ run_id=str(self.task_run.id),+ relay_id="relay-conversion",+ text=self._RICH_ANSWER,)+ )- assert mock_post.call_args.args[0].endswith(expected)+ assert mock_post.call_args.args[0].endswith(self._RICH_ANSWER)@parameterized.expand([- # The converter turns the heading into inline bold, which survives an inline mention.- ("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."),+ ("heading", "## Heading\n\nBody text.", "<@U123>\n\n## Heading"),+ ("prose", "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_leaves_the_answers_opening_line_only_where_markdown_needs_it(- self, _name, markdown, text, expected_opening, mock_delete_progress, mock_post+ self, _name, 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# 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-{_name}",- text=text,- )+ relay_slack_message(+ RelaySlackMessageInput(+ run_id=str(self.task_run.id),+ relay_id=f"relay-mention-{_name}",+ text=text,)+ )assert mock_post.call_args.args[0].startswith(expected_opening)@@ -199,14 +177,13 @@ class TestRelaySlackMessage(TestCase):def test_the_mention_comes_out_of_the_chunk_budget(self, mock_delete_progress, mock_post):# The mention is added after splitting, so without a reserved allowance the chunk it# lands on exceeds the block cap and posts as plain text, showing the Markdown source.- with patch("products.slack_app.backend.slack_thread.SlackThreadHandler.renders_markdown", return_value=True):- relay_slack_message(- RelaySlackMessageInput(- run_id=str(self.task_run.id),- relay_id="relay-mention-budget",- text="word " * 4000, # 20,000 chars, so the first chunk fills the block- )+ relay_slack_message(+ RelaySlackMessageInput(+ run_id=str(self.task_run.id),+ relay_id="relay-mention-budget",+ text="word " * 4000, # 20,000 chars, so the first chunk fills the block)+ )assert all(len(call.args[0]) <= SLACK_MARKDOWN_TEXT_MAX_LEN for call in mock_post.call_args_list)@@ -508,7 +485,8 @@ class TestRelaySlackMessage(TestCase):self.assertEqual(composed_call.kwargs["channel"], "C123")self.assertEqual(composed_call.kwargs["thread_ts"], "1111.1")answer_block, header_block, image_block, actions_block = composed_call.kwargs["blocks"]- self.assertEqual(answer_block["text"]["text"], "<@U123> Here's the trend.")+ self.assertEqual(answer_block["type"], "markdown")+ self.assertEqual(answer_block["text"], "<@U123> Here's the trend.")self.assertEqual(header_block["text"]["text"], "*Signups by week*")self.assertEqual(image_block,@@ -625,206 +603,7 @@ class TestRelaySlackMessage(TestCase):artifact.refresh_from_db()self.assertEqual(artifact.versions[0]["delivery_status"], "pending")self.assertEqual(artifact.location["delivery_status"], "pending")- mock_post.assert_called_once_with("<@U123> Here's the trend.", with_footer=True, markdown=False)---class TestMarkdownToSlackMrkdwn(unittest.TestCase):- @parameterized.expand(- [- ("bold", "**hello**", "*hello*"),- ("italic_asterisk", "*italic*", "_italic_"),- ("italic_underscore", "_italic_", "_italic_"),- ("bold_italic", "***boldit***", "*_boldit_*"),- ("strikethrough", "~~removed~~", "~removed~"),- # "Approximately" tildes in front of a quantity would otherwise pair up as- # Slack strikethrough delimiters and strike through the text between them.- # The tilde operator (∼) looks the same but carries no formatting meaning.- (- "approx_tildes_do_not_strike_through",- "**~$36.0k**, averaging **~$5.1k/day** by ~2pm",- "*∼$36.0k*, averaging *∼$5.1k/day* by ∼2pm",- ),- ("link", "[Click here](https://example.com)", "<https://example.com|Click here>"),- ("h1", "# Title", "*Title*"),- ("h3", "### Section", "*Section*"),- ("dash_bullets", "- one\n- two", "• one\n• two"),- ("ordered_list_preserved", "1. one\n2. two", "1. one\n2. two"),- ("task_list", "- [ ] todo\n- [x] done", "• ☐ todo\n• ☑ done"),- ("horizontal_rule", "---", "──────────"),- ("blockquote_preserved", "> quote", "> quote"),- ("nested_bold_in_dash_list", "- **MIT** is permissive", "• *MIT* is permissive"),- (- "bold_markdown_link",- "**[pr-shepherd](https://us.posthog.com/project/2/llm-analytics/skills/pr-shepherd)**",- "*<https://us.posthog.com/project/2/llm-analytics/skills/pr-shepherd|pr-shepherd>*",- ),- # Agent emits double-asterisk closing markers inside the angle brackets- # (`**<url**>`). Without the repair pass the converter would halve those- # asterisks in place and produce `*<url*>`, which Slack renders as- # literal text with no link and no bold.- (- "agent_typo_double_asterisk_autolink",- "**<https://us.posthog.com/project/2/llm-analytics/skills/pr-shepherd**>",- "*<https://us.posthog.com/project/2/llm-analytics/skills/pr-shepherd>*",- ),- (- "agent_typo_double_asterisk_labeled_link",- "**<https://us.posthog.com/project/2/llm-analytics/skills/pr-shepherd|pr-shepherd**>",- "*<https://us.posthog.com/project/2/llm-analytics/skills/pr-shepherd|pr-shepherd>*",- ),- # Bare URL wrapped directly in markdown bold. Without the pre-wrap pass the- # converter halves the markers in place and emits ``*https://x.com*``, which- # Slack renders as literal asterisks around an auto-linked URL — the exact- # papercut on the PR-completion message that prompted this repair.- (- "agent_typo_bare_url_in_bold",- "Draft PR opened: **https://github.com/PostHog/posthog.com/pull/17450**",- "Draft PR opened: *<https://github.com/PostHog/posthog.com/pull/17450>*",- ),- (- "agent_typo_bare_url_in_italic_asterisk",- "see *https://example.com*",- "see _<https://example.com>_",- ),- ("plain_text_unchanged", "Hello world", "Hello world"),- ("inline_code_preserved", "Use `git commit`", "Use `git commit`"),- ]- )- def test_inline_conversions(self, _name, markdown, expected):- assert _markdown_to_slack_mrkdwn(markdown) == expected-- def test_empty_string_returns_unchanged(self):- assert _markdown_to_slack_mrkdwn("") == ""-- def test_table_renders_as_fenced_code_block_with_aligned_columns(self):- md = "| License | Key Points |\n|---|---|\n| MIT | Permissive |\n| GPL | Copyleft |"- # Widest cells per column: 'License' (7) and 'Key Points' (10). Two-space gutter.- # Trailing whitespace is rstripped, so the GPL row's narrower last cell isn't padded.- expected = "```\nLicense Key Points\nMIT Permissive\nGPL Copyleft\n```"- assert _markdown_to_slack_mrkdwn(md) == expected-- def test_table_strips_inline_markdown_from_cells(self):- md = "| Name | Note |\n|---|---|\n| **MIT** | [docs](https://x.com) |"- result = _markdown_to_slack_mrkdwn(md)- # Bold markers and link syntax don't render inside a code block, so we strip them.- assert "**" not in result- assert "MIT" in result- assert "docs" in result- assert "https://x.com" not in result-- def test_pipe_rows_without_separator_are_not_treated_as_a_table(self):- # No separator row → likely incidental pipes, not a table. Leave alone.- md = "| a | b |\n| c | d |"- result = _markdown_to_slack_mrkdwn(md)- assert "```" not in result---class TestRepairLinkTrailingMarkers(unittest.TestCase):- @parameterized.expand(- [- ("autolink_double_asterisk", "**<https://x.com**>", "**<https://x.com>**"),- ("autolink_single_asterisk", "*<https://x.com*>", "*<https://x.com>*"),- ("autolink_underscore", "_<https://x.com_>", "_<https://x.com>_"),- ("autolink_strikethrough", "~<https://x.com~>", "~<https://x.com>~"),- (- "labeled_link_double_asterisk",- "**<https://x.com|label**>",- "**<https://x.com|label>**",- ),- (- "two_broken_links_in_one_line",- "**<https://a.com**> and **<https://b.com**>",- "**<https://a.com>** and **<https://b.com>**",- ),- ("well_formed_autolink_unchanged", "**<https://x.com>**", "**<https://x.com>**"),- ("plain_text_unchanged", "Hello world", "Hello world"),- # Mismatched openers/closers shouldn't be rewritten — leave alone so we- # don't silently corrupt content that looks vaguely link-shaped.- ("mismatched_markers_unchanged", "**<https://x.com*>", "**<https://x.com*>"),- ]- )- def test_repair(self, _name, text, expected):- assert _repair_link_trailing_markers(text) == expected---class TestWrapBareUrlsInEmphasis(unittest.TestCase):- @parameterized.expand(- [- ("bold_bare_url", "**https://x.com**", "**<https://x.com>**"),- ("italic_bare_url", "*https://x.com*", "*<https://x.com>*"),- ("underscore_bare_url", "_https://x.com_", "_<https://x.com>_"),- ("strike_bare_url", "~~https://x.com~~", "~~<https://x.com>~~"),- (- "url_with_path_and_query",- "**https://github.com/PostHog/posthog.com/pull/17450?foo=bar**",- "**<https://github.com/PostHog/posthog.com/pull/17450?foo=bar>**",- ),- (- "two_bare_urls_in_one_line",- "**https://a.com** and *https://b.com*",- "**<https://a.com>** and *<https://b.com>*",- ),- # Surrounded by sentence text — only the wrapped URL should be touched.- (- "url_inside_sentence",- "Draft PR opened: **https://x.com/pr/1**",- "Draft PR opened: **<https://x.com/pr/1>**",- ),- # Already bracketed — leave alone so we don't double-wrap.- ("autolink_already_bracketed", "**<https://x.com>**", "**<https://x.com>**"),- # Standard markdown link — handled correctly by the converter as-is.- ("markdown_link_in_bold_unchanged", "**[label](https://x.com)**", "**[label](https://x.com)**"),- # Non-URL bold spans must not be rewritten.- ("plain_bold_unchanged", "**hello world**", "**hello world**"),- ("plain_text_unchanged", "Visit https://x.com without bolding", "Visit https://x.com without bolding"),- # A bare URL not directly adjacent to the marker shouldn't be wrapped — the- # surrounding text means the emphasis already flanks whitespace and Slack- # renders it correctly without help.- (- "url_inside_bold_span_with_surrounding_text",- "**check https://x.com later**",- "**check https://x.com later**",- ),- ]- )- def test_wrap(self, _name, text, expected):- assert _wrap_bare_urls_in_emphasis(text) == expected---class TestNeutralizeApproxTildes(unittest.TestCase):- @parameterized.expand(- [- ("dollar", "~$36.0k", "∼$36.0k"),- ("bare_number", "~5.1k/day", "∼5.1k/day"),- ("time", "roughly ~2pm PT", "roughly ∼2pm PT"),- ("percent", "up ~10% MoM", "up ∼10% MoM"),- ("euro", "~€40", "∼€40"),- ("multiple_on_one_line", "~$5k then ~$9k", "∼$5k then ∼$9k"),- # A genuine ``~~strikethrough~~`` run must survive untouched — its tildes are- # adjacent to each other, not to a quantity.- ("strikethrough_run_preserved", "~~$5 off~~", "~~$5 off~~"),- # A tilde glued to a preceding word is a git ref or range, not "approximately".- ("git_ref_left_alone", "rebase onto HEAD~2", "rebase onto HEAD~2"),- ("numeric_range_left_alone", "5~10 items", "5~10 items"),- # Paths, standalone tildes, and non-quantity tildes are literal characters that- # never form an accidental strikethrough, so they are left alone.- ("path_left_alone", "see ~/notes/report.md", "see ~/notes/report.md"),- ("tilde_before_letter_left_alone", "~foo", "~foo"),- ("tilde_before_space_left_alone", "~ $5", "~ $5"),- ("plain_text_unchanged", "no tildes here", "no tildes here"),- # Code spans/fences hold literal content Slack never strikes through, so a tilde- # there stays ASCII even when it looks like an approximation.- ("inline_code_left_alone", "run `git reset HEAD~1` and `~$5`", "run `git reset HEAD~1` and `~$5`"),- (- "fenced_block_left_alone",- "```\ninstall foo@~1.2.0\ncost ~$5\n```",- "```\ninstall foo@~1.2.0\ncost ~$5\n```",- ),- ("approx_outside_code_still_converted", "about ~$5 for `~$9`", "about ∼$5 for `~$9`"),- ]- )- def test_neutralize(self, _name, text, expected):- assert _neutralize_approx_tildes(text) == expected+ mock_post.assert_called_once_with("<@U123> Here's the trend.", with_footer=True, markdown=True)class TestAppendUnconfirmedAttachmentNotice(unittest.TestCase):@@ -848,21 +627,25 @@ class TestAppendUnconfirmedAttachmentNotice(unittest.TestCase):class TestSplitTextForSlack(TestCase):+ # The splitter takes its limit from the caller and behaves the same at any size, so these+ # cases use a small one to keep the fixtures small. Production passes the markdown block cap.+ _LIMIT = 3500+def test_short_text_returns_single_chunk(self):- assert _split_markdown_for_slack("hello world") == ["hello world"]+ assert _split_markdown_for_slack("hello world", self._LIMIT) == ["hello world"]def test_each_chunk_under_limit(self):paragraph = ("word " * 200).strip()text = "\n\n".join([paragraph] * 10)- chunks = _split_markdown_for_slack(text)+ chunks = _split_markdown_for_slack(text, self._LIMIT)assert len(chunks) > 1for chunk in chunks:- assert len(chunk) <= SLACK_MESSAGE_TEXT_LIMIT+ assert len(chunk) <= self._LIMITdef test_split_prefers_paragraph_boundary(self):paragraph = ("alpha " * 400).strip() # ~2400 chars per paragraphtext = f"{paragraph}\n\n{paragraph}"- chunks = _split_markdown_for_slack(text)+ chunks = _split_markdown_for_slack(text, self._LIMIT)assert len(chunks) == 2assert chunks[0] == paragraphassert chunks[1] == paragraph@@ -870,75 +653,41 @@ class TestSplitTextForSlack(TestCase):def test_split_falls_back_to_line_within_paragraph(self):line = ("alpha " * 100).strip() # ~600 charstext = "\n".join([line] * 10) # single paragraph, ~6000 chars- chunks = _split_markdown_for_slack(text)+ chunks = _split_markdown_for_slack(text, self._LIMIT)assert len(chunks) >= 2for chunk in chunks:for chunk_line in chunk.split("\n"):assert chunk_line == linedef test_hard_breaks_single_long_line(self):- line = "x" * (SLACK_MESSAGE_TEXT_LIMIT + 500)- chunks = _split_markdown_for_slack(line)+ line = "x" * (self._LIMIT + 500)+ chunks = _split_markdown_for_slack(line, self._LIMIT)assert len(chunks) == 2- assert all(len(chunk) <= SLACK_MESSAGE_TEXT_LIMIT for chunk in chunks)+ assert all(len(chunk) <= self._LIMIT for chunk in chunks)assert "".join(chunks) == linedef test_oversized_code_block_keeps_fences_balanced(self):body_lines = [f"line {i:04d}" for i in range(800)]body = "\n".join(body_lines)text = f"```python\n{body}\n```"- chunks = _split_markdown_for_slack(text)+ chunks = _split_markdown_for_slack(text, self._LIMIT)assert len(chunks) >= 2for chunk in chunks:assert chunk.startswith("```python\n")assert chunk.endswith("\n```")assert chunk.count("```") == 2- assert len(chunk) <= SLACK_MESSAGE_TEXT_LIMIT+ assert len(chunk) <= self._LIMITdef test_mixed_text_and_code_block_preserves_block(self):prefix = "intro paragraph\n\n"suffix = "\n\ntrailing paragraph"code = "```js\n" + "console.log('hi');\n" * 10 + "```"text = prefix + code + suffix- chunks = _split_markdown_for_slack(text)+ chunks = _split_markdown_for_slack(text, self._LIMIT)joined = "\n\n".join(chunks)assert "```js\n" in joinedassert joined.count("```") % 2 == 0- def test_paragraph_split_preserves_markdown_for_per_chunk_conversion(self):- # Each chunk must stay a valid markdown document on its own so that the- # per-chunk mrkdwn conversion produces correctly-rendered output.- paragraph_a = "This **bold** and [link](https://example.com) " * 50- paragraph_b = "Another **bold** and [link](https://example.com) " * 50- text = f"{paragraph_a.strip()}\n\n{paragraph_b.strip()}"- chunks = _split_markdown_for_slack(text)- assert len(chunks) == 2- for chunk in chunks:- converted = _markdown_to_slack_mrkdwn(chunk)- assert "*bold*" in converted- assert "<https://example.com|link>" in converted- assert "**" not in converted # inline bold markers must be fully converted-- def test_hard_char_break_leaves_broken_inline_span_as_literal(self):- # A single line longer than the limit forces a hard char break. Doing it- # before conversion means a halved ``**bold**`` simply fails to match the- # converter regex on either side, so both chunks keep the literal ``**``- # rather than ending up with a dangling unbalanced ``*`` in Slack mrkdwn.- prefix = "x" * (SLACK_MESSAGE_TEXT_LIMIT - 4)- line = prefix + "**bold**" + "y" * 100- chunks = _split_markdown_for_slack(line)- assert len(chunks) == 2- converted_first = _markdown_to_slack_mrkdwn(chunks[0])- converted_second = _markdown_to_slack_mrkdwn(chunks[1])- # Neither chunk should contain a valid Slack-mrkdwn ``*bold*`` because- # the span was halved; both should preserve the raw asterisks instead.- assert "*bold*" not in converted_first- assert "*bold*" not in converted_second- # And, critically, no chunk leaks a lone unbalanced ``*`` that would- # turn the rest of the message italic.- for chunk in (converted_first, converted_second):- assert chunk.count("*") % 2 == 0-class TestRelaySlackMessageChunking(TestCase):org: ClassVar[Organization]@@ -993,8 +742,8 @@ class TestRelaySlackMessageChunking(TestCase):mock_post,mock_update,):- paragraph = ("alpha " * 400).strip()- text = "\n\n".join([paragraph] * 4)+ paragraph = ("alpha " * 1000).strip() # ~6000 chars+ text = "\n\n".join([paragraph] * 3)relay_slack_message(RelaySlackMessageInput(run_id=str(self.task_run.id),@@ -1079,5 +828,5 @@ class TestRelaySlackMessageChunking(TestCase):))- mock_post.assert_called_once_with("<@U456> Here you go.", with_footer=True, markdown=False)+ mock_post.assert_called_once_with("<@U456> Here you go.", with_footer=True, markdown=True)mock_post_footer.assert_not_called()diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.py b/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.pyindex e4e9e8a83af2..5595136793c7 100644--- a/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.py+++ b/products/tasks/backend/temporal/slack_relay/tests/test_object_tags.py@@ -2,7 +2,6 @@ import unittestfrom parameterized import parameterized-from products.tasks.backend.temporal.slack_relay.activities import _markdown_to_slack_mrkdwnfrom products.tasks.backend.temporal.slack_relay.object_tags import (rewrite_object_tags_for_slack,split_incomplete_tag_suffix,@@ -198,22 +197,6 @@ class TestRewriteObjectTagsForSlack(unittest.TestCase):assert rendered.endswith(f"[beta]({PROJECT}/feature_flags/42?unfurl=false)")assert rendered.count('<insight id="open">') == 300- def test_rewritten_output_survives_mrkdwn_conversion(self) -> None:- text = (- 'Two tiles: <insight id="F6tNdPRe">ready-only</insight> and <insight id="jjF0PSO2" display="block"/>\n\n'- '<hogql display="block" title="DAU">SELECT 1</hogql>'- )- converted = _markdown_to_slack_mrkdwn(rewrite(text))- assert f"<{PROJECT}/insights/F6tNdPRe?unfurl=false|ready-only>" in converted- assert f"<{PROJECT}/insights/jjF0PSO2|Insight jjF0PSO2>" in converted- assert f"*<{PROJECT}/sql?open_query=SELECT%201&unfurl=false|DAU>*" in converted- assert "```\nSELECT 1\n```" in converted- assert "<hogql" not in converted-- def test_entities_in_labels_survive_mrkdwn_conversion(self) -> None:- converted = _markdown_to_slack_mrkdwn(rewrite('<insight id="1" title="Error rate > 1%"/>'))- assert converted == f"<{PROJECT}/insights/1?unfurl=false|Error rate > 1%>"-class TestSplitIncompleteTagSuffix(unittest.TestCase):@parameterized.expand(