:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): post loop reports to Slack (#76948)
Dylan Martin5aed73f63606
diff --git a/products/tasks/backend/loop_notifications.py b/products/tasks/backend/loop_notifications.pyindex 6a11b1cc0adb..27a9ff19ad1b 100644--- a/products/tasks/backend/loop_notifications.py+++ b/products/tasks/backend/loop_notifications.py@@ -9,7 +9,7 @@ Celery task and Temporal activity contexts alike, no request assumed.(all optional): ``title`` / ``body`` override the generated copy, ``url``links to the run or PR, ``task_id`` / ``task_run_id`` identify the run forpush deep-linking and email idempotency, ``report`` is the run's final agent-message, delivered in the email body only.+message, delivered in email and Slack bodies."""from typing import Any@@ -66,7 +66,7 @@ def dispatch_loop_event(loop: Loop, event: str, payload: dict[str, Any]) -> Noneconfig = loop.notifications if isinstance(loop.notifications, dict) else {}_send_push(loop, event, title, payload, config.get("push") or {})_send_email(loop, event, title, body, payload, config.get("email") or {})- _send_slack(loop, event, title, body, config.get("slack") or {})+ _send_slack(loop, event, title, body, payload, config.get("slack") or {})def _event_copy(loop: Loop, event: str, payload: dict[str, Any]) -> tuple[str, str]:@@ -176,7 +176,9 @@ def _send_email(logger.warning("loop_notifications.email_failed", loop_id=str(loop.id), loop_event=event, exc_info=True)-def _send_slack(loop: Loop, event: str, title: str, body: str, channel_config: dict[str, Any]) -> None:+def _send_slack(+ loop: Loop, event: str, title: str, body: str, payload: dict[str, Any], channel_config: dict[str, Any]+) -> None:if not _channel_enabled(channel_config, event):returnparams = channel_config.get("params") or {}@@ -191,7 +193,9 @@ def _send_slack(loop: Loop, event: str, title: str, body: str, channel_config: d"loop_notifications.slack_integration_missing", loop_id=str(loop.id), integration_id=integration_id)return- text = _truncate(f"*{title}*\n{body}", _SLACK_BODY_MAX_CHARS)+ report = payload.get("report")+ slack_body = str(report) if report else body+ text = _truncate(f"*{_escape_slack_mrkdwn(title)}*\n{_escape_slack_mrkdwn(slack_body)}", _SLACK_BODY_MAX_CHARS)SlackIntegration(integration).client.chat_postMessage(channel=channel, text=text, unfurl_links=False, unfurl_media=False)@@ -246,3 +250,7 @@ def _truncate(text: str, limit: int) -> str:if len(text) <= limit:return textreturn text[: limit - 1] + "…"+++def _escape_slack_mrkdwn(text: str) -> str:+ return text.replace("&", "&").replace("<", "<").replace(">", ">")diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex 62212f8fe4cc..5de9c4363b04 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -691,7 +691,7 @@ def _tool_args_preview(raw_input: Any) -> str | None:def _extract_agent_message_text(event_data: dict) -> str | None:- """Text delta from an agent message event, else None."""+ """Text from an agent message event, else None."""pi_event = _pi_conversation_event(event_data)if pi_event is not None and pi_event.get("type") == "assistant_message_chunk":content = pi_event.get("content")@@ -705,7 +705,7 @@ def _extract_agent_message_text(event_data: dict) -> str | None:return Noneparams = notification.get("params") or {}update = params.get("update") or {}- if update.get("sessionUpdate") != "agent_message_chunk":+ if update.get("sessionUpdate") not in {"agent_message", "agent_message_chunk"}:return Nonecontent = update.get("content")if not isinstance(content, dict):diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex 9c48c63dce23..e634f6d667ed 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -849,6 +849,16 @@ def _agent_chunk_event(text: str) -> dict:}+def _agent_message_event(text: str) -> dict:+ return {+ "type": "notification",+ "notification": {+ "method": "session/update",+ "params": {"update": {"sessionUpdate": "agent_message", "content": {"type": "text", "text": text}}},+ },+ }++class TestFinalMessageTracker:def test_snapshots_joined_prose_at_end_of_turn(self) -> None:tracker = FinalMessageTracker()@@ -857,6 +867,12 @@ class TestFinalMessageTracker:assert tracker.end_turn() == "Weekly summary."+ def test_snapshots_full_agent_message_at_end_of_turn(self) -> None:+ tracker = FinalMessageTracker()+ tracker.collect(_agent_message_event("Weekly summary."))++ assert tracker.end_turn() == "Weekly summary."+def test_tool_only_turn_returns_none_so_prior_report_survives(self) -> None:tracker = FinalMessageTracker()tracker.collect(_agent_chunk_event("The report."))diff --git a/products/tasks/backend/tests/test_loop_notifications.py b/products/tasks/backend/tests/test_loop_notifications.pyindex 4b315704f324..cd31b316f8a2 100644--- a/products/tasks/backend/tests/test_loop_notifications.py+++ b/products/tasks/backend/tests/test_loop_notifications.py@@ -248,3 +248,90 @@ class TestDispatchLoopEventEmailReport(LoopNotificationsTestCase):mock_email_message_cls.assert_called_once()template_context = mock_email_message_cls.call_args.kwargs["template_context"]self.assertEqual(template_context["report"], expected_report)+++class TestDispatchLoopEventSlackReport(LoopNotificationsTestCase):+ def setUp(self):+ super().setUp()+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T123",+ config={"team": {"id": "T123"}},+ sensitive_config={"access_token": "xoxb-test"},+ )++ def create_loop_with_slack(self, **overrides) -> Loop:+ notifications = {+ "slack": {+ "enabled": True,+ "events": ["run_completed"],+ "params": {"integration_id": self.integration.id, "channel": "C123"},+ }+ }+ return self.create_loop(notifications=notifications, **overrides)++ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.create_notification")+ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.SlackIntegration")+ def test_slack_body_uses_report_when_present(self, mock_slack_cls, _mock_create_notification):+ loop = self.create_loop_with_slack()+ fake_client = MagicMock()+ mock_slack_cls.return_value.client = fake_client++ dispatch_loop_event(loop, "run_completed", {"report": "Weekly summary: all green."})++ fake_client.chat_postMessage.assert_called_once_with(+ channel="C123",+ text='*Loop "Daily digest" finished*\nWeekly summary: all green.',+ unfurl_links=False,+ unfurl_media=False,+ )++ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.create_notification")+ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.SlackIntegration")+ def test_slack_report_escapes_control_tokens(self, mock_slack_cls, _mock_create_notification):+ loop = self.create_loop_with_slack(name='Digest <!channel> & "more"')+ fake_client = MagicMock()+ mock_slack_cls.return_value.client = fake_client++ dispatch_loop_event(loop, "run_completed", {"report": "Investigate <!channel> and <https://evil.test|this>."})++ fake_client.chat_postMessage.assert_called_once_with(+ channel="C123",+ text=(+ '*Loop "Digest <!channel> & "more"" finished*\n'+ "Investigate <!channel> and <https://evil.test|this>."+ ),+ unfurl_links=False,+ unfurl_media=False,+ )++ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.create_notification")+ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.SlackIntegration")+ def test_slack_body_falls_back_to_default_body_without_report(self, mock_slack_cls, _mock_create_notification):+ loop = self.create_loop_with_slack()+ fake_client = MagicMock()+ mock_slack_cls.return_value.client = fake_client++ dispatch_loop_event(loop, "run_completed", {})++ fake_client.chat_postMessage.assert_called_once_with(+ channel="C123",+ text='*Loop "Daily digest" finished*\nThe run finished successfully.',+ unfurl_links=False,+ unfurl_media=False,+ )++ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.create_notification")+ @patch(f"{LOOP_NOTIFICATIONS_MODULE}.SlackIntegration")+ def test_slack_report_is_truncated_to_slack_body_limit(self, mock_slack_cls, _mock_create_notification):+ loop = self.create_loop_with_slack()+ fake_client = MagicMock()+ mock_slack_cls.return_value.client = fake_client++ dispatch_loop_event(loop, "run_completed", {"report": "x" * 4000})++ text = fake_client.chat_postMessage.call_args.kwargs["text"]+ self.assertEqual(len(text), 3000)+ self.assertTrue(text.startswith('*Loop "Daily digest" finished*\n'))+ self.assertTrue(text.endswith("…"))