: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): add @PostHog follow-up nudge to scout Slack output (#75479)
Radu Raicea4051dfb7adc5
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.pyindex bc8fdbba74ff..b62671e4b3e3 100644--- a/products/signals/backend/scout_harness/slack_delivery.py+++ b/products/signals/backend/scout_harness/slack_delivery.py@@ -6,6 +6,7 @@ from urllib.parse import quotefrom django.conf import settings+import structlogfrom slack_sdk.errors import SlackApiErrorfrom posthog.models.integration import Integration, SlackIntegration@@ -19,6 +20,8 @@ from products.signals.backend.slack_formatting import (truncate_slack_section,)+logger = structlog.get_logger(__name__)+_PERMANENT_SLACK_ERROR_CODES = frozenset({"account_inactive",@@ -37,6 +40,9 @@ _PERMANENT_SLACK_ERROR_CODES = frozenset(ScoutSlackOutputType = Literal["finding", "report"]+# Posted as an in-thread reply under every scout Slack message, inviting @PostHog follow-ups.+_SCOUT_SLACK_REPLY_TEXT = "💬 If you have questions, reply in this thread and mention *`@PostHog`*!"+@dataclass(frozen=True)class ScoutSlackDestination:@@ -71,6 +77,44 @@ def slack_api_error_code(exc: SlackApiError) -> str | None:return error_code if isinstance(error_code, str) else None+def _post_scout_slack_reply(+ client: object,+ *,+ channel_id: str,+ thread_ts: object,+ scout_team_id: int,+ integration_team_id: int,+) -> None:+ """Invite @PostHog follow-ups when the Slack connection uses the scout's environment.++ Best-effort and non-blocking: the scout message itself has already been delivered, so a failed+ or missing follow-up never fails the delivery (and so never re-posts the parent on retry).+ """+ if integration_team_id != scout_team_id:+ logger.info(+ "scout_slack_followup_reply_skipped_environment_mismatch",+ scout_team_id=scout_team_id,+ integration_team_id=integration_team_id,+ channel=channel_id,+ )+ return+ if not isinstance(thread_ts, str) or not thread_ts:+ return+ try:+ client.chat_postMessage( # type: ignore[attr-defined]+ channel=channel_id,+ thread_ts=thread_ts,+ blocks=[{"type": "context", "elements": [{"type": "mrkdwn", "text": _SCOUT_SLACK_REPLY_TEXT}]}],+ text=_SCOUT_SLACK_REPLY_TEXT,+ unfurl_links=False,+ unfurl_media=False,+ )+ except Exception:+ # Swallow everything (not just SlackApiError): a transport-level failure here must never+ # fail the task and retry the already-delivered parent message.+ logger.warning("scout_slack_followup_reply_failed", channel=channel_id, exc_info=True)++def _prettify_scout_name(skill_name: str) -> str:cleaned = skill_name.removeprefix("signals-scout-").replace("-", " ").replace("_", " ").strip()return cleaned[:1].upper() + cleaned[1:] if cleaned else "Scout"@@ -159,8 +203,9 @@ def post_scout_emission_to_slack(channel_id = _slack_channel_id(channel)blocks, fallback = build_scout_slack_message(emission)+ client = SlackIntegration(integration).clienttry:- SlackIntegration(integration).client.chat_postMessage(+ response = client.chat_postMessage(channel=channel_id,blocks=blocks,text=fallback,@@ -177,6 +222,14 @@ def post_scout_emission_to_slack() from excraise+ _post_scout_slack_reply(+ client,+ channel_id=channel_id,+ thread_ts=response.get("ts"),+ scout_team_id=emission.team_id,+ integration_team_id=integration.team_id,+ )+def build_scout_report_slack_message(report: SignalReport, run: SignalScoutRun) -> tuple[list[dict], str]:scout_name = _prettify_scout_name(run.skill_name)@@ -232,8 +285,9 @@ def post_scout_report_to_slack()channel_id = _slack_channel_id(channel)blocks, fallback = build_scout_report_slack_message(report, run)+ client = SlackIntegration(integration).clienttry:- SlackIntegration(integration).client.chat_postMessage(+ response = client.chat_postMessage(channel=channel_id,blocks=blocks,text=fallback,@@ -249,3 +303,11 @@ def post_scout_report_to_slack(error_code=error_code,) from excraise++ _post_scout_slack_reply(+ client,+ channel_id=channel_id,+ thread_ts=response.get("ts"),+ scout_team_id=run.team_id,+ integration_team_id=integration.team_id,+ )diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.pyindex 30c35523abe7..6b064ce93cf0 100644--- a/products/signals/backend/test/test_scout_slack_delivery.py+++ b/products/signals/backend/test/test_scout_slack_delivery.py@@ -55,7 +55,7 @@ class TestScoutSlackDelivery(BaseTest):source_id=f"run:{run.id}:finding:checkout-500s",)- def test_posts_safe_slack_mrkdwn_through_project_integration_with_stable_delivery_id(self) -> None:+ def test_posts_safe_mrkdwn_but_does_not_invite_followup_for_child_environment(self) -> None:emission = self._make_emission("**Checkout** failures [trace](https://example.com/trace) <!channel> [ping](!here)")@@ -67,6 +67,7 @@ class TestScoutSlackDelivery(BaseTest):)integration = Integration.objects.create(team=child_team, kind=Integration.IntegrationKind.SLACK)fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000100"}with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:slack_integration.return_value.client = fake_client@@ -76,9 +77,10 @@ class TestScoutSlackDelivery(BaseTest):channel="CSCOUTS|#scout-findings",)- call = fake_client.chat_postMessage.call_args.kwargs+ call = fake_client.chat_postMessage.call_args_list[0].kwargsassert call["channel"] == "CSCOUTS"assert call["client_msg_id"] == str(emission.id)+ assert "thread_ts" not in callsection = call["blocks"][1]["text"]["text"]assert "*Checkout*" in sectionassert "<https://example.com/trace|trace>" in section@@ -88,6 +90,7 @@ class TestScoutSlackDelivery(BaseTest):assert call["blocks"][-1]["elements"][0]["url"] == (f"{settings.SITE_URL}/project/{self.team.id}/inbox/scouts/signals-scout-error-tracking/checkout%2F500s")+ assert fake_client.chat_postMessage.call_count == 1def test_posts_report_with_safe_markdown_and_delivery_id(self) -> None:emission = self._make_emission()@@ -99,6 +102,7 @@ class TestScoutSlackDelivery(BaseTest):)integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000200"}delivery_id = "01864f4c-6957-7d3f-8d85-1d775e527265"with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:@@ -113,9 +117,10 @@ class TestScoutSlackDelivery(BaseTest):"CSCOUTS|#scout-findings",)- call = fake_client.chat_postMessage.call_args.kwargs+ call = fake_client.chat_postMessage.call_args_list[0].kwargsassert call["channel"] == "CSCOUTS"assert call["client_msg_id"] == delivery_id+ assert "thread_ts" not in callsection = call["blocks"][2]["text"]["text"]assert "*Checkout*" in sectionassert "<!channel>" not in section@@ -124,6 +129,58 @@ class TestScoutSlackDelivery(BaseTest):assert call["blocks"][-1]["elements"][0]["url"] == (f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}")+ reply = fake_client.chat_postMessage.call_args_list[1].kwargs+ assert reply["thread_ts"] == "1785418710.000200"+ assert reply["blocks"][0]["type"] == "context"++ 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 = False+ self.organization.save()+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Checkout failed",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000400"}++ 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",+ )++ assert fake_client.chat_postMessage.call_count == 2+ reply = fake_client.chat_postMessage.call_args_list[1].kwargs+ assert reply["thread_ts"] == "1785418710.000400"++ def test_reply_transport_failure_does_not_fail_delivery(self) -> None:+ # The parent message already landed, so a failing follow-up reply — even a non-SlackApiError+ # transport error — must be swallowed rather than fail the task and retry the whole delivery.+ emission = self._make_emission()+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.side_effect = [{"ts": "1785418710.000500"}, ConnectionError("boom")]++ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:+ slack_integration.return_value.client = fake_client+ post_scout_emission_to_slack(+ emission,+ integration_id=integration.id,+ channel="CSCOUTS|#scout-findings",+ )++ assert fake_client.chat_postMessage.call_count == 2def test_task_skips_report_suppressed_before_delivery(self) -> None:emission = self._make_emission()