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.

fix(slack_app): stop gating mentions on a personal GitHub (#80074)

Vojta Bartoš855b92f0ba0f
diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.py
index a6dfc9f910cb..9f226b140969 100644
--- a/posthog/temporal/ai/slack_app/__init__.py
+++ b/posthog/temporal/ai/slack_app/__init__.py
@@ -26,12 +26,10 @@ from posthog.temporal.ai.slack_app.activities import (
handle_posthog_code_slack_mention_command_activity,
mark_slack_app_message_processing_activity,
mark_slack_app_message_queued_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,
@@ -65,9 +63,7 @@ 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,
@@ -114,12 +110,10 @@ __all__ = [
"handle_posthog_code_slack_mention_command_activity",
"mark_slack_app_message_processing_activity",
"mark_slack_app_message_queued_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 503d963f9077..26fbc729e2de 100644
--- a/posthog/temporal/ai/slack_app/activities/__init__.py
+++ b/posthog/temporal/ai/slack_app/activities/__init__.py
@@ -14,12 +14,10 @@ from posthog.temporal.ai.slack_app.activities.messaging import (
block_posthog_code_task_if_no_personal_github_activity,
mark_slack_app_message_processing_activity,
mark_slack_app_message_queued_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,
@@ -68,12 +66,10 @@ __all__ = [
"handle_posthog_code_slack_mention_command_activity",
"mark_slack_app_message_processing_activity",
"mark_slack_app_message_queued_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/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.py
index 2eca04e7ed51..50355b63ab39 100644
--- a/posthog/temporal/ai/slack_app/activities/classifiers.py
+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py
@@ -66,8 +66,8 @@ def classify_task_needs_repo(
Biased toward False: a false negative answers an analytics ask with no repo
(recoverable — the user re-asks with code intent), while a false positive
- walls the user behind the Connect-GitHub gate even for "what's my DAU".
- Defaults to False on error for the same reason.
+ spends a discovery-agent sandbox run on "what's my DAU". Defaults to False
+ on error for the same reason.
"""
conversation = "\n".join(f"{msg['user']}: {msg['text']}" for msg in thread_messages)
normalized = f"{conversation}\nLatest message: {event_text}".lower()
@@ -152,8 +152,8 @@ def classify_task_needs_repo(
"event names, identification logic, SDK setup) — that's a code fix in their repo → "
"needs_repo. When in doubt, lean needs_repo=false — code-focused tasks usually carry "
"explicit signals (file extensions, 'PR', 'commit', framework names, function or class "
- "names). Analytics, data, and configuration asks are the common case and should not be "
- "walled behind a Connect-GitHub prompt on a guess.\n\n"
+ "names). Analytics, data, and configuration asks are the common case and should not send "
+ "us hunting for a repository on a guess.\n\n"
f"Conversation:\n{conversation}\n\n"
f"Latest message: {event_text}\n\n"
'Respond with ONLY a JSON object: {{"needs_repo": true}} or {{"needs_repo": false}}'
diff --git a/posthog/temporal/ai/slack_app/activities/messaging.py b/posthog/temporal/ai/slack_app/activities/messaging.py
index 8fa1b878a6dd..b762891afeb9 100644
--- a/posthog/temporal/ai/slack_app/activities/messaging.py
+++ b/posthog/temporal/ai/slack_app/activities/messaging.py
@@ -1,4 +1,3 @@
-import json
from typing import Any
import structlog
@@ -169,7 +168,6 @@ 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 usable personal GitHub.
@@ -190,7 +188,6 @@ def block_posthog_code_task_if_no_personal_github_activity(
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
inputs = coerce_mention_workflow_inputs(inputs)
@@ -204,13 +201,6 @@ def block_posthog_code_task_if_no_personal_github_activity(
kind="slack",
integration_id=inputs.slack_team_id,
)
- 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
-
# A stale row (present but unusable) gets reconnect wording; a missing one gets setup wording.
has_stale_github = UserIntegration.objects.filter(
user_id=user_id,
@@ -230,164 +220,6 @@ def block_posthog_code_task_if_no_personal_github_activity(
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.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
-
- inputs = coerce_mention_workflow_inputs(inputs)
- if tasks_facade.user_can_author_repository(user_id, repository):
- return "proceed"
-
- # Three states remain once we can't author: usable credentials without access to this
- # repo, a stale row whose credentials have expired, or no personal row at all. They need
- # different wording — the stale case must not read as a repo-access problem.
- has_usable_personal_github = tasks_facade.user_has_usable_personal_github(user_id)
- has_personal_github_row = UserIntegration.objects.filter(
- user_id=user_id,
- kind=UserIntegration.IntegrationKind.GITHUB,
- ).exists()
- github_stale = has_personal_github_row and not has_usable_personal_github
- 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 github_stale:
- text = (
- "Your personal GitHub connection has expired, so the PR will be authored by the "
- "PostHog bot.\nTo change this, reconnect your personal integration."
- )
- elif has_usable_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_usable_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,
- reconnect=github_stale,
- )
- return "blocked"
-
-
-@close_db_connections
-def post_posthog_code_authorship_timeout_activity(
- inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str
-) -> None:
- from products.slack_app.backend.models import SlackThreadTaskMapping
-
- inputs = coerce_mention_workflow_inputs(inputs)
- # 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.",
- )
-
-
@activity.defn
@close_db_connections
def post_posthog_code_picker_timeout_activity(
diff --git a/posthog/temporal/ai/slack_app/activities/repo_selection.py b/posthog/temporal/ai/slack_app/activities/repo_selection.py
index 411c7b2d7a76..251d8bfefa94 100644
--- a/posthog/temporal/ai/slack_app/activities/repo_selection.py
+++ b/posthog/temporal/ai/slack_app/activities/repo_selection.py
@@ -57,8 +57,8 @@ def cascade_posthog_code_repository_activity(
if not all_repos:
# No repos means no repo, whatever the team has installed. Deciding here that the user must
# connect a personal install would gate the mention before anyone has asked whether it is
- # even about code; `no_repo` routes through the repo-need classifier first, so analytics and
- # configuration asks get answered and only genuine coding asks reach the Connect-GitHub prompt.
+ # even about code; `no_repo` becomes a repo-less task instead, and the agent tells the user
+ # to connect GitHub only once it can see that the ask needs code.
return PostHogCodeRepoCascadeOutcome(mode="no_repo", repository=None, reason="no_repos")
if len(all_repos) == 1:
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 e5d3fed0016a..12efb7292d76 100644
--- a/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
+++ b/posthog/temporal/ai/slack_app/posthog_code_slack_mention.py
@@ -20,11 +20,9 @@ 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
@@ -35,6 +33,7 @@ POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES = 15
# Temporal patch IDs — arbitrary strings recorded in workflow history.
_PATCH_ID_FILE_ONLY_FOLLOWUP_BYPASS = "slack-file-only-followup-bypass-v1"
_PATCH_ID_MODEL_CLASSIFIER = "slack-app-model-classifier-v1"
+_PATCH_ID_NO_PERSONAL_GITHUB_GATE = "slack-no-personal-github-gate-v1"
@workflow.defn(name="posthog-code-slack-mention-processing")
@@ -42,7 +41,6 @@ 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:
@@ -56,51 +54,11 @@ 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
@@ -215,40 +173,30 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
if cascade.mode == "auto":
repository = cascade.repository
elif cascade.mode == "no_repo":
- # Cascade emits `no_repo` whenever the mentioning user resolves no
- # repos. Classify first so non-coding asks ("how do I configure
- # retention?") still answer with no repo; coding asks surface the
- # connect-personal-GitHub prompt instead of silently no-op'ing.
+ # Cascade emits `no_repo` whenever the mentioning user resolves no repos.
+ # The mention still becomes a task. Whether the ask needs code is the
+ # agent's call once it can see the request, and the agent is the one that
+ # tells the user to connect GitHub if it turns out to need a repo. Deciding
+ # that here meant a single false positive from the needs-repo classifier
+ # walled a plain analytics question behind a Connect button.
repository = None
- needs_repo = await _execute_posthog_code_activity(
- classify_posthog_code_task_needs_repo_activity,
- event.get("text", ""),
- thread_messages,
- )
- if needs_repo:
- blocked = await _execute_posthog_code_activity(
- block_posthog_code_task_if_no_personal_github_activity,
- inputs,
- channel,
- thread_ts,
- user_id,
+ if not workflow.patched(_PATCH_ID_NO_PERSONAL_GITHUB_GATE):
+ # Replay-only, for executions that recorded the classify-then-block pair.
+ needs_repo = await _execute_posthog_code_activity(
+ classify_posthog_code_task_needs_repo_activity,
+ event.get("text", ""),
+ thread_messages,
)
- if blocked:
- return
- elif cascade.mode == "needs_user_github":
- # Replay-only: the cascade no longer emits this mode, because gating on a
- # missing personal install before classifying the ask walled analytics
- # questions behind the Connect button. Kept so executions that recorded it
- # before the change still replay against the same command sequence; drop it
- # once the workflow history retention window has elapsed.
- await _execute_posthog_code_activity(
- block_posthog_code_task_if_no_personal_github_activity,
- inputs,
- channel,
- thread_ts,
- user_id,
- )
- return
+ if needs_repo:
+ blocked = await _execute_posthog_code_activity(
+ block_posthog_code_task_if_no_personal_github_activity,
+ inputs,
+ channel,
+ thread_ts,
+ user_id,
+ )
+ if blocked:
+ return
else:
# Multiple candidates and no explicit mention. Cheap Haiku
# check first to skip the agent entirely for analytics/config
@@ -303,12 +251,6 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
)
return
repository = self._selected_repo
- 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
# Read a per-task model choice ("use fable for this one") out of the
# mention. Runs here, past every gate that can still abandon the
# mention, so the reply announcing the model only ever describes a task
@@ -357,22 +299,6 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
)
-async def _gate_on_personal_github(
- inputs: PostHogCodeSlackMentionWorkflowInputs,
- channel: str,
- thread_ts: str,
- user_id: int,
-) -> bool:
- """Return True when the workflow must abort because the mentioner has no personal GitHub."""
- return await _execute_posthog_code_activity(
- block_posthog_code_task_if_no_personal_github_activity,
- inputs,
- channel,
- thread_ts,
- user_id,
- )
-
-
async def _execute_posthog_code_activity(activity_fn: Any, *args: Any) -> Any:
return await workflow.execute_activity(
activity_fn,
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 04cb5c9fbd7c..5cad30d7ea21 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, True],
+ args=[picker_inputs, channel, thread_ts, user_id],
start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),
retry_policy=RetryPolicy(maximum_attempts=3),
)
diff --git a/posthog/temporal/ai/slack_app/slack_app_mention.py b/posthog/temporal/ai/slack_app/slack_app_mention.py
index e7ff8e68dcb7..3c7c823a5808 100644
--- a/posthog/temporal/ai/slack_app/slack_app_mention.py
+++ b/posthog/temporal/ai/slack_app/slack_app_mention.py
@@ -36,9 +36,9 @@ SLACK_APP_MENTION_SEED_IN_INIT_PATCH = "slack-app-mention-seed-in-init"
# The queue awaits each child serially, so a child that never completes stalls every
# later message in the conversation and the user sees nothing but an :eyes: reaction
-# that never resolves. The ceiling sits above any healthy run: the child's own waits
-# (15 minutes for the repo picker, 15 more for authorship confirmation) plus its
-# 10-minute activity timeouts stay well inside an hour.
+# that never resolves. The ceiling sits above any healthy run: the child's own wait
+# (15 minutes for the repo picker) plus its 10-minute activity timeouts stay well
+# inside an hour.
SLACK_APP_MENTION_CHILD_EXECUTION_TIMEOUT = timedelta(hours=1)
# Bounding the child and telling the user when it dies both add workflow commands, so
# executions started before this shipped keep replaying the unbounded, silent path.
@@ -71,8 +71,8 @@ class SlackAppMentionWorkflow(PostHogWorkflow):
up as ``new_message`` signals, and the loop runs each one as a child
``PostHogCodeSlackMentionWorkflow`` — under the same per-message workflow
ID the flag-off dispatch would use — awaiting its completion before
- starting the next. Interactive signals (repo picker, authorship
- confirmation) never touch this workflow: the child bakes its own ID into
+ starting the next. Interactive signals (the repo picker) never touch this
+ workflow: the child bakes its own ID into
the prompts it posts, so the interactivity webhook signals the child
directly, exactly as in the standalone shape. After the idle timeout with
an empty queue the workflow completes; the next message simply starts a
diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.py
index 06de55ddb126..babeefd0e391 100644
--- a/posthog/temporal/ai/slack_app/types.py
+++ b/posthog/temporal/ai/slack_app/types.py
@@ -150,10 +150,10 @@ class PostHogCodeRepoCascadeOutcome:
"""Synchronous fast-path repo resolution before the discovery agent runs.
`auto` → use `repository` directly. `no_repo` → the mentioning user resolves no
- repos, so the workflow classifies the ask and only gates on a personal GitHub
- install when it actually needs code. `agent_needed` → there are multiple
- candidates and no explicit mention. `needs_user_github` is no longer emitted and
- survives only so workflow executions that recorded it still replay.
+ repos, so the mention becomes a repo-less task and the agent decides whether the
+ ask needs code. `agent_needed` → there are multiple candidates and no explicit
+ mention. `needs_user_github` is neither emitted nor handled any more; the value
+ stays in the `Literal` only so an old payload still parses.
"""
mode: Literal["auto", "no_repo", "agent_needed", "needs_user_github"]
diff --git a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
index 31cdbb8ad1a3..8c4dedd0f6a8 100644
--- a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
+++ b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
@@ -62,6 +62,10 @@ class _Recorder:
self.forward_results: dict[str, bool] = {}
# ts -> cascade mode; missing means "auto" with a fixed repository.
self.cascade_modes: dict[str, Literal["auto", "no_repo", "agent_needed", "needs_user_github"]] = {}
+ # ts per personal-GitHub gate call, in execution order.
+ self.github_gate_calls: list[str] = []
+ # event text per needs-repo classifier call, in execution order.
+ self.needs_repo_calls: list[str] = []
# ts -> gate the create-task fake blocks on, to hold a message mid-processing.
self.create_gates: dict[str, asyncio.Event] = {}
self.create_reached: dict[str, asyncio.Event] = {}
@@ -117,6 +121,7 @@ def _fake_activities(rec: _Recorder) -> list:
@activity.defn(name="classify_posthog_code_task_needs_repo_activity")
async def needs_repo(event_text: str, thread_messages: list[dict[str, str]]) -> bool:
+ rec.needs_repo_calls.append(event_text)
return True
@activity.defn(name="discover_posthog_code_repository_via_agent_activity")
@@ -144,27 +149,17 @@ def _fake_activities(rec: _Recorder) -> list:
rec.picker_workflow_id = workflow_id
rec.picker_posted.set()
- @activity.defn(name="resolve_posthog_code_authorship_activity")
- async def resolve_authorship(
- inputs: PostHogCodeSlackMentionWorkflowInputs,
- channel: str,
- thread_ts: str,
- slack_user_id: str,
- user_id: int,
- workflow_id: str,
- repository: str,
- ) -> str:
- return "proceed"
-
@activity.defn(name="block_posthog_code_task_if_no_personal_github_activity")
async def block_github(
inputs: PostHogCodeSlackMentionWorkflowInputs,
channel: str,
thread_ts: str,
user_id: int,
- allow_bot_prs: bool = False,
) -> bool:
- return False
+ rec.github_gate_calls.append(inputs.event["ts"])
+ # Blocks whenever it is reached, so a test that expects a task can only pass
+ # by not reaching it.
+ return True
@activity.defn(name="classify_slack_app_model_override_activity")
async def classify_model_override(input: SlackAppModelOverrideInput) -> SlackAppModelOverride | None:
@@ -198,10 +193,6 @@ def _fake_activities(rec: _Recorder) -> list:
async def picker_timeout(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:
return None
- @activity.defn(name="post_posthog_code_authorship_timeout_activity")
- async def authorship_timeout(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:
- return None
-
@activity.defn(name="post_posthog_code_internal_error_activity")
async def internal_error(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:
rec.internal_errors.append(inputs.event["ts"])
@@ -231,12 +222,10 @@ def _fake_activities(rec: _Recorder) -> list:
needs_repo,
discover,
post_picker,
- resolve_authorship,
block_github,
classify_model_override,
create_task,
picker_timeout,
- authorship_timeout,
internal_error,
resolve_user,
]
@@ -383,6 +372,20 @@ async def test_duplicate_slack_event_id_is_processed_once():
assert rec.created == [("1.1", "org/auto-repo")]
+async def test_mention_resolving_no_repo_creates_a_task_without_the_github_gate():
+ rec = _Recorder()
+ rec.cascade_modes["1.1"] = "no_repo"
+
+ async with _Harness(rec) as h:
+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", _message("1.1"))
+ await asyncio.wait_for(handle.result(), timeout=30)
+
+ assert rec.created == [("1.1", None)]
+ assert rec.github_gate_calls == []
+ assert rec.needs_repo_calls == []
+
+
@pytest.mark.asyncio
async def test_untagged_followup_forwards_without_task_creation_or_reactions():
rec = _Recorder()
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 6da45aa675cc..3dfaca84e78b 100644
--- a/posthog/temporal/tests/ai/test_block_missing_user_github.py
+++ b/posthog/temporal/tests/ai/test_block_missing_user_github.py
@@ -2,8 +2,6 @@ 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
@@ -113,36 +111,6 @@ 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.temporal.ai.slack_app.activities.messaging.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.temporal.ai.slack_app.activities.messaging.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
deleted file mode 100644
index 97d029b4a88d..000000000000
--- a/posthog/temporal/tests/ai/test_cascade_bot_prs.py
+++ /dev/null
@@ -1,97 +0,0 @@
-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"
-
- @parameterized.expand(
- [
- ("with_team_install", True),
- ("without_team_install", False),
- ]
- )
- @patch("products.slack_app.backend.api.GitHubIntegration")
- @patch("products.slack_app.backend.api.posthoganalytics.feature_enabled", return_value=False)
- def test_flag_off_defers_gating_to_the_workflow_classifier(
- self, _name, has_team_install, _mock_feature_enabled, mock_team_github_class
- ):
- # A team install must not turn an unresolved repo into a hard gate: `no_repo` sends the
- # workflow through the repo-need classifier, so analytics asks get answered rather than
- # walled behind the Connect-GitHub prompt.
- if has_team_install:
- 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 == "no_repo"
- mock_team_github_class.assert_not_called()
diff --git a/posthog/temporal/tests/ai/test_cascade_team_install.py b/posthog/temporal/tests/ai/test_cascade_team_install.py
new file mode 100644
index 000000000000..08e6dd061a6c
--- /dev/null
+++ b/posthog/temporal/tests/ai/test_cascade_team_install.py
@@ -0,0 +1,82 @@
+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,
+ )
+
+
+class TestCascadeTeamInstall(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={}
+ )
+
+ @parameterized.expand(
+ [
+ ("with_team_install", True),
+ ("without_team_install", False),
+ ]
+ )
+ def test_a_team_install_contributes_no_repos(self, _name, has_team_install):
+ # Repo resolution reads the mentioner's personal install only, so a workspace whose
+ # team install covers the repo still resolves `no_repo` for a user without one.
+ if has_team_install:
+ Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="gh-team-1",
+ config={"account": {"name": "posthog"}},
+ sensitive_config={"access_token": "gh-team-token"},
+ )
+
+ outcome = cascade_posthog_code_repository_activity(
+ _make_inputs(self.slack_integration.id), "fix the thing", self.user.id
+ )
+
+ assert outcome.mode == "no_repo"
+
+ @patch("products.slack_app.backend.api.UserGitHubIntegration")
+ def test_a_personal_install_resolves_its_single_repo(self, mock_user_github_class):
+ from posthog.models.user_integration import UserIntegration
+
+ UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.GITHUB,
+ integration_id="gh-user-1",
+ config={},
+ sensitive_config={"access_token": "gh-user-token"},
+ )
+ mock_user_github = MagicMock()
+ mock_user_github.list_all_cached_repositories.return_value = [
+ {"id": 1, "name": "posthog", "full_name": "posthog/posthog"}
+ ]
+ mock_user_github_class.return_value = mock_user_github
+
+ outcome = cascade_posthog_code_repository_activity(
+ _make_inputs(self.slack_integration.id), "fix the thing", self.user.id
+ )
+
+ assert outcome.mode == "auto"
+ assert outcome.repository == "posthog/posthog"
diff --git a/posthog/temporal/tests/ai/test_resolve_authorship.py b/posthog/temporal/tests/ai/test_resolve_authorship.py
deleted file mode 100644
index 7bb8b2691c96..000000000000
--- a/posthog/temporal/tests/ai/test_resolve_authorship.py
+++ /dev/null
@@ -1,156 +0,0 @@
-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.temporal.ai.slack_app.activities.messaging.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", "can't author PRs"),
- ("no_repo_access_flag_off", ["posthog/other-repo"], None, False, "blocked", "can't author PRs"),
- ("expired_refresh_token_flag_on", ["posthog/target-repo"], 1, True, "awaiting_confirmation", "expired"),
- ("expired_refresh_token_flag_off", ["posthog/target-repo"], 1, False, "blocked", "expired"),
- ]
- )
- @patch("posthog.temporal.ai.slack_app.activities.messaging.SlackIntegration")
- def test_unusable_personal_github_never_proceeds(
- self, _name, repos, refresh_token_expires_at, flag_on, expected_status, expected_text, 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 expected_text in kwargs["text"]
-
- @patch("products.slack_app.backend.feature_flags.posthoganalytics.feature_enabled", return_value=False)
- @patch("posthog.temporal.ai.slack_app.activities.messaging.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.temporal.ai.slack_app.activities.messaging.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.temporal.ai.slack_app.activities.messaging.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.temporal.ai.slack_app.activities.messaging.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 bb3a50a62e6a..c81a7718fc81 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -27,7 +27,6 @@ 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,
@@ -63,7 +62,6 @@ from products.slack_app.backend.feature_flags import (
ASSISTANT_REQUIRED_SCOPES,
is_slack_app_assistant_enabled,
is_slack_app_assistant_flag_enabled,
- is_slack_app_bot_prs_enabled,
is_slack_app_oauth_enabled,
is_slack_app_untagged_thread_followups_enabled,
)
@@ -920,16 +918,7 @@ 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]:
- """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]
-
-
-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."""
+ """Repo names available to the mentioner, from their personal GitHub install. Cached per user."""
if user_id is None:
return []
cache_key = _user_repo_list_cache_key(user_id)
@@ -969,17 +958,6 @@ def _get_user_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,
@@ -3449,73 +3427,6 @@ 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."""
@@ -4204,7 +4115,6 @@ 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)
alert_snooze_uuid = _extract_alert_snooze_hints(payload)
inbox_integration_id = inbox_interactivity.extract_inbox_hints(payload)
@@ -4232,13 +4142,6 @@ 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.
@@ -4362,8 +4265,6 @@ 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 eea4e39a9ecb..31f12bab20f9 100644
--- a/products/slack_app/backend/feature_flags.py
+++ b/products/slack_app/backend/feature_flags.py
@@ -38,7 +38,6 @@ 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"
SLACK_APP_LIVING_ARTIFACTS_FLAG = "slack-app-living-artifacts"
SLACK_APP_CANVAS_FILE_ARTIFACTS_FLAG = "slack-app-canvas-file-artifacts"
SLACK_APP_MODEL_CLASSIFIER_FLAG = "slack-app-model-classifier"
@@ -240,28 +239,6 @@ def is_slack_app_untagged_thread_followups_enabled(integration: Integration, sla
return False
-def is_slack_app_bot_prs_enabled(team: Team) -> bool:
- """Gate for the workspace's team GitHub install contributing repos alongside the
- mentioner's personal one. A GitHub-side capability, so this is the flag alone."""
- 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_flag_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 a13e216fdbc3..f8314fe90224 100644
--- a/products/slack_app/backend/tests/test_guess_repository.py
+++ b/products/slack_app/backend/tests/test_guess_repository.py
@@ -132,111 +132,6 @@ 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 8168fc01123d..4aa632e0089d 100644
--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py
+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
@@ -257,88 +257,6 @@ 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):