: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
feat(signals): post long scout reports to Slack as a thread (#86441)
posthog[bot]94af918b248a
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 5fd88b748738..6b9d7245c4fc 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -1963,6 +1963,15 @@ class SignalScoutSlackDestinationSerializer(serializers.Serializer):"Null while choosing a channel; no messages are sent until it is set."),)+ thread_reports = serializers.BooleanField(+ required=False,+ default=False,+ help_text=(+ "When true, post a report as a thread: a short lead in the channel and the rest split "+ "by the report's Markdown headings into replies. Keeps a long summary from being clipped "+ "at Slack's section limit. Off by default, and it does not change how findings post."+ ),+ )class SignalScoutOutputDestinationsSerializer(serializers.Serializer):diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.pyindex 35ed70846f3a..4450f604a9c5 100644--- a/products/signals/backend/scout_harness/slack_delivery.py+++ b/products/signals/backend/scout_harness/slack_delivery.py@@ -9,13 +9,17 @@ from django.conf import settingsimport structlogfrom slack_sdk.errors import SlackApiError+from posthog.dataclasses import frozenfrom posthog.models.integration import Integration, SlackIntegrationfrom products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRunfrom products.signals.backend.slack_formatting import (+ SLACK_SECTION_TEXT_MAX_LEN,+ chunk_slack_mrkdwn,escape_slack_mrkdwn,markdown_to_slack_mrkdwn,slack_channel_id_from_target,+ split_markdown_by_headings,strip_chart_references,truncate_slack_section,)@@ -53,6 +57,7 @@ _SCOUT_SLACK_REPLY_TEXT = "💬 If you have questions, reply in this thread andclass ScoutSlackDestination:integration_id: intchannel: str+ thread_reports: bool = Falseclass ScoutSlackPermanentDeliveryError(RuntimeError):@@ -74,7 +79,11 @@ def get_scout_slack_destination(output_destinations: object) -> ScoutSlackDestinreturn Noneif not isinstance(channel, str) or not channel.strip():return None- return ScoutSlackDestination(integration_id=integration_id, channel=channel.strip())+ return ScoutSlackDestination(+ integration_id=integration_id,+ channel=channel.strip(),+ thread_reports=slack.get("thread_reports") is True,+ )def slack_api_error_code(exc: SlackApiError) -> str | None:@@ -276,6 +285,75 @@ def build_scout_report_slack_message(report: SignalReport, run: SignalScoutRun)return blocks, fallback+def _report_summary_chunks(report: SignalReport) -> list[str]:+ """Convert the report summary to mrkdwn, splitting into thread chunks only when it is too long.++ A summary that fits one Slack section stays a single chunk, so a short report posts as one message+ however many headings it has. A longer one splits at its own Markdown headings, packing adjacent+ sections into as few chunks as each fits in one Slack section, so the reply count tracks content+ size rather than heading count and the thread keeps its full tail. The split runs after+ `strip_chart_references` so a chart link never straddles two messages."""+ summary_text = strip_chart_references((report.summary or "").strip())+ rendered = markdown_to_slack_mrkdwn(summary_text)+ if len(rendered) <= SLACK_SECTION_TEXT_MAX_LEN:+ return [rendered] if rendered else []+ chunks: list[str] = []+ current = ""+ for segment in split_markdown_by_headings(summary_text):+ rendered_segment = markdown_to_slack_mrkdwn(segment.strip())+ if not rendered_segment:+ continue+ candidate = f"{current}\n\n{rendered_segment}" if current else rendered_segment+ if len(candidate) <= SLACK_SECTION_TEXT_MAX_LEN:+ current = candidate+ continue+ # The running block is full: flush it, then hard-chunk the oversized segment on its line ends.+ # Keep the last piece open so a following short section packs onto it instead of opening a new reply.+ if current:+ chunks.append(current)+ segment_chunks = chunk_slack_mrkdwn(rendered_segment)+ chunks.extend(segment_chunks[:-1])+ current = segment_chunks[-1] if segment_chunks else ""+ if current:+ chunks.append(current)+ return chunks+++@frozen+class ScoutReportThreadMessages:+ """A threaded report delivery: the channel lead message plus its ordered thread replies."""++ lead_blocks: list[dict]+ fallback: str+ reply_blocks: list[list[dict]]+++def build_scout_report_thread_slack_messages(report: SignalReport, run: SignalScoutRun) -> ScoutReportThreadMessages:+ """Render a report as a channel lead plus one reply per remaining summary chunk.++ The lead carries the scout name, the report title, the first summary chunk, and the report link.+ Every later chunk becomes a threaded reply, so a long summary keeps its full tail in the channel+ instead of being clipped at the section cap."""+ scout_name = _prettify_scout_name(run.skill_name)+ header = _report_header(report)+ lead_blocks: list[dict] = [+ {+ "type": "context",+ "elements": [{"type": "mrkdwn", "text": f"*Scout · {escape_slack_mrkdwn(scout_name)}*"}],+ },+ {"type": "header", "text": {"type": "plain_text", "text": header}},+ ]++ chunks = _report_summary_chunks(report)+ if chunks:+ lead_blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": chunks[0]}})+ lead_blocks.append(_report_link_block(report))++ reply_blocks = [[{"type": "section", "text": {"type": "mrkdwn", "text": chunk}}] for chunk in chunks[1:]]+ fallback = f"Scout · {escape_slack_mrkdwn(scout_name)}: {escape_slack_mrkdwn(header[:200])}"+ return ScoutReportThreadMessages(lead_blocks=lead_blocks, fallback=fallback, reply_blocks=reply_blocks)++def build_scout_report_note_slack_message(report: SignalReport, run: SignalScoutRun, note: str) -> tuple[list[dict], str]:@@ -309,6 +387,42 @@ def build_scout_report_note_slack_message(return blocks, fallback+def _post_scout_report_thread_replies(+ client: object,+ *,+ channel_id: str,+ thread_ts: object,+ delivery_id: str,+ reply_blocks: list[list[dict]],+ fallback: str,+) -> None:+ """Post the remaining summary chunks as threaded replies under an already-delivered lead.++ Best-effort per reply: the lead already carries the report link, so a failed chunk logs and the+ delivery still succeeds rather than re-posting the lead on retry."""+ if not isinstance(thread_ts, str) or not thread_ts:+ return+ for index, blocks in enumerate(reply_blocks):+ try:+ client.chat_postMessage( # type: ignore[attr-defined]+ channel=channel_id,+ thread_ts=thread_ts,+ blocks=blocks,+ text=fallback,+ client_msg_id=f"{delivery_id}:{index}",+ unfurl_links=False,+ unfurl_media=False,+ )+ except Exception:+ logger.warning(+ "scout_slack_report_thread_reply_failed",+ channel=channel_id,+ delivery_id=delivery_id,+ chunk_index=index,+ exc_info=True,+ )++def post_scout_report_to_slack(report: SignalReport,run: SignalScoutRun,@@ -317,6 +431,7 @@ def post_scout_report_to_slack(integration_id: int,channel: str,edit_note: str | None = None,+ thread_reports: bool = False,) -> None:if report.team_id != run.team_id:raise ScoutSlackPermanentDeliveryError(@@ -329,11 +444,20 @@ def post_scout_report_to_slack(project_id=report.team.project_id,)channel_id = _slack_channel_id(channel)- blocks, fallback = (- build_scout_report_note_slack_message(report, run, edit_note)- if edit_note is not None- else build_scout_report_slack_message(report, run)- )+ # Threading applies to a full report only: a note edit is short and posts as a single update.+ threaded = thread_reports and edit_note is None+ reply_blocks: list[list[dict]] = []+ if edit_note is not None:+ blocks, fallback = build_scout_report_note_slack_message(report, run, edit_note)+ elif threaded:+ thread_messages = build_scout_report_thread_slack_messages(report, run)+ blocks, fallback, reply_blocks = (+ thread_messages.lead_blocks,+ thread_messages.fallback,+ thread_messages.reply_blocks,+ )+ else:+ blocks, fallback = build_scout_report_slack_message(report, run)client = SlackIntegration(integration).clienttry:response = client.chat_postMessage(@@ -353,10 +477,21 @@ def post_scout_report_to_slack() from excraise+ thread_ts = response.get("ts")+ if threaded:+ _post_scout_report_thread_replies(+ client,+ channel_id=channel_id,+ thread_ts=thread_ts,+ delivery_id=delivery_id,+ reply_blocks=reply_blocks,+ fallback=fallback,+ )+_post_scout_slack_reply(client,channel_id=channel_id,- thread_ts=response.get("ts"),+ thread_ts=thread_ts,scout_team_id=run.team_id,integration_team_id=integration.team_id,)diff --git a/products/signals/backend/scout_harness/slack_delivery_queue.py b/products/signals/backend/scout_harness/slack_delivery_queue.pyindex 160342dfcfaf..c94c151c0969 100644--- a/products/signals/backend/scout_harness/slack_delivery_queue.py+++ b/products/signals/backend/scout_harness/slack_delivery_queue.py@@ -55,6 +55,7 @@ def queue_configured_scout_slack_delivery(integration_id=destination.integration_id,channel=destination.channel,edit_note=edit_note[:MAX_SLACK_NOTE_SNAPSHOT_LEN] if edit_note is not None else None,+ thread_reports=destination.thread_reports,),robust=True,)diff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.pyindex 3050f6b4c045..6999674b9d31 100644--- a/products/signals/backend/slack_formatting.py+++ b/products/signals/backend/slack_formatting.py@@ -122,6 +122,123 @@ def truncate_slack_section(text: str) -> str:return text[: SLACK_SECTION_TEXT_MAX_LEN - 1].rstrip() + "…"+# A top-of-line ATX heading (`# `…`###### `). The scout writes its summary in Markdown, so its own+# headings are the natural seams to split a long report on for threaded Slack delivery.+_MARKDOWN_HEADING_RE = re.compile(r"^#{1,6}[ \t]+\S")+# Opens or closes a fenced code block (``` or ~~~, up to three leading spaces per CommonMark). A+# `# ` line inside a fence is code, not a heading: splitting there would orphan the fence and hand+# the snippet to the mrkdwn converter as prose.+_MARKDOWN_FENCE_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})")+++def _heading_line_offsets(text: str) -> list[int]:+ """Character offsets of the ATX heading lines, skipping any inside a fenced code block."""+ offsets: list[int] = []+ fence: str | None = None # marker of the currently open fence, else None+ offset = 0+ for line in text.split("\n"):+ fence_match = _MARKDOWN_FENCE_RE.match(line)+ if fence is not None:+ # Close only on the same fence character, at least as long as the opener (CommonMark).+ if fence_match and fence_match.group(1)[0] == fence[0] and len(fence_match.group(1)) >= len(fence):+ fence = None+ elif fence_match:+ fence = fence_match.group(1)+ elif _MARKDOWN_HEADING_RE.match(line):+ offsets.append(offset)+ offset += len(line) + 1 # +1 for the "\n" that split dropped+ return offsets+++def split_markdown_by_headings(text: str) -> list[str]:+ """Split a Markdown summary into the lead and one segment per heading.++ The first element is the text before the first heading (empty when the summary opens with one).+ Each later element is a heading and the body under it. Headings inside fenced code blocks are+ left in place, so a snippet is never split mid-fence. No content is dropped."""+ text = text.strip()+ if not text:+ return []+ starts = _heading_line_offsets(text)+ if not starts:+ return [text]+ segments = [text[: starts[0]]]+ for index, start in enumerate(starts):+ end = starts[index + 1] if index + 1 < len(starts) else len(text)+ segments.append(text[start:end])+ return segments+++# End of a sentence, allowing a closing quote or bracket before the space that follows it.+_SENTENCE_END_RE = re.compile(r"[.!?…][\"')\]]*\s")+_WHITESPACE_RUN_RE = re.compile(r"\s+")+# A converter-emitted angle token left open at the end of a candidate chunk, as in `<https://ex`.+# Slack renders each half of a broken link as visible junk, so a cut here moves back before the `<`.+_TRAILING_OPEN_ANGLE_RE = re.compile(r"<[^<>]*$")+# A break earlier than this share of the limit spends a whole reply on a stub, so the ladder in+# `_line_break_index` prefers the next (later-breaking) rung over an early sentence or word end.+_MIN_LINE_BREAK_FILL = 0.6+++def _pull_back_before_open_angle(window: str, index: int) -> int:+ """Move a cut back before an angle token it would otherwise split, or leave it alone."""+ match = _TRAILING_OPEN_ANGLE_RE.search(window[:index])+ return match.start() if match else index+++def _line_break_index(line: str, limit: int) -> int:+ """Index to cut a line that exceeds the limit on its own, preferring the most readable boundary.++ Tries a sentence end, then any whitespace, so a reply never opens mid-word. Falls back to the+ limit only for an unbreakable run such as a long URL or an encoded blob. Every rung stays out of+ an angle token, because half a link is worse to read than an early break."""+ window = line[:limit]+ floor = int(limit * _MIN_LINE_BREAK_FILL)+ for pattern in (_SENTENCE_END_RE, _WHITESPACE_RUN_RE):+ matches = list(pattern.finditer(window))+ if not matches:+ continue+ index = _pull_back_before_open_angle(window, matches[-1].end())+ if index >= floor:+ return index+ hard_cut = _pull_back_before_open_angle(window, limit)+ # A token longer than the whole window has nowhere safe to break, so the link is split anyway.+ return hard_cut if hard_cut > 0 else limit+++def chunk_slack_mrkdwn(text: str) -> list[str]:+ """Split converted mrkdwn into chunks that each fit one Slack section, breaking on line ends.++ A line longer than the limit on its own breaks at the best boundary `_line_break_index` finds,+ so a report written as unbroken prose still reads as sentences. Returns no empty chunks, so the+ tail of a long report reaches the channel instead of being clipped at the section cap."""+ text = text.strip()+ if not text:+ return []+ if len(text) <= SLACK_SECTION_TEXT_MAX_LEN:+ return [text]+ chunks: list[str] = []+ current = ""+ for line in text.split("\n"):+ while len(line) > SLACK_SECTION_TEXT_MAX_LEN:+ if current:+ chunks.append(current.rstrip())+ current = ""+ cut = _line_break_index(line, SLACK_SECTION_TEXT_MAX_LEN)+ chunks.append(line[:cut].rstrip())+ line = line[cut:]+ candidate = f"{current}\n{line}" if current else line+ if len(candidate) > SLACK_SECTION_TEXT_MAX_LEN:+ if current:+ chunks.append(current.rstrip())+ current = line+ else:+ current = candidate+ if current.strip():+ chunks.append(current.rstrip())+ return chunks++def slack_channel_id_from_target(value: str) -> str:"""Extract the Slack channel ID from the frontend picker's `id|#name` value."""return value.split("|", 1)[0].strip()diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 94389dededd8..6484b3f021e9 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -138,6 +138,7 @@ def deliver_scout_slack_output(integration_id: int,channel: str,edit_note: str | None = None,+ thread_reports: bool = False,) -> None:context = {"team_id": team_id,@@ -181,6 +182,7 @@ def deliver_scout_slack_output(integration_id=integration_id,channel=channel,edit_note=edit_note,+ thread_reports=thread_reports,)else:logger.warning("signals_scout.slack_delivery_output_type_invalid", **context)@@ -233,12 +235,17 @@ def enqueue_scout_slack_delivery(integration_id: int,channel: str,edit_note: str | None = None,+ thread_reports: bool = False,) -> None:"""Publish after commit, capturing broker failures without affecting the completed emit."""try:- # `edit_note` rides as a kwarg only when set, so every delivery without one keeps the+ # Each optional arg rides as a kwarg only when set, so a delivery without one keeps the# payload shape workers running the previous task signature still accept.- extra_kwargs: dict[str, str] = {"edit_note": edit_note} if edit_note is not None else {}+ extra_kwargs: dict[str, str | bool] = {}+ if edit_note is not None:+ extra_kwargs["edit_note"] = edit_note+ if thread_reports:+ extra_kwargs["thread_reports"] = Truedeliver_scout_slack_output.delay(team_id,output_type,diff --git a/products/signals/backend/test/test_scout_create_api.py b/products/signals/backend/test/test_scout_create_api.pyindex 37734694b343..78c8e2876897 100644--- a/products/signals/backend/test/test_scout_create_api.py+++ b/products/signals/backend/test/test_scout_create_api.py@@ -64,7 +64,9 @@ class TestSignalScoutCreateAPI(APIBaseTest):assert config.enabled is Falseassert config.emit is Falseassert config.run_cron_schedule == "30 9 * * 1-5"- assert config.output_destinations == payload["config"]["output_destinations"]+ assert config.output_destinations == {+ "slack": {**payload["config"]["output_destinations"]["slack"], "thread_reports": False}+ }assert response.json()["config"]["description"] == payload["description"]def test_create_stores_normalized_tags_from_the_config_block(self) -> None:diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex b3938dc7ea01..2f55626ee3c7 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -2114,7 +2114,9 @@ class TestScoutHarnessConfigAPI(APIBaseTest):)assert response.status_code == status.HTTP_200_OK- assert response.json()["output_destinations"] == destination+ # A partial update skips the `thread_reports` default, so the flag reaches the reader+ # through the response only and the stored destination keeps the shape it was sent in.+ assert response.json()["output_destinations"] == {"slack": {**destination["slack"], "thread_reports": False}}config.refresh_from_db()assert config.output_destinations == destinationdiff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.pyindex 0b9851242ce5..8d436dda85a7 100644--- a/products/signals/backend/test/test_scout_slack_delivery.py+++ b/products/signals/backend/test/test_scout_slack_delivery.py@@ -4,8 +4,10 @@ from unittest.mock import MagicMock, patchfrom django.apps import appsfrom django.conf import settings+from django.test import SimpleTestCasefrom celery.exceptions import Retry+from parameterized import parameterizedfrom slack_sdk.errors import SlackApiErrorfrom posthog.models import Team@@ -14,12 +16,30 @@ from posthog.models.integration import Integrationfrom products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRunfrom products.signals.backend.scout_harness.slack_delivery import (ScoutSlackPermanentDeliveryError,+ get_scout_slack_destination,post_scout_emission_to_slack,)from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_deliveryfrom products.signals.backend.tasks import deliver_scout_slack_output, enqueue_scout_slack_delivery+class TestGetScoutSlackDestination(SimpleTestCase):+ @parameterized.expand(+ [+ ("explicit_true", {"thread_reports": True}, True),+ ("omitted_defaults_off", {}, False),+ ("explicit_false", {"thread_reports": False}, False),+ # Only a real boolean True turns threading on; a truthy non-bool stays off.+ ("truthy_non_bool_stays_off", {"thread_reports": "yes"}, False),+ ]+ )+ def test_parses_thread_reports(self, _name: str, extra: dict, expected: bool) -> None:+ destination = get_scout_slack_destination({"slack": {"integration_id": 7, "channel": "C1|#x", **extra}})++ assert destination is not None+ assert destination.thread_reports is expected++class FakeSlackResponse(dict):def __init__(self, data: dict, headers: dict | None = None) -> None:super().__init__(data)@@ -202,6 +222,161 @@ class TestScoutSlackDelivery(BaseTest):assert delay.call_args_list[0].kwargs == {}assert delay.call_args_list[1].kwargs == {"edit_note": "Re-validated on the next run"}+ def test_enqueue_omits_thread_reports_kwarg_when_off(self) -> None:+ # Same backward-compat contract as edit_note: the flag rides as a kwarg only when on, so a+ # worker on the previous task signature never sees an unknown keyword for a default delivery.+ with patch.object(deliver_scout_slack_output, "delay") as delay:+ enqueue_scout_slack_delivery(+ team_id=self.team.id,+ output_type="report",+ output_id="ddab8ee5-2bb8-4226-b145-6732d31dc344",+ run_id="e3865391-bc89-44e6-86f7-2d4405627daf",+ delivery_id="b316c1d1-6901-49eb-8223-96d4df69f67f",+ integration_id=9,+ channel="CSCOUTS|#scout-findings",+ )+ enqueue_scout_slack_delivery(+ team_id=self.team.id,+ output_type="report",+ output_id="ddab8ee5-2bb8-4226-b145-6732d31dc344",+ run_id="e3865391-bc89-44e6-86f7-2d4405627daf",+ delivery_id="c4f7d2e2-7012-4afc-9334-a7e5df70a80a",+ integration_id=9,+ channel="CSCOUTS|#scout-findings",+ thread_reports=True,+ )++ assert delay.call_args_list[0].kwargs == {}+ assert delay.call_args_list[1].kwargs == {"thread_reports": True}++ def test_threaded_report_posts_lead_and_delivers_the_full_tail(self) -> None:+ # The bug: a summary past the section cap was truncated with an ellipsis, so the tail never+ # reached the channel. With thread_reports on, the lead posts to the channel and the rest+ # rides as threaded replies, so a distinctive tail marker still arrives.+ emission = self._make_emission()+ tail_marker = "TAIL_MARKER_9137"+ summary = (+ "Lead paragraph before any heading.\n\n"+ "## First finding\n" + ("First body line.\n" * 400) + "\n"+ "## Second finding\n" + ("Second body line.\n" * 400) + f"\nClosing note {tail_marker}."+ )+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary=summary,+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000500"}++ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ "CSCOUTS|#scout-findings",+ thread_reports=True,+ )++ calls = fake_client.chat_postMessage.call_args_list+ lead = calls[0].kwargs+ assert "thread_ts" not in lead+ assert lead["blocks"][1]["text"]["text"] == "Checkout failures"+ replies = calls[1:]+ assert len(replies) > 1+ assert all(reply.kwargs["thread_ts"] == "1785418710.000500" for reply in replies)+ # Every posted section stays within the cap, and nothing is ellipsis-truncated.+ section_texts = [+ block["text"]["text"] for call in calls for block in call.kwargs["blocks"] if block["type"] == "section"+ ]+ assert all(len(text) <= 2900 for text in section_texts)+ assert not any(text.endswith("…") for text in section_texts)+ assert any(tail_marker in text for text in section_texts)++ def test_threaded_short_report_with_headings_posts_a_single_message(self) -> None:+ # Threading must track content size, not heading count: a short report that fits one Slack+ # section posts as one message however many headings it has, so it never floods a thread.+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Lead line.\n\n## First\nshort body\n\n## Second\nshort body",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000600"}++ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ "CSCOUTS|#scout-findings",+ thread_reports=True,+ )++ # Only the lead message and the unconditional @PostHog follow-up reply — no per-heading replies.+ calls = fake_client.chat_postMessage.call_args_list+ assert len(calls) == 2+ assert "thread_ts" not in calls[0].kwargs+ section_texts = [block["text"]["text"] for block in calls[0].kwargs["blocks"] if block["type"] == "section"]+ assert len(section_texts) == 1+ assert "First" in section_texts[0] and "Second" in section_texts[0]+ assert calls[1].kwargs["blocks"][0]["type"] == "context"++ def test_threaded_report_packs_many_small_headings_into_few_replies(self) -> None:+ # A report past the section cap made of many small heading sections must pack adjacent+ # sections up to the Slack limit, not post one reply per heading. Otherwise the reply count+ # tracks heading count and a heading-dense report bursts a request per heading into the thread.+ emission = self._make_emission()+ heading_count = 50+ summary = "".join(+ f"## Section {i}\nBody line for section {i} with a bit of detail to add length.\n\n"+ for i in range(heading_count)+ )+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary=summary,+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000700"}++ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ "CSCOUTS|#scout-findings",+ thread_reports=True,+ )++ calls = fake_client.chat_postMessage.call_args_list+ section_texts = [+ block["text"]["text"] for call in calls for block in call.kwargs["blocks"] if block["type"] == "section"+ ]+ # Packed: far fewer sections than headings, each within the cap, and no section is dropped.+ assert len(section_texts) < heading_count // 5+ assert all(len(text) <= 2900 for text in section_texts)+ joined = "\n".join(section_texts)+ assert all(f"Section {i}" in joined for i in range(heading_count))+def test_reply_posted_regardless_of_ai_approval(self) -> None:# The Slack follow-up invite is unconditional — no AI-approval gate on scout output.self.organization.is_ai_data_processing_approved = Falsediff --git a/products/signals/backend/test/test_signal_scout_models.py b/products/signals/backend/test/test_signal_scout_models.pyindex 6d88f994235d..72b5d9dbab52 100644--- a/products/signals/backend/test/test_signal_scout_models.py+++ b/products/signals/backend/test/test_signal_scout_models.py@@ -120,6 +120,7 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):integration_id=17,channel="CSCOUTS|#scout-findings",edit_note=None,+ thread_reports=False,)def test_enabling_scout_logs_activity(self) -> None:diff --git a/products/signals/backend/test/test_slack_formatting.py b/products/signals/backend/test/test_slack_formatting.pyindex e374023cf457..d2d72e6b71bc 100644--- a/products/signals/backend/test/test_slack_formatting.py+++ b/products/signals/backend/test/test_slack_formatting.py@@ -4,7 +4,13 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from products.signals.backend.slack_formatting import markdown_to_slack_mrkdwn, strip_chart_references+from products.signals.backend.slack_formatting import (+ SLACK_SECTION_TEXT_MAX_LEN,+ chunk_slack_mrkdwn,+ markdown_to_slack_mrkdwn,+ split_markdown_by_headings,+ strip_chart_references,+)class TestStripChartReferences(SimpleTestCase):@@ -85,3 +91,100 @@ class TestStripChartReferences(SimpleTestCase):strip_chart_references(summary)assert time.perf_counter() - started < 0.5+++class TestSplitMarkdownByHeadings(SimpleTestCase):+ def test_lead_precedes_one_segment_per_heading(self) -> None:+ summary = "Intro line.\n\n## First\nbody one\n\n### Second\nbody two"+ segments = split_markdown_by_headings(summary)++ assert segments[0].strip() == "Intro line."+ assert segments[1].startswith("## First")+ assert segments[2].startswith("### Second")+ assert len(segments) == 3++ def test_leading_heading_yields_empty_lead(self) -> None:+ segments = split_markdown_by_headings("## Only\nbody")++ assert segments[0] == ""+ assert segments[1].startswith("## Only")++ def test_summary_without_headings_stays_one_segment(self) -> None:+ assert split_markdown_by_headings("no headings here") == ["no headings here"]++ def test_empty_summary_yields_no_segments(self) -> None:+ assert split_markdown_by_headings(" ") == []++ @parameterized.expand([("backtick_fence", "```"), ("tilde_fence", "~~~")])+ def test_column_zero_hash_inside_a_fence_does_not_split(self, _name: str, fence: str) -> None:+ # The bug this guards: a `# ` line inside a fenced code block used to be read as a heading and+ # split there, orphaning the fence and mangling the snippet when each segment was converted.+ summary = f"Intro.\n\n{fence}\n# not a heading\nconfig value\n{fence}\n\nTail."+ assert split_markdown_by_headings(summary) == [summary]++ def test_real_heading_after_a_fence_still_splits(self) -> None:+ summary = "```\n# in code\n```\n\n## Real heading\nbody"+ segments = split_markdown_by_headings(summary)++ assert segments[0].strip() == "```\n# in code\n```"+ assert segments[1].startswith("## Real heading")+ assert len(segments) == 2+++class TestChunkSlackMrkdwn(SimpleTestCase):+ def test_short_text_is_one_chunk(self) -> None:+ assert chunk_slack_mrkdwn("short") == ["short"]++ def test_long_text_splits_within_the_section_limit_without_losing_the_tail(self) -> None:+ # The bug this guards: a summary past the section cap used to be truncated with an ellipsis,+ # dropping everything after ~2,900 characters. Chunking must keep every line.+ lines = [f"line {index}" for index in range(600)]+ chunks = chunk_slack_mrkdwn("\n".join(lines))++ assert len(chunks) > 1+ assert all(len(chunk) <= SLACK_SECTION_TEXT_MAX_LEN for chunk in chunks)+ recovered = "\n".join(chunks)+ assert all(line in recovered for line in lines)++ @parameterized.expand(+ [+ ("plain_run", "x" * (SLACK_SECTION_TEXT_MAX_LEN * 2 + 5)),+ ("link_longer_than_a_section", "<https://example.com/" + "z" * (SLACK_SECTION_TEXT_MAX_LEN * 2) + "|l>"),+ ]+ )+ def test_unbreakable_run_is_hard_sliced(self, _name: str, line: str) -> None:+ # A run with no sentence, word, or token boundary has nowhere safe to break, so it is sliced+ # at the limit. Guards both halves of that fallback: it has to terminate, and it has to keep+ # every character rather than dropping the remainder.+ chunks = chunk_slack_mrkdwn(line)++ assert all(len(chunk) <= SLACK_SECTION_TEXT_MAX_LEN for chunk in chunks)+ assert "".join(chunks) == line++ @parameterized.expand(+ [+ ("sentence_ends", "The mount call times out and the retry never fires. "),+ ("no_sentence_ends", "mount timeout retry never fires again "),+ ]+ )+ def test_text_only_report_never_breaks_mid_word(self, _name: str, sentence: str) -> None:+ # The bug this guards: a report with no Markdown headings is one long line, which used to be+ # sliced at exactly the section cap, so a reply opened mid-word ("...since Tue" / "sday and+ # the retry..."). Comparing word sequences catches that, because a mid-word cut turns one+ # word into two and no longer round-trips.+ line = (sentence * 400).strip()+ chunks = chunk_slack_mrkdwn(line)++ assert len(chunks) > 1+ assert all(len(chunk) <= SLACK_SECTION_TEXT_MAX_LEN for chunk in chunks)+ assert " ".join(chunks).split() == line.split()++ def test_link_spanning_the_section_boundary_is_kept_whole(self) -> None:+ # The bug this guards: a cut inside a converter-emitted `<url|label>` token leaves half a+ # link in each message, and Slack renders both halves as visible junk.+ link = "<https://example.com/a/very/long/path|the failing request>"+ line = "x" * (SLACK_SECTION_TEXT_MAX_LEN - 20) + link + " and the prose that follows it."+ chunks = chunk_slack_mrkdwn(line)++ assert all(len(chunk) <= SLACK_SECTION_TEXT_MAX_LEN for chunk in chunks)+ assert any(link in chunk for chunk in chunks)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 8881d975d4c7..c60b89712877 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -1876,6 +1876,8 @@ export interface SignalScoutSlackDestinationApi {* @nullable*/channel?: string | null+ /** When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post. */+ thread_reports?: boolean}export interface SignalScoutOutputDestinationsApi {diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 37b82fdafe8b..bcd358ebdf91 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -336,6 +336,7 @@ export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax = 255+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault = falseexport const signalsScoutCreateBodyConfigOneRunCronScheduleMax = 100export const signalsScoutCreateBodyConfigOneModelMax = 200@@ -416,6 +417,14 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod.describe("Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."),+ thread_reports: zod+ .boolean()+ .default(+ signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault+ )+ .describe(+ "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post."+ ),}),zod.null(),])@@ -506,6 +515,7 @@ export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax = 255+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneThreadReportsDefault = falseexport const signalsScoutConfigCreateBodyRunCronScheduleMax = 100export const signalsScoutConfigCreateBodyModelMax = 200@@ -549,6 +559,12 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod.describe("Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."),+ thread_reports: zod+ .boolean()+ .default(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneThreadReportsDefault)+ .describe(+ "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post."+ ),}),zod.null(),])@@ -628,6 +644,7 @@ export const signalsScoutConfigUpdateBodyRunCronScheduleMax = 100export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax = 255+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneThreadReportsDefault = falseexport const signalsScoutConfigUpdateBodyModelMax = 200export const signalsScoutConfigUpdateBodyTagsMax = 10@@ -679,6 +696,12 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod.describe("Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."),+ thread_reports: zod+ .boolean()+ .default(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneThreadReportsDefault)+ .describe(+ "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post."+ ),}),zod.null(),])diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsxindex c32197942744..c3cd76521505 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx@@ -1,7 +1,7 @@import { useMountedLogic, useValues } from 'kea'import { IconTrash } from '@posthog/icons'-import { LemonButton, LemonSelect, Link } from '@posthog/lemon-ui'+import { LemonButton, LemonSelect, LemonSwitch, Link } from '@posthog/lemon-ui'import { integrationsLogic } from 'lib/integrations/integrationsLogic'import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'@@ -41,7 +41,27 @@ export function ScoutSlackDestination({return}onChange({- slack: { integration_id: selectedIntegration.id, channel },+ slack: {+ integration_id: selectedIntegration.id,+ channel,+ thread_reports: destination?.thread_reports ?? false,+ },+ })+ }++ const setThreadReports = (threadReports: boolean): void => {+ // Toggle threading only against the stored destination's own workspace. Writing a fallback+ // integration id next to the stored channel would pair the channel with a different+ // workspace and break delivery, so require the configured integration to resolve here.+ if (!configuredIntegration || !destination?.channel) {+ return+ }+ onChange({+ slack: {+ integration_id: configuredIntegration.id,+ channel: destination.channel,+ thread_reports: threadReports,+ },})}@@ -106,6 +126,17 @@ export function ScoutSlackDestination({: 'Pick a channel to turn notifications on. PostHog must be in the channel. Invite it with '}<code>/invite @PostHog</code>.</span>+ {configuredIntegration && hasChannel ? (+ <LemonSwitch+ size="small"+ checked={destination?.thread_reports ?? false}+ onChange={setThreadReports}+ disabledReason={disabledReason}+ label="Post long reports as a thread"+ tooltip="Post a short lead in the channel and split the rest by the report's headings into replies, so a long summary is not cut off."+ bordered+ />+ ) : null}</div>)}</div>diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1199c731bb4f..7eee34cb9185 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -62820,6 +62820,8 @@ export namespace Schemas {* @nullable*/channel?: string | null;+ /** When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post. */+ thread_reports?: boolean;}export interface SignalScoutOutputDestinations {diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex 8c8f61b5be31..3a71663f98fa 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -424,6 +424,7 @@ export const signalsScoutCreateBodyConfigOneRunIntervalMinutesMax = 43200export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneChannelMax = 255+export const signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault = falseexport const signalsScoutCreateBodyConfigOneRunCronScheduleMax = 100export const signalsScoutCreateBodyConfigOneModelMax = 200@@ -504,6 +505,14 @@ export const SignalsScoutCreateBody = /* @__PURE__ */ zod.describe("Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."),+ thread_reports: zod+ .boolean()+ .default(+ signalsScoutCreateBodyConfigOneOutputDestinationsOneSlackOneThreadReportsDefault+ )+ .describe(+ "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post."+ ),}),zod.null(),])@@ -609,6 +618,7 @@ export const signalsScoutConfigCreateBodyRunIntervalMinutesMax = 43200export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneChannelMax = 255+export const signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneThreadReportsDefault = falseexport const signalsScoutConfigCreateBodyRunCronScheduleMax = 100export const signalsScoutConfigCreateBodyModelMax = 200@@ -652,6 +662,12 @@ export const SignalsScoutConfigCreateBody = /* @__PURE__ */ zod.describe("Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."),+ thread_reports: zod+ .boolean()+ .default(signalsScoutConfigCreateBodyOutputDestinationsOneSlackOneThreadReportsDefault)+ .describe(+ "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post."+ ),}),zod.null(),])@@ -740,6 +756,7 @@ export const signalsScoutConfigUpdateBodyRunCronScheduleMax = 100export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneChannelMax = 255+export const signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneThreadReportsDefault = falseexport const signalsScoutConfigUpdateBodyModelMax = 200export const signalsScoutConfigUpdateBodyTagsMax = 10@@ -791,6 +808,12 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod.describe("Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until it is set."),+ thread_reports: zod+ .boolean()+ .default(signalsScoutConfigUpdateBodyOutputDestinationsOneSlackOneThreadReportsDefault)+ .describe(+ "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post."+ ),}),zod.null(),])diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.jsonindex 71f54c49e808..23e960ae86cb 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-create.json@@ -62,6 +62,11 @@"description": "ID of the Slack integration whose bot posts this scout's findings and reports.","minimum": 1,"type": "number"+ },+ "thread_reports": {+ "default": false,+ "description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",+ "type": "boolean"}},"required": ["integration_id"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.jsonindex d6b8b1263126..44490541ecc6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-config-update.json@@ -65,6 +65,11 @@"description": "ID of the Slack integration whose bot posts this scout's findings and reports.","minimum": 1,"type": "number"+ },+ "thread_reports": {+ "default": false,+ "description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",+ "type": "boolean"}},"required": ["integration_id"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.jsonindex e3539112831f..deaa563afa91 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/scout-create-prepare.json@@ -69,6 +69,11 @@"description": "ID of the Slack integration whose bot posts this scout's findings and reports.","minimum": 1,"type": "number"+ },+ "thread_reports": {+ "default": false,+ "description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",+ "type": "boolean"}},"required": ["integration_id"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.jsonindex 71f54c49e808..23e960ae86cb 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-create.json@@ -62,6 +62,11 @@"description": "ID of the Slack integration whose bot posts this scout's findings and reports.","minimum": 1,"type": "number"+ },+ "thread_reports": {+ "default": false,+ "description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",+ "type": "boolean"}},"required": ["integration_id"],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.jsonindex d6b8b1263126..44490541ecc6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-update.json@@ -65,6 +65,11 @@"description": "ID of the Slack integration whose bot posts this scout's findings and reports.","minimum": 1,"type": "number"+ },+ "thread_reports": {+ "default": false,+ "description": "When true, post a report as a thread: a short lead in the channel and the rest split by the report's Markdown headings into replies. Keeps a long summary from being clipped at Slack's section limit. Off by default, and it does not change how findings post.",+ "type": "boolean"}},"required": ["integration_id"],