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.

feat(slack_app): render agent answers as Markdown behind a flag (#97232)

Vojta Bartoš88ad80622614
diff --git a/posthog/helpers/slack_markdown.py b/posthog/helpers/slack_markdown.py
new file mode 100644
index 000000000000..1d82050e7ba5
--- /dev/null
+++ b/posthog/helpers/slack_markdown.py
@@ -0,0 +1,18 @@
+"""Building a Slack `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.
+"""
+
+from __future__ import annotations
+
+# 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
+
+
+def slack_markdown_block(text: str) -> dict:
+ """The block Slack renders Markdown in. The caller is responsible for `text` being safe to
+ show and within `SLACK_MARKDOWN_TEXT_MAX_LEN`, because Slack rejects the whole message
+ otherwise."""
+ return {"type": "markdown", "text": text}
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.py
index e843975c82ad..8bf9eb7a949c 100644
--- a/products/signals/backend/scout_harness/slack_delivery.py
+++ b/products/signals/backend/scout_harness/slack_delivery.py
@@ -12,6 +12,7 @@ from slack_sdk.errors import SlackApiError
from slack_sdk.web import SlackResponse, WebClient
from posthog.dataclasses import frozen
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_block
from posthog.models.integration import Integration, SlackIntegration
from posthog.redis import get_client
@@ -24,14 +25,12 @@ from products.signals.backend.scout_harness.slack_charts import (
strip_chart_blocks,
)
from products.signals.backend.slack_formatting import (
- SLACK_MARKDOWN_TEXT_MAX_LEN,
chunk_slack_text,
defuse_slack_tokens,
escape_slack_mrkdwn,
group_segments_to_limit,
prepare_slack_markdown,
slack_channel_id_from_target,
- slack_markdown_block,
split_markdown_by_headings,
strip_chart_references,
)
diff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.py
index 9aa096a47e02..447c6590fde0 100644
--- a/products/signals/backend/slack_formatting.py
+++ b/products/signals/backend/slack_formatting.py
@@ -4,11 +4,7 @@ import re
from collections import Counter
from posthog.dataclasses import frozen
-
-# A Slack `markdown` block takes Markdown directly, and 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
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN
# A summary places a chart inline with a markdown link targeting `chart:<chart_id>`. Slack cannot
# place an image mid-sentence, and the link degrades badly if left alone: `chart:` is no scheme a
@@ -116,11 +112,6 @@ def truncate_slack_text(text: str, limit: int) -> str:
return text[: limit - 1].rstrip() + "…"
-def slack_markdown_block(text: str) -> dict:
- """The Slack block that renders Markdown, for text `prepare_slack_markdown` has already made safe."""
- return {"type": "markdown", "text": text}
-
-
def prepare_slack_markdown(text: str) -> str:
"""Make untrusted Markdown safe to hand Slack, and keep it inside one markdown block.
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 61f718885eba..a0b44fafe420 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -22,6 +22,7 @@ from collections.abc import Iterable
from django.conf import settings
from posthog.event_usage import groups
+from posthog.helpers.slack_markdown import slack_markdown_block as _markdown_block
from posthog.models import User
from posthog.models.integration import Integration, SlackIntegration
from posthog.ph_client import ph_scoped_capture
@@ -45,7 +46,6 @@ from products.signals.backend.slack_formatting import (
is_safe_slack_http_url as _is_safe_http_url,
prepare_slack_markdown as _prepare_markdown,
slack_channel_id_from_target as _channel_id_from_target,
- slack_markdown_block as _markdown_block,
strip_chart_references as _strip_chart_references,
)
from products.signals.backend.slack_notification_targets import is_slack_member_target, lookup_slack_user_id_by_email
diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.py
index d612fc69a5d2..cf9a231701e8 100644
--- a/products/signals/backend/test/test_scout_slack_delivery.py
+++ b/products/signals/backend/test/test_scout_slack_delivery.py
@@ -12,6 +12,7 @@ from celery.exceptions import Retry
from parameterized import parameterized
from slack_sdk.errors import SlackApiError
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN
from posthog.models import Team
from posthog.models.integration import Integration
from posthog.redis import get_client
@@ -28,7 +29,6 @@ from products.signals.backend.scout_harness.slack_delivery import (
post_scout_emission_to_slack,
)
from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_delivery
-from products.signals.backend.slack_formatting import SLACK_MARKDOWN_TEXT_MAX_LEN
from products.signals.backend.tasks import deliver_scout_slack_output, enqueue_scout_slack_delivery
diff --git a/products/signals/backend/test/test_slack_formatting.py b/products/signals/backend/test/test_slack_formatting.py
index 75e315b16468..430a62bea330 100644
--- a/products/signals/backend/test/test_slack_formatting.py
+++ b/products/signals/backend/test/test_slack_formatting.py
@@ -4,8 +4,9 @@ from django.test import SimpleTestCase
from parameterized import parameterized
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN
+
from products.signals.backend.slack_formatting import (
- SLACK_MARKDOWN_TEXT_MAX_LEN,
chunk_slack_text,
defuse_slack_tokens,
escape_slack_mrkdwn,
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index b06b65b7d3f6..ca22044fc6aa 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -46,6 +46,7 @@ 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.
@@ -124,6 +125,22 @@ 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 surface
calls — ``im:history`` in particular, without which the assistant would answer
diff --git a/products/slack_app/backend/slack_thread.py b/products/slack_app/backend/slack_thread.py
index 15ddef6dab25..9808981bd6c4 100644
--- a/products/slack_app/backend/slack_thread.py
+++ b/products/slack_app/backend/slack_thread.py
@@ -6,9 +6,10 @@ import structlog
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_block
from posthog.models.integration import Integration, SlackIntegration
-from products.slack_app.backend.feature_flags import is_slack_app_forking_enabled
+from products.slack_app.backend.feature_flags import is_slack_app_forking_enabled, is_slack_app_markdown_enabled
from products.slack_app.backend.services.model_catalogue import describe_run_model
from products.slack_app.backend.services.slack_messages import (
RunFooter,
@@ -45,6 +46,11 @@ _TASK_FIELD_LIMIT = 256
_MARKDOWN_CHUNK_LIMIT = 12000
_SECTION_TEXT_LIMIT = 3000
+# Slack rejects the request outright for these, and repeating the same blocks cannot change the
+# answer, so the reply is posted plainly instead. The same pair is what the scout delivery in
+# signals treats as a block rejection.
+_BLOCK_REJECTION_ERROR_CODES = frozenset({"invalid_blocks", "invalid_blocks_format"})
+
def _split_markdown_text(text: str, limit: int = _MARKDOWN_CHUNK_LIMIT) -> list[str]:
"""≤limit pieces at paragraph/line boundaries. Slack stitches chunks server-side."""
@@ -149,6 +155,7 @@ class SlackThreadHandler:
self._client: WebClient | None = None
self._bot_user_id: str | None = None
self._fork_flag: bool | None = None
+ self._markdown_flag: bool | None = None
self._code_access: bool | None = None
def _get_integration(self) -> Integration:
@@ -170,6 +177,24 @@ 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't
open it.
@@ -574,46 +599,82 @@ class SlackThreadHandler:
except Exception as e:
logger.warning("slack_app_post_footer_failed", error=str(e))
- def post_thread_message(self, text: str, with_footer: bool = False) -> None:
- """Post a plain message in the existing thread.
+ def _answer_blocks(
+ self, text: str, footer: dict[str, Any] | None, *, markdown: bool
+ ) -> list[dict[str, Any]] | None:
+ """The blocks carrying one answer, or `None` to post it as plain text instead.
- ``with_footer`` closes the message with the provenance footer, for the last
- chunk of a non-streamed answer — the streamed path appends its own instead.
- Passing it only adds blocks when there is actually a footer to show, so an
- ordinary message stays a plain-text post.
+ Under `mrkdwn` a footerless answer needs no blocks, because a plain-text message renders
+ `mrkdwn` on its own, so an ordinary message stays the plain-text post it has always been.
+ A `markdown` block has no such equivalent: without it Slack shows the Markdown source, so
+ the answer always carries one.
+
+ The menu and the thumbs are only asked for once a footer exists, which keeps a reply with
+ nothing to describe off the integration lookup behind their gates.
"""
- # A section block caps at 3000 characters; over that, dropping the footer costs a
- # line of provenance, while keeping it would cost the whole message. The menu and
- # the thumbs go with it: an answer that long can only be posted as plain text,
- # which carries no blocks at all.
- footer = self._footer_block() if with_footer and len(text) <= _SECTION_TEXT_LIMIT else None
- # No footer means no blocks at all, so an ordinary message stays the plain-text
- # post it has always been. `expand` keeps the answer fully visible: a section
- # collapses behind "Show more", which plain text never did.
- blocks: list[dict[str, Any]] | None = None
- if footer:
- answer: dict[str, Any] = {"type": "section", "expand": True, "text": {"type": "mrkdwn", "text": text}}
+ if markdown:
+ blocks = [slack_markdown_block(text)]
+ elif footer:
+ # `expand` keeps the answer fully visible: a section collapses behind "Show more",
+ # which plain text never did.
+ blocks = [{"type": "section", "expand": True, "text": {"type": "mrkdwn", "text": text}}]
+ else:
+ return None
+ if not footer:
+ return blocks
+ menu = self._fork_menu()
+ if markdown:
+ # A `markdown` block takes no accessory, so the menu follows the answer in an
+ # `actions` block of its own, which is where the streamed replies already put it.
+ blocks.append(footer)
+ if menu:
+ blocks.append(fork_menu_actions_block(menu))
+ else:
# The menu hangs off the answer, not the footer: a `context` block rejects
# interactive elements, and moving the footer to a `section` to hold one
# would cost it the muted styling that makes it read as a footer.
- menu = self._fork_menu()
if menu:
- answer["accessory"] = menu
- blocks = [answer, footer]
- # The thumbs close the message, below the footer, where a reader of any other
- # AI app already looks for them.
- feedback = self._feedback_block()
- if feedback:
- blocks.append(feedback)
+ blocks[0]["accessory"] = menu
+ blocks.append(footer)
+ # The thumbs close the message, below the footer, where a reader of any other
+ # AI app already looks for them.
+ feedback = self._feedback_block()
+ if feedback:
+ blocks.append(feedback)
+ return blocks
+
+ def post_thread_message(self, text: str, with_footer: bool = False, *, markdown: bool = False) -> None:
+ """Post a plain message in the existing thread.
+
+ ``with_footer`` closes the message with the provenance footer, for the last
+ 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.
+ """
+ # 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 keeping
+ # it would cost the whole message. The menu and the thumbs go with it.
+ markdown = markdown and len(text) <= SLACK_MARKDOWN_TEXT_MAX_LEN
+ fits_in_a_block = markdown or len(text) <= _SECTION_TEXT_LIMIT
+ footer = self._footer_block() if with_footer and fits_in_a_block else None
+ blocks = self._answer_blocks(text, footer, markdown=markdown)
try:
self._post_in_thread(text=text, blocks=blocks)
except SlackApiError as e:
# Slack rejects a request whose blocks are invalid outright — the `text`
# fallback does not rescue it — so the answer would go down with its footer.
- # Describing a run must never cost the reader the run's answer.
- if blocks and e.response.get("error") == "invalid_blocks":
- logger.warning("slack_app_footer_blocks_rejected", error=str(e))
- self.post_thread_message(text)
+ # Describing a run must never cost the reader the run's answer. Posting plainly
+ # rather than retrying through this method drops every block at once, so a
+ # rejection Slack repeats cannot loop.
+ if blocks and e.response.get("error") in _BLOCK_REJECTION_ERROR_CODES:
+ logger.warning("slack_app_answer_blocks_rejected", error=str(e))
+ try:
+ self._post_in_thread(text=text)
+ except Exception as retry_error:
+ logger.warning("slack_post_thread_message_failed", error=str(retry_error))
return
logger.warning("slack_post_thread_message_failed", error=str(e))
except Exception as e:
diff --git a/products/slack_app/backend/tests/test_slack_thread.py b/products/slack_app/backend/tests/test_slack_thread.py
index 0d1de0bbfbf8..eb93f23e2ff5 100644
--- a/products/slack_app/backend/tests/test_slack_thread.py
+++ b/products/slack_app/backend/tests/test_slack_thread.py
@@ -6,6 +6,7 @@ from django.test import SimpleTestCase
from parameterized import parameterized
from slack_sdk.errors import SlackApiError
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN
from posthog.models.integration import Integration
from products.slack_app.backend.services.slack_messages import RunFooter
@@ -584,3 +585,94 @@ class TestForkMenuOnReplies(SimpleTestCase):
blocks = mock_client.chat_postMessage.call_args.kwargs["blocks"]
assert blocks[-1]["type"] == "context"
assert "accessory" not in blocks[0]
+
+
+class TestMarkdownAnswerBlocks(SimpleTestCase):
+ """Under the gate the answer carries a `markdown` block, which takes no accessory and caps
+ at a different length than the `section` it replaces."""
+
+ def _handler(self) -> SlackThreadHandler:
+ context = SlackThreadContext(integration_id=1, channel="C001", thread_ts="1234.5678")
+ return SlackThreadHandler(context, RunFooter(model="claude-opus-5"))
+
+ @parameterized.expand([("with_footer", True), ("without_footer", False)])
+ @patch.object(SlackThreadHandler, "_get_integration")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_the_answer_always_carries_a_markdown_block(
+ self, _name: str, with_footer: bool, mock_get_client, mock_get_integration
+ ) -> None:
+ # A plain-text message renders mrkdwn on its own, which is why a footerless answer
+ # used to carry no blocks. Markdown has no such equivalent, so without the block
+ # Slack shows the source and `## Heading` reaches the reader as literal text.
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_get_integration.return_value = Integration(id=7, config={"app_id": "A1"}, integration_id="T1")
+
+ self._handler().post_thread_message("## Heading\n\n**bold**", with_footer=with_footer, markdown=True)
+
+ blocks = mock_client.chat_postMessage.call_args.kwargs["blocks"]
+ assert blocks[0] == {"type": "markdown", "text": "## Heading\n\n**bold**"}
+
+ @patch("products.slack_app.backend.slack_thread.is_slack_app_forking_enabled", return_value=True)
+ @patch.object(SlackThreadHandler, "_get_integration")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_the_menu_gets_its_own_block_because_markdown_takes_no_accessory(
+ self, mock_get_client, mock_get_integration, _forking
+ ) -> None:
+ # Slack rejects the whole message when a block carries a field it does not define,
+ # so an accessory left on the answer would cost the reader the answer itself.
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_get_integration.return_value = Integration(id=7, config={"app_id": "A1"}, integration_id="T1")
+
+ self._handler().post_thread_message("the answer", with_footer=True, markdown=True)
+
+ blocks = mock_client.chat_postMessage.call_args.kwargs["blocks"]
+ assert [block["type"] for block in blocks] == ["markdown", "context", "actions"]
+ assert "accessory" not in blocks[0]
+
+ @patch.object(SlackThreadHandler, "_get_integration")
+ @patch.object(SlackThreadHandler, "_get_client")
+ def test_an_answer_past_the_block_cap_posts_in_full_as_plain_text(
+ self, mock_get_client, mock_get_integration
+ ) -> None:
+ # A markdown block Slack would reject for its length must cost the answer its
+ # formatting, never any of its content.
+ mock_client = MagicMock()
+ mock_get_client.return_value = mock_client
+ mock_get_integration.return_value = Integration(id=7, config={"app_id": "A1"}, integration_id="T1")
+ text = "x" * (SLACK_MARKDOWN_TEXT_MAX_LEN + 1)
+
+ self._handler().post_thread_message(text, with_footer=True, markdown=True)
+
+ kwargs = mock_client.chat_postMessage.call_args.kwargs
+ assert kwargs["text"] == text
+ assert not kwargs.get("blocks")
+
+ @parameterized.expand([("invalid_blocks",), ("invalid_blocks_format",)])
+ @patch.object(SlackThreadHandler, "_get_integration")
+ @patch.object(SlackThreadHandler, "_get_client")
+ 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.
+ # 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()
+ mock_client.chat_postMessage.side_effect = SlackApiError(error_code, {"error": error_code})
+ mock_get_client.return_value = mock_client
+ mock_get_integration.return_value = Integration(id=7, config={"app_id": "A1"}, integration_id="T1")
+
+ self._handler().post_thread_message("the answer", with_footer=True, markdown=True)
+
+ assert mock_client.chat_postMessage.call_count == 2
+ retry = mock_client.chat_postMessage.call_args_list[1].kwargs
+ assert 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 False
diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.py
index aa5bf3887bbe..1ddd8c903cce 100644
--- a/products/tasks/backend/logic/services/living_artifacts.py
+++ b/products/tasks/backend/logic/services/living_artifacts.py
@@ -24,6 +24,7 @@ import structlog
from slack_sdk.errors import SlackApiError
from posthog.event_usage import groups
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_block
from posthog.ph_client import ph_scoped_capture
from posthog.storage import object_storage
from posthog.utils import absolute_uri
@@ -852,12 +853,15 @@ def has_pending_slack_image_artifacts(run: TaskRun) -> bool:
def deliver_pending_slack_file_artifacts(
- run: TaskRun, *, answer_sections: list[str] | None = None
+ run: TaskRun, *, answer_sections: list[str] | None = None, answer_is_markdown: bool = False
) -> 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 converted answer text): text sections first, then one card per
+ (the relay's answer text): text sections first, then one card per
chart (title, image block, "Open in PostHog" button). Chart images reference a
url minted here from their export asset — Slack's image proxy fetches the PNG
from us, so no file upload (and no files:write scope) is involved; other images
@@ -966,6 +970,7 @@ 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,
)
@@ -975,9 +980,9 @@ 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.
- sections = [section for section in answer_sections if section.strip()]
- posted = [_post_thread_text(slack, mapping=mapping, text=section) for section in sections]
- result.answer_posted = bool(sections) and all(posted)
+ blocks = _answer_text_blocks(answer_sections, markdown=answer_is_markdown)
+ posted = [_post_answer_block(slack, mapping=mapping, block=block) for block in blocks]
+ result.answer_posted = bool(blocks) and all(posted)
for artifact, version_payload, content_type in other_files:
if not has_file_scope:
@@ -1106,6 +1111,7 @@ 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:
@@ -1117,21 +1123,41 @@ def _post_composed_answer_message(
post succeeds, so an activity that dies part-way through doesn't replay the cards
that already landed."""
sections = [section for section in answer_sections if section.strip()]
- section_blocks = _section_blocks(sections)
+ section_blocks = _answer_text_blocks(sections, markdown=answer_is_markdown)
card_blocks: list[dict[str, Any]] = []
for card in image_cards:
card_blocks.extend(_chart_card_blocks(card))
- spill_count = max(len(section_blocks) - max(_SLACK_MESSAGE_BLOCK_LIMIT - len(card_blocks), 0), 0)
+ 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)
posted_blocks = 0
for block in section_blocks[:spill_count]:
- posted_blocks += 1 if _post_thread_text(slack, mapping=mapping, text=block["text"]["text"]) else 0
+ # 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)
+ return False
+ posted_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.
if len(kept) + len(card_blocks) <= _SLACK_MESSAGE_BLOCK_LIMIT:
- fallback_text = sections[0] if sections else _artifact_fallback_text(image_cards[0].artifact)
+ # The fallback names what this message shows, which is the block it kept rather than the
+ # 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)
try:
if _post_blocks_with_processing_retry(
slack,
@@ -1148,10 +1174,10 @@ def _post_composed_answer_message(
except Exception:
logger.warning("task_artifact.slack_composed_message_failed", exc_info=True)
- # Degraded path: the answer must not be lost — post the text plainly, then each
+ # Degraded path: the answer must not be lost — post the text on its own, then each
# card on its own so one bad card can't sink the others.
for block in kept:
- posted_blocks += 1 if _post_thread_text(slack, mapping=mapping, text=block["text"]["text"]) else 0
+ posted_blocks += 1 if _post_answer_block(slack, mapping=mapping, block=block) else 0
for card in image_cards:
try:
if _post_blocks_with_processing_retry(
@@ -1169,34 +1195,56 @@ def _post_composed_answer_message(
return bool(section_blocks) and posted_blocks == len(section_blocks)
-# Section blocks hard-cap at 3000 chars. The relay pre-splits at 2900 before conversion,
-# but the mention prefix and mrkdwn expansion (table column padding, escapes) can push a
-# section past that — re-split after conversion, preferring whitespace so the cut doesn't
-# land inside a converted mrkdwn entity like `<url|text>`. Tables convert to fenced blocks,
-# so a cut inside one is closed and reopened to keep each block self-contained.
+# 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 _section_blocks(sections: list[str]) -> list[dict[str, Any]]:
+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
blocks: list[dict[str, Any]] = []
for section in sections:
- for piece in _split_section_text(section):
- blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": piece}})
+ for piece in _split_section_text(section, limit_chars=limit):
+ blocks.append(slack_markdown_block(piece) if markdown else _mrkdwn_section_block(piece))
return blocks
-def _split_section_text(section: str) -> list[str]:
+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.
+ """
+ blocks = [block] if block["type"] == "markdown" else None
+ return _post_thread_text(slack, mapping=mapping, text=_answer_block_text(block), blocks=blocks)
+
+
+def _split_section_text(section: str, *, limit_chars: int) -> list[str]:
pieces: list[str] = []
remaining = section
reopen = ""
while True:
candidate = reopen + remaining
- if len(candidate) <= _SLACK_SECTION_BLOCK_CHAR_LIMIT:
+ if len(candidate) <= limit_chars:
if candidate.strip():
pieces.append(candidate)
return pieces
- limit = _SLACK_SECTION_BLOCK_CHAR_LIMIT
+ limit = limit_chars
if candidate[:limit].count(_SLACK_CODE_FENCE) % 2:
limit -= len(f"\n{_SLACK_CODE_FENCE}")
window = candidate[:limit]
@@ -1215,12 +1263,18 @@ def _split_section_text(section: str) -> list[str]:
pieces.append(piece)
-def _post_thread_text(slack: Any, *, mapping: Any, text: str) -> bool:
- """Post one plain text message, reporting whether it landed — callers use this to decide
- whether the answer still needs a fallback, so a swallowed failure must not read as sent."""
+def _post_thread_text(slack: Any, *, mapping: Any, text: str, blocks: list[dict[str, Any]] | None = None) -> bool:
+ """Post one message, reporting whether it landed — callers use this to decide whether the
+ answer still needs a fallback, so a swallowed failure must not read as sent.
+
+ ``blocks`` is for text a plain message cannot render, and ``text`` stays the notification
+ fallback beside it."""
try:
return (
- post_slack_thread_reply(slack, channel=mapping.channel, thread_ts=mapping.thread_ts, text=text) is not None
+ post_slack_thread_reply(
+ slack, channel=mapping.channel, thread_ts=mapping.thread_ts, text=text, blocks=blocks
+ )
+ is not None
)
except Exception:
logger.warning("task_artifact.slack_thread_text_failed", exc_info=True)
diff --git a/products/tasks/backend/logic/services/tests/test_living_artifacts.py b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
index 758e2b112f07..2454bf526318 100644
--- a/products/tasks/backend/logic/services/tests/test_living_artifacts.py
+++ b/products/tasks/backend/logic/services/tests/test_living_artifacts.py
@@ -9,6 +9,7 @@ from django.test import SimpleTestCase, TestCase, override_settings
from parameterized import parameterized
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN
from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
@@ -22,9 +23,10 @@ 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,
- _section_blocks,
_SlackImageCard,
create_living_artifact,
edit_living_artifact,
@@ -708,16 +710,26 @@ class TestChartCardBlockBuilders(SimpleTestCase):
blocks = _chart_card_blocks(_SlackImageCard(artifact, {}, file_id="F123"))
self.assertEqual([b["type"] for b in blocks], expected_block_types)
- def test_oversized_sections_split_below_block_char_cap(self):
- blocks = _section_blocks(["a" * 6500, "short"])
- self.assertEqual([len(b["text"]["text"]) for b in blocks], [3000, 3000, 500, 5])
- self.assertEqual(blocks[-1]["text"]["text"], "short")
+ @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 = _section_blocks([words.strip()])
+ blocks = _answer_text_blocks([words.strip()], markdown=False)
self.assertGreater(len(blocks), 1)
for block in blocks:
text = block["text"]["text"]
@@ -728,7 +740,7 @@ class TestChartCardBlockBuilders(SimpleTestCase):
# 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 = _section_blocks([f"{_SLACK_CODE_FENCE}\n{table}{_SLACK_CODE_FENCE}"])
+ blocks = _answer_text_blocks([f"{_SLACK_CODE_FENCE}\n{table}{_SLACK_CODE_FENCE}"], markdown=False)
self.assertGreater(len(blocks), 1)
for block in blocks:
text = block["text"]["text"]
@@ -741,7 +753,7 @@ class TestChartCardBlockBuilders(SimpleTestCase):
# 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 = _section_blocks([section])
+ blocks = _answer_text_blocks([section], markdown=False)
self.assertGreater(len(blocks), 1)
for block in blocks:
text = block["text"]["text"]
@@ -787,6 +799,7 @@ 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,
)
@@ -795,6 +808,57 @@ class TestChartCardBlockBuilders(SimpleTestCase):
for call in slack.chat_postMessage.call_args_list:
self.assertEqual(call.kwargs["text"], "&lt;!channel&gt; spike")
+ def test_a_composed_message_carries_one_markdown_block_and_spills_the_rest(self):
+ # Slack budgets 12,000 characters across every markdown block in one payload, so
+ # keeping several of them would fail the composed message and lose both the answer
+ # and the charts it was carrying.
+ slack = MagicMock()
+ slack.chat_postMessage.return_value = {"ok": True, "ts": "1111.2"}
+ cards = [_SlackImageCard(TaskArtifact(name="Chart"), {}, file_id="F0")]
+
+ answer_posted = _post_composed_answer_message(
+ slack,
+ 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,
+ )
+
+ self.assertTrue(answer_posted)
+ posted = [call.kwargs.get("blocks") or [] for call in slack.chat_postMessage.call_args_list]
+ # Every message renders its own Markdown, so a spilled section reads like an unspilled one.
+ self.assertEqual([[b["type"] for b in blocks] for blocks in posted[:2]], [["markdown"], ["markdown"]])
+ self.assertEqual([blocks[0]["text"] for blocks in posted[:2]], ["## First", "## Second"])
+ # The last section rides with the cards, and it is the only markdown block there.
+ composed = posted[-1]
+ self.assertEqual([b["type"] for b in composed if b["type"] == "markdown"], ["markdown"])
+ self.assertEqual(composed[0]["text"], "## Third")
+ # Slack reads the top-level text for the notification, the screen reader, and the
+ # mentions it pings, so it has to name the block this message shows.
+ self.assertEqual(slack.chat_postMessage.call_args_list[-1].kwargs["text"], "## Third")
+
+ def test_an_exhausted_budget_stops_before_the_composed_message(self):
+ # A partial spill already makes the caller repost the whole answer, so posting the
+ # composed message too would duplicate it in the thread and burn the chart delivery.
+ slack = MagicMock()
+ slack.chat_postMessage.return_value = {"ok": True, "ts": "1111.2"}
+ cards = [_SlackImageCard(TaskArtifact(name="Chart"), {}, file_id="F0")]
+
+ answer_posted = _post_composed_answer_message(
+ slack,
+ 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
+ )
+
+ self.assertFalse(answer_posted)
+ slack.chat_postMessage.assert_not_called()
+
@parameterized.expand(
[
("composed", 1),
@@ -815,6 +879,7 @@ 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.py
index 63564080c5d7..e74749cd2bac 100644
--- a/products/tasks/backend/temporal/slack_relay/activities.py
+++ b/products/tasks/backend/temporal/slack_relay/activities.py
@@ -5,6 +5,7 @@ from markdown_to_mrkdwn import SlackMarkdownConverter
from temporalio import activity
from posthog.dataclasses import frozen
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import close_db_connections
@@ -421,18 +422,6 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:
origin_product=mapping.task.origin_product,
)
- # Pending chart images compose into a single Slack message together with the answer
- # text (section blocks cap at 3000 chars, tighter than plain messages), so pick the
- # chunk limit before splitting.
- compose_with_charts = has_pending_slack_files and has_pending_slack_image_artifacts(task_run)
- 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.
- chunks = [_markdown_to_slack_mrkdwn(chunk) for chunk in _split_markdown_for_slack(text, limit=chunk_limit)]
-
context = SlackThreadContext(
integration_id=mapping.integration_id,
channel=mapping.channel,
@@ -453,7 +442,41 @@ 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)
- mention_prefix = f"<@{target}> " if target else ""
+
+ # 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()
+
+ # 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 " "
+ 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]
def _record_sent_relay(state: dict[str, Any]) -> None:
sent_relay_ids = state.get("slack_sent_relay_ids") or []
@@ -482,7 +505,9 @@ 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_posted
+ answer_posted = deliver_pending_slack_file_artifacts(
+ task_run, answer_sections=sections, answer_is_markdown=markdown
+ ).answer_posted
if 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.
@@ -493,7 +518,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)
+ handler.post_thread_message(f"{prefix}{chunk}", with_footer=index == len(chunks) - 1, markdown=markdown)
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.py
index 1182de855c47..e68629341323 100644
--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py
@@ -10,6 +10,7 @@ from django.test import TestCase, override_settings
from parameterized import parameterized
from slack_sdk.errors import SlackApiError
+from posthog.helpers.slack_markdown import SLACK_MARKDOWN_TEXT_MAX_LEN
from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
@@ -135,6 +136,79 @@ class TestRelaySlackMessage(TestCase):
assert mock_post.call_args.args[0].turn_trace_id == trace_id
+ _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,
+ )
+ )
+
+ assert mock_post.call_args.args[0].endswith(expected)
+
+ @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"),
+ ]
+ )
+ @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
+ ):
+ # 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.
+ 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.",
+ )
+ )
+
+ assert mock_post.call_args.args[0].startswith(expected_opening)
+
+ @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_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
+ )
+ )
+
+ assert all(len(call.args[0]) <= SLACK_MARKDOWN_TEXT_MAX_LEN for call in mock_post.call_args_list)
+
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")
@patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")
def test_relay_does_not_post_when_claim_write_fails(self, mock_delete_progress, mock_post):
@@ -550,7 +624,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)
+ mock_post.assert_called_once_with("<@U123> Here's the trend.", with_footer=True, markdown=False)
class TestMarkdownToSlackMrkdwn(unittest.TestCase):
@@ -1004,5 +1078,5 @@ class TestRelaySlackMessageChunking(TestCase):
)
)
- mock_post.assert_called_once_with("<@U456> Here you go.", with_footer=True)
+ mock_post.assert_called_once_with("<@U456> Here you go.", with_footer=True, markdown=False)
mock_post_footer.assert_not_called()