: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): route CI follow-ups to a GitHub comment instead of Slack (#74247)
Michael Matlokaae779c2223e4
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex a7199e03d551..c7efa4068449 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -34,7 +34,7 @@ import posthoganalyticsfrom posthog.event_usage import groupsfrom posthog.models import Team, User-from posthog.models.integration import Integration+from posthog.models.integration import GitHubIntegration, Integrationfrom products.tasks.backend.constants import (AGENT_OTEL_TELEMETRY_STATE_KEY,@@ -2906,6 +2906,39 @@ def _pick_relay_text(*, text: str, text_parts: list[str] | None) -> str:return text+def _post_ci_followup_as_github_comment(run: TaskRun, pr_url: str, body: str) -> None:+ """Best-effort: post a run follow-up message as a comment on its already-opened PR.++ ``pr_url`` comes from caller-writable run output, so it's validated against the task's own+ repository before we comment with the team GitHub App — otherwise a same-team caller could+ set an arbitrary ``pr_url`` and post as the app on any repo the installation can reach.++ Failures (no/mismatched repository, no GitHub integration, or the GitHub API rejecting the+ comment) are logged and swallowed. The caller drops the message from Slack regardless — a+ failed comment must not resurface autonomous CI noise in the thread.+ """+ if not _is_github_pull_request_url_for_repository(pr_url, run.task.repository):+ logger.warning(+ "task_run_ci_followup_comment_repo_mismatch",+ extra={"run_id": str(run.id), "repository": run.task.repository},+ )+ return+ integration = run.task.github_integration+ if integration is None:+ logger.warning("task_run_ci_followup_comment_no_integration", extra={"run_id": str(run.id)})+ return+ try:+ result = GitHubIntegration(integration).comment_on_pull_request_from_url(pr_url, body)+ except Exception:+ logger.exception("task_run_ci_followup_comment_failed", extra={"run_id": str(run.id)})+ return+ if not result.get("success"):+ logger.warning(+ "task_run_ci_followup_comment_rejected",+ extra={"run_id": str(run.id), "error": result.get("error")},+ )++def relay_task_run_message(run_id: str | UUID,task_id: str | UUID,@@ -2920,7 +2953,8 @@ def relay_task_run_message(Returns ``(status, relay_id)`` where status is ``"accepted"`` (relay_id set), ``"skipped"``(run not found / terminal / no Slack mapping / empty text / streamed inline under the- agent-design flag), or ``"failed"``.+ agent-design flag / posted as a GitHub comment because it's an autonomous follow-up on an+ already-opened PR), or ``"failed"``.When ``text_parts`` is provided the last non-empty entry is used — it's thepost-last-tool-use answer, and posting only that keeps the interim narration@@ -2950,12 +2984,24 @@ def relay_task_run_message(return "skipped", Noneif bool((run.state or {}).get(AGENT_DESIGN_STATE_KEY)):+ # Agent-design runs stream inline into the plan block — keep that delivery even after a PR+ # is open, so this must win over the CI-follow-up diversion below.try:signal_agent_text_delta(run.workflow_id, trimmed)except Exception:logger.exception("task_run_relay_text_signal_failed", extra={"run_id": str(run.id)})return "skipped", None+ # Once the run has opened a PR, autonomous CI/review follow-ups (the agent re-triggered by+ # the CI loop, not by a person) belong on the PR, not trailing behind the "PR opened" card in+ # Slack. A reply to a human's thread message carries that message's id — those stay in Slack so+ # the conversation isn't diverted. Autonomous follow-ups have no answering message_id: comment+ # on the PR best-effort and drop the message from Slack either way — never fall back to Slack.+ pr_url = (run.output or {}).get("pr_url")+ if pr_url and message_id is None:+ _post_ci_followup_as_github_comment(run, pr_url, trimmed)+ return "skipped", None+try:relay_id = execute_posthog_code_agent_relay_workflow(run_id=str(run.id),diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex fb5fa4ab19ec..d45a793944b8 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -5059,6 +5059,145 @@ class TestTaskRunAPI(BaseTaskAPITest):message_id=None,)+ def _pr_run_with_slack_and_github(self):+ from posthog.models.integration import Integration++ from products.slack_app.backend.models import SlackThreadTaskMapping++ github_integration = Integration.objects.create(team=self.team, kind="github", integration_id="gh-1", config={})+ task = self.create_task()+ task.github_integration = github_integration+ task.repository = "posthog/posthog"+ task.save(update_fields=["github_integration", "repository"])+ run = TaskRun.objects.create(+ task=task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ output={"pr_url": "https://github.com/posthog/posthog/pull/1"},+ )+ slack_integration = Integration.objects.create(+ team=self.team, kind="slack", integration_id="T_SLACK", config={}+ )+ SlackThreadTaskMapping.objects.create(+ team=self.team,+ integration=slack_integration,+ slack_workspace_id="T_SLACK",+ channel="C123",+ thread_ts="1234.5678",+ task=task,+ task_run=run,+ mentioning_slack_user_id="U123",+ )+ return task, run++ @patch("products.tasks.backend.facade.api.GitHubIntegration")+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")+ def test_relay_message_autonomous_followup_after_pr_posts_github_comment(+ self, mock_execute_relay, mock_github_class+ ):+ task, run = self._pr_run_with_slack_and_github()+ mock_github = MagicMock()+ mock_github.comment_on_pull_request_from_url.return_value = {"success": True}+ mock_github_class.return_value = mock_github++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/relay_message/",+ {"text": "Fixed the failing lint check and pushed."},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"status": "skipped"})+ mock_github.comment_on_pull_request_from_url.assert_called_once_with(+ "https://github.com/posthog/posthog/pull/1", "Fixed the failing lint check and pushed."+ )+ mock_execute_relay.assert_not_called()++ @patch("products.tasks.backend.facade.api.GitHubIntegration")+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")+ def test_relay_message_reply_to_human_after_pr_stays_in_slack(self, mock_execute_relay, mock_github_class):+ task, run = self._pr_run_with_slack_and_github()+ mock_github = MagicMock()+ mock_github_class.return_value = mock_github+ mock_execute_relay.return_value = "relay-1"++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/relay_message/",+ {"text": "Sure, here's the answer to your question.", "message_id": "slack:C123:9999.0:1234.5678"},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"status": "accepted", "relay_id": "relay-1"})+ mock_github.comment_on_pull_request_from_url.assert_not_called()+ mock_execute_relay.assert_called_once()++ @patch("products.tasks.backend.facade.api.GitHubIntegration")+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")+ def test_relay_message_ci_followup_not_posted_to_pr_outside_task_repository(+ self, mock_execute_relay, mock_github_class+ ):+ # pr_url is caller-writable; a PR outside the task's own repository must never be commented on.+ task, run = self._pr_run_with_slack_and_github()+ run.output = {"pr_url": "https://github.com/posthog/other-repo/pull/1"}+ run.save(update_fields=["output"])+ mock_github = MagicMock()+ mock_github_class.return_value = mock_github++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/relay_message/",+ {"text": "Fixed the failing lint check and pushed."},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"status": "skipped"})+ mock_github.comment_on_pull_request_from_url.assert_not_called()+ mock_execute_relay.assert_not_called()++ @patch("products.tasks.backend.temporal.client.signal_agent_text_delta")+ @patch("products.tasks.backend.facade.api.GitHubIntegration")+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")+ def test_relay_message_agent_design_streams_inline_even_after_pr(+ self, mock_execute_relay, mock_github_class, mock_signal_delta+ ):+ from products.tasks.backend.temporal.process_task.activities.feature_flags import AGENT_DESIGN_STATE_KEY++ task, run = self._pr_run_with_slack_and_github()+ run.state = {AGENT_DESIGN_STATE_KEY: True}+ run.save(update_fields=["state"])+ mock_github = MagicMock()+ mock_github_class.return_value = mock_github++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/relay_message/",+ {"text": "Here's the updated plan."},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"status": "skipped"})+ mock_signal_delta.assert_called_once()+ mock_github.comment_on_pull_request_from_url.assert_not_called()++ @patch("products.tasks.backend.facade.api.GitHubIntegration")+ @patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")+ def test_relay_message_ci_followup_dropped_when_github_comment_fails(self, mock_execute_relay, mock_github_class):+ task, run = self._pr_run_with_slack_and_github()+ mock_github = MagicMock()+ mock_github.comment_on_pull_request_from_url.return_value = {"success": False, "error": "boom"}+ mock_github_class.return_value = mock_github++ response = self.client.post(+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/relay_message/",+ {"text": "Fixed the failing lint check and pushed."},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), {"status": "skipped"})+ mock_execute_relay.assert_not_called()+@patch("products.tasks.backend.temporal.client.execute_posthog_code_agent_relay_workflow")def test_relay_message_skips_when_no_slack_mapping(self, mock_execute_relay):task = self.create_task()