Skip to content

: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.

feat: Allow users to continue with PostHog bot in Slack (#63009)

Jordan Mryyaneae90a132e0c
diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.py
index 93013df01b8c..456852b300f6 100644
--- a/posthog/temporal/ai/slack_app/__init__.py
+++ b/posthog/temporal/ai/slack_app/__init__.py
@@ -23,10 +23,12 @@ from posthog.temporal.ai.slack_app.activities import (
forward_posthog_code_followup_activity,
handle_posthog_code_rules_command_activity,
handle_posthog_code_slack_mention_command_activity,
+ post_posthog_code_authorship_timeout_activity,
post_posthog_code_internal_error_activity,
post_posthog_code_no_repos_activity,
post_posthog_code_picker_timeout_activity,
post_posthog_code_repo_picker_activity,
+ resolve_posthog_code_authorship_activity,
resolve_posthog_code_slack_command_user_activity,
resolve_posthog_code_slack_user_activity,
run_posthog_slack_inbox_onboarding_activity,
@@ -53,7 +55,9 @@ SLACK_APP_ACTIVITIES = [
post_posthog_code_no_repos_activity,
post_posthog_code_repo_picker_activity,
block_posthog_code_task_if_no_personal_github_activity,
+ resolve_posthog_code_authorship_activity,
post_posthog_code_picker_timeout_activity,
+ post_posthog_code_authorship_timeout_activity,
post_posthog_code_internal_error_activity,
create_posthog_code_task_for_repo_activity,
forward_posthog_code_followup_activity,
@@ -89,10 +93,12 @@ __all__ = [
"forward_posthog_code_followup_activity",
"handle_posthog_code_rules_command_activity",
"handle_posthog_code_slack_mention_command_activity",
+ "post_posthog_code_authorship_timeout_activity",
"post_posthog_code_internal_error_activity",
"post_posthog_code_no_repos_activity",
"post_posthog_code_picker_timeout_activity",
"post_posthog_code_repo_picker_activity",
+ "resolve_posthog_code_authorship_activity",
"resolve_posthog_code_slack_command_user_activity",
"resolve_posthog_code_slack_user_activity",
"run_posthog_slack_inbox_onboarding_activity",
diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.py
index 78b5eaa6287a..02dc8ba6b76c 100644
--- a/posthog/temporal/ai/slack_app/activities/__init__.py
+++ b/posthog/temporal/ai/slack_app/activities/__init__.py
@@ -10,10 +10,12 @@ from posthog.temporal.ai.slack_app.activities.messaging import (
POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE,
POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,
block_posthog_code_task_if_no_personal_github_activity,
+ post_posthog_code_authorship_timeout_activity,
post_posthog_code_internal_error_activity,
post_posthog_code_no_repos_activity,
post_posthog_code_picker_timeout_activity,
post_posthog_code_repo_picker_activity,
+ resolve_posthog_code_authorship_activity,
)
from posthog.temporal.ai.slack_app.activities.onboarding import (
run_posthog_slack_inbox_onboarding,
@@ -58,10 +60,12 @@ __all__ = [
"forward_posthog_code_followup_activity",
"handle_posthog_code_rules_command_activity",
"handle_posthog_code_slack_mention_command_activity",
+ "post_posthog_code_authorship_timeout_activity",
"post_posthog_code_internal_error_activity",
"post_posthog_code_no_repos_activity",
"post_posthog_code_picker_timeout_activity",
"post_posthog_code_repo_picker_activity",
+ "resolve_posthog_code_authorship_activity",
"resolve_posthog_code_slack_command_user_activity",
"resolve_posthog_code_slack_user_activity",
"run_posthog_slack_inbox_onboarding",
diff --git a/posthog/temporal/ai/slack_app/activities/messaging.py b/posthog/temporal/ai/slack_app/activities/messaging.py
index 09da65e3807c..41596cde9966 100644
--- a/posthog/temporal/ai/slack_app/activities/messaging.py
+++ b/posthog/temporal/ai/slack_app/activities/messaging.py
@@ -1,4 +1,5 @@
-from typing import Any
+import json
+from typing import TYPE_CHECKING, Any
import structlog
from temporalio import activity
@@ -6,6 +7,9 @@ from temporalio import activity
from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs
from posthog.temporal.common.utils import close_db_connections
+if TYPE_CHECKING:
+ from posthog.models.integration import SlackIntegration
+
logger = structlog.get_logger(__name__)
POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE = (
@@ -98,6 +102,48 @@ def post_posthog_code_repo_picker_activity(
)
+def _post_connect_personal_github_prompt(
+ slack: "SlackIntegration",
+ *,
+ channel: str,
+ thread_ts: str,
+ settings_url: str,
+ user_id: int,
+ team_id: int,
+) -> None:
+ """Post the single-button "Connect GitHub" prompt for a task held on a missing personal GitHub install."""
+ text = (
+ "I can't start this task yet — you haven't connected your personal GitHub. "
+ "Connect it so I can open the pull request as you, then mention me again."
+ )
+ slack.client.chat_postMessage(
+ channel=channel,
+ thread_ts=thread_ts,
+ text=text,
+ blocks=[
+ {"type": "section", "text": {"type": "mrkdwn", "text": text}},
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Connect GitHub", "emoji": True},
+ "url": settings_url,
+ "style": "primary",
+ }
+ ],
+ },
+ ],
+ )
+ logger.info(
+ "slack_app_task_blocked_no_personal_github",
+ user_id=user_id,
+ team_id=team_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+
+
@activity.defn
@close_db_connections
def block_posthog_code_task_if_no_personal_github_activity(
@@ -105,6 +151,7 @@ def block_posthog_code_task_if_no_personal_github_activity(
channel: str,
thread_ts: str,
user_id: int,
+ allow_bot_prs: bool = False,
) -> bool:
"""Gate a repo-bound coding-agent task on the mentioner having a personal GitHub.
@@ -121,6 +168,8 @@ def block_posthog_code_task_if_no_personal_github_activity(
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.user_integration import UserIntegration
+ from products.slack_app.backend.feature_flags import is_slack_app_bot_prs_enabled
+
has_personal_github = UserIntegration.objects.filter(
user_id=user_id,
kind=UserIntegration.IntegrationKind.GITHUB,
@@ -133,40 +182,172 @@ def block_posthog_code_task_if_no_personal_github_activity(
kind="slack",
integration_id=inputs.slack_team_id,
)
- slack = SlackIntegration(integration)
+ if allow_bot_prs:
+ team_has_github = Integration.objects.filter(
+ team=integration.team, kind=Integration.IntegrationKind.GITHUB
+ ).exists()
+ if team_has_github and is_slack_app_bot_prs_enabled(integration.team):
+ return False
+ slack = SlackIntegration(integration)
settings_url = f"{settings.SITE_URL}/project/{integration.team_id}/settings/user-personal-integrations"
- text = (
- "I can't start this task yet — you haven't connected your personal GitHub. "
- "Connect it so I can open the pull request as you, then mention me again."
- )
- slack.client.chat_postMessage(
+ _post_connect_personal_github_prompt(
+ slack,
channel=channel,
thread_ts=thread_ts,
- text=text,
- blocks=[
- {"type": "section", "text": {"type": "mrkdwn", "text": text}},
- {
- "type": "actions",
- "elements": [
- {
- "type": "button",
- "text": {"type": "plain_text", "text": "Connect GitHub", "emoji": True},
- "url": settings_url,
- "style": "primary",
- }
- ],
- },
- ],
+ settings_url=settings_url,
+ user_id=user_id,
+ team_id=integration.team_id,
)
- logger.info(
- "posthog_code_task_blocked_no_personal_github",
+ return True
+
+
+@close_db_connections
+def resolve_posthog_code_authorship_activity(
+ inputs: PostHogCodeSlackMentionWorkflowInputs,
+ channel: str,
+ thread_ts: str,
+ slack_user_id: str,
+ user_id: int,
+ workflow_id: str,
+ repository: str,
+) -> str:
+ """Gate PR authorship for a repo-bound task: returns "proceed", "awaiting_confirmation", or "blocked"."""
+ from django.conf import settings
+
+ from posthog.models.integration import Integration, SlackIntegration
+ from posthog.models.user_integration import UserIntegration
+
+ from products.slack_app.backend.feature_flags import is_slack_app_bot_prs_enabled
+ from products.tasks.backend.facade import api as tasks_facade
+
+ if tasks_facade.user_can_author_repository(user_id, repository):
+ return "proceed"
+
+ has_personal_github = UserIntegration.objects.filter(
+ user_id=user_id,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ ).exists()
+ integration = Integration.objects.select_related("team", "team__organization").get(
+ id=inputs.integration_id,
+ kind="slack",
+ integration_id=inputs.slack_team_id,
+ )
+ team = integration.team
+ slack = SlackIntegration(integration)
+ settings_url = f"{settings.SITE_URL}/project/{integration.team_id}/settings/user-personal-integrations"
+ team_has_github = Integration.objects.filter(team=team, kind=Integration.IntegrationKind.GITHUB).exists()
+
+ if is_slack_app_bot_prs_enabled(team) and team_has_github:
+ if has_personal_github:
+ text = (
+ f"Your personal GitHub can't author PRs in `{repository}`, so the PR will be authored by the "
+ "PostHog bot.\nTo change this, update your personal integration."
+ )
+ else:
+ text = (
+ "You have no personal integration setup yet. The PR will be authored by the PostHog bot.\n"
+ "To change this, set up a personal integration."
+ )
+ slack.client.chat_postMessage(
+ channel=channel,
+ thread_ts=thread_ts,
+ text=text,
+ blocks=[
+ {"type": "section", "text": {"type": "mrkdwn", "text": text}},
+ {
+ "type": "actions",
+ "elements": [
+ {
+ "type": "button",
+ "action_id": "posthog_code_continue_as_bot",
+ "text": {"type": "plain_text", "text": "Continue as PostHog", "emoji": True},
+ "value": json.dumps(
+ {
+ "workflow_id": workflow_id,
+ "integration_id": integration.id,
+ "mentioning_slack_user_id": slack_user_id,
+ }
+ ),
+ },
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Connect GitHub", "emoji": True},
+ "url": settings_url,
+ "style": "primary",
+ },
+ ],
+ },
+ ],
+ metadata={"event_type": "posthog_code_authorship", "event_payload": {"workflow_id": workflow_id}},
+ )
+ logger.info(
+ "slack_app_authorship_confirmation_posted",
+ user_id=user_id,
+ team_id=integration.team_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ return "awaiting_confirmation"
+
+ if has_personal_github:
+ slack.client.chat_postMessage(
+ channel=channel,
+ thread_ts=thread_ts,
+ text=(
+ f"I can't start this task yet — your personal GitHub can't author PRs in `{repository}`. "
+ "Update your personal integration, then mention me again."
+ ),
+ )
+ logger.info(
+ "slack_app_task_blocked_personal_github_missing_repo",
+ user_id=user_id,
+ team_id=integration.team_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ return "blocked"
+
+ _post_connect_personal_github_prompt(
+ slack,
+ channel=channel,
+ thread_ts=thread_ts,
+ settings_url=settings_url,
user_id=user_id,
team_id=integration.team_id,
+ )
+ return "blocked"
+
+
+@close_db_connections
+def post_posthog_code_authorship_timeout_activity(
+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str
+) -> None:
+ from posthog.models.integration import Integration, SlackIntegration
+
+ from products.slack_app.backend.models import SlackThreadTaskMapping
+
+ # Skip the expired message if another workflow already created a task for this thread.
+ if SlackThreadTaskMapping.objects.filter(
+ integration_id=inputs.integration_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ ).exists():
+ return
+
+ integration = Integration.objects.select_related("team", "team__organization").get(
+ id=inputs.integration_id,
+ kind="slack",
+ integration_id=inputs.slack_team_id,
+ )
+ slack = SlackIntegration(integration)
+ slack.client.chat_postMessage(
channel=channel,
thread_ts=thread_ts,
+ text="I didn't hear back, so I haven't started the task. Mention PostHog again to retry.",
)
- return True
@activity.defn
diff --git a/posthog/temporal/ai/slack_app/activities/repo_selection.py b/posthog/temporal/ai/slack_app/activities/repo_selection.py
index 668fc53d45d3..aebba300b387 100644
--- a/posthog/temporal/ai/slack_app/activities/repo_selection.py
+++ b/posthog/temporal/ai/slack_app/activities/repo_selection.py
@@ -48,6 +48,7 @@ def cascade_posthog_code_repository_activity(
return PostHogCodeRepoCascadeOutcome(mode="no_repo", repository=None, reason="legacy_no_user_id")
from products.slack_app.backend.api import _extract_explicit_repo, _get_full_repo_names
+ from products.slack_app.backend.feature_flags import is_slack_app_bot_prs_enabled
integration = Integration.objects.select_related("team", "team__organization").get(
id=inputs.integration_id,
@@ -57,12 +58,12 @@ def cascade_posthog_code_repository_activity(
all_repos = _get_full_repo_names(integration, user_id=user_id)
if not all_repos:
- # A connected team install with no personal install is recoverable via the gate prompt;
- # a team with no install at all is genuinely no-op.
+ # With bot PRs off, a team install means a missing personal install is recoverable via the
+ # gate prompt; with bot PRs on, team repos are already folded into all_repos, so empty is no-op.
team_has_github = Integration.objects.filter(
team=integration.team, kind=Integration.IntegrationKind.GITHUB
).exists()
- if team_has_github:
+ if team_has_github and not is_slack_app_bot_prs_enabled(integration.team):
return PostHogCodeRepoCascadeOutcome(mode="needs_user_github", repository=None, reason="no_user_repos")
return PostHogCodeRepoCascadeOutcome(mode="no_repo", repository=None, reason="no_repos")
diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
index af133ed57b21..882ca077f2c7 100644
--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
@@ -18,9 +18,11 @@ from posthog.temporal.ai.slack_app import (
discover_posthog_code_repository_via_agent_activity,
enforce_posthog_code_billing_quota_activity,
forward_posthog_code_followup_activity,
+ post_posthog_code_authorship_timeout_activity,
post_posthog_code_internal_error_activity,
post_posthog_code_picker_timeout_activity,
post_posthog_code_repo_picker_activity,
+ resolve_posthog_code_authorship_activity,
resolve_posthog_code_slack_user_activity,
)
from posthog.temporal.common.base import PostHogWorkflow
@@ -34,6 +36,7 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
def __init__(self) -> None:
self._selected_repo: str | None = None
self._repo_selection_resolved = False
+ self._authorship_resolved = False
@workflow.signal
async def repo_selected(self, repository: str) -> None:
@@ -47,11 +50,51 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
self._repo_selection_resolved = True
self._selected_repo = None
+ @workflow.signal
+ async def authorship_confirmed(self) -> None:
+ self._authorship_resolved = True
+
@staticmethod
def parse_inputs(inputs: list[str]) -> PostHogCodeSlackMentionWorkflowInputs:
loaded = json.loads(inputs[0])
return PostHogCodeSlackMentionWorkflowInputs(**loaded)
+ async def _resolve_authorship(
+ self,
+ inputs: PostHogCodeSlackMentionWorkflowInputs,
+ channel: str,
+ thread_ts: str,
+ slack_user_id: str,
+ user_id: int,
+ repository: str,
+ ) -> bool:
+ """Return True if the workflow must stop (blocked or timed out); False to proceed."""
+ status = await _execute_posthog_code_activity(
+ resolve_posthog_code_authorship_activity,
+ inputs,
+ channel,
+ thread_ts,
+ slack_user_id,
+ user_id,
+ workflow.info().workflow_id,
+ repository,
+ )
+ if status == "proceed":
+ return False
+ if status == "awaiting_confirmation":
+ try:
+ await workflow.wait_condition(
+ lambda: self._authorship_resolved,
+ timeout=timedelta(minutes=POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES),
+ )
+ except TimeoutError:
+ await _execute_posthog_code_activity(
+ post_posthog_code_authorship_timeout_activity, inputs, channel, thread_ts
+ )
+ return True
+ return False
+ return True
+
@workflow.run
async def run(self, inputs: PostHogCodeSlackMentionWorkflowInputs) -> None:
event = inputs.event
@@ -240,8 +283,12 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
)
return
repository = self._selected_repo
- if repository and await _gate_on_personal_github(inputs, channel, thread_ts, user_id):
- return
+ if repository:
+ if workflow.patched("posthog-code-authorship-confirm-2026-06"):
+ if await self._resolve_authorship(inputs, channel, thread_ts, slack_user_id, user_id, repository):
+ return
+ elif await _gate_on_personal_github(inputs, channel, thread_ts, user_id):
+ return
await _execute_posthog_code_activity(
create_posthog_code_task_for_repo_activity,
inputs,
diff --git a/posthog/temporal/ai/slack_app/posthog_code_slack_mention_command.py b/posthog/temporal/ai/slack_app/posthog_code_slack_mention_command.py
index 5cad30d7ea21..04cb5c9fbd7c 100644
--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention_command.py
+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention_command.py
@@ -106,7 +106,7 @@ class PostHogCodeSlackMentionCommandWorkflow(PostHogWorkflow):
blocked = await workflow.execute_activity(
block_posthog_code_task_if_no_personal_github_activity,
- args=[picker_inputs, channel, thread_ts, user_id],
+ args=[picker_inputs, channel, thread_ts, user_id, True],
start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),
retry_policy=RetryPolicy(maximum_attempts=3),
)
diff --git a/posthog/temporal/tests/ai/test_block_missing_user_github.py b/posthog/temporal/tests/ai/test_block_missing_user_github.py
index bf16eceb8774..7897598acba0 100644
--- a/posthog/temporal/tests/ai/test_block_missing_user_github.py
+++ b/posthog/temporal/tests/ai/test_block_missing_user_github.py
@@ -2,6 +2,8 @@ from unittest.mock import MagicMock, patch
from django.test import TestCase
+from parameterized import parameterized
+
from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
@@ -87,6 +89,36 @@ class TestBlockPostHogCodeTaskIfNoPersonalGitHub(TestCase):
assert blocked is True
mock_slack.client.chat_postMessage.assert_called_once()
+ @parameterized.expand(
+ [
+ ("flag_on_with_team_install_proceeds", True, True, False),
+ ("flag_off_with_team_install_blocks", False, True, True),
+ ("flag_on_without_team_install_blocks", True, False, True),
+ ]
+ )
+ @patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled")
+ @patch("posthog.models.integration.SlackIntegration")
+ def test_allow_bot_prs_gates_on_flag_and_team_install(
+ self, _name, flag_on, has_team_install, expect_blocked, mock_slack_cls, mock_flag
+ ):
+ mock_flag.return_value = flag_on
+ if has_team_install:
+ Integration.objects.create(
+ team=self.team,
+ kind="github",
+ config={"account": {"name": "posthog"}},
+ sensitive_config={"access_token": "ghp-test"},
+ )
+ mock_slack = MagicMock()
+ mock_slack_cls.return_value = mock_slack
+
+ blocked = block_posthog_code_task_if_no_personal_github_activity(
+ _make_inputs(self.integration.id), "C123", "1234.5678", self.user.id, True
+ )
+
+ assert blocked is expect_blocked
+ assert mock_slack.client.chat_postMessage.called is expect_blocked
+
@patch("posthog.models.integration.SlackIntegration")
def test_another_users_github_integration_does_not_count(self, mock_slack_cls):
other_user = User.objects.create(email="[email protected]")
diff --git a/posthog/temporal/tests/ai/test_cascade_bot_prs.py b/posthog/temporal/tests/ai/test_cascade_bot_prs.py
new file mode 100644
index 000000000000..fc4131c7e852
--- /dev/null
+++ b/posthog/temporal/tests/ai/test_cascade_bot_prs.py
@@ -0,0 +1,85 @@
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.test import TestCase
+
+from parameterized import parameterized
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.temporal.ai.slack_app import (
+ PostHogCodeSlackMentionWorkflowInputs,
+ cascade_posthog_code_repository_activity,
+)
+
+
+def _make_inputs(integration_id: int, slack_team_id: str = "T_SLACK") -> PostHogCodeSlackMentionWorkflowInputs:
+ return PostHogCodeSlackMentionWorkflowInputs(
+ event={"channel": "C123", "ts": "1234.5678", "user": "U_ALICE", "text": "<@BOT> fix the thing"},
+ integration_id=integration_id,
+ slack_team_id=slack_team_id,
+ )
+
+
+def _repo_dict(full_name: str, repo_id: int = 1) -> dict:
+ org, name = full_name.split("/")
+ return {"id": repo_id, "name": name, "full_name": full_name}
+
+
+class TestCascadeBotPRs(TestCase):
+ def setUp(self):
+ cache.clear()
+ self.org = Organization.objects.create(name="TestOrg")
+ self.team = Team.objects.create(organization=self.org, name="TestTeam")
+ self.user = User.objects.create(email="[email protected]")
+ self.slack_integration = Integration.objects.create(
+ team=self.team, kind="slack", integration_id="T_SLACK", config={}
+ )
+
+ def _create_team_github_integration(self) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="gh-team-1",
+ config={"account": {"name": "posthog"}},
+ sensitive_config={"access_token": "gh-team-token"},
+ )
+
+ @parameterized.expand(
+ [
+ ("single_repo_auto", ["posthog/posthog"], "auto"),
+ ("many_repos_agent", ["posthog/a", "posthog/b"], "agent_needed"),
+ ]
+ )
+ @patch("products.slack_app.backend.api.GitHubIntegration")
+ @patch("products.slack_app.backend.api.posthoganalytics.feature_enabled", return_value=True)
+ def test_flag_on_with_team_install_resolves_repos(
+ self, _name, team_repos, expected_mode, _mock_feature_enabled, mock_team_github_class
+ ):
+ self._create_team_github_integration()
+ mock_team_github = MagicMock()
+ mock_team_github.list_all_cached_repositories.return_value = [
+ _repo_dict(name, i) for i, name in enumerate(team_repos)
+ ]
+ mock_team_github_class.return_value = mock_team_github
+
+ outcome = cascade_posthog_code_repository_activity(
+ _make_inputs(self.slack_integration.id), "fix the thing", self.user.id
+ )
+
+ assert outcome.mode == expected_mode
+ assert outcome.mode != "needs_user_github"
+
+ @patch("products.slack_app.backend.api.GitHubIntegration")
+ @patch("products.slack_app.backend.api.posthoganalytics.feature_enabled", return_value=False)
+ def test_flag_off_with_team_install_blocks_on_user_github(self, _mock_feature_enabled, mock_team_github_class):
+ self._create_team_github_integration()
+
+ outcome = cascade_posthog_code_repository_activity(
+ _make_inputs(self.slack_integration.id), "fix the thing", self.user.id
+ )
+
+ assert outcome.mode == "needs_user_github"
+ mock_team_github_class.assert_not_called()
diff --git a/posthog/temporal/tests/ai/test_resolve_authorship.py b/posthog/temporal/tests/ai/test_resolve_authorship.py
new file mode 100644
index 000000000000..9af7ba8aa1ba
--- /dev/null
+++ b/posthog/temporal/tests/ai/test_resolve_authorship.py
@@ -0,0 +1,155 @@
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.test import TestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
+from posthog.temporal.ai.slack_app import (
+ PostHogCodeSlackMentionWorkflowInputs,
+ resolve_posthog_code_authorship_activity,
+)
+
+
+def _make_inputs(integration_id: int, slack_team_id: str = "T_SLACK") -> PostHogCodeSlackMentionWorkflowInputs:
+ return PostHogCodeSlackMentionWorkflowInputs(
+ event={"channel": "C123", "ts": "1234.5678", "user": "U_ALICE", "text": "<@BOT> do something"},
+ integration_id=integration_id,
+ slack_team_id=slack_team_id,
+ )
+
+
+class TestResolvePostHogCodeAuthorship(TestCase):
+ def setUp(self):
+ cache.clear()
+ self.org = Organization.objects.create(name="TestOrg")
+ self.team = Team.objects.create(organization=self.org, name="TestTeam")
+ self.user = User.objects.create(email="[email protected]")
+ self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})
+
+ def _add_team_github(self) -> None:
+ Integration.objects.create(
+ team=self.team,
+ kind="github",
+ config={"account": {"name": "posthog"}},
+ sensitive_config={"access_token": "ghp-test"},
+ )
+
+ def _add_personal_github(self, repos: list[str] | None = None, refresh_token_expires_at: int | None = None) -> None:
+ config: dict = {}
+ if refresh_token_expires_at is not None:
+ config["user_refresh_token_expires_at"] = refresh_token_expires_at
+ UserIntegration.objects.create(
+ user=self.user,
+ kind="github",
+ integration_id="gh-1",
+ config=config,
+ sensitive_config={"user_access_token": "at", "user_refresh_token": "rt"},
+ repository_cache=[{"full_name": name} for name in (repos or [])],
+ repository_cache_updated_at=timezone.now(),
+ )
+
+ def _call(self, repository: str = "posthog/target-repo") -> str:
+ return resolve_posthog_code_authorship_activity(
+ _make_inputs(self.integration.id), "C123", "1234.5678", "U_ALICE", self.user.id, "wf-123", repository
+ )
+
+ @patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.models.integration.SlackIntegration")
+ def test_personal_github_with_repo_access_proceeds_and_posts_nothing(self, mock_slack_cls, _mock_flag):
+ self._add_personal_github(repos=["posthog/target-repo"])
+ mock_slack = MagicMock()
+ mock_slack_cls.return_value = mock_slack
+
+ assert self._call() == "proceed"
+ mock_slack.client.chat_postMessage.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("no_repo_access_flag_on", ["posthog/other-repo"], None, True, "awaiting_confirmation"),
+ ("no_repo_access_flag_off", ["posthog/other-repo"], None, False, "blocked"),
+ ("expired_refresh_token_flag_on", ["posthog/target-repo"], 1, True, "awaiting_confirmation"),
+ ]
+ )
+ @patch("posthog.models.integration.SlackIntegration")
+ def test_unusable_personal_github_never_proceeds(
+ self, _name, repos, refresh_token_expires_at, flag_on, expected_status, mock_slack_cls
+ ):
+ self._add_personal_github(repos=repos, refresh_token_expires_at=refresh_token_expires_at)
+ self._add_team_github()
+ mock_slack = MagicMock()
+ mock_slack_cls.return_value = mock_slack
+
+ with patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=flag_on):
+ assert self._call() == expected_status
+
+ kwargs = mock_slack.client.chat_postMessage.call_args.kwargs
+ assert "can't author PRs in `posthog/target-repo`" in kwargs["text"]
+
+ @patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)
+ @patch("posthog.models.integration.SlackIntegration")
+ def test_no_personal_flag_off_blocks_with_single_button(self, mock_slack_cls, _mock_flag):
+ self._add_team_github()
+ mock_slack = MagicMock()
+ mock_slack_cls.return_value = mock_slack
+
+ assert self._call() == "blocked"
+ kwargs = mock_slack.client.chat_postMessage.call_args.kwargs
+ assert "haven't connected" in kwargs["text"]
+ action_block = next(b for b in kwargs["blocks"] if b.get("type") == "actions")
+ elements = action_block["elements"]
+ assert len(elements) == 1
+ assert elements[0]["text"]["text"] == "Connect GitHub"
+ assert "action_id" not in elements[0]
+
+ @patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.models.integration.SlackIntegration")
+ def test_no_personal_flag_on_with_team_install_awaits_confirmation(self, mock_slack_cls, _mock_flag):
+ self._add_team_github()
+ mock_slack = MagicMock()
+ mock_slack_cls.return_value = mock_slack
+
+ assert self._call() == "awaiting_confirmation"
+ kwargs = mock_slack.client.chat_postMessage.call_args.kwargs
+ assert "no personal integration setup yet" in kwargs["text"]
+ assert "authored by the PostHog bot" in kwargs["text"]
+ assert "set up a personal integration" in kwargs["text"]
+
+ action_block = next(b for b in kwargs["blocks"] if b.get("type") == "actions")
+ action_ids = [e.get("action_id") for e in action_block["elements"]]
+ assert "posthog_code_continue_as_bot" in action_ids
+ # URL button has no action_id, so Slack sends no interactivity request.
+ connect_button = next(e for e in action_block["elements"] if e.get("url"))
+ assert "action_id" not in connect_button
+ assert kwargs["metadata"]["event_payload"]["workflow_id"] == "wf-123"
+
+ @patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.models.integration.SlackIntegration")
+ def test_no_personal_flag_on_without_team_install_blocks(self, mock_slack_cls, _mock_flag):
+ mock_slack = MagicMock()
+ mock_slack_cls.return_value = mock_slack
+
+ assert self._call() == "blocked"
+ kwargs = mock_slack.client.chat_postMessage.call_args.kwargs
+ assert "haven't connected" in kwargs["text"]
+
+ @parameterized.expand(
+ [
+ ("other_service_user_integration", "other-service"),
+ ]
+ )
+ @patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=True)
+ @patch("posthog.models.integration.SlackIntegration")
+ def test_non_github_personal_integration_does_not_count(self, _name, kind, mock_slack_cls, _mock_flag):
+ UserIntegration.objects.create(user=self.user, kind=kind, integration_id="x", config={}, sensitive_config={})
+ self._add_team_github()
+ mock_slack = MagicMock()
+ mock_slack_cls.return_value = mock_slack
+
+ assert self._call() == "awaiting_confirmation"
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 2072f75c17fe..89f744c51022 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -26,6 +26,7 @@ from posthog.git import extract_explicit_repo
from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES
from posthog.models.integration import (
SLACK_INTEGRATION_KINDS,
+ GitHubIntegration,
Integration,
SlackIntegration,
SlackIntegrationError,
@@ -53,6 +54,7 @@ from posthog.utils import get_instance_region
from products.slack_app.backend import inbox_channel, onboarding
from products.slack_app.backend.feature_flags import (
is_slack_app_assistant_enabled,
+ is_slack_app_bot_prs_enabled,
is_slack_app_oauth_enabled,
is_slack_app_untagged_thread_followups_enabled,
)
@@ -849,13 +851,16 @@ def _extract_explicit_repo(text: str, all_repos: list[str]) -> str | None:
def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> list[str]:
- """Return canonical org/repo names from the mentioning user's GitHub install, or [] if unavailable.
+ """Repo names available to the mentioner: their personal install, plus the team install when bot PRs are on."""
+ user_repos = _get_user_repo_names(integration, user_id=user_id)
+ if not is_slack_app_bot_prs_enabled(integration.team):
+ return user_repos
+ combined = set(user_repos) | set(_get_team_repo_names(integration))
+ return sorted(combined)[:_MAX_GITHUB_REPOS]
- Repos are scoped to the user's personal GitHub integration so the picker matches the
- identity that will author the resulting pull request. Users without a personal install
- see an empty list; the downstream personal-GitHub gate posts the connect-GitHub prompt.
- A `None` user_id (e.g. a workflow replay predating per-user scoping) also returns [].
- """
+
+def _get_user_repo_names(integration: Integration, *, user_id: int | None) -> list[str]:
+ """Repo names from the mentioner's personal GitHub install, or []. Cached per user."""
if user_id is None:
return []
cache_key = _user_repo_list_cache_key(user_id)
@@ -895,6 +900,17 @@ def _get_full_repo_names(integration: Integration, *, user_id: int | None) -> li
return result
+def _get_team_repo_names(integration: Integration) -> list[str]:
+ """Repo names from the team's org-owned GitHub install (cached JSONField read), or []."""
+ team_integration = Integration.objects.filter(
+ team=integration.team, kind=Integration.IntegrationKind.GITHUB
+ ).first()
+ if team_integration is None:
+ return []
+ github = GitHubIntegration(team_integration)
+ return [repo["full_name"] for repo in github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS)]
+
+
def _replace_repo_picker_message_with_selection(
*,
integration_id: int,
@@ -2595,9 +2611,10 @@ def _extract_picker_hints(payload: dict) -> tuple[int | None, str | None]:
return integration_id, mentioning_slack_user_id
-def _extract_terminate_hints(payload: dict) -> tuple[int | None, str | None]:
+def _extract_action_value_hints(payload: dict, action_id: str) -> tuple[int | None, str | None]:
+ """Pull (integration_id, mentioning_slack_user_id) from a block action's JSON value, or (None, None)."""
actions = payload.get("actions", [])
- action = next((a for a in actions if a.get("action_id") == "posthog_code_terminate_task"), None)
+ action = next((a for a in actions if a.get("action_id") == action_id), None)
if not action:
return None, None
@@ -2619,6 +2636,10 @@ def _extract_terminate_hints(payload: dict) -> tuple[int | None, str | None]:
return integration_id, mentioning_user_id
+def _extract_terminate_hints(payload: dict) -> tuple[int | None, str | None]:
+ return _extract_action_value_hints(payload, "posthog_code_terminate_task")
+
+
def _handle_repo_picker_options(payload: dict) -> JsonResponse:
"""Return filtered repo options for the external_select picker."""
action = payload.get("action_id") or (payload.get("actions", [{}])[0].get("action_id", ""))
@@ -2868,6 +2889,73 @@ def _handle_no_repo_needed_submit(payload: dict) -> HttpResponse:
return HttpResponse(status=200)
+def _handle_continue_as_bot(payload: dict) -> HttpResponse:
+ action = next(
+ (a for a in payload.get("actions", []) if a.get("action_id") == "posthog_code_continue_as_bot"),
+ None,
+ )
+ if not action:
+ return HttpResponse(status=200)
+
+ try:
+ value = json.loads(action.get("value") or "{}")
+ except (TypeError, ValueError):
+ value = {}
+
+ workflow_id = value.get("workflow_id")
+ integration_id = value.get("integration_id")
+ expected_user_id = value.get("mentioning_slack_user_id")
+
+ if not workflow_id:
+ logger.info("slack_app_continue_as_bot_missing_workflow_id")
+ return HttpResponse(status=200)
+
+ clicker_id = payload.get("user", {}).get("id")
+ if not expected_user_id or clicker_id != expected_user_id:
+ logger.info(
+ "slack_app_continue_as_bot_user_mismatch",
+ workflow_id=workflow_id,
+ expected_user_id=expected_user_id,
+ clicker_id=clicker_id,
+ )
+ return HttpResponse(status=200)
+
+ try:
+ client = sync_connect()
+ handle = client.get_workflow_handle(workflow_id)
+ asyncio.run(handle.signal(PostHogCodeSlackMentionWorkflow.authorship_confirmed))
+ except Exception as e:
+ logger.warning("slack_app_continue_as_bot_signal_failed", workflow_id=workflow_id, error=str(e))
+ return HttpResponse(status=200)
+
+ # Best-effort: replace the prompt so it can't be clicked twice.
+ slack_team_id = payload.get("team", {}).get("id")
+ channel = payload.get("channel", {}).get("id")
+ message_ts = payload.get("message", {}).get("ts")
+ if integration_id and slack_team_id and channel and message_ts:
+ try:
+ # nosemgrep: idor-lookup-without-team — Slack webhook: no team context; scoped by PK + kind + Slack team ID
+ integration = Integration.objects.get(
+ id=integration_id, kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id
+ )
+ text = "Continuing as PostHog — the PR will be authored by the PostHog bot."
+ SlackIntegration(integration).client.chat_update(
+ channel=channel,
+ ts=message_ts,
+ text=text,
+ blocks=[{"type": "section", "text": {"type": "mrkdwn", "text": text}}],
+ )
+ except Exception:
+ logger.warning(
+ "slack_app_continue_as_bot_picker_update_failed",
+ workflow_id=workflow_id,
+ channel=channel,
+ message_ts=message_ts,
+ )
+
+ return HttpResponse(status=200)
+
+
def _delete_ephemeral_via_response_url(response_url: str) -> None:
"""Remove the original ephemeral prompt via the interactivity ``response_url`` once its public
threaded outcome has been posted."""
@@ -3222,6 +3310,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
context = _decode_picker_context(context_token) if context_token else None
hinted_integration_id, hinted_user_id = _extract_picker_hints(payload)
terminate_integration_id, terminate_user_id = _extract_terminate_hints(payload)
+ authorship_integration_id, _ = _extract_action_value_hints(payload, "posthog_code_continue_as_bot")
dismiss_integration_id = _extract_dismiss_hints(payload)
inbox_integration_id = inbox_interactivity.extract_inbox_hints(payload)
requesting_user = payload.get("user", {}).get("id", "")
@@ -3248,6 +3337,13 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
kind=SLACK_INTEGRATION_KIND,
integration_id=slack_team_id,
).exists()
+ elif slack_team_id and authorship_integration_id:
+ # Mentioner check lives in the handler, so routing only confirms we own the integration.
+ local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team
+ id=authorship_integration_id, # nosemgrep: idor-taint-user-input-to-model-get
+ kind=SLACK_INTEGRATION_KIND,
+ integration_id=slack_team_id,
+ ).exists()
elif slack_team_id and dismiss_integration_id:
# Routing/region-ownership only — this just claims the workspace's integration locally.
# Authorization (report-team match + org-member gate) is enforced in _handle_signals_dismiss_report.
@@ -3358,6 +3454,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
return _handle_repo_picker_submit(payload)
if action_id == "posthog_code_repo_none":
return _handle_no_repo_needed_submit(payload)
+ if action_id == "posthog_code_continue_as_bot":
+ return _handle_continue_as_bot(payload)
if action_id == "posthog_code_terminate_task":
return _handle_terminate_task_submit(payload)
if action_id == CHANNEL_APPROVAL_ACTION_APPROVE:
diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.py
index f62e26fd7218..78524aaec344 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -32,6 +32,7 @@ SLACK_APP_OAUTH_FLAG = "slack-app-oauth"
SLACK_APP_HOME_FLAG = "slack-app-home"
SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"
SLACK_APP_ASSISTANT_FLAG = "slack-app-assistant"
+SLACK_APP_BOT_PRS_FLAG = "slack-app-bot-prs"
UNTAGGED_THREAD_FOLLOWUPS_FLAG = "posthog-slack-app-untagged-thread-followups"
@@ -135,6 +136,26 @@ def is_slack_app_untagged_thread_followups_enabled(integration: Integration, sla
return False
+def is_slack_app_bot_prs_enabled(team: Team) -> bool:
+ organization_id = str(team.organization_id)
+ project_id = str(team.id)
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ SLACK_APP_BOT_PRS_FLAG,
+ str(team.uuid),
+ groups={"organization": organization_id, "project": project_id},
+ group_properties={"organization": {"id": organization_id}, "project": {"id": project_id}},
+ person_properties=_region_properties(),
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception:
+ logger.exception("slack_app_bot_prs_flag_check_failed", team_id=team.id)
+ return False
+
+
def is_slack_app_assistant_enabled(team: Team) -> bool:
"""Kill-switch for the DM assistant. Evaluated on the workspace's team (a
stable key) so the feature can be checked before resolving the DMing user —
diff --git a/products/slack_app/backend/tests/test_guess_repository.py b/products/slack_app/backend/tests/test_guess_repository.py
index fbdb10f28f11..099b503556ee 100644
--- a/products/slack_app/backend/tests/test_guess_repository.py
+++ b/products/slack_app/backend/tests/test_guess_repository.py
@@ -132,6 +132,111 @@ class TestGetFullRepoNames:
assert result == ["posthog/alpha", "posthog/middle", "posthog/zebra"]
+@patch("products.slack_app.backend.api.GitHubIntegration")
+@patch("products.slack_app.backend.api.UserGitHubIntegration")
+class TestGetFullRepoNamesBotPRs:
+ @pytest.fixture(autouse=True)
+ def setup(self, db):
+ cache.clear()
+ self.organization = Organization.objects.create(name="Bot Org")
+ self.team = Team.objects.create(organization=self.organization, name="Bot Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="user-bot")
+ self.slack_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_BOT",
+ sensitive_config={"access_token": "xoxb-bot"},
+ )
+
+ def _create_team_github_integration(self) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="gh-team-1",
+ config={"account": {"name": "posthog"}},
+ sensitive_config={"access_token": "gh-team-token"},
+ )
+
+ @patch("products.slack_app.backend.api.posthoganalytics.feature_enabled", return_value=False)
+ def test_flag_off_excludes_team_repos(self, _mock_feature_enabled, mock_user_github_class, mock_team_github_class):
+ _create_user_github_integration(self.user)
+ self._create_team_github_integration()
+
+ mock_user_github = MagicMock()
+ mock_user_github.list_all_cached_repositories.return_value = [
+ _repo_dict("posthog", "posthog", 1),
+ _repo_dict("posthog", "posthog-js", 2),
+ ]
+ mock_user_github_class.return_value = mock_user_github
+
+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)
+
+ # The team install is present but, with the flag off, must never be consulted.
+ assert result == ["posthog/posthog", "posthog/posthog-js"]
+ mock_team_github_class.assert_not_called()
+
+ @patch("products.slack_app.backend.api.posthoganalytics.feature_enabled", return_value=True)
+ def test_flag_on_no_team_install_returns_only_user_repos(
+ self, _mock_feature_enabled, mock_user_github_class, mock_team_github_class
+ ):
+ _create_user_github_integration(self.user)
+
+ mock_user_github = MagicMock()
+ mock_user_github.list_all_cached_repositories.return_value = [
+ _repo_dict("posthog", "posthog", 1),
+ _repo_dict("posthog", "posthog-js", 2),
+ ]
+ mock_user_github_class.return_value = mock_user_github
+
+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)
+
+ assert result == ["posthog/posthog", "posthog/posthog-js"]
+ mock_team_github_class.assert_not_called()
+
+ @patch("products.slack_app.backend.api.posthoganalytics.feature_enabled", return_value=True)
+ def test_flag_on_unions_user_and_team_repos(
+ self, _mock_feature_enabled, mock_user_github_class, mock_team_github_class
+ ):
+ _create_user_github_integration(self.user)
+ self._create_team_github_integration()
+
+ mock_user_github = MagicMock()
+ mock_user_github.list_all_cached_repositories.return_value = [
+ _repo_dict("posthog", "posthog-js", 1),
+ _repo_dict("posthog", "shared", 2),
+ ]
+ mock_user_github_class.return_value = mock_user_github
+
+ mock_team_github = MagicMock()
+ mock_team_github.list_all_cached_repositories.return_value = [
+ _repo_dict("posthog", "posthog", 3),
+ _repo_dict("posthog", "shared", 2),
+ ]
+ mock_team_github_class.return_value = mock_team_github
+
+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)
+
+ assert result == ["posthog/posthog", "posthog/posthog-js", "posthog/shared"]
+
+ @patch("products.slack_app.backend.api.posthoganalytics.feature_enabled", return_value=True)
+ def test_flag_on_no_personal_install_returns_team_repos(
+ self, _mock_feature_enabled, mock_user_github_class, mock_team_github_class
+ ):
+ self._create_team_github_integration()
+
+ mock_team_github = MagicMock()
+ mock_team_github.list_all_cached_repositories.return_value = [
+ _repo_dict("posthog", "posthog", 1),
+ _repo_dict("posthog", "plugin-server", 2),
+ ]
+ mock_team_github_class.return_value = mock_team_github
+
+ result = _get_full_repo_names(self.slack_integration, user_id=self.user.id)
+
+ assert result == ["posthog/plugin-server", "posthog/posthog"]
+ mock_user_github_class.assert_not_called()
+
+
@patch("products.slack_app.backend.api.UserGitHubIntegration")
class TestGetFullRepoNamesCache:
@pytest.fixture(autouse=True)
diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
index 10b2004d7726..b8b52ada8f62 100644
--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py
+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
@@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.core.cache import cache
from django.test import TestCase, override_settings
+from parameterized import parameterized
from rest_framework.test import APIClient
from posthog.models.integration import Integration
@@ -233,6 +234,88 @@ class TestRepoPickerOptions(TestCase):
update_call = mock_webclient_class.return_value.chat_update.call_args.kwargs
assert "without a repository" in update_call["text"].lower()
+ @patch("posthog.models.integration.WebClient")
+ @patch("products.slack_app.backend.api.sync_connect")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_continue_as_bot_signals_authorship_confirmed(self, mock_config, mock_sync_connect, mock_webclient_class):
+ from posthog.temporal.ai.slack_app.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflow
+
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_webclient_class.return_value = MagicMock()
+ mock_handle = MagicMock()
+ mock_handle.signal = AsyncMock()
+ mock_sync_connect.return_value.get_workflow_handle.return_value = mock_handle
+
+ payload = {
+ "type": "block_actions",
+ "user": {"id": "U123"},
+ "actions": [
+ {
+ "action_id": "posthog_code_continue_as_bot",
+ "value": json.dumps(
+ {
+ "workflow_id": "posthog-code-mention-T12345:C001:1234.5678",
+ "integration_id": self.posthog_code_integration.id,
+ "mentioning_slack_user_id": "U123",
+ }
+ ),
+ "action_ts": "1700000000.123",
+ }
+ ],
+ "channel": {"id": "C001"},
+ "message": {"ts": "1234.9999"},
+ }
+ response = self._post_interactivity(payload)
+ assert response.status_code == 200
+ mock_sync_connect.return_value.get_workflow_handle.assert_called_once_with(
+ "posthog-code-mention-T12345:C001:1234.5678"
+ )
+ mock_handle.signal.assert_called_once_with(PostHogCodeSlackMentionWorkflow.authorship_confirmed)
+ mock_webclient_class.return_value.chat_update.assert_called_once()
+
+ @parameterized.expand(
+ [
+ ("clicker_mismatch", "U_OTHER", "U123"),
+ ("missing_expected_user_fails_closed", "U123", None),
+ ]
+ )
+ @patch("posthog.models.integration.WebClient")
+ @patch("products.slack_app.backend.api.sync_connect")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_continue_as_bot_does_not_signal_without_verified_mentioner(
+ self, _name, clicker_id, expected_user_id, mock_config, mock_sync_connect, mock_webclient_class
+ ):
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_webclient_class.return_value = MagicMock()
+ mock_handle = MagicMock()
+ mock_handle.signal = AsyncMock()
+ mock_sync_connect.return_value.get_workflow_handle.return_value = mock_handle
+
+ value = {
+ "workflow_id": "posthog-code-mention-T12345:C001:1234.5678",
+ "integration_id": self.posthog_code_integration.id,
+ }
+ if expected_user_id is not None:
+ value["mentioning_slack_user_id"] = expected_user_id
+
+ payload = {
+ "type": "block_actions",
+ "user": {"id": clicker_id},
+ "actions": [
+ {
+ "action_id": "posthog_code_continue_as_bot",
+ "value": json.dumps(value),
+ "action_ts": "1700000000.123",
+ }
+ ],
+ "channel": {"id": "C001"},
+ "message": {"ts": "1234.9999"},
+ }
+ response = self._post_interactivity(payload)
+ assert response.status_code == 200
+ mock_sync_connect.assert_not_called()
+ mock_handle.signal.assert_not_called()
+
@patch("posthog.models.integration.WebClient")
@patch("products.slack_app.backend.api.SlackIntegration.slack_config")
def test_submit_without_workflow_id_posts_expired(self, mock_config, mock_webclient_class):
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 4eb34353ebc5..8e8899cc5e7a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2132,6 +2132,17 @@ def relay_task_run_message(
# --- Task run creation / start / cloud resume ---
+def user_can_author_repository(user_id: int, repository: str) -> bool:
+ from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import path
+ get_user_github_integration,
+ user_github_integration_is_usable,
+ )
+
+ user = User.objects.filter(id=user_id).first()
+ integration = get_user_github_integration(user, repository=repository, allow_refresh=False)
+ return user_github_integration_is_usable(integration)
+
+
def _ensure_task_team_github_integration(task: Task) -> bool:
if task.github_integration_id is not None:
return True