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(slack_app): serve commands from /posthog only (#103638)

Vojta Bartošfe365d3e43c4
diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.py
index 1ed2ac48b3d9..a3e1f43bafeb 100644
--- a/posthog/temporal/ai/slack_app/__init__.py
+++ b/posthog/temporal/ai/slack_app/__init__.py
@@ -23,7 +23,6 @@ from posthog.temporal.ai.slack_app.activities import (
discover_posthog_code_repository_via_agent_activity,
enforce_posthog_code_billing_quota_activity,
forward_posthog_code_followup_activity,
- handle_posthog_code_rules_command_activity,
handle_posthog_code_slack_mention_command_activity,
mark_slack_app_message_processing_activity,
mark_slack_app_message_queued_activity,
@@ -40,7 +39,6 @@ from posthog.temporal.ai.slack_app.types import (
SLACK_APP_PROCESSING_REACTION,
SLACK_APP_QUEUED_REACTION,
PostHogCodeRepoCascadeOutcome,
- PostHogCodeRulesCommandResult,
PostHogCodeSlackMentionCommandResult,
PostHogCodeSlackMentionCommandWorkflowInputs,
PostHogCodeSlackMentionWorkflowInputs,
@@ -73,7 +71,6 @@ SLACK_APP_ACTIVITIES = [
post_posthog_code_internal_error_activity,
create_posthog_code_task_for_repo_activity,
forward_posthog_code_followup_activity,
- handle_posthog_code_rules_command_activity,
create_posthog_code_routing_rule_activity,
handle_posthog_code_slack_mention_command_activity,
mark_slack_app_message_processing_activity,
@@ -89,7 +86,6 @@ __all__ = [
"SLACK_APP_PROCESSING_REACTION",
"SLACK_APP_QUEUED_REACTION",
"PostHogCodeRepoCascadeOutcome",
- "PostHogCodeRulesCommandResult",
"PostHogCodeSlackMentionCommandResult",
"PostHogCodeSlackMentionCommandWorkflowInputs",
"PostHogCodeSlackMentionWorkflowInputs",
@@ -116,7 +112,6 @@ __all__ = [
"discover_posthog_code_repository_via_agent_activity",
"enforce_posthog_code_billing_quota_activity",
"forward_posthog_code_followup_activity",
- "handle_posthog_code_rules_command_activity",
"handle_posthog_code_slack_mention_command_activity",
"mark_slack_app_message_processing_activity",
"mark_slack_app_message_queued_activity",
diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.py
index bb41f63a1786..7da66c185780 100644
--- a/posthog/temporal/ai/slack_app/activities/__init__.py
+++ b/posthog/temporal/ai/slack_app/activities/__init__.py
@@ -33,7 +33,6 @@ from posthog.temporal.ai.slack_app.activities.repo_selection import (
)
from posthog.temporal.ai.slack_app.activities.rules import (
create_posthog_code_routing_rule_activity,
- handle_posthog_code_rules_command_activity,
handle_posthog_code_slack_mention_command_activity,
)
from posthog.temporal.ai.slack_app.activities.task_creation import (
@@ -65,7 +64,6 @@ __all__ = [
"discover_posthog_code_repository_via_agent_activity",
"enforce_posthog_code_billing_quota_activity",
"forward_posthog_code_followup_activity",
- "handle_posthog_code_rules_command_activity",
"handle_posthog_code_slack_mention_command_activity",
"mark_slack_app_message_processing_activity",
"mark_slack_app_message_queued_activity",
diff --git a/posthog/temporal/ai/slack_app/activities/messaging.py b/posthog/temporal/ai/slack_app/activities/messaging.py
index 78f5c0a25966..5b8593352c33 100644
--- a/posthog/temporal/ai/slack_app/activities/messaging.py
+++ b/posthog/temporal/ai/slack_app/activities/messaging.py
@@ -22,7 +22,7 @@ POSTHOG_CODE_SLACK_MENTION_PICKER_GUIDANCE = (
"Please select the repository for this task. "
"Or click *No repo needed* to continue without one. "
"Or @mention me again and include the exact repository as `org/repo`. "
- 'You can also add routing rules with `@PostHog rules add "description" [org/repo]`.'
+ 'You can also add routing rules with `/posthog rules add "description" [org/repo]`.'
)
POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE = "Select the repository for this routing rule."
diff --git a/posthog/temporal/ai/slack_app/activities/rules.py b/posthog/temporal/ai/slack_app/activities/rules.py
index 1183e5dbe386..16c0a89c0d26 100644
--- a/posthog/temporal/ai/slack_app/activities/rules.py
+++ b/posthog/temporal/ai/slack_app/activities/rules.py
@@ -2,7 +2,6 @@ import structlog
from temporalio import activity
from posthog.temporal.ai.slack_app.types import (
- PostHogCodeRulesCommandResult,
PostHogCodeSlackMentionCommandResult,
PostHogCodeSlackMentionCommandWorkflowInputs,
PostHogCodeSlackMentionWorkflowInputs,
@@ -14,46 +13,6 @@ from products.slack_app.backend.services.slack_messages import post_slack_epheme
logger = structlog.get_logger(__name__)
-@close_db_connections
-def handle_posthog_code_rules_command_activity(
- inputs: PostHogCodeSlackMentionWorkflowInputs,
- channel: str,
- thread_ts: str,
- slack_user_id: str,
- user_id: int,
-) -> PostHogCodeRulesCommandResult:
- from posthog.models.integration import Integration, SlackIntegration
-
- from products.slack_app.backend.api import parse_rules_command
- from products.slack_app.backend.services.commands import dispatch_rules_command
-
- command = parse_rules_command(inputs.event.get("text", ""))
- if not command:
- return PostHogCodeRulesCommandResult(status="not_a_command")
- # Picker flow is unique to this workflow; the command service can't drive a
- # workflow signal, so catch it here before delegating.
- if command.action == "add" and not command.repository:
- return PostHogCodeRulesCommandResult(status="needs_picker", pending_rule_text=command.rule_text)
-
- integration = Integration.objects.select_related("team", "team__organization").get(
- id=inputs.integration_id,
- kind="slack",
- integration_id=inputs.slack_team_id,
- )
- dispatch_rules_command(
- command,
- SlackIntegration(integration),
- integration,
- channel=channel,
- thread_ts=thread_ts,
- slack_user_id=slack_user_id,
- slack_workspace_id=inputs.slack_team_id,
- user_id=user_id,
- )
- return PostHogCodeRulesCommandResult(status="handled")
-
-
@activity.defn
@close_db_connections
def create_posthog_code_routing_rule_activity(
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 e79309aecd92..b52673496a13 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
@@ -52,9 +52,8 @@ class PostHogCodeSlackMentionCommandWorkflow(PostHogWorkflow):
@workflow.run
async def run(self, inputs: PostHogCodeSlackMentionCommandWorkflowInputs) -> None:
- # The mention surface resolves the user at routing time and passes it in.
- # The slash surface passes ``None`` on purpose so its webhook ack stays
- # inside Slack's 3s budget, and resolution happens here instead.
+ # The slash surface passes ``None`` so its webhook ack stays inside Slack's 3s budget,
+ # and resolution happens here instead.
user_id = inputs.user_id
if user_id is None:
user_id = await workflow.execute_activity(
diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.py
index 1bd18b41bb7c..dd6e0469c6b5 100644
--- a/posthog/temporal/ai/slack_app/types.py
+++ b/posthog/temporal/ai/slack_app/types.py
@@ -186,19 +186,17 @@ class SlackAppProjectRoute(BaseModel):
integration_id: int
-@dataclass
+@frozen
class PostHogCodeSlackMentionCommandWorkflowInputs:
event: dict[str, Any]
integration_ids: list[int]
slack_team_id: str
- # Resolved at routing time on the mention path. The slash surface passes
- # ``None`` on purpose — it defers user resolution into the workflow's first
- # activity to keep its webhook ack under Slack's 3s budget — so the
- # in-workflow resolve fallback is permanent, not a legacy shim.
+ # ``None`` defers resolution into the workflow's first activity, keeping the webhook ack under
+ # Slack's 3s budget. The workflow branches on this, so removing either the field or the branch
+ # changes a recorded command sequence and breaks replay for runs in flight.
user_id: int | None = None
- # The invoking surface's prefix, used verbatim in user-facing help/error copy:
- # ``@PostHog`` for mentions, ``/posthog`` for the slash command.
- command_prefix: str = "@PostHog"
+ # Read from the payload rather than hardcoded, because a workspace can rename the command.
+ command_prefix: str = "/posthog"
@frozen
@@ -235,12 +233,6 @@ class SlackRepoSelectionOutcome:
repo_research_run_id: str | None = None
-@dataclass
-class PostHogCodeRulesCommandResult:
- status: str # "not_a_command" | "handled" | "needs_picker"
- pending_rule_text: str | None = None
-
-
@dataclass
class PostHogCodeSlackMentionCommandResult:
"""Outcome of the synchronous command-dispatch activity.
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 680e0d606715..f8271068ff35 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -66,7 +66,7 @@ from products.slack_app.backend.feature_flags import (
from products.slack_app.backend.helpers import local_dev_slack_email
from products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping, UntaggedFollowupMode
from products.slack_app.backend.services import inbox_interactivity, slack_welcome_messages, turn_feedback
-from products.slack_app.backend.services.commands import SLASH_COMMAND_PREFIX
+from products.slack_app.backend.services.commands import SLASH_COMMAND_PREFIX, mention_command_redirect
from products.slack_app.backend.services.integration_resolver import (
UserResolutionFailure,
load_integrations,
@@ -236,16 +236,11 @@ class SlackUserContext:
slack_email: str | None
-@dataclass
+@frozen
class RulesCommand:
- """Parsed `@PostHog <command>` mention text.
-
- Most actions (``list``, ``add``, ``remove``, ``help``, ``default_*``) are
- dispatched post-routing inside the Temporal workflow's first activity. The
- ``project_*`` actions are dispatched pre-routing — they decide which
- integration the workflow runs against — so the routing layer in `api.py`
- handles them before ``start_workflow`` and the workflow activity ignores
- them defensively.
+ """Parsed `/posthog <command>` text.
+
+ The same parser reads mention text, where a match means the mention is not a task description.
"""
action: Literal[
@@ -1652,9 +1647,8 @@ def _post_pick_a_project_hint(
"""Tell the user that this workspace is connected to multiple PostHog
projects, list the ones they can reach, and point at the two ways to pick one.
- The slash command is offered rather than the `@PostHog project <id>` mention because it
- reads the same on both surfaces this runs on: a channel mention and a DM, where there
- is no app to mention.
+ The slash command reads the same on both surfaces this runs on: a channel mention, and a DM,
+ where there is no app to mention in the first place.
Returns whether the hint was posted, so callers can record whether the user was
left with an explanation or with silence.
@@ -2430,10 +2424,19 @@ def route_posthog_code_event_to_relevant_region(
candidates = resolution.candidates
target = resolution.integration
- # Rules command is meaningful only when the user actually typed
- # ``@PostHog`` — an untagged thread reply can never be a rules command.
- if untagged_followup_mapping is None and parse_rules_command(event.get("text", "")) is not None:
- return _start_command_workflow(event, candidates, slack_team_id, event_id, user_id=posthog_user.id)
+ # Recognised but not run: unrecognised, ``@PostHog project 452770`` becomes a task about
+ # its own syntax. Only a message addressed to the app can be a command.
+ if untagged_followup_mapping is None:
+ mention_command = parse_rules_command(event.get("text", ""))
+ if mention_command is not None:
+ # The redirect reply is static, but its analytics event attributes to whichever
+ # install it is sent through, so use the resolution's stable tie-break rather than
+ # the head of ``candidates`` — that order reshuffles as auth verdicts expire.
+ redirect_probe = resolution.resolved_or_first()
+ if redirect_probe is not None:
+ return _redirect_mention_command(
+ mention_command, event, redirect_probe, slack_team_id, posthog_user=posthog_user
+ )
# A tagged-thread ``message`` is bound to its mapping's integration —
# the mapping was the user's last explicit choice in this thread, so no
@@ -2700,6 +2703,54 @@ def resolve_region_or_terminal_route(
return None
+def _redirect_mention_command(
+ command: RulesCommand,
+ event: dict[str, Any],
+ probe: Integration,
+ slack_team_id: str,
+ *,
+ posthog_user: User,
+) -> str:
+ """Point a mention that reads as a command at the slash command, without running it.
+
+ ``probe`` needs no project resolved first, because the reply is static text. It is still the
+ resolution's stable pick, so the analytics event lands on the same project every time.
+
+ The reply goes out ephemerally with no fallback: a channel-visible one would announce the
+ integration in an externally-shared channel that has not approved it yet.
+ """
+ channel = event.get("channel")
+ slack_user_id = event.get("user")
+ if not isinstance(channel, str) or not isinstance(slack_user_id, str):
+ return ROUTE_HANDLED_LOCALLY
+
+ logger.info(
+ "slack_app_mention_command_redirected",
+ slack_team_id=slack_team_id,
+ channel=channel,
+ action=command.action,
+ )
+ capture_slack_event(
+ probe,
+ "slack app command used",
+ slack_user_id=slack_user_id,
+ posthog_user=posthog_user,
+ action=command.action,
+ source="mention",
+ )
+ # Slack sets ``thread_ts`` to ``ts`` on a thread-opening post as well, and an ephemeral
+ # anchored there is invisible from the channel view the mentioner is looking at.
+ thread_ts = event.get("thread_ts")
+ _post_slack_user_ephemeral(
+ SlackIntegration(probe),
+ channel,
+ slack_user_id,
+ thread_ts if isinstance(thread_ts, str) and not _is_top_level_channel_post(event) else None,
+ mention_command_redirect(command),
+ )
+ return ROUTE_HANDLED_LOCALLY
+
+
def _start_command_workflow(
event: dict,
integrations: list[Integration],
@@ -2707,7 +2758,7 @@ def _start_command_workflow(
event_id: str | None,
*,
user_id: int | None,
- command_prefix: str = "@PostHog",
+ command_prefix: str,
) -> str:
# ``user_id=None`` defers user resolution into the workflow — the slash entry
# point uses it to keep its ack under Slack's 3s budget.
diff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.py
index c37536aa2b79..66ee1651713e 100644
--- a/products/slack_app/backend/models.py
+++ b/products/slack_app/backend/models.py
@@ -132,12 +132,12 @@ class SlackSettings(UUIDModel):
Two row shapes share this table:
- ``slack_user_id`` set → that Slack user's personal settings for this workspace.
- Written by the Slack `@PostHog project <id>` directive or the user-level
+ Written by the Slack `/posthog project <id>` command or the user-level
settings UI.
- ``slack_user_id IS NULL`` → workspace-wide fallback, applied when an
inbound event's Slack user has no personal row yet. Written via the
PostHog project-level settings UI by a team admin, or via the Slack
- `@PostHog project workspace <id>` directive by a Slack workspace
+ `/posthog project workspace <id>` command by a Slack workspace
admin/owner.
A user-specific row, if present, always wins over the workspace-wide row at
diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.py
index 4005ccf26ed7..47a5c68c5699 100644
--- a/products/slack_app/backend/services/commands.py
+++ b/products/slack_app/backend/services/commands.py
@@ -12,10 +12,23 @@ if TYPE_CHECKING:
MENTION_COMMAND_PREFIX = "@PostHog"
SLASH_COMMAND_PREFIX = "/posthog"
-MENTION_HELP_REDIRECT = (
- f"Run `{SLASH_COMMAND_PREFIX} help` to see the available commands. "
- "To start a task, mention me with a description of the work."
-)
+# `help` and the retired `default repo` verbs have no entry, so they fall back to the listing.
+_SLASH_EQUIVALENT = {
+ "list": "rules list",
+ "add": 'rules add "description" org/repo',
+ "remove": "rules remove <number>",
+ "project_show": "project",
+ "project_set": "project <id>",
+ "project_set_workspace": "project workspace <id>",
+}
+
+
+def mention_command_redirect(command: "RulesCommand") -> str:
+ """The reply to a mention that reads as a command. Only the slash surface runs commands."""
+ return (
+ f"Commands have moved. Run `{SLASH_COMMAND_PREFIX} {_SLASH_EQUIVALENT.get(command.action, 'help')}` instead.\n"
+ "To start a task, mention me with a description of the work."
+ )
def rule_text_too_long_message(rule_text: str) -> str:
@@ -54,10 +67,9 @@ def _handle_help(
*,
command_prefix: str,
) -> None:
- """Post the command listing. Only the slash surface reaches this; see ``dispatch_rules_command``."""
from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin
- # Task creation and thread follow-ups have no slash equivalent, but this listing is the only
+ # Task creation and thread follow-ups stay on the mention surface, and this listing is the only
# help a user can reach, so it documents them under the mention prefix they actually type.
lines = [
"*Available commands:*\n",
@@ -95,7 +107,7 @@ def _handle_rules_list(
thread_ts: str,
*,
slack_user_id: str,
- command_prefix: str = MENTION_COMMAND_PREFIX,
+ command_prefix: str,
) -> None:
from posthog.models.repo_routing_rule import RepoRoutingRule
@@ -200,7 +212,7 @@ def _handle_rules_remove(
rule_numbers: list[int] | None,
*,
slack_user_id: str,
- command_prefix: str = MENTION_COMMAND_PREFIX,
+ command_prefix: str,
) -> None:
from posthog.models.repo_routing_rule import RepoRoutingRule
@@ -252,7 +264,7 @@ def _handle_project_show(
user_id: int,
workspace_candidates: list[Integration] | None = None,
*,
- command_prefix: str = MENTION_COMMAND_PREFIX,
+ command_prefix: str,
) -> None:
from posthog.models.user import User
@@ -393,7 +405,7 @@ def _handle_project_set_workspace(
target_team_id: int,
workspace_candidates: list[Integration] | None = None,
*,
- command_prefix: str = MENTION_COMMAND_PREFIX,
+ command_prefix: str,
) -> None:
"""Set the workspace-wide default project (the ``slack_user_id IS NULL`` row),
which applies to every Slack user in the workspace without a personal default.
@@ -528,7 +540,7 @@ def dispatch_rules_command(
slack_workspace_id: str,
user_id: int,
workspace_candidates: list[Integration] | None = None,
- command_prefix: str = MENTION_COMMAND_PREFIX,
+ command_prefix: str,
) -> None:
"""Run the right handler for a parsed ``RulesCommand``. Assumes the caller has
already resolved a single ``integration`` to act on; project commands also
@@ -538,13 +550,13 @@ def dispatch_rules_command(
repo" reply. The mention workflow's picker flow must catch that case
*before* calling this dispatcher.
- ``command_prefix`` is the entry-point token surfaced in user-facing help and
- error strings — ``@PostHog`` for mentions, ``/posthog`` for the slash command
- surface. Defaults preserve the mention copy for existing callers.
+ ``command_prefix`` is the entry-point token surfaced in user-facing help and error strings. It
+ is the slash command as the workspace invoked it, which a workspace is free to rename, so it is
+ read from the payload rather than assumed to be ``/posthog``.
Commands configure the app rather than produce work: routing rules, project
defaults, the help listing. The answer concerns whoever ran the command, so
- every reply below goes out ephemerally, on both surfaces.
+ every reply below goes out ephemerally.
"""
from posthog.models.user import User
@@ -556,19 +568,11 @@ def dispatch_rules_command(
slack_user_id=slack_user_id,
posthog_user=User.objects.filter(id=user_id).first(),
action=command.action,
- source="mention" if command_prefix == MENTION_COMMAND_PREFIX else "slash_command",
+ source="slash_command",
)
if command.action == "help":
- # The slash command owns the listing, so a mention only points at it. Answering here
- # rather than inside the handler keeps the Slack users.info call the listing needs off
- # the mention path entirely.
- if command_prefix == MENTION_COMMAND_PREFIX:
- post_slack_ephemeral(
- slack.client, channel=channel, user=slack_user_id, thread_ts=thread_ts, text=MENTION_HELP_REDIRECT
- )
- else:
- _handle_help(slack, integration, channel, thread_ts, slack_user_id, command_prefix=command_prefix)
+ _handle_help(slack, integration, channel, thread_ts, slack_user_id, command_prefix=command_prefix)
elif command.action == "list":
_handle_rules_list(
slack,
diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.py
index 509349835833..58c0e27712cc 100644
--- a/products/slack_app/backend/services/integration_resolver.py
+++ b/products/slack_app/backend/services/integration_resolver.py
@@ -1,5 +1,5 @@
from collections.abc import Iterable
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal
from django.db.models import Q
@@ -7,6 +7,7 @@ from django.db.models import Q
import structlog
from posthog.comment.formatting import escape_slack_mrkdwn
+from posthog.dataclasses import frozen
from posthog.helpers.slack_scopes import bot_is_ready
from posthog.models.integration import Integration
from posthog.models.user import User
@@ -59,24 +60,29 @@ def user_resolution_failure_reply(
return None
-@dataclass
+def _resolved_or_oldest(integration: Integration | None, candidates: list[Integration]) -> Integration | None:
+ """The resolved integration, falling back to the oldest install in `candidates`.
+
+ Surfaces that must act on *some* integration rather than prompt for one share this
+ tie-break, so a workspace with no saved pick is answered for the same project
+ whichever surface handles it. Ordered by id rather than taken off the front of
+ `candidates`: the auth filter sorts that list freshest-verdict-first, which
+ reshuffles as cache entries expire and would make the fallback drift.
+ """
+ if integration is not None and integration in candidates:
+ return integration
+ return min(candidates, key=lambda candidate: candidate.id, default=None)
+
+
+@frozen
class ResolutionResult:
integration: Integration | None
source: ResolutionSource
candidates: list[Integration] = field(default_factory=list)
def resolved_or_first(self) -> Integration | None:
- """The resolved integration, falling back to the workspace's oldest install.
-
- Surfaces that must act on *some* integration rather than prompt for one share this
- tie-break, so a workspace with no saved pick is answered for the same project
- whichever surface handles it. Ordered by id rather than taken off the front of
- `candidates`: the auth filter sorts that list freshest-verdict-first, which
- reshuffles as cache entries expire and would make the fallback drift.
- """
- if self.integration is not None and self.integration in self.candidates:
- return self.integration
- return min(self.candidates, key=lambda candidate: candidate.id, default=None)
+ """The resolved integration, falling back to the workspace's oldest install."""
+ return _resolved_or_oldest(self.integration, self.candidates)
def project_label(integration: Integration) -> str:
@@ -196,7 +202,7 @@ def resolve_from_candidates(
# Refuse a stale default whose target is no longer in the candidate
# set — e.g. the integration's kind was changed away from the one
# we were asked to resolve, or it was deleted+recreated. The user
- # can overwrite the row at any time with `@PostHog project <id>`.
+ # can overwrite the row at any time with `/posthog project <id>`.
if target.id not in candidate_ids:
continue
source: ResolutionSource = "user_default" if default.slack_user_id else "workspace_default"
@@ -288,7 +294,7 @@ def routable_projects(*, slack_team_id: str, slack_user_id: str, user: User) ->
return reachable if len(reachable) > 1 else []
-@dataclass
+@frozen
class UserAndIntegrationsResolution:
"""Outcome of the user identification + access-filter step.
@@ -308,6 +314,10 @@ class UserAndIntegrationsResolution:
failure_reason: UserResolutionFailure | None = None
slack_email: str | None = None
+ def resolved_or_first(self) -> Integration | None:
+ """The integration this resolution picked, falling back to the oldest one the user can reach."""
+ return _resolved_or_oldest(self.integration, self.candidates)
+
def resolve_user_for_workspace(
*,
diff --git a/products/slack_app/backend/tests/test_guess_repository.py b/products/slack_app/backend/tests/test_guess_repository.py
index 0cf8ee1e0c9b..271eb8aa659e 100644
--- a/products/slack_app/backend/tests/test_guess_repository.py
+++ b/products/slack_app/backend/tests/test_guess_repository.py
@@ -22,7 +22,6 @@ from products.slack_app.backend.api import (
_user_repo_list_cache_key,
parse_rules_command,
)
-from products.slack_app.backend.services.commands import MENTION_HELP_REDIRECT
def _repo_dict(org: str, name: str, repo_id: int = 1) -> dict:
@@ -424,7 +423,9 @@ class TestHandleRulesCommandActivity:
def setup(self, db):
self.organization = Organization.objects.create(name="Test Org")
self.team = Team.objects.create(organization=self.organization, name="Test Team")
- self.user = User.objects.create(email="[email protected]", distinct_id="user-1")
+ # Org membership matters: the command activity resolves its target through the
+ # access-filtered resolver, which drops a project the caller cannot reach.
+ self.user = User.objects.create_and_join(self.organization, "[email protected]", "pw")
self.integration = Integration.objects.create(
team=self.team,
@@ -438,6 +439,16 @@ class TestHandleRulesCommandActivity:
self.slack_user_id = "U_SLACK"
def _make_inputs(self, text: str):
+ from posthog.temporal.ai.slack_app import PostHogCodeSlackMentionCommandWorkflowInputs
+
+ return PostHogCodeSlackMentionCommandWorkflowInputs(
+ event={"text": text, "channel": self.channel, "thread_ts": self.thread_ts, "user": self.slack_user_id},
+ integration_ids=[self.integration.id],
+ slack_team_id="T12345",
+ user_id=self.user.id,
+ )
+
+ def _make_picker_inputs(self, text: str):
from posthog.temporal.ai.slack_app import PostHogCodeSlackMentionWorkflowInputs
return PostHogCodeSlackMentionWorkflowInputs(
@@ -452,40 +463,14 @@ class TestHandleRulesCommandActivity:
mock_slack = MagicMock()
mock_slack_cls.return_value = mock_slack
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs("<@U123> rules list"),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
- )
+ result = handle_posthog_code_slack_mention_command_activity(self._make_inputs("rules list"), self.user.id)
- assert result.status == "handled"
+ assert result.status == "done"
msg = mock_slack.client.chat_postEphemeral.call_args
assert "No routing rules" in msg.kwargs["text"]
- @patch("posthog.models.integration.SlackIntegration")
- def test_help_points_at_the_slash_command(self, mock_slack_cls):
- mock_slack = MagicMock()
- mock_slack_cls.return_value = mock_slack
-
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
-
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs("<@U123> help"),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
- )
-
- # The mention is still consumed as a command rather than becoming a task.
- assert result.status == "handled"
- msg = mock_slack.client.chat_postEphemeral.call_args
- assert msg.kwargs["text"] == MENTION_HELP_REDIRECT
-
@patch("posthog.models.integration.SlackIntegration")
def test_list_shows_rules(self, mock_slack_cls):
mock_slack = MagicMock()
@@ -498,17 +483,11 @@ class TestHandleRulesCommandActivity:
team=self.team, rule_text="Backend issues", repository="posthog/posthog", priority=1
)
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs("<@U123> rules list"),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
- )
+ result = handle_posthog_code_slack_mention_command_activity(self._make_inputs("rules list"), self.user.id)
- assert result.status == "handled"
+ assert result.status == "done"
msg = mock_slack.client.chat_postEphemeral.call_args
assert "JS SDK bugs" in msg.kwargs["text"]
assert "Backend issues" in msg.kwargs["text"]
@@ -521,17 +500,13 @@ class TestHandleRulesCommandActivity:
mock_slack = MagicMock()
mock_slack_cls.return_value = mock_slack
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs('<@U123> rules add "JS SDK bugs" posthog/posthog-js'),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
+ result = handle_posthog_code_slack_mention_command_activity(
+ self._make_inputs('rules add "JS SDK bugs" posthog/posthog-js'), self.user.id
)
- assert result.status == "handled"
+ assert result.status == "done"
rule = RepoRoutingRule.objects.get(team=self.team)
assert rule.rule_text == "JS SDK bugs"
assert rule.repository == "posthog/posthog-js"
@@ -539,18 +514,15 @@ class TestHandleRulesCommandActivity:
assert "Added rule" in msg.kwargs["text"]
def test_add_without_repo_returns_needs_picker(self):
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs('<@U123> rules add "JS SDK bugs"'),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
+ result = handle_posthog_code_slack_mention_command_activity(
+ self._make_inputs('rules add "JS SDK bugs"'), self.user.id
)
assert result.status == "needs_picker"
assert result.pending_rule_text == "JS SDK bugs"
+ assert result.target_integration_id == self.integration.id
@patch("products.slack_app.backend.api._get_full_repo_names", return_value=["posthog/posthog"])
@patch("posthog.models.integration.SlackIntegration")
@@ -558,17 +530,13 @@ class TestHandleRulesCommandActivity:
mock_slack = MagicMock()
mock_slack_cls.return_value = mock_slack
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs('<@U123> rules add "JS bugs" posthog/nonexistent'),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
+ result = handle_posthog_code_slack_mention_command_activity(
+ self._make_inputs('rules add "JS bugs" posthog/nonexistent'), self.user.id
)
- assert result.status == "handled"
+ assert result.status == "done"
assert RepoRoutingRule.objects.filter(team=self.team).count() == 0
msg = mock_slack.client.chat_postEphemeral.call_args
assert "not connected" in msg.kwargs["text"]
@@ -578,18 +546,14 @@ class TestHandleRulesCommandActivity:
mock_slack = MagicMock()
mock_slack_cls.return_value = mock_slack
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
long_rule = "x" * (RepoRoutingRule.MAX_RULE_TEXT_LENGTH + 1)
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs(f'<@U123> rules add "{long_rule}" posthog/posthog-js'),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
+ result = handle_posthog_code_slack_mention_command_activity(
+ self._make_inputs(f'rules add "{long_rule}" posthog/posthog-js'), self.user.id
)
- assert result.status == "handled"
+ assert result.status == "done"
assert RepoRoutingRule.objects.filter(team=self.team).count() == 0
msg = mock_slack.client.chat_postEphemeral.call_args
assert f"limit is {RepoRoutingRule.MAX_RULE_TEXT_LENGTH}" in msg.kwargs["text"]
@@ -599,21 +563,17 @@ class TestHandleRulesCommandActivity:
mock_slack = MagicMock()
mock_slack_cls.return_value = mock_slack
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
RepoRoutingRule.objects.bulk_create(
RepoRoutingRule(team=self.team, rule_text=f"Rule {n}", repository="posthog/posthog-js", priority=n)
for n in range(RepoRoutingRule.MAX_RULES_PER_TEAM)
)
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs('<@U123> rules add "One more" posthog/posthog-js'),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
+ result = handle_posthog_code_slack_mention_command_activity(
+ self._make_inputs('rules add "One more" posthog/posthog-js'), self.user.id
)
- assert result.status == "handled"
+ assert result.status == "done"
assert RepoRoutingRule.objects.filter(team=self.team).count() == RepoRoutingRule.MAX_RULES_PER_TEAM
msg = mock_slack.client.chat_postEphemeral.call_args
assert f"already has {RepoRoutingRule.MAX_RULES_PER_TEAM} rules" in msg.kwargs["text"]
@@ -627,7 +587,7 @@ class TestHandleRulesCommandActivity:
long_rule = "x" * (RepoRoutingRule.MAX_RULE_TEXT_LENGTH + 1)
create_posthog_code_routing_rule_activity(
- self._make_inputs("<@U123> ignored"),
+ self._make_picker_inputs("ignored"),
self.channel,
self.thread_ts,
self.user.id,
@@ -647,17 +607,11 @@ class TestHandleRulesCommandActivity:
RepoRoutingRule.objects.create(team=self.team, rule_text="First rule", repository="org/repo", priority=0)
RepoRoutingRule.objects.create(team=self.team, rule_text="Second rule", repository="org/repo2", priority=1)
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs("<@U123> rules remove 1"),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
- )
+ result = handle_posthog_code_slack_mention_command_activity(self._make_inputs("rules remove 1"), self.user.id)
- assert result.status == "handled"
+ assert result.status == "done"
assert RepoRoutingRule.objects.filter(team=self.team).count() == 1
remaining = RepoRoutingRule.objects.get(team=self.team)
assert remaining.rule_text == "Second rule"
@@ -669,33 +623,23 @@ class TestHandleRulesCommandActivity:
RepoRoutingRule.objects.create(team=self.team, rule_text="Only rule", repository="org/repo", priority=0)
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs("<@U123> rules remove 5"),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
- )
+ result = handle_posthog_code_slack_mention_command_activity(self._make_inputs("rules remove 5"), self.user.id)
- assert result.status == "handled"
+ assert result.status == "done"
assert RepoRoutingRule.objects.filter(team=self.team).count() == 1
msg = mock_slack.client.chat_postEphemeral.call_args
assert "does not exist" in msg.kwargs["text"]
def test_non_command_returns_not_a_command(self):
- from posthog.temporal.ai.slack_app import handle_posthog_code_rules_command_activity
+ from posthog.temporal.ai.slack_app import handle_posthog_code_slack_mention_command_activity
- result = handle_posthog_code_rules_command_activity(
- self._make_inputs("<@U123> fix the bug in posthog-js"),
- self.channel,
- self.thread_ts,
- self.slack_user_id,
- self.user.id,
+ result = handle_posthog_code_slack_mention_command_activity(
+ self._make_inputs("fix the bug in posthog-js"), self.user.id
)
- assert result.status == "not_a_command"
+ assert result.status == "done"
class TestRepoRoutingRuleModel:
diff --git a/products/slack_app/backend/tests/test_mention_command_activity.py b/products/slack_app/backend/tests/test_mention_command_activity.py
index a3ed51f2920a..719b89f730c7 100644
--- a/products/slack_app/backend/tests/test_mention_command_activity.py
+++ b/products/slack_app/backend/tests/test_mention_command_activity.py
@@ -10,8 +10,6 @@ from posthog.models.user import User
from posthog.temporal.ai.slack_app.activities.rules import handle_posthog_code_slack_mention_command_activity
from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionCommandWorkflowInputs
-from products.slack_app.backend.services.commands import MENTION_HELP_REDIRECT
-
class TestMentionCommandActivity:
@pytest.fixture(autouse=True)
@@ -26,54 +24,43 @@ class TestMentionCommandActivity:
)
self.user = User.objects.create_and_join(self.organization, "[email protected]", "pw")
- def _inputs(
- self, *, command_prefix: str, event_extra: dict[str, str]
- ) -> PostHogCodeSlackMentionCommandWorkflowInputs:
+ def _inputs(self, *, event_extra: dict[str, str]) -> PostHogCodeSlackMentionCommandWorkflowInputs:
event = {"channel": "C1", "user": "U1", "text": "help", **event_extra}
return PostHogCodeSlackMentionCommandWorkflowInputs(
event=event,
integration_ids=[self.integration.id],
slack_team_id="T_WS",
user_id=self.user.id,
- command_prefix=command_prefix,
+ command_prefix="/posthog",
)
@parameterized.expand(
[
# A slash command outside a thread carries neither ts nor thread_ts, so the reply
# anchors to the channel root.
- ("slash_outside_thread", "/posthog", {}, "", "*Available commands:*"),
- # A top-level mention carries only its own ts (no thread_ts). The reply
- # must anchor to the channel root, not that ts — a thread-anchored reply
- # is invisible to a user who isn't already viewing the thread.
- ("mention_top_level", "@PostHog", {"ts": "111.1"}, "", MENTION_HELP_REDIRECT),
- # A mention inside a real thread carries thread_ts; the reply threads there.
- ("mention_in_thread", "@PostHog", {"ts": "222.2", "thread_ts": "111.1"}, "111.1", MENTION_HELP_REDIRECT),
+ ("outside_thread", {}, ""),
+ ("in_thread", {"thread_ts": "111.1"}, "111.1"),
]
)
@patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")
@patch("posthog.models.integration.SlackIntegration")
- def test_dispatches_with_surface_prefix(
+ def test_reply_is_anchored_to_the_surface_the_caller_is_looking_at(
self,
_name: str,
- command_prefix: str,
event_extra: dict[str, str],
expected_thread_ts: str,
- expected_text: str,
mock_slack_cls,
mock_info,
) -> None:
mock_info.return_value = {"user": {"is_admin": False, "is_owner": False}}
client = mock_slack_cls.return_value.client
- result = handle_posthog_code_slack_mention_command_activity(
- self._inputs(command_prefix=command_prefix, event_extra=event_extra), self.user.id
- )
+ result = handle_posthog_code_slack_mention_command_activity(self._inputs(event_extra=event_extra), self.user.id)
assert result.status == "done"
- # Both surfaces answer only the caller, so nothing lands in the channel.
+ # A command answers only the caller, so nothing lands in the channel.
assert client.chat_postMessage.call_count == 0
client.chat_postEphemeral.assert_called_once()
# A channel-root reply carries no anchor at all rather than an empty one.
assert client.chat_postEphemeral.call_args.kwargs.get("thread_ts", "") == expected_thread_ts
- assert expected_text in client.chat_postEphemeral.call_args.kwargs["text"]
+ assert "*Available commands:*" in client.chat_postEphemeral.call_args.kwargs["text"]
diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
index 20945e8cd904..2b2d7b92bbd6 100644
--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py
+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
@@ -689,106 +689,58 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
workflow_inputs = mock_sync_connect.return_value.start_workflow.call_args.kwargs["start_signal_args"][0]
assert workflow_inputs.user_id == self.user.id
+ @parameterized.expand(
+ [
+ ("project_set", "<@UBOT123> project 2", "/posthog project <id>"),
+ ("project_show", "<@UBOT123> project", "/posthog project`"),
+ ("project_set_workspace", "<@UBOT123> project workspace 2", "/posthog project workspace <id>"),
+ ("rules_list", "<@UBOT123> rules list", "/posthog rules list"),
+ ("rules_add_no_repo", '<@UBOT123> rules add "investigate flaky tests"', "/posthog rules add"),
+ ("help", "<@UBOT123> help", "/posthog help"),
+ # Retired on both surfaces, so it points at the listing rather than its slash twin.
+ ("deprecated_default_repo", "<@UBOT123> default repo set org/repo", "/posthog help"),
+ ]
+ )
+ @patch("products.slack_app.backend.api._post_slack_user_ephemeral")
@patch("products.slack_app.backend.api.asyncio.run")
@patch("products.slack_app.backend.api.sync_connect")
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
- def test_command_workflow_receives_resolved_user_id(self, mock_sync_connect, mock_asyncio_run):
- # Command path mirrors the mention path: routing resolves the user once
- # and the command workflow gets ``user_id`` so it skips its legacy
- # resolve-user activity on replay-safe code paths.
- from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region
-
- request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
- event = {**self.event, "text": "<@UBOT123> project 2"}
-
- route_posthog_code_event_to_relevant_region(request, event, "T12345")
-
- mock_sync_connect.return_value.start_workflow.assert_called_once()
- workflow_inputs = mock_sync_connect.return_value.start_workflow.call_args.args[1]
- assert workflow_inputs.user_id == self.user.id
-
- @patch("products.slack_app.backend.api.asyncio.run")
- @patch("products.slack_app.backend.api.sync_connect")
- @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
- def test_command_text_routes_to_command_workflow(self, mock_sync_connect, mock_asyncio_run):
- # Command text in a mention must dispatch the command workflow, never the agent
- # mention workflow — even when a single coding-agent integration exists.
- from posthog.temporal.ai.slack_app.posthog_code_slack_mention_command import (
- PostHogCodeSlackMentionCommandWorkflow,
- )
-
+ def test_mention_that_reads_as_a_command_is_redirected_and_starts_nothing(
+ self, _name, text, expected_pointer, mock_sync_connect, mock_asyncio_run, mock_ephemeral
+ ):
+ # Unrecognised, ``@PostHog project 2`` becomes a coding task about its own syntax.
from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
- event = {**self.event, "text": "<@UBOT123> project 2"}
- result = route_posthog_code_event_to_relevant_region(request, event, "T12345")
+ result = route_posthog_code_event_to_relevant_region(request, {**self.event, "text": text}, "T12345")
assert result == ROUTE_HANDLED_LOCALLY
- mock_sync_connect.return_value.start_workflow.assert_called_once()
- kicked_off = mock_sync_connect.return_value.start_workflow.call_args.args[0]
- assert kicked_off == PostHogCodeSlackMentionCommandWorkflow.run
- mock_asyncio_run.assert_called_once()
+ mock_sync_connect.assert_not_called()
+ mock_asyncio_run.assert_not_called()
+ assert expected_pointer in mock_ephemeral.call_args.args[4]
- @patch("products.slack_app.backend.api.asyncio.run")
- @patch("products.slack_app.backend.api.sync_connect")
+ @parameterized.expand(
+ [
+ ("top_level", {}, None),
+ ("thread_opener", {"thread_ts": "1234.5678"}, None),
+ ("thread_reply", {"thread_ts": "1111.2222"}, "1111.2222"),
+ ]
+ )
+ @patch("products.slack_app.backend.api._post_slack_user_ephemeral")
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
- def test_command_workflow_receives_all_workspace_candidates(self, mock_sync_connect, mock_asyncio_run):
- # When multiple coding-agent integrations exist for the same workspace, all of
- # their IDs must be forwarded to the command workflow so it can handle project
- # commands without the caller having to pre-resolve a single target.
- from posthog.models.team.team import Team
-
- other_team = Team.objects.create(organization=self.organization, name="Other")
- other_integration = Integration.objects.create(
- team=other_team,
- kind="slack",
- integration_id="T12345",
- config=self.posthog_code_integration.config,
- sensitive_config={"access_token": "xoxb-other"},
- )
-
- from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
+ def test_mention_command_redirect_anchors_to_the_surface_the_user_is_viewing(
+ self, _name, extra_event_fields, expected_anchor, mock_ephemeral
+ ):
+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region
request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
- event = {**self.event, "text": "<@UBOT123> project 2"}
- result = route_posthog_code_event_to_relevant_region(request, event, "T12345")
-
- assert result == ROUTE_HANDLED_LOCALLY
- mock_sync_connect.return_value.start_workflow.assert_called_once()
- workflow_inputs = mock_sync_connect.return_value.start_workflow.call_args.args[1]
- assert set(workflow_inputs.integration_ids) == {
- self.posthog_code_integration.id,
- other_integration.id,
- }
-
- @patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False)
- @patch("products.slack_app.backend.api.asyncio.run")
- @patch("products.slack_app.backend.api.sync_connect")
- @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
- def test_rules_add_without_repo_routes_to_command_workflow_for_picker(
- self, mock_sync_connect, mock_asyncio_run, _mock_us_claim
- ):
- # ``rules add "description"`` with no inline repo is still a command, so
- # the webhook hands it to the command workflow. The command workflow
- # itself drives the interactive repo picker (its own signal handlers and
- # wait_condition); the agent mention workflow is never involved.
- from posthog.temporal.ai.slack_app.posthog_code_slack_mention_command import (
- PostHogCodeSlackMentionCommandWorkflow,
+ route_posthog_code_event_to_relevant_region(
+ request, {**self.event, "text": "<@UBOT123> help", **extra_event_fields}, "T12345"
)
- from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
-
- request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")
- event = {**self.event, "text": '<@UBOT123> rules add "investigate flaky tests"'}
-
- result = route_posthog_code_event_to_relevant_region(request, event, "T12345")
-
- assert result == ROUTE_HANDLED_LOCALLY
- mock_sync_connect.return_value.start_workflow.assert_called_once()
- kicked_off = mock_sync_connect.return_value.start_workflow.call_args.args[0]
- assert kicked_off == PostHogCodeSlackMentionCommandWorkflow.run
+ assert mock_ephemeral.call_args.args[3] == expected_anchor
@patch("products.slack_app.backend.api.handle_posthog_link_unfurl")
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
diff --git a/products/slack_app/backend/tests/test_project_set_workspace.py b/products/slack_app/backend/tests/test_project_set_workspace.py
index 70f839b824f8..221474a4ba44 100644
--- a/products/slack_app/backend/tests/test_project_set_workspace.py
+++ b/products/slack_app/backend/tests/test_project_set_workspace.py
@@ -1,8 +1,6 @@
import pytest
from unittest.mock import MagicMock, patch
-from parameterized import parameterized
-
from posthog.models.integration import Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
@@ -11,12 +9,11 @@ from posthog.models.user import User
from products.slack_app.backend.api import RulesCommand
from products.slack_app.backend.models import SlackSettings
from products.slack_app.backend.services.commands import (
- MENTION_HELP_REDIRECT,
+ SLASH_COMMAND_PREFIX,
_handle_project_set_workspace,
dispatch_rules_command,
)
-SLASH_COMMAND_PREFIX = "/posthog"
WORKSPACE_HELP_LINE = "`/posthog project workspace <id>`"
@@ -50,6 +47,7 @@ class TestHandleProjectSetWorkspace:
user_id=self.user.id,
target_team_id=target_team_id,
workspace_candidates=[self.integration],
+ command_prefix=SLASH_COMMAND_PREFIX,
)
@patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")
@@ -127,8 +125,8 @@ class TestHandleHelp:
self.user = User.objects.create_and_join(self.organization, "[email protected]", "pw")
self.slack = MagicMock()
- def _help_text(self, command_prefix: str = SLASH_COMMAND_PREFIX) -> str:
- """Dispatch `help` the way a real command does, so the surface branch is exercised too."""
+ def _help_text(self) -> str:
+ """Dispatch `help` the way a real command does, rather than calling the handler."""
dispatch_rules_command(
RulesCommand(action="help"),
self.slack,
@@ -138,7 +136,7 @@ class TestHandleHelp:
slack_user_id="U1",
slack_workspace_id="T_WS",
user_id=self.user.id,
- command_prefix=command_prefix,
+ command_prefix=SLASH_COMMAND_PREFIX,
)
return self.slack.client.chat_postEphemeral.call_args.kwargs["text"]
@@ -167,15 +165,9 @@ class TestHandleHelp:
assert "`@PostHog <task description>`" in text
assert "reply in an active thread" in text
- @parameterized.expand([("slash", SLASH_COMMAND_PREFIX), ("mention", "@PostHog")])
@patch("products.slack_app.backend.services.slack_user_info.get_slack_user_info")
- def test_help_is_ephemeral_to_the_caller(self, _name, command_prefix, mock_info):
+ def test_help_is_ephemeral_to_the_caller(self, mock_info):
mock_info.return_value = _slack_user_info(is_admin=False, is_owner=False)
- self._help_text(command_prefix=command_prefix)
+ self._help_text()
assert self.slack.client.chat_postMessage.call_count == 0
assert self.slack.client.chat_postEphemeral.call_args.kwargs["user"] == "U1"
-
- def test_mention_help_redirects_to_the_slash_command(self):
- text = self._help_text(command_prefix="@PostHog")
- assert text == MENTION_HELP_REDIRECT
- assert "Available commands" not in text
diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.py
index 5edba5aa89bf..6cae579ff9a0 100644
--- a/products/slack_app/backend/tests/test_thread_message_routing.py
+++ b/products/slack_app/backend/tests/test_thread_message_routing.py
@@ -379,24 +379,24 @@ class TestRouteThreadMessage(TestCase):
# --- Rules command not invoked for untagged --------------------------
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
- def test_rules_command_text_does_not_trigger_command_workflow(self):
- """A rules-shaped message in an untagged thread (no @mention) must not
- kick off the command workflow — the user never tagged us. It should
- flow through to the regular mention workflow with
+ def test_rules_command_text_does_not_trigger_command_redirect(self):
+ """A rules-shaped message in an untagged thread (no @mention) must not be read as a
+ command — the user never addressed us, so they are owed no pointer at the slash
+ command. It should flow through to the regular mention workflow with
``untagged_followup=True`` so the classifier in the workflow can drop
it as off-topic."""
from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
rules_text = '@PostHog rules add "use the helper" org/repo'
with (
- patch("products.slack_app.backend.api._start_command_workflow") as mock_command,
+ patch("products.slack_app.backend.api._redirect_mention_command") as mock_redirect,
patch(
"products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY
) as mock_start,
):
result = self._route(self._make_event(text=rules_text))
assert result == ROUTE_HANDLED_LOCALLY
- mock_command.assert_not_called()
+ mock_redirect.assert_not_called()
mock_start.assert_called_once()
assert mock_start.call_args.kwargs["untagged_followup"] is True
diff --git a/products/slack_app/backend/tests/views/test_slack_command.py b/products/slack_app/backend/tests/views/test_slack_command.py
index 3bef4ef54767..4dd8244a4041 100644
--- a/products/slack_app/backend/tests/views/test_slack_command.py
+++ b/products/slack_app/backend/tests/views/test_slack_command.py
@@ -151,6 +151,26 @@ class TestSlashCommandDispatch(_SlashCommandTestBase):
assert self.mock_start.call_args.kwargs["command_prefix"] == "/posthog"
assert self.integration in self.mock_start.call_args.args[1]
+ def test_every_workspace_integration_is_forwarded(self) -> None:
+ """``project <id>`` can name any project the workspace is connected to, so the entry
+ point forwards the whole candidate set. Sending one would leave the others unreachable,
+ with no surface left to pick them from."""
+ from posthog.models.team.team import Team
+
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ other_integration = Integration.objects.create(
+ team=other_team,
+ kind="slack",
+ integration_id="T12345",
+ sensitive_config={"access_token": "xoxb-other"},
+ )
+
+ response = self._post_slash_command(self._default_payload(text="project 42"))
+
+ assert response.status_code == 200
+ forwarded = {i.id for i in self.mock_start.call_args.args[1]}
+ assert forwarded == {self.integration.id, other_integration.id}
+
def test_unknown_sub_command_returns_help_text(self) -> None:
response = self._post_slash_command(self._default_payload(text="frobnicate the widgets"))
diff --git a/products/tasks/backend/presentation/views/repo_routing_rules_api.py b/products/tasks/backend/presentation/views/repo_routing_rules_api.py
index 0cc989bcfa19..c505327c5b8d 100644
--- a/products/tasks/backend/presentation/views/repo_routing_rules_api.py
+++ b/products/tasks/backend/presentation/views/repo_routing_rules_api.py
@@ -74,7 +74,7 @@ class RepoRoutingRuleSerializer(serializers.ModelSerializer):
class RepoRoutingRuleViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
"""Team routing rules that steer agent repo selection (`RepoRoutingRule`).
- The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ The same rows the Slack `/posthog rules` commands manage; the repo selection agent
reads them ordered by priority when picking a repository for a task. Rules whose
repository is not connected to the project are ignored at selection time, so a
stale rule is inert rather than harmful — which is why writes here don't check the
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 758ac77f0b18..c9ce3c795889 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -2862,7 +2862,7 @@ export const getTasksRepoRoutingRulesListUrl = (projectId: string) => {
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the
@@ -2885,7 +2885,7 @@ export const getTasksRepoRoutingRulesCreateUrl = (projectId: string) => {
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the
@@ -2911,7 +2911,7 @@ export const getTasksRepoRoutingRulesRetrieveUrl = (projectId: string, id: strin
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the
@@ -2935,7 +2935,7 @@ export const getTasksRepoRoutingRulesUpdateUrl = (projectId: string, id: string)
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the
@@ -2962,7 +2962,7 @@ export const getTasksRepoRoutingRulesPartialUpdateUrl = (projectId: string, id:
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the
@@ -2989,7 +2989,7 @@ export const getTasksRepoRoutingRulesDestroyUrl = (projectId: string, id: string
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the
diff --git a/products/tasks/frontend/generated/api.zod.ts b/products/tasks/frontend/generated/api.zod.ts
index 6d35824a6353..72445f7a4c5c 100644
--- a/products/tasks/frontend/generated/api.zod.ts
+++ b/products/tasks/frontend/generated/api.zod.ts
@@ -3529,7 +3529,7 @@ export const TasksConfigCreateBody = /* @__PURE__ */ zod
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the
@@ -3555,7 +3555,7 @@ export const TasksRepoRoutingRulesCreateBody = /* @__PURE__ */ zod.object({
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the
@@ -3581,7 +3581,7 @@ export const TasksRepoRoutingRulesUpdateBody = /* @__PURE__ */ zod.object({
/**
* Team routing rules that steer agent repo selection (`RepoRoutingRule`).
*
- * The same rows the Slack `@PostHog rules` commands manage; the repo selection agent
+ * The same rows the Slack `/posthog rules` commands manage; the repo selection agent
* reads them ordered by priority when picking a repository for a task. Rules whose
* repository is not connected to the project are ignored at selection time, so a
* stale rule is inert rather than harmful — which is why writes here don't check the