: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(slack-bot): Let same-team users send task follow-ups (#60260)
Michael Matlokae99a2588b17b
diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.pyindex 0b4e54cbb69b..aa0ae7be5cb7 100644--- a/posthog/temporal/ai/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/posthog_code_slack_mention.py@@ -29,10 +29,6 @@ from products.tasks.backend.services.agent_command import send_user_messagefrom products.tasks.backend.services.connection_token import create_sandbox_connection_tokenfrom products.tasks.backend.temporal.client import execute_task_processing_workflow-# Imports from `products.slack_app.backend.api` stay inline: that module imports-# `PostHogCodeSlackMentionWorkflow*` from this one, so a top-level import would-# create a circular dependency.-logger = structlog.get_logger(__name__)@@ -652,6 +648,11 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):)+# `api.py` imports the workflow classes above, so keep this module-level import+# after their definitions to avoid a circular import during module initialization.+from products.slack_app.backend.api import resolve_slack_user # noqa: E402++async def _gate_on_personal_github(inputs: "PostHogCodeSlackMentionWorkflowInputs",channel: str,@@ -708,8 +709,6 @@ def resolve_posthog_code_slack_user_activity(thread_ts: str,slack_user_id: str,) -> int | None:- from products.slack_app.backend.api import resolve_slack_user-integration = Integration.objects.select_related("team", "team__organization").get(id=inputs.integration_id,kind="slack",@@ -1409,20 +1408,33 @@ def forward_posthog_code_followup_activity()slack = SlackIntegration(integration)+ followup_user_text_prefix: str | None = Noneif slack_user_id != mapping.mentioning_slack_user_id:+ # The follow-up is from a different Slack user than the one who started the+ # thread. Try to resolve them to a PostHog user with access to the same team+ # — if so, let them participate; the message is still relayed in the original+ # author's name (their sandbox token, their identity to the agent), with the+ # actual sender's name prefixed onto the text so the agent sees who spoke.+ resolved = resolve_slack_user(slack, integration, slack_user_id, channel, thread_ts)+ if not resolved:+ logger.info(+ "posthog_code_followup_unauthorized_actor",+ channel=channel,+ thread_ts=thread_ts,+ expected=mapping.mentioning_slack_user_id,+ actual=slack_user_id,+ )+ return True+ actor_name = resolved.user.get_full_name() or resolved.slack_email+ followup_user_text_prefix = f"{actor_name}: "logger.info(- "posthog_code_followup_unauthorized_actor",- channel=channel,- thread_ts=thread_ts,- expected=mapping.mentioning_slack_user_id,- actual=slack_user_id,- )- slack.client.chat_postMessage(+ "posthog_code_followup_cross_user_authorized",channel=channel,thread_ts=thread_ts,- text="Only the person who started this task can send follow-up messages to the agent.",+ initiator=mapping.mentioning_slack_user_id,+ actor=slack_user_id,+ actor_user_id=resolved.user.id,)- return Trueif _block_if_team_over_quota(integration=integration,@@ -1445,6 +1457,7 @@ def forward_posthog_code_followup_activity(slack_user_id,event_text,user_message_ts,+ user_text_prefix=followup_user_text_prefix,)sandbox_url = (task_run.state or {}).get("sandbox_url")@@ -1460,6 +1473,8 @@ def forward_posthog_code_followup_activity(user_text = re.sub(r"<@[A-Z0-9]+>", "", event_text).strip()if not user_text:return True+ if followup_user_text_prefix:+ user_text = followup_user_text_prefix + user_textif user_message_ts:_safe_react(slack.client, channel, user_message_ts, "eyes")@@ -1527,12 +1542,15 @@ def _resume_task_with_new_run(slack_user_id: str,event_text: str,user_message_ts: str | None,+ user_text_prefix: str | None = None,) -> bool:"""Create a new run on the same task when a follow-up arrives after the previous run completed."""user_text = re.sub(r"<@[A-Z0-9]+>", "", event_text).strip()if not user_text:return True+ if user_text_prefix:+ user_text = user_text_prefix + user_textcreated_by = mapping.task.created_byif not created_by:diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.pyindex 8ba6bed96889..c8ef998a1624 100644--- a/products/slack_app/backend/tests/test_followup_forwarding.py+++ b/products/slack_app/backend/tests/test_followup_forwarding.py@@ -17,6 +17,7 @@ from posthog.temporal.ai.posthog_code_slack_mention import (forward_posthog_code_followup_activity,)+from products.slack_app.backend.api import SlackUserContextfrom products.slack_app.backend.models import SlackThreadTaskMapping@@ -677,8 +678,9 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert "gh pr checkout https://github.com/org/repo/pull/1" in new_run.state.get("initial_prompt_override", "")assert "gh pr checkout https://github.com/org/repo/pull/1" in new_run.state.get("pending_user_message", "")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user", return_value=None)@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")- def test_terminal_run_unauthorized_user_returns_true_with_error(self, mock_slack_cls):+ def test_terminal_run_unauthorized_user_returns_true_with_resolver_feedback(self, mock_slack_cls, mock_resolve):self.task_run.status = self.TaskRun.Status.COMPLETEDself.task_run.save()self._create_mapping(mentioning_user="U_ALICE")@@ -691,8 +693,8 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):)assert result is True- call_kwargs = mock_slack_instance.client.chat_postMessage.call_args.kwargs- assert "Only the person who started" in call_kwargs["text"]+ mock_resolve.assert_called_once_with(mock_slack_instance, self.integration, "U_BOB", "C123", "1234.5678")+ mock_slack_instance.client.chat_postMessage.assert_not_called()@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")def test_terminal_run_missing_created_by_returns_true_with_error(self, mock_slack_cls):@@ -738,8 +740,9 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):)assert mapping.task_run_id == self.task_run.id+ @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user", return_value=None)@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")- def test_unauthorized_actor_returns_true_with_message(self, mock_slack_cls):+ def test_unauthorized_actor_returns_true_with_resolver_feedback(self, mock_slack_cls, mock_resolve):self._create_mapping(mentioning_user="U_ALICE")mock_slack_instance = MagicMock()mock_slack_cls.return_value = mock_slack_instance@@ -749,9 +752,106 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):inputs, "C123", "1234.5678", "U_BOB", "do something", "1234.5679")assert result is True- mock_slack_instance.client.chat_postMessage.assert_called_once()- call_kwargs = mock_slack_instance.client.chat_postMessage.call_args.kwargs- assert "Only the person who started" in call_kwargs["text"]+ mock_resolve.assert_called_once_with(mock_slack_instance, self.integration, "U_BOB", "C123", "1234.5678")+ mock_slack_instance.client.chat_postMessage.assert_not_called()++ @patch("posthog.temporal.ai.posthog_code_slack_mention.create_sandbox_connection_token", return_value="jwt-token")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.send_user_message")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")+ def test_cross_user_followup_authorized_prefixes_actor_name(+ self, mock_slack_cls, mock_resolve, mock_send, mock_token+ ):+ # A second user in the same PostHog org and team should be allowed to chip in+ # on the thread; their message is forwarded under the original author's identity+ # but their name is prepended so the agent knows who actually spoke.+ self._create_mapping(mentioning_user="U_ALICE")+ bob = User.objects.create(email="[email protected]", first_name="Bob")+ mock_slack_instance = MagicMock()+ mock_slack_cls.return_value = mock_slack_instance+ mock_resolve.return_value = SlackUserContext(user=bob, slack_email="[email protected]")+ mock_send.return_value = _command_result(success=True, status_code=200)++ inputs = _make_inputs(self.integration.id)+ result = forward_posthog_code_followup_activity(+ inputs, "C123", "1234.5678", "U_BOB", "<@BOT> please retry the build", "1234.5679"+ )++ assert result is True+ mock_send.assert_called_once_with(+ self.task_run, "Bob: please retry the build", auth_token="jwt-token", timeout=90+ )+ # No "Only the person who started" denial; the message went through.+ post_calls = [+ call+ for call in mock_slack_instance.client.chat_postMessage.call_args_list+ if "Only the person who started" in call.kwargs.get("text", "")+ ]+ assert not post_calls++ @patch("posthog.temporal.ai.posthog_code_slack_mention.create_sandbox_connection_token", return_value="jwt-token")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.send_user_message")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")+ def test_cross_user_followup_falls_back_to_email_when_no_full_name(+ self, mock_slack_cls, mock_resolve, mock_send, mock_token+ ):+ self._create_mapping(mentioning_user="U_ALICE")+ bob = User.objects.create(email="[email protected]") # no full name+ mock_slack_cls.return_value = MagicMock()+ mock_resolve.return_value = SlackUserContext(user=bob, slack_email="[email protected]")+ mock_send.return_value = _command_result(success=True, status_code=200)++ inputs = _make_inputs(self.integration.id)+ forward_posthog_code_followup_activity(inputs, "C123", "1234.5678", "U_BOB", "<@BOT> ping", "1234.5679")++ mock_send.assert_called_once_with(self.task_run, "[email protected]: ping", auth_token="jwt-token", timeout=90)++ @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user", return_value=None)+ @patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")+ def test_cross_user_followup_unmapped_user_delegates_feedback_to_resolver(self, mock_slack_cls, mock_resolve):+ # A second Slack user who can't be resolved to a PostHog member of this team+ # still can't participate, but resolve_slack_user owns the exact feedback+ # because it knows whether email, org membership, or team access failed.+ self._create_mapping(mentioning_user="U_ALICE")+ mock_slack_instance = MagicMock()+ mock_slack_cls.return_value = mock_slack_instance++ inputs = _make_inputs(self.integration.id)+ result = forward_posthog_code_followup_activity(+ inputs, "C123", "1234.5678", "U_BOB", "<@BOT> sneak in", "1234.5679"+ )++ assert result is True+ mock_resolve.assert_called_once_with(mock_slack_instance, self.integration, "U_BOB", "C123", "1234.5678")+ mock_slack_instance.client.chat_postMessage.assert_not_called()++ @patch("posthog.temporal.ai.posthog_code_slack_mention.execute_task_processing_workflow")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.resolve_slack_user")+ @patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")+ def test_cross_user_terminal_run_resume_prefixes_actor_name(+ self, mock_slack_cls, mock_resolve, mock_execute_workflow+ ):+ # The terminal-resume path goes through `_resume_task_with_new_run`, which has+ # its own user_text derivation. Make sure the prefix lands there too so the+ # new run's initial prompt also carries the actor's name.+ self.task_run.status = self.TaskRun.Status.COMPLETED+ self.task_run.save()+ self._create_mapping(mentioning_user="U_ALICE")+ bob = User.objects.create(email="[email protected]", first_name="Bob")+ mock_slack_cls.return_value = MagicMock()+ mock_resolve.return_value = SlackUserContext(user=bob, slack_email="[email protected]")++ inputs = _make_inputs(self.integration.id)+ result = forward_posthog_code_followup_activity(+ inputs, "C123", "1234.5678", "U_BOB", "<@BOT> fix the tests", "1234.5679"+ )++ assert result is True+ new_run_id = mock_execute_workflow.call_args.kwargs["run_id"]+ new_run = self.TaskRun.objects.get(id=new_run_id)+ assert new_run.state.get("pending_user_message") == "Bob: fix the tests"+ assert new_run.state.get("initial_prompt_override") == "Bob: fix the tests"@patch("posthog.temporal.ai.posthog_code_slack_mention.SlackIntegration")def test_sandbox_not_ready_returns_true_with_message(self, mock_slack_cls):