:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(slack_app): add /posthog slash command surface (#67025)
Vojta Bartoš5f24051e286c
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex bef427fbf16b..b80b32f7d025 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -43280,7 +43280,7 @@"type": "string"},"SlackIntegrationScopeInReview": {- "enum": ["assistant:write", "channels:manage", "im:history", "mpim:read"],+ "enum": ["assistant:write", "channels:manage", "commands", "im:history", "mpim:read"],"type": "string"},"SlashCommandName": {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex a8003d088b39..81e416105598 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -5423,6 +5423,7 @@ export const SLACK_INTEGRATION_SCOPES = Object.values(SlackIntegrationScope)export enum SlackIntegrationScopeInReview {ASSISTANT_WRITE = 'assistant:write',CHANNELS_MANAGE = 'channels:manage',+ COMMANDS = 'commands',IM_HISTORY = 'im:history',MPIM_READ = 'mpim:read',}diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex adc7511e7583..a5dab14d704a 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3104,6 +3104,7 @@ class SlackIntegrationScope(StrEnum):class SlackIntegrationScopeInReview(StrEnum):ASSISTANT_WRITE = "assistant:write"CHANNELS_MANAGE = "channels:manage"+ COMMANDS = "commands"IM_HISTORY = "im:history"MPIM_READ = "mpim:read"diff --git a/posthog/temporal/ai/slack_app/activities/rules.py b/posthog/temporal/ai/slack_app/activities/rules.pyindex c150d8a0c1d5..e3d9dc315396 100644--- a/posthog/temporal/ai/slack_app/activities/rules.py+++ b/posthog/temporal/ai/slack_app/activities/rules.py@@ -23,10 +23,10 @@ def handle_posthog_code_rules_command_activity() -> PostHogCodeRulesCommandResult:from posthog.models.integration import Integration, SlackIntegration- from products.slack_app.backend.api import _parse_rules_command+ from products.slack_app.backend.api import parse_rules_commandfrom products.slack_app.backend.services.commands import dispatch_rules_command- command = _parse_rules_command(inputs.event.get("text", ""))+ 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@@ -119,17 +119,18 @@ def handle_posthog_code_slack_mention_command_activity() -> PostHogCodeSlackMentionCommandResult:from posthog.models.integration import SlackIntegration- from products.slack_app.backend.api import _parse_rules_command+ from products.slack_app.backend.api import parse_rules_commandfrom products.slack_app.backend.services.commands import dispatch_rules_command, resolve_command_targetevent = inputs.eventchannel = event.get("channel")- thread_ts = event.get("thread_ts") or event.get("ts")+ # Empty anchor posts at the channel root — correct for a slash command invoked outside a thread.+ thread_ts = event.get("thread_ts") or event.get("ts") or ""slack_user_id = event.get("user")- if not channel or not thread_ts or not slack_user_id:+ if not channel or not slack_user_id:return PostHogCodeSlackMentionCommandResult(status="done")- command = _parse_rules_command(event.get("text", ""))+ command = parse_rules_command(event.get("text", ""))if command is None:return PostHogCodeSlackMentionCommandResult(status="done")@@ -154,7 +155,7 @@ def handle_posthog_code_slack_mention_command_activity(else:text = ("This Slack workspace is connected to multiple PostHog projects. "- "Use `@PostHog project <id>` to set a default first, then re-run your command."+ f"Use `{inputs.command_prefix} project <id>` to set a default first, then re-run your command.")SlackIntegration(candidates[0]).client.chat_postEphemeral(channel=channel,@@ -187,5 +188,6 @@ def handle_posthog_code_slack_mention_command_activity(slack_workspace_id=inputs.slack_team_id,user_id=user_id,workspace_candidates=candidates,+ command_prefix=inputs.command_prefix,)return PostHogCodeSlackMentionCommandResult(status="done")diff --git a/posthog/temporal/ai/slack_app/activities/task_creation.py b/posthog/temporal/ai/slack_app/activities/task_creation.pyindex db114c01ab59..58696e5c6a32 100644--- a/posthog/temporal/ai/slack_app/activities/task_creation.py+++ b/posthog/temporal/ai/slack_app/activities/task_creation.py@@ -536,11 +536,11 @@ def forward_posthog_code_followup_activity("""from posthog.models.integration import Integration, SlackIntegration- from products.slack_app.backend.api import _parse_rules_command, resolve_slack_user+ from products.slack_app.backend.api import parse_rules_command, resolve_slack_userfrom products.slack_app.backend.models import SlackThreadTaskMappingfrom products.tasks.backend.facade import api as tasks_facade- if _parse_rules_command(event_text):+ if parse_rules_command(event_text):return Falsetry:diff --git a/posthog/temporal/ai/slack_app/activities/user_resolution.py b/posthog/temporal/ai/slack_app/activities/user_resolution.pyindex 9ae26ef4bff1..01b54814039a 100644--- a/posthog/temporal/ai/slack_app/activities/user_resolution.py+++ b/posthog/temporal/ai/slack_app/activities/user_resolution.py@@ -40,9 +40,10 @@ def resolve_posthog_code_slack_command_user_activity(event = inputs.eventchannel = event.get("channel")- thread_ts = event.get("thread_ts") or event.get("ts")+ # Empty anchor posts feedback at the channel root — correct for a slash command outside a thread.+ thread_ts = event.get("thread_ts") or event.get("ts") or ""slack_user_id = event.get("user")- if not channel or not thread_ts or not slack_user_id or not inputs.integration_ids:+ if not channel or not slack_user_id or not inputs.integration_ids:return Nonecandidates = list(@@ -68,7 +69,7 @@ def resolve_posthog_code_slack_command_user_activity(thread_ts=thread_ts,text=("I couldn't find your PostHog account in any organization connected to this Slack "- "workspace. Ask an admin to invite you, then mention me again."+ "workspace. Ask an admin to invite you, then try again."),)return Nonediff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.pyindex 1186e49dfe06..a492a6b5cf01 100644--- a/posthog/temporal/ai/slack_app/types.py+++ b/posthog/temporal/ai/slack_app/types.py@@ -40,11 +40,14 @@ class PostHogCodeSlackMentionCommandWorkflowInputs:event: dict[str, Any]integration_ids: list[int]slack_team_id: str- # Resolved at routing time. ``None`` only on in-flight workflow histories- # started before this field existed; those fall back to the in-workflow- # resolve activity. Remove the fallback (and this field's optionality)- # once the workflow history retention window has elapsed.+ # 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.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"@dataclassdiff --git a/posthog/urls.py b/posthog/urls.pyindex 0092e25b366e..f6757d6da9b2 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -60,7 +60,11 @@ from products.slack_app.backend.api import (posthog_code_interactivity_handler,slack_workspace_claims_view,)-from products.slack_app.backend.views import slack_user_link_authorize, slack_user_link_callback+from products.slack_app.backend.views import (+ slack_app_command_handler,+ slack_user_link_authorize,+ slack_user_link_callback,+)from products.surveys.backend.api.survey import public_survey_pagefrom products.tasks.backend.facade.agent_proxy import agent_proxy_callbackfrom products.user_interviews.backend.presentation.webhooks import (@@ -467,6 +471,7 @@ urlpatterns = [path("uploaded_media/<str:image_uuid>", uploaded_media.download),opt_slash_path("slack/interactivity-callback", posthog_code_interactivity_handler),opt_slash_path("slack/event-callback", posthog_code_event_handler),+ opt_slash_path("slack/command-callback", slack_app_command_handler),opt_slash_path("slack/workspace/claims", slack_workspace_claims_view),# GitHub App webhook — fans out to tasks (PRs) and conversations (issues)opt_slash_path("webhooks/github/pr", github_webhook),diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 2231b620b06b..2072f75c17fe 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -482,7 +482,7 @@ WORKSPACE_CLAIMS_TIMEOUT_SECONDS = (1, 1)WORKSPACE_CLAIMS_CACHE_TTL_SECONDS = 60-def _cross_region_routing_enabled() -> bool:+def cross_region_routing_enabled() -> bool:# Cross-region routing only makes sense between PostHog Cloud US and EU — they share the# Slack app's signing secret and split workspace ownership between them. The hosted dev# environment (CLOUD_DEPLOYMENT="DEV"), local dev, E2E, and self-hosted deployments all run@@ -508,15 +508,15 @@ def _eu_region_domain() -> str:return "eu.posthog.com"-def _is_us_host(host: str) -> bool:+def is_us_host(host: str) -> bool:return host == _us_region_domain()-def _other_region_domain(incoming_host: str) -> str:- return _eu_region_domain() if _is_us_host(incoming_host) else _us_region_domain()+def other_region_domain(incoming_host: str) -> str:+ return _eu_region_domain() if is_us_host(incoming_host) else _us_region_domain()-def _was_proxied(request: HttpRequest) -> bool:+def was_proxied(request: HttpRequest) -> bool:# Match the literal value the sender sets (`"1"`) rather than coercing the header value to# bool — semgrep flags the latter as nan-injection and we control the sender anyway.return request.headers.get(REGION_PROXY_HEADER) == "1"@@ -588,7 +588,7 @@ def does_other_region_claim_workspace(*, slack_team_id: str, kinds: list[str], i)return cached- target_domain = _other_region_domain(incoming_host)+ target_domain = other_region_domain(incoming_host)scheme = "http" if settings.DEBUG else "https"target_url = f"{scheme}://{target_domain}/slack/workspace/claims/"@@ -689,7 +689,7 @@ def _strip_bot_mentions(text: str) -> str:return re.sub(r"<@[A-Z0-9]+>", "", text).strip()-def _parse_rules_command(text: str) -> RulesCommand | None:+def parse_rules_command(text: str) -> RulesCommand | None:cleaned = _strip_bot_mentions(text).strip()if not cleaned:return None@@ -1584,7 +1584,7 @@ def _route_assistant_event(channel=channel_id,thread_ts=thread_ts,)- region_route = _resolve_region_or_terminal_route(+ region_route = resolve_region_or_terminal_route(request,slack_team_id,candidates_present=bool(result.candidates),@@ -1645,17 +1645,17 @@ def route_posthog_code_event_to_relevant_region() -> str:event_type = event.get("type")incoming_host = request.get_host()- proxied = _was_proxied(request)- other_domain = _other_region_domain(incoming_host)+ proxied = was_proxied(request)+ other_domain = other_region_domain(incoming_host)# In local dev we run a single instance, so cross-region routing is meaningless: the only# consumer is this process. Disable both the probe and the proxy hop and always handle# locally.- can_defer_to_other_region = _cross_region_routing_enabled() and not _is_us_host(incoming_host) and not proxied+ can_defer_to_other_region = cross_region_routing_enabled() and not is_us_host(incoming_host) and not proxiedlogger.info("slack_app_route_enter",incoming_host=incoming_host,- is_us=_is_us_host(incoming_host),+ is_us=is_us_host(incoming_host),proxied=proxied,other_domain=other_domain,can_defer=can_defer_to_other_region,@@ -1738,7 +1738,7 @@ def route_posthog_code_event_to_relevant_region(channel=channel_str,thread_ts=thread_ts_str,)- region_route = _resolve_region_or_terminal_route(+ region_route = resolve_region_or_terminal_route(request,slack_team_id,candidates_present=bool(workspace_result.candidates),@@ -1811,7 +1811,7 @@ def route_posthog_code_event_to_relevant_region(# 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:+ 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)# A tagged-thread ``message`` is bound to its mapping's integration —@@ -1930,7 +1930,7 @@ def _route_to_other_region_or_drop(Single-region deployments (local dev, hosted dev, E2E, self-hosted) have no other regionto forward to, so we just record the miss and stop."""- if proxied or not _cross_region_routing_enabled():+ if proxied or not cross_region_routing_enabled():logger.warning("slack_app_no_integration_found",slack_team_id=slack_team_id,@@ -1940,7 +1940,7 @@ def _route_to_other_region_or_drop(return _proxy_event_and_return_route(request, other_domain)-def _resolve_region_or_terminal_route(+def resolve_region_or_terminal_route(request: HttpRequest,slack_team_id: str,*,@@ -1970,8 +1970,11 @@ def _start_command_workflow(slack_team_id: str,event_id: str | None,*,- user_id: int,+ user_id: int | None,+ command_prefix: str = "@PostHog",) -> 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._start_posthog_code_workflow(PostHogCodeSlackMentionCommandWorkflow,PostHogCodeSlackMentionCommandWorkflowInputs(@@ -1979,6 +1982,7 @@ def _start_command_workflow(integration_ids=[i.id for i in integrations],slack_team_id=slack_team_id,user_id=user_id,+ command_prefix=command_prefix,),id_prefix="posthog-code-mention-command",slack_team_id=slack_team_id,@@ -3272,7 +3276,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:integration_id=slack_team_id,).exists()- proxied = _was_proxied(request)+ proxied = was_proxied(request)incoming_host = request.get_host()logger.info("slack_app_interactivity_resolution",@@ -3288,12 +3292,12 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:proxied=proxied,)- if not local and not proxied and _cross_region_routing_enabled():+ if not local and not proxied and cross_region_routing_enabled():# The payload's integration_id pinpoints exactly one row, so a lookup would tell us# nothing new — just forward to the other region. The loop header keeps us at one hop.# Skipped in single-region deployments (local dev, hosted dev, E2E, self-hosted) where# there is no other region to talk to.- target = _other_region_domain(incoming_host)+ target = other_region_domain(incoming_host)upstream = _proxy_event_to_region(request, target)if upstream is not None:logger.info(diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.pyindex 416602cdd798..52076bae3724 100644--- a/products/slack_app/backend/services/commands.py+++ b/products/slack_app/backend/services/commands.py@@ -8,34 +8,53 @@ if TYPE_CHECKING:def _handle_help(- slack: SlackIntegration, integration: Integration, channel: str, thread_ts: str, slack_user_id: str+ slack: SlackIntegration,+ integration: Integration,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ *,+ command_prefix: str = "@PostHog",) -> None:from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin- lines = [- "*Available commands:*\n",- "`@PostHog <task description>` — Create a task for the agent to work on",- "`@PostHog rules list` — Show all routing rules",- '`@PostHog rules add "description" org/repo` — Add a routing rule',- '`@PostHog rules add "description"` — Add a routing rule (pick repo from list)',- "`@PostHog rules remove <number(s)>` — Remove routing rules by number (e.g. `remove 1` or `remove 1,2`)",- "`@PostHog project` — Show which PostHog project your mentions route to in this workspace",- "`@PostHog project <id>` — Set the PostHog project your mentions route to in this workspace",- ]+ # Task creation only makes sense on the mention surface — slash commands lack the thread+ # context the workflow needs, so omit it when the user discovered help via ``/posthog``.+ lines = ["*Available commands:*\n"]+ if command_prefix == "@PostHog":+ lines.append(f"`{command_prefix} <task description>` — Create a task for the agent to work on")+ lines.extend(+ [+ f"`{command_prefix} rules list` — Show all routing rules",+ f'`{command_prefix} rules add "description" org/repo` — Add a routing rule',+ f'`{command_prefix} rules add "description"` — Add a routing rule (pick repo from list)',+ f"`{command_prefix} rules remove <number(s)>` — Remove routing rules by number (e.g. `remove 1` or `remove 1,2`)",+ f"`{command_prefix} project` — Show which PostHog project your mentions route to in this workspace",+ f"`{command_prefix} project <id>` — Set the PostHog project your mentions route to in this workspace",+ ]+ )# The workspace-wide default is admins/owners-only, so only surface it to them.if is_slack_workspace_admin(slack, integration, slack_user_id):lines.append(- "`@PostHog project workspace <id>` — Set the workspace-wide default project (Slack admins/owners only)"+ f"`{command_prefix} project workspace <id>` — Set the workspace-wide default project (Slack admins/owners only)")- lines.append("`@PostHog help` — Show this message\n")- lines.append("You can also reply in an active thread to send follow-up messages to the agent.")+ lines.append(f"`{command_prefix} help` — Show this message\n")+ if command_prefix == "@PostHog":+ lines.append("You can also reply in an active thread to send follow-up messages to the agent.")slack.client.chat_postMessage(channel=channel, thread_ts=thread_ts, text="\n".join(lines))-def _handle_rules_list(slack: SlackIntegration, integration: Integration, channel: str, thread_ts: str) -> None:+def _handle_rules_list(+ slack: SlackIntegration,+ integration: Integration,+ channel: str,+ thread_ts: str,+ *,+ command_prefix: str = "@PostHog",+) -> None:from posthog.models.repo_routing_rule import RepoRoutingRulerules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))@@ -43,7 +62,10 @@ def _handle_rules_list(slack: SlackIntegration, integration: Integration, channeslack.client.chat_postMessage(channel=channel,thread_ts=thread_ts,- text='No routing rules configured. Add one with `@PostHog rules add "description" [org/repo]`. Omit the repo to pick from a list.',+ text=(+ f'No routing rules configured. Add one with `{command_prefix} rules add "description" '+ "[org/repo]`. Omit the repo to pick from a list."+ ),)return@@ -113,6 +135,8 @@ def _handle_rules_remove(channel: str,thread_ts: str,rule_numbers: list[int] | None,+ *,+ command_prefix: str = "@PostHog",) -> None:from posthog.models.repo_routing_rule import RepoRoutingRule@@ -120,7 +144,7 @@ def _handle_rules_remove(slack.client.chat_postMessage(channel=channel,thread_ts=thread_ts,- text="Please provide valid rule number(s). Use `@PostHog rules list` to see current rules.",+ text=f"Please provide valid rule number(s). Use `{command_prefix} rules list` to see current rules.",)return@@ -130,7 +154,7 @@ def _handle_rules_remove(slack.client.chat_postMessage(channel=channel,thread_ts=thread_ts,- text=f"Rule {'number' if len(invalid) == 1 else 'numbers'} {', '.join(f'#{n}' for n in invalid)} {'does' if len(invalid) == 1 else 'do'} not exist. There are {len(rules)} rule(s). Use `@PostHog rules list` to see them.",+ text=f"Rule {'number' if len(invalid) == 1 else 'numbers'} {', '.join(f'#{n}' for n in invalid)} {'does' if len(invalid) == 1 else 'do'} not exist. There are {len(rules)} rule(s). Use `{command_prefix} rules list` to see them.",)return@@ -157,6 +181,8 @@ def _handle_project_show(slack_workspace_id: str,user_id: int,workspace_candidates: list[Integration] | None = None,+ *,+ command_prefix: str = "@PostHog",) -> None:from posthog.models.user import User@@ -191,7 +217,7 @@ def _handle_project_show(text=(f"Your mentions in this workspace route to *{target.team.organization.name} · "f"{target.team.name}* (id `{target.team_id}`). "- "Change it with `@PostHog project <id>`."+ f"Change it with `{command_prefix} project <id>`."),)return@@ -214,7 +240,7 @@ def _handle_project_show("You haven't set a default project for this Slack workspace yet. Available PostHog ""projects you can pick:\n"f"{lines}\n\n"- "Set one with `@PostHog project <id>`."+ f"Set one with `{command_prefix} project <id>`."),)@@ -291,6 +317,8 @@ def _handle_project_set_workspace(user_id: int,target_team_id: int,workspace_candidates: list[Integration] | None = None,+ *,+ command_prefix: str = "@PostHog",) -> 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.@@ -353,7 +381,7 @@ def _handle_project_set_workspace(text=(f"Workspace-wide default set to *{target.team.organization.name} · {target.team.name}* "f"(id `{target.team_id}`). Mentions from anyone without a personal default "- "(`@PostHog project <id>`) now route here."+ f"(`{command_prefix} project <id>`) now route here."),)@@ -421,6 +449,7 @@ def dispatch_rules_command(slack_workspace_id: str,user_id: int,workspace_candidates: list[Integration] | None = None,+ command_prefix: str = "@PostHog",) -> None:"""Run the right handler for a parsed ``RulesCommand``. Assumes the caller hasalready resolved a single ``integration`` to act on; project commands also@@ -429,24 +458,30 @@ def dispatch_rules_command(``rules add`` without an inline repo is handled here as a plain "specify therepo" 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."""if command.action == "help":- _handle_help(slack, integration, channel, thread_ts, slack_user_id)+ _handle_help(slack, integration, channel, thread_ts, slack_user_id, command_prefix=command_prefix)elif command.action == "list":- _handle_rules_list(slack, integration, channel, thread_ts)+ _handle_rules_list(slack, integration, channel, thread_ts, command_prefix=command_prefix)elif command.action == "add":if not command.repository:slack.client.chat_postMessage(channel=channel,thread_ts=thread_ts,- text='Please specify the repo inline: `@PostHog rules add "description" org/repo`.',+ text=f'Please specify the repo inline: `{command_prefix} rules add "description" org/repo`.',)else:_handle_rules_add(slack, integration, channel, thread_ts, user_id, command.rule_text or "", command.repository)elif command.action == "remove":- _handle_rules_remove(slack, integration, channel, thread_ts, command.rule_numbers)+ _handle_rules_remove(+ slack, integration, channel, thread_ts, command.rule_numbers, command_prefix=command_prefix+ )elif command.action == "project_show":_handle_project_show(slack,@@ -456,6 +491,7 @@ def dispatch_rules_command(slack_workspace_id,user_id,workspace_candidates=workspace_candidates,+ command_prefix=command_prefix,)elif command.action == "project_set":if command.project_team_id is None:@@ -483,4 +519,5 @@ def dispatch_rules_command(user_id,command.project_team_id,workspace_candidates=workspace_candidates,+ command_prefix=command_prefix,)diff --git a/products/slack_app/backend/services/slack_auth.py b/products/slack_app/backend/services/slack_auth.pyindex 3666109442ec..9adfa6b85e2d 100644--- a/products/slack_app/backend/services/slack_auth.py+++ b/products/slack_app/backend/services/slack_auth.py@@ -247,7 +247,7 @@ def check_integrations_auth_and_filter(mentions racing here just overwrite each other with the same verdict.Empty return when every candidate is broken/unknown is intentional and- upstream code already handles it: ``_resolve_region_or_terminal_route``+ upstream code already handles it: ``resolve_region_or_terminal_route``routes events to ``ROUTE_NO_INTEGRATION`` when no candidates are present,matching the behavior we'd see if the DB had no rows for this workspace.diff --git a/products/slack_app/backend/tests/test_guess_repository.py b/products/slack_app/backend/tests/test_guess_repository.pyindex 9bccdd8fb194..fbdb10f28f11 100644--- a/products/slack_app/backend/tests/test_guess_repository.py+++ b/products/slack_app/backend/tests/test_guess_repository.py@@ -19,8 +19,8 @@ from products.slack_app.backend.api import (_extract_explicit_repo,_get_full_repo_names,_invalidate_user_repo_list_cache,- _parse_rules_command,_user_repo_list_cache_key,+ parse_rules_command,)@@ -409,7 +409,7 @@ class TestParseRulesCommand:])def test_parses_command(self, _name, text, expected):- assert _parse_rules_command(text) == expected+ assert parse_rules_command(text) == expected@parameterized.expand([@@ -423,7 +423,7 @@ class TestParseRulesCommand:])def test_returns_none_for_non_commands(self, _name, text):- assert _parse_rules_command(text) is None+ assert parse_rules_command(text) is Noneclass TestHandleRulesCommandActivity:diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.pyindex a40dd2d8191b..5b096d802ba8 100644--- a/products/slack_app/backend/tests/test_integration_resolver.py+++ b/products/slack_app/backend/tests/test_integration_resolver.py@@ -603,7 +603,7 @@ class TestLoadIntegrationsAuthStateFilter:def test_all_broken_returns_empty(self):# When every candidate is cached as broken, return an empty list.- # Upstream code (``_resolve_region_or_terminal_route``) treats an empty+ # Upstream code (``resolve_region_or_terminal_route``) treats an empty# candidate set the same way it'd handle a workspace with no rows at# all — falls through to ``ROUTE_NO_INTEGRATION``. Recovery paths:# the 6h TTL expires, OAuth reconnect invalidates the cache, or adiff --git a/products/slack_app/backend/tests/test_mention_command_activity.py b/products/slack_app/backend/tests/test_mention_command_activity.pynew file mode 100644index 000000000000..7f5302768f98--- /dev/null+++ b/products/slack_app/backend/tests/test_mention_command_activity.py@@ -0,0 +1,70 @@+import pytest+from unittest.mock import patch++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.activities.rules import handle_posthog_code_slack_mention_command_activity+from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionCommandWorkflowInputs+++class TestMentionCommandActivity:+ @pytest.fixture(autouse=True)+ def setup(self, db):+ self.organization = Organization.objects.create(name="Org")+ self.team = Team.objects.create(organization=self.organization, name="Team A")+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T_WS",+ sensitive_config={"access_token": "xoxb-a"},+ )+ self.user = User.objects.create_and_join(self.organization, "[email protected]", "pw")++ def _inputs(self, *, command_prefix: str, with_thread: bool) -> PostHogCodeSlackMentionCommandWorkflowInputs:+ event = {"channel": "C1", "user": "U1", "text": "help"}+ if with_thread:+ event["ts"] = "111.1"+ return PostHogCodeSlackMentionCommandWorkflowInputs(+ event=event,+ integration_ids=[self.integration.id],+ slack_team_id="T_WS",+ user_id=self.user.id,+ command_prefix=command_prefix,+ )++ @parameterized.expand(+ [+ # A slash command outside a thread carries no ``ts``; the reply must+ # still go out (channel-root anchor) rather than silently no-op on the+ # guard, and it must speak the ``/posthog`` surface.+ ("slash_outside_thread", "/posthog", False, ""),+ # The mention surface always carries a ``ts`` and keeps its copy.+ ("mention_in_thread", "@PostHog", True, "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(+ self,+ _name: str,+ command_prefix: str,+ with_thread: bool,+ expected_thread_ts: 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, with_thread=with_thread), self.user.id+ )++ assert result.status == "done"+ client.chat_postMessage.assert_called_once()+ assert client.chat_postMessage.call_args.kwargs["thread_ts"] == expected_thread_ts+ assert command_prefix in client.chat_postMessage.call_args.kwargs["text"]diff --git a/products/slack_app/backend/tests/test_project_directive_parser.py b/products/slack_app/backend/tests/test_project_directive_parser.pyindex 3a28efc4c4e5..b531bbdf1709 100644--- a/products/slack_app/backend/tests/test_project_directive_parser.py+++ b/products/slack_app/backend/tests/test_project_directive_parser.py@@ -1,6 +1,6 @@from parameterized import parameterized-from products.slack_app.backend.api import RulesCommand, _parse_rules_command+from products.slack_app.backend.api import RulesCommand, parse_rules_commandclass TestParseProjectCommand:@@ -78,7 +78,7 @@ class TestParseProjectCommand:])def test_recognized(self, _name: str, text: str, expected: RulesCommand) -> None:- assert _parse_rules_command(text) == expected+ assert parse_rules_command(text) == expected@parameterized.expand([@@ -95,6 +95,6 @@ class TestParseProjectCommand:def test_not_a_project_command(self, _name: str, text: str) -> None:# The unified parser may still recognize other commands (e.g. "rules list");# we only assert no `project_*` match comes back.- result = _parse_rules_command(text)+ result = parse_rules_command(text)if result is not None:assert result.action not in {"project_show", "project_set", "project_set_workspace"}diff --git a/products/slack_app/backend/tests/views/test_slack_command.py b/products/slack_app/backend/tests/views/test_slack_command.pynew file mode 100644index 000000000000..44d9e66f620a--- /dev/null+++ b/products/slack_app/backend/tests/views/test_slack_command.py@@ -0,0 +1,184 @@+"""Tests for the slash command webhook view.++The parser, dispatcher, and command workflow are covered by their own tests —+this file exercises the entry point's responsibilities: request validation,+retry handling, region routing, and handing a mention-shaped event plus the+``/posthog`` surface to the command workflow.+"""++from typing import Any+from urllib.parse import urlencode++from unittest.mock import patch++from django.core.cache import cache+from django.test import TestCase+from django.test.client import RequestFactory++from parameterized import parameterized+from rest_framework.test import APIClient++from posthog.helpers.slack_scopes import REQUIRED_SLACK_SCOPES+from posthog.models.integration import Integration+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.team.team import Team+from posthog.models.user import User++from products.slack_app.backend.models import SlackUserProfileCache+from products.slack_app.backend.tests.helpers import sign_slack_request++SIGNING_SECRET = "posthog-code-test-secret"+SLASH_COMMAND_PATH = "/slack/command-callback/"+++class _SlashCommandTestBase(TestCase):+ def setUp(self) -> None:+ cache.clear()+ self.client = APIClient()+ self.factory = RequestFactory()+ 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")+ OrganizationMembership.objects.create(organization=self.organization, user=self.user)+ self.user.current_organization = self.organization+ self.user.current_team = self.team+ self.user.save()+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T12345",+ config={"scope": ",".join(sorted(REQUIRED_SLACK_SCOPES))},+ sensitive_config={"access_token": "xoxb-posthog-code-test"},+ )++ from django.utils import timezone++ SlackUserProfileCache.objects.create(+ integration=self.integration,+ slack_user_id="U123",+ email="[email protected]",+ display_name="Dev",+ real_name="Dev User",+ refreshed_at=timezone.now(),+ )++ # Every test in this file relies on the same signing-secret / SlackIntegration mocks;+ # lifting them into setUp via ``enterContext`` removes per-test decorator stacks and+ # keeps the test bodies focused on the slash-command behavior under exercise.+ self._mock_config = self.enterContext(+ patch("products.slack_app.backend.views.slack_command.SlackIntegration.slack_config")+ )+ self._mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": SIGNING_SECRET}++ def _post_slash_command(self, payload: dict[str, str]) -> Any:+ body = urlencode(payload).encode()+ signature, ts = sign_slack_request(body, SIGNING_SECRET)+ return self.client.post(+ SLASH_COMMAND_PATH,+ data=body,+ content_type="application/x-www-form-urlencoded",+ HTTP_X_SLACK_SIGNATURE=signature,+ HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,+ )++ def _default_payload(self, **overrides: str) -> dict[str, str]:+ payload = {+ "command": "/posthog",+ "team_id": "T12345",+ "user_id": "U123",+ "channel_id": "C001",+ "text": "",+ "response_url": "https://hooks.slack.example/abc",+ "trigger_id": "trig-1",+ }+ payload.update(overrides)+ return payload+++class TestSlashCommandWebhookValidation(_SlashCommandTestBase):+ def test_method_not_allowed_on_get(self) -> None:+ response = self.client.get(SLASH_COMMAND_PATH)+ assert response.status_code == 405++ def test_rejects_bad_signature(self) -> None:+ self._mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": "different-secret"}+ response = self._post_slash_command(self._default_payload(text="help"))+ assert response.status_code == 403++ def test_missing_required_payload_fields(self) -> None:+ response = self._post_slash_command(self._default_payload(team_id="", user_id=""))+ assert response.status_code == 200+ body = response.json()+ assert body["response_type"] == "ephemeral"+ assert "Missing Slack payload" in body["text"]+++class TestSlashCommandDispatch(_SlashCommandTestBase):+ def setUp(self) -> None:+ super().setUp()+ # The entry point hands off to the durable command workflow (a Temporal+ # start — a genuine boundary), then acks Slack. Stub the start so tests+ # assert on the synthesised event and surface it forwards.+ self.mock_start = self.enterContext(+ patch("products.slack_app.backend.views.slack_command._start_command_workflow")+ )++ @parameterized.expand(+ [+ ("explicit_help", "help", "help"),+ # A bare ``/posthog`` (empty text) is treated as ``/posthog help``.+ ("bare_falls_back_to_help", "", "help"),+ ("rules_list", "rules list", "rules list"),+ ("project_set", "project 42", "project 42"),+ ]+ )+ def test_known_subcommand_starts_command_workflow(self, _name: str, text: str, expected_event_text: str) -> None:+ response = self._post_slash_command(self._default_payload(text=text))++ assert response.status_code == 200+ assert response.content == b""+ self.mock_start.assert_called_once()+ event = self.mock_start.call_args.args[0]+ # The workflow re-parses the text, so the entry point's job is to forward+ # a faithful mention-shaped event, not a parsed command.+ assert event["text"] == expected_event_text+ assert event["channel"] == "C001"+ assert event["user"] == "U123"+ # User resolution is deferred to the workflow to keep the ack under 3s.+ assert self.mock_start.call_args.kwargs["user_id"] is None+ # ``command_prefix`` is what surfaces in user-facing help/error copy — must+ # match the entry point so the strings tell users to type ``/posthog ...``.+ assert self.mock_start.call_args.kwargs["command_prefix"] == "/posthog"+ assert self.integration in self.mock_start.call_args.args[1]++ def test_unknown_sub_command_returns_help_text(self) -> None:+ response = self._post_slash_command(self._default_payload(text="frobnicate the widgets"))++ assert response.status_code == 200+ body = response.json()+ assert body["response_type"] == "ephemeral"+ assert "didn't recognize" in body["text"]+ self.mock_start.assert_not_called()++ def test_thread_ts_flows_through_to_workflow(self) -> None:+ """Slash commands invoked inside a thread carry ``thread_ts`` on the payload;+ passing it through keeps the bot's reply in-thread instead of dropping it at+ the bottom of the channel. Outside a thread the key is absent so the reply+ lands at the channel root."""+ in_thread = self._post_slash_command(self._default_payload(text="rules list", thread_ts="1700000000.001"))+ assert in_thread.status_code == 200+ assert self.mock_start.call_args.args[0]["thread_ts"] == "1700000000.001"++ self.mock_start.reset_mock()+ outside_thread = self._post_slash_command(self._default_payload(text="rules list"))+ assert outside_thread.status_code == 200+ assert "thread_ts" not in self.mock_start.call_args.args[0]+++class TestSlashCommandWorkspaceMissing(_SlashCommandTestBase):+ def test_unknown_workspace_returns_not_connected_message(self) -> None:+ response = self._post_slash_command(self._default_payload(team_id="T_UNKNOWN", text="help"))+ assert response.status_code == 200+ body = response.json()+ assert body["response_type"] == "ephemeral"+ assert "isn't connected" in body["text"]diff --git a/products/slack_app/backend/views/__init__.py b/products/slack_app/backend/views/__init__.pyindex 411061c62d64..7296c64342f2 100644--- a/products/slack_app/backend/views/__init__.py+++ b/products/slack_app/backend/views/__init__.py@@ -5,6 +5,7 @@ products.slack_app.backend.views import <name>`` without reaching into theper-flow submodule. New view modules should be re-exported here too."""+from products.slack_app.backend.views.slack_command import slack_app_command_handlerfrom products.slack_app.backend.views.slack_user_link import slack_user_link_authorize, slack_user_link_callback-__all__ = ["slack_user_link_authorize", "slack_user_link_callback"]+__all__ = ["slack_app_command_handler", "slack_user_link_authorize", "slack_user_link_callback"]diff --git a/products/slack_app/backend/views/slack_command.py b/products/slack_app/backend/views/slack_command.pynew file mode 100644index 000000000000..1550c0a42c74--- /dev/null+++ b/products/slack_app/backend/views/slack_command.py@@ -0,0 +1,158 @@+"""Slack slash command entry point.++Handles ``POST /slack/command-callback`` — the webhook Slack hits when a user+runs ``/posthog ...`` in a channel or DM. The vocabulary mirrors the+``@PostHog <command>`` mention path (``help``, ``rules ...``, ``project ...``);+free-text task creation stays on the mention path because slash commands lack+the thread context the task workflow depends on.++Slack imposes a hard 3-second response budget on slash commands — a slow first+response surfaces to the user as ``operation_timeout``. Cheap validation and+region routing stay inline; the slow work (user resolution, dispatch, posting+back to Slack) runs in the same durable Temporal command workflow the mention+path uses. We synthesise a mention-shaped ``event`` from the slash payload, hand+it to ``_start_command_workflow``, and ack Slack immediately with a 200.+"""++from typing import Any++from django.http import HttpRequest, HttpResponse, JsonResponse+from django.views.decorators.csrf import csrf_exempt++import structlog++from posthog.models.integration import SlackIntegration, SlackIntegrationError, validate_slack_request++from products.slack_app.backend.api import (+ ROUTE_NO_INTEGRATION,+ ROUTE_PROXY_FAILED,+ SLACK_INTEGRATION_KIND,+ _start_command_workflow,+ cross_region_routing_enabled,+ is_us_host,+ other_region_domain,+ parse_rules_command,+ resolve_region_or_terminal_route,+ was_proxied,+)+from products.slack_app.backend.services.integration_resolver import load_integrations++logger = structlog.get_logger(__name__)++SLASH_COMMAND_NAME = "/posthog"+++@csrf_exempt+def slack_app_command_handler(request: HttpRequest) -> HttpResponse:+ if request.method != "POST":+ return HttpResponse(status=405)++ try:+ slack_config = SlackIntegration.slack_config()+ validate_slack_request(request, slack_config["SLACK_APP_SIGNING_SECRET"])+ except SlackIntegrationError as e:+ logger.warning("slack_app_slash_command_invalid_request", error=str(e))+ return HttpResponse("Invalid request", status=403)++ # Slack replays the POST verbatim when an ack fails to reach it; short-circuit+ # so a retry can't start a second command workflow for the same click.+ retry_num = request.headers.get("X-Slack-Retry-Num")+ if retry_num:+ logger.info("slack_app_slash_command_retry", retry_num=retry_num)+ return HttpResponse(status=200)++ payload = request.POST+ slack_team_id = payload.get("team_id", "")+ slack_user_id = payload.get("user_id", "")+ channel_id = payload.get("channel_id", "")+ # Present only when invoked inside a thread; forwarding it keeps the reply in-thread.+ thread_ts = payload.get("thread_ts", "")+ raw_text = (payload.get("text") or "").strip()+ command_name = payload.get("command", SLASH_COMMAND_NAME)+ # Unique per invocation — used to derive a distinct workflow id since slash+ # payloads carry no message ``ts`` or event id to key on.+ trigger_id = payload.get("trigger_id", "")++ if not slack_team_id or not slack_user_id:+ return _ephemeral_response("Missing Slack payload fields.")++ # A bare ``/posthog`` (no arguments) behaves as ``/posthog help``.+ sub_command_text = raw_text or "help"+ parsed = parse_rules_command(sub_command_text)++ logger.info(+ "slack_app_slash_command_received",+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id,+ channel_id=channel_id,+ command=command_name,+ sub_command=parsed.action if parsed is not None else "unknown",+ )+ if parsed is None:+ return _ephemeral_response(_unknown_command_help(command_name))++ # Region routing is cheap, so it stays inline — the sync response gives the+ # invoker immediate feedback when the workspace isn't connected.+ incoming_host = request.get_host()+ proxied = was_proxied(request)+ other_domain = other_region_domain(incoming_host)+ can_defer = cross_region_routing_enabled() and not is_us_host(incoming_host) and not proxied++ workspace_result = load_integrations(+ slack_team_id=slack_team_id,+ kinds=[SLACK_INTEGRATION_KIND],+ slack_user_id=slack_user_id,+ )+ region_route = resolve_region_or_terminal_route(+ request,+ slack_team_id,+ candidates_present=bool(workspace_result.candidates),+ kinds=[SLACK_INTEGRATION_KIND],+ proxied=proxied,+ other_domain=other_domain,+ incoming_host=incoming_host,+ can_defer=can_defer,+ )+ # ``None`` means handle locally; the ROUTE_* values are terminal exits.+ if region_route == ROUTE_NO_INTEGRATION:+ return _ephemeral_response(+ "This Slack workspace isn't connected to a PostHog organization. "+ "Connect it from a project's *Integrations* page first."+ )+ if region_route == ROUTE_PROXY_FAILED:+ return _ephemeral_response("Couldn't reach the PostHog backend — try again in a moment.")+ if region_route is not None:+ # ROUTE_PROXIED: the sibling region already accepted the forwarded payload+ # and will post the bot's reply through its own Slack client. Ack with 200.+ return HttpResponse(status=200)++ # Synthesise a mention-shaped event and hand off to the durable workflow;+ # ``user_id=None`` defers the slow user resolution off the request path.+ event: dict[str, Any] = {"channel": channel_id, "user": slack_user_id, "text": sub_command_text}+ if thread_ts:+ event["thread_ts"] = thread_ts++ _start_command_workflow(+ event,+ workspace_result.candidates,+ slack_team_id,+ event_id=trigger_id or None,+ user_id=None,+ command_prefix=command_name,+ )+ return HttpResponse(status=200)+++def _ephemeral_response(text: str) -> JsonResponse:+ return JsonResponse({"response_type": "ephemeral", "text": text})+++def _unknown_command_help(command_name: str) -> str:+ return (+ "I didn't recognize that sub-command. Try one of:\n"+ f"• `{command_name} help`\n"+ f"• `{command_name} rules list`\n"+ f'• `{command_name} rules add "description" org/repo`\n'+ f"• `{command_name} rules remove <number(s)>`\n"+ f"• `{command_name} project [<id>]`"+ )