: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): route @PostHog mentions to the right project in multi-integration workspaces (#60249)
Vojta Bartoš231b27d09bf6
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex ee0e9ac762f9..0c54824aa880 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -326,6 +326,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"CodeInviteRedemption", # via CodeInvite"SandboxSnapshot", # via Integration"SlackUserProfileCache", # via Integration+ "SlackSettings", # via Integration}team_scoped: set[str] = set()diff --git a/posthog/temporal/ai/__init__.py b/posthog/temporal/ai/__init__.pyindex 2a234d65c0f3..37605f7e0ed9 100644--- a/posthog/temporal/ai/__init__.py+++ b/posthog/temporal/ai/__init__.py@@ -28,6 +28,11 @@ from posthog.temporal.ai.posthog_code_slack_mention import (resolve_posthog_code_slack_user_activity,select_posthog_code_repository_activity,)+from posthog.temporal.ai.posthog_code_slack_mention_command import (+ PostHogCodeSlackMentionCommandWorkflow,+ handle_posthog_code_slack_mention_command_activity,+ resolve_posthog_code_slack_command_user_activity,+)from posthog.temporal.ai.research_agent import ResearchAgentWorkflow, process_research_agent_activityfrom posthog.temporal.ai.slack_conversation import (SlackConversationRunnerWorkflow,@@ -56,6 +61,7 @@ AI_WORKFLOWS = [SummarizeLLMTracesWorkflow,SlackConversationRunnerWorkflow,PostHogCodeSlackMentionWorkflow,+ PostHogCodeSlackMentionCommandWorkflow,PostHogCodeSlackTerminateTaskWorkflow,AnomalyInvestigationWorkflow,]@@ -72,6 +78,8 @@ AI_ACTIVITIES = [enforce_posthog_code_billing_quota_activity,resolve_posthog_code_slack_user_activity,handle_posthog_code_rules_command_activity,+ handle_posthog_code_slack_mention_command_activity,+ resolve_posthog_code_slack_command_user_activity,collect_posthog_code_thread_messages_activity,create_posthog_code_routing_rule_activity,cascade_posthog_code_repository_activity,diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.pyindex 9ee013b3f069..c09fe99039c0 100644--- a/posthog/temporal/ai/posthog_code_slack_mention.py+++ b/posthog/temporal/ai/posthog_code_slack_mention.py@@ -285,52 +285,60 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):if not user_id:return- rules_result = await _execute_posthog_code_activity(- handle_posthog_code_rules_command_activity,- inputs,- channel,- thread_ts,- slack_user_id,- user_id,- )- if rules_result.status == "handled":- return- if rules_result.status == "needs_picker":- await _execute_posthog_code_activity(- post_posthog_code_repo_picker_activity,+ # Commands are dispatched by PostHogCodeSlackMentionCommandWorkflow,+ # which also owns the ``rules add`` repo picker. New mention runs+ # never reach the rules-handling branch — the patch records that.+ # Workflows started before the patch was introduced (history with no+ # patch marker) still need this branch on replay to remain+ # deterministic, so we keep the original logic gated behind the+ # patch check.+ if not workflow.patched("posthog-code-mention-skip-rules-command"):+ rules_result = await _execute_posthog_code_activity(+ handle_posthog_code_rules_command_activity,inputs,channel,thread_ts,slack_user_id,- event,- workflow.info().workflow_id,- POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,- False,+ user_id,)- try:- await workflow.wait_condition(- lambda: self._repo_selection_resolved,- timeout=timedelta(minutes=POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES),- )- except TimeoutError:+ if rules_result.status == "handled":+ return+ if rules_result.status == "needs_picker":await _execute_posthog_code_activity(- post_posthog_code_picker_timeout_activity, inputs, channel, thread_ts+ post_posthog_code_repo_picker_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ event,+ workflow.info().workflow_id,+ POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,+ False,)- return+ try:+ await workflow.wait_condition(+ lambda: self._repo_selection_resolved,+ timeout=timedelta(minutes=POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES),+ )+ except TimeoutError:+ await _execute_posthog_code_activity(+ post_posthog_code_picker_timeout_activity, inputs, channel, thread_ts+ )+ return- if not self._selected_repo:- return+ if not self._selected_repo:+ return- await _execute_posthog_code_activity(- create_posthog_code_routing_rule_activity,- inputs,- channel,- thread_ts,- user_id,- rules_result.pending_rule_text,- self._selected_repo,- )- return+ await _execute_posthog_code_activity(+ create_posthog_code_routing_rule_activity,+ inputs,+ channel,+ thread_ts,+ user_id,+ rules_result.pending_rule_text,+ self._selected_repo,+ )+ returnthread_messages = await _execute_posthog_code_activity(collect_posthog_code_thread_messages_activity,@@ -602,165 +610,32 @@ def handle_posthog_code_rules_command_activity(user_id: int,) -> PostHogCodeRulesCommandResult:from products.slack_app.backend.api import _parse_rules_command+ from products.slack_app.backend.services.commands import dispatch_rules_commandcommand = _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-posthog-code",integration_id=inputs.slack_team_id,)- slack = SlackIntegration(integration)-- if command.action == "help":- _handle_help(slack, channel, thread_ts)- elif command.action == "list":- _handle_rules_list(slack, integration, channel, thread_ts)- elif command.action == "add":- if not command.repository:- return PostHogCodeRulesCommandResult(status="needs_picker", pending_rule_text=command.rule_text)- _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)- elif command.action == "deprecated_default_repo":- slack.client.chat_postMessage(- channel=channel,- thread_ts=thread_ts,- text=(- "`default repo` commands have been removed. PostHog now selects the repository "- "automatically based on your message context — just describe what you need."- ),- )-- return PostHogCodeRulesCommandResult(status="handled")---def _handle_help(slack: Any, channel: str, thread_ts: str) -> None:- slack.client.chat_postMessage(- channel=channel,- thread_ts=thread_ts,- text=(- "*Available commands:*\n\n"- "`@PostHog <task description>` — Create a task for the agent to work on\n"- "`@PostHog rules list` — Show all routing rules\n"- '`@PostHog rules add "description" org/repo` — Add a routing rule\n'- '`@PostHog rules add "description"` — Add a routing rule (pick repo from list)\n'- "`@PostHog rules remove <number(s)>` — Remove routing rules by number (e.g. `remove 1` or `remove 1,2`)\n"- "`@PostHog help` — Show this message\n\n"- "You can also reply in an active thread to send follow-up messages to the agent."- ),- )---def _handle_rules_list(slack: Any, integration: Any, channel: str, thread_ts: str) -> None:- rules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))- if not rules:- slack.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.',- )- return-- lines = [f"{i + 1}. {r.rule_text} → `{r.repository}`" for i, r in enumerate(rules)]- slack.client.chat_postMessage(+ dispatch_rules_command(+ command,+ SlackIntegration(integration),+ integration,channel=channel,thread_ts=thread_ts,- text="*Routing rules:*\n" + "\n".join(lines),- )---def _handle_rules_add(- slack: Any,- integration: Any,- channel: str,- thread_ts: str,- user_id: int,- rule_text: str,- repository: str,-) -> None:- from products.slack_app.backend.api import _extract_explicit_repo, _get_full_repo_names-- all_repos = _get_full_repo_names(integration)- if not all_repos:- slack.client.chat_postMessage(- channel=channel,- thread_ts=thread_ts,- text="No connected GitHub repositories found for this project.",- )- return-- matched_repo = _extract_explicit_repo(repository, all_repos)- if not matched_repo:- slack.client.chat_postMessage(- channel=channel,- thread_ts=thread_ts,- text=f"Repository `{repository}` is not connected to this project.",- )- return-- current_max = (- RepoRoutingRule.objects.filter(team_id=integration.team_id)- .order_by("-priority")- .values_list("priority", flat=True)- .first()- )- max_priority = (current_max + 1) if current_max is not None else 0- RepoRoutingRule.objects.create(- team_id=integration.team_id,- rule_text=rule_text,- repository=matched_repo,- priority=max_priority,- created_by_id=user_id,- )- slack.client.chat_postMessage(- channel=channel,- thread_ts=thread_ts,- text=f"Added rule: {rule_text} → `{matched_repo}`",- )---def _handle_rules_remove(- slack: Any,- integration: Any,- channel: str,- thread_ts: str,- rule_numbers: list[int] | None,-) -> None:- if not rule_numbers or any(n < 1 for n in rule_numbers):- 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.",- )- return-- rules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))- invalid = [n for n in rule_numbers if n > len(rules)]- if invalid:- 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.",- )- return-- # Collect rules to delete (use sorted unique numbers, delete in reverse to keep indices stable)- to_delete = sorted(set(rule_numbers), reverse=True)- removed: list[str] = []- for n in to_delete:- rule = rules[n - 1]- removed.append(f"#{n}: {rule.rule_text}")- rule.delete()-- removed.reverse()- slack.client.chat_postMessage(- channel=channel,- thread_ts=thread_ts,- text=f"Removed rule{'s' if len(removed) > 1 else ''} {', '.join(removed)}",+ slack_user_id=slack_user_id,+ slack_workspace_id=inputs.slack_team_id,+ user_id=user_id,)+ return PostHogCodeRulesCommandResult(status="handled")@activity.defndiff --git a/posthog/temporal/ai/posthog_code_slack_mention_command.py b/posthog/temporal/ai/posthog_code_slack_mention_command.pynew file mode 100644index 000000000000..c65b9a2ebe6b--- /dev/null+++ b/posthog/temporal/ai/posthog_code_slack_mention_command.py@@ -0,0 +1,280 @@+import json+from dataclasses import dataclass+from datetime import timedelta+from typing import Any++from temporalio import activity, workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow++POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS = 60+# Matches the mention workflow's picker wait window so the bot's behaviour is+# consistent across both flows. The lifetime of a command workflow that posts a+# picker is bounded by this timeout.+POSTHOG_CODE_SLACK_COMMAND_PICKER_TIMEOUT_MINUTES = 25+++@dataclass+class PostHogCodeSlackMentionCommandWorkflowInputs:+ event: dict[str, Any]+ integration_ids: list[int]+ slack_team_id: str+++@dataclass+class PostHogCodeSlackMentionCommandResult:+ """Outcome of the synchronous command-dispatch activity.++ ``status="done"`` means the command was handled (or refused) inline by the+ activity and the workflow has nothing left to do. ``status="needs_picker"``+ means the parsed command is a ``rules add`` without an inline repository,+ and the workflow must drive the interactive repo-picker flow against+ ``target_integration_id`` using ``pending_rule_text``.+ """++ status: str # "done" | "needs_picker"+ pending_rule_text: str | None = None+ target_integration_id: int | None = None++[email protected](name="posthog-code-slack-mention-command")+class PostHogCodeSlackMentionCommandWorkflow(PostHogWorkflow):+ def __init__(self) -> None:+ self._selected_repo: str | None = None+ self._repo_selection_resolved = False++ @workflow.signal+ async def repo_selected(self, repository: str) -> None:+ if not self._repo_selection_resolved:+ self._repo_selection_resolved = True+ self._selected_repo = repository++ @workflow.signal+ async def no_repo_needed(self) -> None:+ # Signal name mirrors the mention workflow's: the interactivity endpoint+ # routes by workflow_id, but addresses the signal by name. Both names+ # must match so a picker posted by either workflow can be resolved.+ if not self._repo_selection_resolved:+ self._repo_selection_resolved = True+ self._selected_repo = None++ @staticmethod+ def parse_inputs(inputs: list[str]) -> PostHogCodeSlackMentionCommandWorkflowInputs:+ loaded = json.loads(inputs[0])+ return PostHogCodeSlackMentionCommandWorkflowInputs(**loaded)++ @workflow.run+ async def run(self, inputs: PostHogCodeSlackMentionCommandWorkflowInputs) -> None:+ from posthog.temporal.ai.posthog_code_slack_mention import (+ POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,+ PostHogCodeSlackMentionWorkflowInputs,+ create_posthog_code_routing_rule_activity,+ post_posthog_code_picker_timeout_activity,+ post_posthog_code_repo_picker_activity,+ )++ user_id = await workflow.execute_activity(+ resolve_posthog_code_slack_command_user_activity,+ args=[inputs],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if user_id is None:+ return++ result = await workflow.execute_activity(+ handle_posthog_code_slack_mention_command_activity,+ args=[inputs, user_id],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if result.status != "needs_picker":+ return++ target_integration_id = result.target_integration_id+ pending_rule_text = result.pending_rule_text+ if target_integration_id is None or pending_rule_text is None:+ return++ event = inputs.event+ channel = event.get("channel")+ thread_ts = event.get("thread_ts") or event.get("ts")+ slack_user_id = event.get("user")+ if not isinstance(channel, str) or not isinstance(thread_ts, str) or not isinstance(slack_user_id, str):+ return++ # The picker activities are written against the mention workflow's input+ # shape, but they only read ``integration_id`` / ``slack_team_id`` /+ # ``event`` from it. Synthesise a compatible record for the resolved+ # target so we can reuse the existing picker plumbing without+ # duplicating it.+ picker_inputs = PostHogCodeSlackMentionWorkflowInputs(+ event=inputs.event,+ integration_id=target_integration_id,+ slack_team_id=inputs.slack_team_id,+ )++ await workflow.execute_activity(+ post_posthog_code_repo_picker_activity,+ args=[+ picker_inputs,+ channel,+ thread_ts,+ slack_user_id,+ inputs.event,+ workflow.info().workflow_id,+ POSTHOG_CODE_SLACK_RULES_ADD_PICKER_GUIDANCE,+ False,+ ],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )++ try:+ await workflow.wait_condition(+ lambda: self._repo_selection_resolved,+ timeout=timedelta(minutes=POSTHOG_CODE_SLACK_COMMAND_PICKER_TIMEOUT_MINUTES),+ )+ except TimeoutError:+ await workflow.execute_activity(+ post_posthog_code_picker_timeout_activity,+ args=[picker_inputs, channel, thread_ts],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ return++ if not self._selected_repo:+ return++ await workflow.execute_activity(+ create_posthog_code_routing_rule_activity,+ args=[picker_inputs, channel, thread_ts, user_id, pending_rule_text, self._selected_repo],+ start_to_close_timeout=timedelta(seconds=POSTHOG_CODE_SLACK_COMMAND_ACTIVITY_TIMEOUT_SECONDS),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+++def resolve_posthog_code_slack_command_user_activity(+ inputs: PostHogCodeSlackMentionCommandWorkflowInputs,+) -> int | None:+ from posthog.models.integration import Integration, SlackIntegration++ from products.slack_app.backend.api import _resolve_posthog_user_from_event++ event = inputs.event+ channel = event.get("channel")+ thread_ts = event.get("thread_ts") or event.get("ts")+ slack_user_id = event.get("user")+ if not channel or not thread_ts or not slack_user_id or not inputs.integration_ids:+ return None++ candidates = list(+ Integration.objects.filter(+ id__in=inputs.integration_ids,+ kind="slack-posthog-code",+ integration_id=inputs.slack_team_id,+ ).select_related("team", "team__organization")+ )+ if not candidates:+ return None++ probe = candidates[0]+ posthog_user = _resolve_posthog_user_from_event(+ slack_user_id=slack_user_id,+ probe_integration=probe,+ candidate_integrations=candidates,+ )+ if posthog_user is None:+ SlackIntegration(probe).client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ 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."+ ),+ )+ return None+ return posthog_user.id+++def handle_posthog_code_slack_mention_command_activity(+ inputs: PostHogCodeSlackMentionCommandWorkflowInputs,+ user_id: int,+) -> PostHogCodeSlackMentionCommandResult:+ from posthog.models.integration import SlackIntegration++ from products.slack_app.backend.api import _parse_rules_command+ from products.slack_app.backend.services.commands import dispatch_rules_command, resolve_command_target++ event = inputs.event+ channel = event.get("channel")+ thread_ts = event.get("thread_ts") or event.get("ts")+ slack_user_id = event.get("user")+ if not channel or not thread_ts or not slack_user_id:+ return PostHogCodeSlackMentionCommandResult(status="done")++ command = _parse_rules_command(event.get("text", ""))+ if command is None:+ return PostHogCodeSlackMentionCommandResult(status="done")++ candidates, result = resolve_command_target(+ slack_team_id=inputs.slack_team_id,+ command=command,+ slack_user_id=slack_user_id,+ user_id=user_id,+ channel=channel,+ thread_ts=thread_ts,+ )+ if not candidates:+ return PostHogCodeSlackMentionCommandResult(status="done")+ if result.integration is None:+ # Disambiguate "no access" (empty after access filtering) from+ # "multiple projects available" so users get an actionable hint.+ if not result.candidates:+ text = (+ "You don't have access to any PostHog project connected to this Slack workspace. "+ "Ask an admin to grant you access, then try again."+ )+ 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."+ )+ SlackIntegration(candidates[0]).client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ text=text,+ )+ return PostHogCodeSlackMentionCommandResult(status="done")++ target = result.integration++ # ``rules add`` without an inline repo needs the interactive picker, which+ # only a workflow can drive (it owns the signal). Hand control back so the+ # workflow can post the picker against the resolved target and wait for+ # the user's selection.+ if command.action == "add" and not command.repository:+ return PostHogCodeSlackMentionCommandResult(+ status="needs_picker",+ pending_rule_text=command.rule_text,+ target_integration_id=target.id,+ )++ dispatch_rules_command(+ command,+ SlackIntegration(target),+ target,+ channel=channel,+ thread_ts=thread_ts,+ slack_user_id=slack_user_id,+ slack_workspace_id=inputs.slack_team_id,+ user_id=user_id,+ workspace_candidates=candidates,+ )+ return PostHogCodeSlackMentionCommandResult(status="done")diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 568c23a27c23..48d2a0853dbe 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -26,6 +26,7 @@ class TestAITemporalModuleIntegrity:"SummarizeLLMTracesWorkflow","SlackConversationRunnerWorkflow","PostHogCodeSlackMentionWorkflow",+ "PostHogCodeSlackMentionCommandWorkflow","PostHogCodeSlackTerminateTaskWorkflow","AnomalyInvestigationWorkflow",]@@ -57,6 +58,8 @@ class TestAITemporalModuleIntegrity:"enforce_posthog_code_billing_quota_activity","resolve_posthog_code_slack_user_activity","handle_posthog_code_rules_command_activity",+ "handle_posthog_code_slack_mention_command_activity",+ "resolve_posthog_code_slack_command_user_activity","collect_posthog_code_thread_messages_activity","create_posthog_code_routing_rule_activity","cascade_posthog_code_repository_activity",diff --git a/products/slack_app/backend/admin.py b/products/slack_app/backend/admin.pynew file mode 100644index 000000000000..c55eb67691cb--- /dev/null+++ b/products/slack_app/backend/admin.py@@ -0,0 +1,30 @@+from django.contrib import admin++from .models import SlackSettings++[email protected](SlackSettings)+class SlackSettingsAdmin(admin.ModelAdmin):+ list_select_related = (+ "default_integration",+ "default_integration__team",+ "default_integration__team__organization",+ )+ list_display = (+ "id",+ "slack_workspace_id",+ "slack_user_id",+ "default_integration",+ "updated_at",+ )+ list_filter = ("slack_workspace_id", "created_at")+ search_fields = (+ "slack_workspace_id",+ "slack_user_id",+ "default_integration__integration_id",+ "default_integration__team__name",+ "default_integration__team__organization__name",+ )+ autocomplete_fields = ("default_integration",)+ readonly_fields = ("id", "created_at", "updated_at")+ ordering = ("-updated_at",)diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 4a671974ca10..43a114eb7eb4 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -39,10 +39,16 @@ from posthog.temporal.ai.posthog_code_slack_mention import (PostHogCodeSlackMentionWorkflow,PostHogCodeSlackMentionWorkflowInputs,)+from posthog.temporal.ai.posthog_code_slack_mention_command import (+ PostHogCodeSlackMentionCommandWorkflow,+ PostHogCodeSlackMentionCommandWorkflowInputs,+)from posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import get_instance_region+from products.slack_app.backend.models import SlackUserProfileCache+from products.slack_app.backend.services.integration_resolver import format_project_candidate_list, load_integrationsfrom products.slack_app.backend.slack_link_unfurl import handle_posthog_link_unfurllogger = structlog.get_logger(__name__)@@ -133,10 +139,29 @@ class SlackUserContext:@dataclassclass RulesCommand:- action: Literal["list", "add", "remove", "help", "deprecated_default_repo"]+ """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.+ """++ action: Literal[+ "list",+ "add",+ "remove",+ "help",+ "deprecated_default_repo",+ "project_show",+ "project_set",+ ]rule_text: str | None = Nonerepository: str | None = Nonerule_numbers: list[int] | None = None+ project_team_id: int | None = Nonedef _slack_user_info_cache_key(integration_id: int, slack_user_id: str) -> str:@@ -175,8 +200,6 @@ def _normalize_slack_response(payload: Any) -> dict[str, Any]:def _get_slack_user_info_from_db(integration: Integration, slack_user_id: str) -> dict[str, Any] | None:- from products.slack_app.backend.models import SlackUserProfileCache-try:profile = SlackUserProfileCache.objects.filter(integration_id=integration.id, slack_user_id=slack_user_id@@ -197,8 +220,6 @@ def _get_slack_user_info_from_db(integration: Integration, slack_user_id: str) -def _persist_slack_user_info(integration: Integration, slack_user_id: str, user_info: dict[str, Any]) -> None:- from products.slack_app.backend.models import SlackUserProfileCache-user = user_info.get("user", {})profile = user.get("profile", {})try:@@ -237,8 +258,6 @@ def _get_slack_user_info(slack: SlackIntegration, integration: Integration, slacdef _get_slack_user_id_by_email_from_db(integration: Integration, normalized_email: str) -> str | None:- from products.slack_app.backend.models import SlackUserProfileCache-try:profile = SlackUserProfileCache.objects.filter(integration_id=integration.id,@@ -575,6 +594,14 @@ def _parse_rules_command(text: str) -> RulesCommand | None:if numbers:return RulesCommand(action="remove", rule_numbers=numbers)+ # Trailing text after the id is tolerated but ignored — we only act on the id.+ project_match = re.fullmatch(r"project(?:\s+(\d+)(?:\s+.*)?)?", cleaned, flags=re.IGNORECASE | re.DOTALL)+ if project_match is not None:+ team_id_str = project_match.group(1)+ if team_id_str is None:+ return RulesCommand(action="project_show")+ return RulesCommand(action="project_set", project_team_id=int(team_id_str))+if re.fullmatch(r"help", cleaned, flags=re.IGNORECASE):return RulesCommand(action="help")@@ -1222,88 +1249,211 @@ def _notify_missing_slack_scopes(_post_slack_user_feedback(slack, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)+def _resolve_posthog_user_from_event(+ *,+ slack_user_id: str,+ probe_integration: Integration,+ candidate_integrations: list[Integration],+) -> User | None:+ """Resolve the acting Slack user to a PostHog ``User`` who is a member of+ at least one organization connected to this Slack workspace.++ The probe is used to call Slack's ``users.info``; the candidate list scopes+ the organization-membership check. A user with no membership in any+ connected org returns ``None`` so the caller can refuse the event.+ """+ slack_client = SlackIntegration(probe_integration)+ try:+ user_info = _get_slack_user_info(slack_client, probe_integration, slack_user_id)+ slack_email = user_info.get("user", {}).get("profile", {}).get("email")+ if not slack_email:+ fresh = _normalize_slack_response(slack_client.client.users_info(user=slack_user_id))+ if fresh:+ _persist_slack_user_info(probe_integration, slack_user_id, fresh)+ slack_email = fresh.get("user", {}).get("profile", {}).get("email")+ if not slack_email:+ return None+ org_ids = {c.team.organization_id for c in candidate_integrations}+ if not org_ids:+ return None+ membership = (+ OrganizationMembership.objects.filter(organization_id__in=org_ids, user__email=slack_email)+ .select_related("user")+ .first()+ )+ return membership.user if membership else None+ except Exception:+ logger.warning(+ "posthog_code_resolve_user_failed",+ integration_id=probe_integration.id,+ slack_user_id=slack_user_id,+ exc_info=True,+ )+ return None+++def _post_pick_a_project_hint(+ probe: SlackIntegration,+ candidates: list[Integration],+ event: dict[str, Any],+) -> None:+ """Tell the user that this workspace is connected to multiple PostHog+ projects, and that they should pick one via `@PostHog project <id>`.+ """+ slack_user_id = event.get("user")+ channel = event.get("channel")+ thread_ts = event.get("thread_ts") or event.get("ts")+ if not isinstance(slack_user_id, str) or not isinstance(channel, str) or not isinstance(thread_ts, str):+ return+ text = (+ "This Slack workspace is connected to multiple PostHog projects:\n"+ f"{format_project_candidate_list(candidates)}\n\n"+ "Use `@PostHog project <id>` to pick one — that also saves it as your default."+ )+ _post_slack_user_feedback(probe, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)+++def _start_posthog_code_workflow(+ workflow_cls: Any,+ workflow_inputs: Any,+ *,+ id_prefix: str,+ slack_team_id: str,+ event: dict,+ event_id: str | None,+) -> None:+ fallback = event_id if event_id else f"{event.get('channel', '')}:{event.get('ts', '')}"+ workflow_id = f"{id_prefix}-{slack_team_id}:{fallback}"+ client = sync_connect()+ asyncio.run(+ client.start_workflow(+ workflow_cls.run,+ workflow_inputs,+ id=workflow_id,+ task_queue=settings.MAX_AI_TASK_QUEUE,+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ )+ )++def route_posthog_code_event_to_relevant_region(request: HttpRequest,event: dict,slack_team_id: str,event_id: str | None = None,) -> str:- # One webhook endpoint serves both the notifications integration (kind="slack") and the- # coding-agent integration (kind="slack-posthog-code"). What counts as a "local match" has- # to depend on event type: app_mention needs the coding-agent integration specifically,- # while link_shared (unfurl) works with either kind. Without this, a region that has only a- # notifications install for a workspace would silently swallow mentions instead of- # proxying to the region that holds the coding-agent install.- integrations = list(- Integration.objects.filter(- kind__in=["slack", "slack-posthog-code"],- integration_id=slack_team_id,- )- .select_related("team", "team__organization", "created_by")- .order_by("id")- )- coding_agent_integration = next((i for i in integrations if i.kind == "slack-posthog-code"), None)- any_integration = integrations[0] if integrations else None-event_type = event.get("type")- if event_type == "app_mention":- local_match = coding_agent_integration- else:- local_match = any_integration+ in_region = not (settings.DEBUG and request.get_host() == SLACK_PRIMARY_REGION_DOMAIN)- if local_match and not (settings.DEBUG and request.get_host() == SLACK_PRIMARY_REGION_DOMAIN):- if event_type == "app_mention":- if not _posthog_code_enabled_for_integration(local_match):- logger.info(- "posthog_code_event_flag_off",- slack_team_id=slack_team_id,- organization_id=str(local_match.team.organization_id),- )- return ROUTE_HANDLED_LOCALLY- ignore_reason = _app_mention_ignore_reason(event)- if ignore_reason:- logger.info(- "posthog_code_event_app_mention_ignored",- reason=ignore_reason,- slack_team_id=slack_team_id,- channel=event.get("channel"),- message_ts=event.get("ts"),- )- return ROUTE_HANDLED_LOCALLY- slack = SlackIntegration(local_match)- missing_scopes = slack.missing_scopes(POSTHOG_CODE_REQUIRED_SLACK_SCOPES)- if missing_scopes:- _notify_missing_slack_scopes(slack, event, missing_scopes)- return ROUTE_HANDLED_LOCALLY- if _resolve_pending_repo_picker_from_followup(event, local_match):- return ROUTE_HANDLED_LOCALLY- workflow_inputs = PostHogCodeSlackMentionWorkflowInputs(- event=event,- integration_id=local_match.id,+ if event_type == "app_mention":+ ignore_reason = _app_mention_ignore_reason(event)+ if ignore_reason:+ logger.info(+ "posthog_code_event_app_mention_ignored",+ reason=ignore_reason,slack_team_id=slack_team_id,+ channel=event.get("channel"),+ message_ts=event.get("ts"),)- event_id_or_fallback = event_id if event_id else f"{event.get('channel', '')}:{event.get('ts', '')}"- workflow_id = f"posthog-code-mention-{slack_team_id}:{event_id_or_fallback}"- client = sync_connect()- asyncio.run(- client.start_workflow(- PostHogCodeSlackMentionWorkflow.run,- workflow_inputs,- id=workflow_id,- task_queue=settings.MAX_AI_TASK_QUEUE,- id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,- id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,- )+ return ROUTE_HANDLED_LOCALLY++ result = load_integrations(+ slack_team_id=slack_team_id,+ kinds=["slack-posthog-code"],+ slack_user_id=str(event.get("user") or ""),+ user=None,+ channel=event.get("channel") if isinstance(event.get("channel"), str) else None,+ thread_ts=(event.get("thread_ts") or event.get("ts"))+ if isinstance(event.get("thread_ts") or event.get("ts"), str)+ else None,+ )+ if not result.candidates or not in_region:+ return _proxy_or_no_integration(request, slack_team_id)++ # Gate the entire @PostHog surface on the rollout flag at the candidate+ # level so command workflows, pick-a-project hints, and mention workflows+ # are all covered. Per-candidate filter so a workspace with several+ # PostHog projects can have some on-rollout and some off-rollout cleanly.+ enabled = [c for c in result.candidates if _posthog_code_enabled_for_integration(c)]+ if not enabled:+ logger.info(+ "posthog_code_event_flag_off",+ slack_team_id=slack_team_id,+ candidate_count=len(result.candidates),)- elif event_type == "link_shared":+ return ROUTE_HANDLED_LOCALLY+ candidates = enabled+ target = result.integration if result.integration in enabled else None++ if _parse_rules_command(event.get("text", "")) is not None:+ return _start_command_workflow(event, candidates, slack_team_id, event_id)++ mention_target = target or (candidates[0] if len(candidates) == 1 else None)+ if mention_target is None:+ _post_pick_a_project_hint(SlackIntegration(candidates[0]), candidates, event)+ return ROUTE_HANDLED_LOCALLY++ slack = SlackIntegration(mention_target)+ missing = slack.missing_scopes(POSTHOG_CODE_REQUIRED_SLACK_SCOPES)+ if missing:+ _notify_missing_slack_scopes(slack, event, missing)+ return ROUTE_HANDLED_LOCALLY++ return _start_mention_workflow(event, mention_target, slack_team_id, event_id)++ # link_shared (unfurl) works with either integration kind.+ link_result = load_integrations(slack_team_id=slack_team_id, kinds=["slack", "slack-posthog-code"])+ local_match = link_result.candidates[0] if link_result.candidates else None+ if local_match and in_region:+ if event_type == "link_shared":handle_posthog_link_unfurl(event, local_match)return ROUTE_HANDLED_LOCALLY- elif request.get_host() == SLACK_PRIMARY_REGION_DOMAIN:+ return _proxy_or_no_integration(request, slack_team_id)+++def _proxy_or_no_integration(request: HttpRequest, slack_team_id: str) -> str:+ if request.get_host() == SLACK_PRIMARY_REGION_DOMAIN:success = proxy_slack_event_to_secondary_region(request)return ROUTE_PROXIED if success else ROUTE_PROXY_FAILED- else:- logger.warning("posthog_code_no_integration_found", slack_team_id=slack_team_id)- return ROUTE_NO_INTEGRATION+ logger.warning("posthog_code_no_integration_found", slack_team_id=slack_team_id)+ return ROUTE_NO_INTEGRATION+++def _start_command_workflow(+ event: dict, integrations: list[Integration], slack_team_id: str, event_id: str | None+) -> str:+ _start_posthog_code_workflow(+ PostHogCodeSlackMentionCommandWorkflow,+ PostHogCodeSlackMentionCommandWorkflowInputs(+ event=event,+ integration_ids=[i.id for i in integrations],+ slack_team_id=slack_team_id,+ ),+ id_prefix="posthog-code-mention-command",+ slack_team_id=slack_team_id,+ event=event,+ event_id=event_id,+ )+ return ROUTE_HANDLED_LOCALLY+++def _start_mention_workflow(event: dict, integration: Integration, slack_team_id: str, event_id: str | None) -> str:+ if _resolve_pending_repo_picker_from_followup(event, integration):+ return ROUTE_HANDLED_LOCALLY+ _start_posthog_code_workflow(+ PostHogCodeSlackMentionWorkflow,+ PostHogCodeSlackMentionWorkflowInputs(+ event=event,+ integration_id=integration.id,+ slack_team_id=slack_team_id,+ ),+ id_prefix="posthog-code-mention",+ slack_team_id=slack_team_id,+ event=event,+ event_id=event_id,+ )+ return ROUTE_HANDLED_LOCALLYdef _picker_context_cache_key(context_token: str) -> str:diff --git a/products/slack_app/backend/migrations/0003_slacksettings.py b/products/slack_app/backend/migrations/0003_slacksettings.pynew file mode 100644index 000000000000..324d4e9c6890--- /dev/null+++ b/products/slack_app/backend/migrations/0003_slacksettings.py@@ -0,0 +1,59 @@+# Generated by Django 5.2.14 on 2026-05-29 12:00++import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1177_alter_organization_is_ai_data_processing_approved"),+ ("slack_app", "0002_slackuserprofilecache_is_admin_and_more"),+ ]++ operations = [+ migrations.CreateModel(+ name="SlackSettings",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("slack_workspace_id", models.CharField(max_length=64)),+ (+ "slack_user_id",+ models.CharField(blank=True, max_length=64, null=True),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ (+ "default_integration",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="slack_settings_as_default",+ to="posthog.integration",+ ),+ ),+ ],+ options={+ "constraints": [+ models.UniqueConstraint(+ condition=models.Q(("slack_user_id__isnull", False)),+ fields=("slack_workspace_id", "slack_user_id"),+ name="uniq_slack_settings_per_user",+ ),+ models.UniqueConstraint(+ condition=models.Q(("slack_user_id__isnull", True)),+ fields=("slack_workspace_id",),+ name="uniq_slack_settings_per_workspace",+ ),+ ],+ },+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex af8ae093d394..026dc63df81f 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0002_slackuserprofilecache_is_admin_and_more+0003_slacksettingsdiff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex f6a5caef7ddc..4c2ffaa9b60e 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -1,4 +1,5 @@from django.db import models+from django.db.models import Qfrom posthog.models.utils import UUIDModel@@ -60,3 +61,51 @@ class SlackUserProfileCache(UUIDModel):name="uniq_slack_user_profile_cache_integration_user",)]+++class SlackSettings(UUIDModel):+ """Per-(Slack workspace, Slack user) settings for inbound `slack-posthog-code`+ events. Currently stores the routing default — which PostHog integration a+ mention from this Slack user should route to.++ 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+ settings UI.+ - ``slack_user_id IS NULL`` → workspace-wide fallback, applied when an+ inbound event's Slack user has no personal row yet. Written only via the+ PostHog project-level settings UI by a team admin (never via Slack).++ A user-specific row, if present, always wins over the workspace-wide row at+ resolution time.+ """++ default_integration = models.ForeignKey(+ "posthog.Integration",+ on_delete=models.CASCADE,+ related_name="slack_settings_as_default",+ )+ slack_workspace_id = models.CharField(max_length=64)+ slack_user_id = models.CharField(max_length=64, null=True, blank=True)+ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(+ fields=["slack_workspace_id", "slack_user_id"],+ name="uniq_slack_settings_per_user",+ condition=Q(slack_user_id__isnull=False),+ ),+ # Partial: NULL slack_user_id is the workspace-wide row, which+ # Postgres's default NULL-distinct rule wouldn't otherwise dedupe.+ models.UniqueConstraint(+ fields=["slack_workspace_id"],+ name="uniq_slack_settings_per_workspace",+ condition=Q(slack_user_id__isnull=True),+ ),+ ]++ def __str__(self) -> str:+ who = self.slack_user_id or "(workspace default)"+ return f"{self.slack_workspace_id} / {who} → integration {self.default_integration_id}"diff --git a/products/slack_app/backend/services/__init__.py b/products/slack_app/backend/services/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.pynew file mode 100644index 000000000000..f30230066fa4--- /dev/null+++ b/products/slack_app/backend/services/commands.py@@ -0,0 +1,386 @@+from typing import TYPE_CHECKING++from posthog.models.integration import Integration, SlackIntegration++if TYPE_CHECKING:+ from products.slack_app.backend.api import RulesCommand+ from products.slack_app.backend.services.integration_resolver import ResolutionResult+++def _handle_help(slack: SlackIntegration, channel: str, thread_ts: str) -> None:+ slack.client.chat_postMessage(+ channel=channel,+ thread_ts=thread_ts,+ text=(+ "*Available commands:*\n\n"+ "`@PostHog <task description>` — Create a task for the agent to work on\n"+ "`@PostHog rules list` — Show all routing rules\n"+ '`@PostHog rules add "description" org/repo` — Add a routing rule\n'+ '`@PostHog rules add "description"` — Add a routing rule (pick repo from list)\n'+ "`@PostHog rules remove <number(s)>` — Remove routing rules by number (e.g. `remove 1` or `remove 1,2`)\n"+ "`@PostHog project` — Show which PostHog project your mentions route to in this workspace\n"+ "`@PostHog project <id>` — Set the PostHog project your mentions route to in this workspace\n"+ "`@PostHog help` — Show this message\n\n"+ "You can also reply in an active thread to send follow-up messages to the agent."+ ),+ )+++def _handle_rules_list(slack: SlackIntegration, integration: Integration, channel: str, thread_ts: str) -> None:+ from posthog.models.repo_routing_rule import RepoRoutingRule++ rules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))+ if not rules:+ slack.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.',+ )+ return++ lines = [f"{i + 1}. {r.rule_text} → `{r.repository}`" for i, r in enumerate(rules)]+ slack.client.chat_postMessage(+ channel=channel,+ thread_ts=thread_ts,+ text="*Routing rules:*\n" + "\n".join(lines),+ )+++def _handle_rules_add(+ slack: SlackIntegration,+ integration: Integration,+ channel: str,+ thread_ts: str,+ user_id: int,+ rule_text: str,+ repository: str,+) -> None:+ from posthog.models.repo_routing_rule import RepoRoutingRule++ from products.slack_app.backend.api import _extract_explicit_repo, _get_full_repo_names++ all_repos = _get_full_repo_names(integration)+ if not all_repos:+ slack.client.chat_postMessage(+ channel=channel,+ thread_ts=thread_ts,+ text="No connected GitHub repositories found for this project.",+ )+ return++ matched_repo = _extract_explicit_repo(repository, all_repos)+ if not matched_repo:+ slack.client.chat_postMessage(+ channel=channel,+ thread_ts=thread_ts,+ text=f"Repository `{repository}` is not connected to this project.",+ )+ return++ current_max = (+ RepoRoutingRule.objects.filter(team_id=integration.team_id)+ .order_by("-priority")+ .values_list("priority", flat=True)+ .first()+ )+ max_priority = (current_max + 1) if current_max is not None else 0+ RepoRoutingRule.objects.create(+ team_id=integration.team_id,+ rule_text=rule_text,+ repository=matched_repo,+ priority=max_priority,+ created_by_id=user_id,+ )+ slack.client.chat_postMessage(+ channel=channel,+ thread_ts=thread_ts,+ text=f"Added rule: {rule_text} → `{matched_repo}`",+ )+++def _handle_rules_remove(+ slack: SlackIntegration,+ integration: Integration,+ channel: str,+ thread_ts: str,+ rule_numbers: list[int] | None,+) -> None:+ from posthog.models.repo_routing_rule import RepoRoutingRule++ if not rule_numbers or any(n < 1 for n in rule_numbers):+ 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.",+ )+ return++ rules = list(RepoRoutingRule.objects.filter(team_id=integration.team_id).order_by("priority", "id"))+ invalid = [n for n in rule_numbers if n > len(rules)]+ if invalid:+ 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.",+ )+ return++ to_delete = sorted(set(rule_numbers), reverse=True)+ removed: list[str] = []+ for n in to_delete:+ rule = rules[n - 1]+ removed.append(f"#{n}: {rule.rule_text}")+ rule.delete()++ removed.reverse()+ slack.client.chat_postMessage(+ channel=channel,+ thread_ts=thread_ts,+ text=f"Removed rule{'s' if len(removed) > 1 else ''} {', '.join(removed)}",+ )+++def _handle_project_show(+ slack: SlackIntegration,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ slack_workspace_id: str,+ user_id: int,+ workspace_candidates: list[Integration] | None = None,+) -> None:+ from posthog.models.user import User++ from products.slack_app.backend.services.integration_resolver import (+ format_project_candidate_list,+ load_integrations,+ resolve_from_candidates,+ )++ user = User.objects.get(id=user_id)+ if workspace_candidates is not None:+ result = resolve_from_candidates(+ workspace_candidates,+ slack_team_id=slack_workspace_id,+ slack_user_id=slack_user_id,+ user=user,+ )+ else:+ result = load_integrations(+ slack_team_id=slack_workspace_id,+ kinds=["slack-posthog-code"],+ slack_user_id=slack_user_id,+ user=user,+ )++ if result.integration is not None:+ target = result.integration+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ 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>`."+ ),+ )+ return++ if not result.candidates:+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ text=("I couldn't find your PostHog account in any organization connected to this Slack workspace."),+ )+ return++ lines = format_project_candidate_list(result.candidates)+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ text=(+ "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>`."+ ),+ )+++def _handle_project_set(+ slack: SlackIntegration,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ slack_workspace_id: str,+ user_id: int,+ target_team_id: int,+ workspace_candidates: list[Integration] | None = None,+) -> None:+ from posthog.models.user import User++ from products.slack_app.backend.models import SlackSettings++ user = User.objects.get(id=user_id)+ if not user.teams.filter(id=target_team_id).exists():+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ text=f"You don't have access to project `{target_team_id}`.",+ )+ return++ if workspace_candidates is not None:+ target = next((c for c in workspace_candidates if c.team_id == target_team_id), None)+ else:+ target = (+ Integration.objects.filter(+ kind="slack-posthog-code",+ integration_id=slack_workspace_id,+ team_id=target_team_id,+ )+ .select_related("team", "team__organization")+ .first()+ )+ if target is None:+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ text=f"Project `{target_team_id}` isn't connected to this Slack workspace.",+ )+ return++ SlackSettings.objects.update_or_create(+ slack_workspace_id=slack_workspace_id,+ slack_user_id=slack_user_id,+ defaults={"default_integration": target},+ )+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ text=(+ f"Default set to *{target.team.organization.name} · {target.team.name}* "+ f"(id `{target.team_id}`). I'll route future mentions here — mention me again to "+ "start a task."+ ),+ )+++def resolve_command_target(+ *,+ slack_team_id: str,+ command: "RulesCommand",+ slack_user_id: str,+ user_id: int,+ channel: str,+ thread_ts: str,+) -> tuple[list[Integration], "ResolutionResult"]:+ """Load workspace candidates and decide which one to dispatch against.++ Returns ``(workspace_candidates, result)``. ``result.integration`` is+ ``None`` when no candidate can be auto-picked for the acting user — either+ because access filtering left them with nothing (``result.candidates``+ empty) or because they have access to multiple projects and haven't set a+ default (``result.candidates`` non-empty). The caller picks the appropriate+ "no access" vs "pick a project" message based on which.+ """+ from posthog.models.user import User++ from products.slack_app.backend.services.integration_resolver import (+ ResolutionResult,+ load_integrations,+ resolve_from_candidates,+ )++ initial = load_integrations(slack_team_id=slack_team_id, kinds=["slack-posthog-code"])+ candidates = initial.candidates+ if not candidates:+ return [], ResolutionResult(integration=None, source="needs_picker", candidates=[])++ # Workspace-level commands don't act on team data: ``help`` posts static+ # text, and ``project_show``/``project_set`` enforce access inside the+ # handler. They run against any workspace integration as a probe.+ if command.action in ("project_show", "project_set", "help"):+ return candidates, ResolutionResult(integration=candidates[0], source="sole_candidate", candidates=candidates)++ # Team-scoped commands (``list``/``add``/``remove``) must go through the+ # access-filtered resolver — including the single-integration case, where+ # the shortcut would otherwise dispatch against a project the user has no+ # access to.+ result = resolve_from_candidates(+ candidates,+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id,+ user=User.objects.get(id=user_id),+ channel=channel,+ thread_ts=thread_ts,+ )+ return candidates, result+++def dispatch_rules_command(+ command: "RulesCommand",+ slack: SlackIntegration,+ integration: Integration,+ *,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ slack_workspace_id: str,+ user_id: int,+ workspace_candidates: list[Integration] | None = None,+) -> None:+ """Run the right handler for a parsed ``RulesCommand``. Assumes the caller has+ already resolved a single ``integration`` to act on; project commands also+ accept ``workspace_candidates`` so ``project_set`` can skip a DB lookup.++ ``rules add`` without an inline repo is handled here as a plain "specify the+ repo" reply. The mention workflow's picker flow must catch that case+ *before* calling this dispatcher.+ """+ if command.action == "help":+ _handle_help(slack, channel, thread_ts)+ elif command.action == "list":+ _handle_rules_list(slack, integration, channel, thread_ts)+ 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`.',+ )+ 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)+ elif command.action == "project_show":+ _handle_project_show(+ slack,+ channel,+ thread_ts,+ slack_user_id,+ slack_workspace_id,+ user_id,+ workspace_candidates=workspace_candidates,+ )+ elif command.action == "project_set":+ if command.project_team_id is None:+ return+ _handle_project_set(+ slack,+ channel,+ thread_ts,+ slack_user_id,+ slack_workspace_id,+ user_id,+ command.project_team_id,+ workspace_candidates=workspace_candidates,+ )diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pynew file mode 100644index 000000000000..a5df91f623cc--- /dev/null+++ b/products/slack_app/backend/services/integration_resolver.py@@ -0,0 +1,130 @@+from dataclasses import dataclass, field+from typing import Literal++from django.db.models import Q++from posthog.models.integration import Integration+from posthog.models.user import User++from products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping++ResolutionSource = Literal[+ "thread",+ "user_default",+ "workspace_default",+ "sole_candidate",+ "needs_picker",+]+++@dataclass+class ResolutionResult:+ integration: Integration | None+ source: ResolutionSource+ candidates: list[Integration] = field(default_factory=list)+++def format_project_candidate_list(candidates: list[Integration]) -> str:+ return "\n".join(f"• `{c.team_id}` — {c.team.organization.name} · {c.team.name}" for c in candidates)+++def resolve_from_candidates(+ candidates: list[Integration],+ *,+ slack_team_id: str,+ slack_user_id: str = "",+ user: User | None = None,+ channel: str | None = None,+ thread_ts: str | None = None,+) -> ResolutionResult:+ """Run the routing resolver over a pre-loaded candidate list.++ Precedence: ``thread`` > ``user_default`` > ``workspace_default`` >+ ``sole_candidate`` > ``needs_picker``.++ When ``user`` is provided, defaults whose target is no longer accessible+ silently fall through. When ``user is None`` the resolver trusts saved+ defaults as-is and treats every workspace integration as a candidate.++ Callers that don't need routing (e.g. link_shared / unfurl) can pass+ ``slack_user_id=""``; the SlackSettings lookup is skipped and the result+ falls through to ``sole_candidate`` / ``needs_picker``.+ """+ accessible_team_ids: set[int] | None = set(user.teams.values_list("id", flat=True)) if user is not None else None+ accessible = (+ candidates if accessible_team_ids is None else [i for i in candidates if i.team_id in accessible_team_ids]+ )++ if channel and thread_ts and slack_team_id:+ thread_match = (+ SlackThreadTaskMapping.objects.filter(+ slack_workspace_id=slack_team_id, channel=channel, thread_ts=thread_ts+ )+ .select_related("integration")+ .first()+ )+ # Honour the thread mapping only if the acting user still has access to+ # its project. A revoked-access user replying in an existing agent+ # thread must not bypass the access check via thread continuity.+ if thread_match is not None and (+ accessible_team_ids is None or thread_match.integration.team_id in accessible_team_ids+ ):+ return ResolutionResult(integration=thread_match.integration, source="thread", candidates=accessible)++ if slack_user_id:+ # One query returns at most two rows: the per-user row and the+ # workspace-wide row. Sorting with NULL-last puts the per-user row first.+ defaults = list(+ SlackSettings.objects.filter(slack_workspace_id=slack_team_id)+ .filter(Q(slack_user_id=slack_user_id) | Q(slack_user_id__isnull=True))+ .select_related(+ "default_integration",+ "default_integration__team",+ "default_integration__team__organization",+ )+ )+ defaults.sort(key=lambda d: d.slack_user_id is None)+ candidate_ids = {c.id for c in candidates}+ for default in defaults:+ if accessible_team_ids is not None and default.default_integration.team_id not in accessible_team_ids:+ continue+ # 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>`.+ if default.default_integration.id not in candidate_ids:+ continue+ source: ResolutionSource = "user_default" if default.slack_user_id else "workspace_default"+ return ResolutionResult(integration=default.default_integration, source=source, candidates=accessible)++ if len(accessible) == 1:+ return ResolutionResult(integration=accessible[0], source="sole_candidate", candidates=accessible)+ return ResolutionResult(integration=None, source="needs_picker", candidates=accessible)+++def load_integrations(+ *,+ slack_team_id: str,+ kinds: list[str],+ slack_user_id: str = "",+ user: User | None = None,+ channel: str | None = None,+ thread_ts: str | None = None,+) -> ResolutionResult:+ """Load Slack integrations of the given ``kinds`` for a workspace, then run+ the routing resolver against them. Thin wrapper around+ ``resolve_from_candidates`` that owns the candidate query.+ """+ candidates = list(+ Integration.objects.filter(kind__in=kinds, integration_id=slack_team_id)+ .select_related("team", "team__organization", "created_by")+ .order_by("id")+ )+ return resolve_from_candidates(+ candidates,+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id,+ user=user,+ channel=channel,+ thread_ts=thread_ts,+ )diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.pynew file mode 100644index 000000000000..bf09e6563e8f--- /dev/null+++ b/products/slack_app/backend/tests/test_integration_resolver.py@@ -0,0 +1,365 @@+import pytest++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 SlackSettings, SlackThreadTaskMapping+from products.slack_app.backend.services.integration_resolver import load_integrations++WORKSPACE = "T_WS"+SLACK_USER = "U001"+++class TestResolveIntegration:+ @pytest.fixture(autouse=True)+ def setup(self, db):+ self.organization = Organization.objects.create(name="Org")+ self.team_a = Team.objects.create(organization=self.organization, name="A")+ self.team_b = Team.objects.create(organization=self.organization, name="B")+ # team_c lives in a separate org the user has no membership in.+ self.other_org = Organization.objects.create(name="Other")+ self.team_c = Team.objects.create(organization=self.other_org, name="C")++ self.user = User.objects.create(email="[email protected]", distinct_id="u-1")+ OrganizationMembership.objects.create(user=self.user, organization=self.organization)++ self.integration_a = self._mk_integration(self.team_a)+ self.integration_b = self._mk_integration(self.team_b)+ self.integration_c = self._mk_integration(self.team_c)+ # Different workspace; should never match the WORKSPACE-scoped lookups.+ self.integration_other_workspace = Integration.objects.create(+ team=self.team_a,+ kind="slack-posthog-code",+ integration_id="T_OTHER",+ sensitive_config={"access_token": "xoxb-other"},+ )++ def _mk_integration(self, team: Team) -> Integration:+ return Integration.objects.create(+ team=team,+ kind="slack-posthog-code",+ integration_id=WORKSPACE,+ sensitive_config={"access_token": "xoxb"},+ )++ def _workspace_integrations(self) -> list[Integration]:+ return list(+ Integration.objects.filter(kind="slack-posthog-code", integration_id=WORKSPACE).select_related(+ "team", "team__organization"+ )+ )++ def test_thread_mapping_wins_over_everything(self):+ from products.tasks.backend.models import Task, TaskRun++ task = Task.objects.create(team=self.team_b, title="t")+ task_run = TaskRun.objects.create(team=self.team_b, task=task)+ SlackThreadTaskMapping.objects.create(+ team=self.team_b,+ integration=self.integration_b,+ slack_workspace_id=WORKSPACE,+ channel="C1",+ thread_ts="123.456",+ task=task,+ task_run=task_run,+ mentioning_slack_user_id=SLACK_USER,+ )+ # Even with an unrelated user_default pointing at A, the thread mapping wins.+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id=WORKSPACE,+ slack_user_id=SLACK_USER,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ channel="C1",+ thread_ts="123.456",+ )++ assert result.source == "thread"+ assert result.integration == self.integration_b++ def test_thread_mapping_ignored_when_user_lacks_access(self):+ # Thread mapping targets team_c, which the user has no membership in+ # (it's in `other_org`). The thread match must be skipped — a user+ # whose access was revoked or who never had access can't drive the+ # thread just by replying to it.+ from products.tasks.backend.models import Task, TaskRun++ task = Task.objects.create(team=self.team_c, title="t")+ task_run = TaskRun.objects.create(team=self.team_c, task=task)+ SlackThreadTaskMapping.objects.create(+ team=self.team_c,+ integration=self.integration_c,+ slack_workspace_id=WORKSPACE,+ channel="C1",+ thread_ts="123.456",+ task=task,+ task_run=task_run,+ mentioning_slack_user_id=SLACK_USER,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ channel="C1",+ thread_ts="123.456",+ )++ # Falls through past the thread match to the picker over the user's+ # accessible candidates (A, B).+ assert result.source == "needs_picker"+ assert {i.id for i in result.candidates} == {self.integration_a.id, self.integration_b.id}++ def test_user_default_used_when_accessible(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id=WORKSPACE,+ slack_user_id=SLACK_USER,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ assert result.source == "user_default"+ assert result.integration == self.integration_a++ def test_user_default_ignored_when_target_no_longer_accessible(self):+ # Default points at team_c, which the user has no membership in.+ SlackSettings.objects.create(+ default_integration=self.integration_c,+ slack_workspace_id=WORKSPACE,+ slack_user_id=SLACK_USER,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ # Falls through past user_default: A and B remain accessible → picker.+ assert result.source == "needs_picker"+ assert {i.id for i in result.candidates} == {self.integration_a.id, self.integration_b.id}++ def test_user_default_ignored_when_target_kind_changed(self):+ # Stored default points at integration_a, but its kind was switched+ # away from "slack-posthog-code" (e.g. it became a plain notifications+ # "slack" install). The default must silently fall through rather than+ # routing the user to the wrong-kind integration.+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id=WORKSPACE,+ slack_user_id=SLACK_USER,+ )+ self.integration_a.kind = "slack"+ self.integration_a.save(update_fields=["kind"])++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ # integration_a is no longer in the candidate set (kind filter excludes+ # it), so the stale default is ignored. integration_b is the sole+ # remaining accessible candidate.+ assert result.source == "sole_candidate"+ assert result.integration == self.integration_b++ def test_user_default_wins_over_workspace_default(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id=WORKSPACE,+ slack_user_id=None, # workspace-wide+ )+ SlackSettings.objects.create(+ default_integration=self.integration_b,+ slack_workspace_id=WORKSPACE,+ slack_user_id=SLACK_USER,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ assert result.source == "user_default"+ assert result.integration == self.integration_b++ def test_workspace_default_used_when_no_user_row(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id=WORKSPACE,+ slack_user_id=None,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ assert result.source == "workspace_default"+ assert result.integration == self.integration_a++ def test_workspace_default_ignored_when_target_not_accessible(self):+ # Workspace default points at team_c — the user has no access.+ SlackSettings.objects.create(+ default_integration=self.integration_c,+ slack_workspace_id=WORKSPACE,+ slack_user_id=None,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ # Falls through to candidate selection.+ assert result.source == "needs_picker"+ assert {i.id for i in result.candidates} == {self.integration_a.id, self.integration_b.id}++ def test_sole_candidate_auto_used(self):+ # Remove integration B so only A is accessible to the user in this workspace.+ self.integration_b.delete()++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ assert result.source == "sole_candidate"+ assert result.integration == self.integration_a++ def test_picker_with_multiple_candidates(self):+ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ assert result.integration is None+ assert result.source == "needs_picker"+ assert {i.id for i in result.candidates} == {self.integration_a.id, self.integration_b.id}++ def test_unresolved_user_falls_back_to_full_candidates(self):+ # user=None is the webhook routing layer's call: skip accessibility filtering+ # and trust saved routing rows. Without any defaults, every workspace+ # integration becomes a candidate.+ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=None,+ )++ assert result.integration is None+ assert result.source == "needs_picker"+ assert {i.id for i in result.candidates} == {+ self.integration_a.id,+ self.integration_b.id,+ self.integration_c.id,+ }++ def test_unresolved_user_still_honors_user_default(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id=WORKSPACE,+ slack_user_id=SLACK_USER,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=None,+ )++ assert result.source == "user_default"+ assert result.integration == self.integration_a++ def test_unresolved_user_still_honors_thread_mapping(self):+ from products.tasks.backend.models import Task, TaskRun++ task = Task.objects.create(team=self.team_b, title="t")+ task_run = TaskRun.objects.create(team=self.team_b, task=task)+ SlackThreadTaskMapping.objects.create(+ team=self.team_b,+ integration=self.integration_b,+ slack_workspace_id=WORKSPACE,+ channel="C1",+ thread_ts="123.456",+ task=task,+ task_run=task_run,+ mentioning_slack_user_id=SLACK_USER,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=None,+ channel="C1",+ thread_ts="123.456",+ )++ assert result.source == "thread"+ assert result.integration == self.integration_b++ def test_unresolved_user_trusts_inaccessible_default(self):+ # team_c is in another org. With user=None we don't check accessibility, so+ # the saved default still wins. The workflow's user-resolution will reject+ # the event downstream if needed.+ SlackSettings.objects.create(+ default_integration=self.integration_c,+ slack_workspace_id=WORKSPACE,+ slack_user_id=SLACK_USER,+ )++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=None,+ )++ assert result.source == "user_default"+ assert result.integration == self.integration_c++ def test_other_workspace_integrations_are_excluded(self):+ # Delete integration_b so only integration_a in WORKSPACE remains accessible —+ # verifies the unrelated T_OTHER integration is filtered out by workspace.+ self.integration_b.delete()++ result = load_integrations(+ slack_team_id=WORKSPACE,+ kinds=["slack-posthog-code"],+ slack_user_id=SLACK_USER,+ user=self.user,+ )++ assert result.source == "sole_candidate"+ assert result.integration == self.integration_adiff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.pyindex 685dc1b7a90f..10e0a62e5f1e 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@@ -279,6 +279,87 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):mock_sync_connect.assert_not_called()mock_asyncio_run.assert_not_called()+ @patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_command_text_routes_to_command_workflow(self, mock_sync_connect, mock_asyncio_run, _mock_flag):+ # 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.posthog_code_slack_mention_command import PostHogCodeSlackMentionCommandWorkflow++ 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> 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()+ kicked_off = mock_sync_connect.return_value.start_workflow.call_args.args[0]+ assert kicked_off == PostHogCodeSlackMentionCommandWorkflow.run+ mock_asyncio_run.assert_called_once()++ @patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=True)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_command_workflow_receives_all_workspace_candidates(self, mock_sync_connect, mock_asyncio_run, _mock_flag):+ # 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-posthog-code",+ 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++ request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.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._posthog_code_enabled_for_integration", return_value=True)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_rules_add_without_repo_routes_to_command_workflow_for_picker(+ self, mock_sync_connect, mock_asyncio_run, _mock_flag+ ):+ # ``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.posthog_code_slack_mention_command import PostHogCodeSlackMentionCommandWorkflow++ 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+@patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=False)@patch("products.slack_app.backend.api.asyncio.run")@patch("products.slack_app.backend.api.sync_connect")@@ -294,6 +375,63 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):mock_sync_connect.assert_not_called()mock_asyncio_run.assert_not_called()+ @patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", return_value=False)+ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_command_text_with_flag_off_skips_command_workflow(self, mock_sync_connect, mock_asyncio_run, _mock_flag):+ # Command text from an org outside the rollout must not spawn the command+ # workflow either — the whole @PostHog surface is gated, not just the agent.+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="eu.posthog.com")+ event = {**self.event, "text": "<@UBOT123> help"}++ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region++ result = route_posthog_code_event_to_relevant_region(request, event, "T12345")++ assert result == ROUTE_HANDLED_LOCALLY+ mock_sync_connect.assert_not_called()+ mock_asyncio_run.assert_not_called()++ @patch("products.slack_app.backend.api.asyncio.run")+ @patch("products.slack_app.backend.api.sync_connect")+ @override_settings(DEBUG=False)+ def test_partial_flag_enable_filters_candidates(self, mock_sync_connect, mock_asyncio_run):+ # Two integrations in the same workspace, only one in the rollout. The+ # command workflow should receive only the enabled integration's id.+ from posthog.models.team.team import Team++ other_team = Team.objects.create(organization=self.organization, name="Other")+ disabled_integration = Integration.objects.create(+ team=other_team,+ kind="slack-posthog-code",+ integration_id="T12345",+ config=self.posthog_code_integration.config,+ sensitive_config={"access_token": "xoxb-other"},+ )++ enabled_id = self.posthog_code_integration.id++ def flag_for(integration):+ return integration.id == enabled_id++ with patch("products.slack_app.backend.api._posthog_code_enabled_for_integration", side_effect=flag_for):+ 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> help"}++ 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 workflow_inputs.integration_ids == [enabled_id]+ assert disabled_integration.id not in workflow_inputs.integration_ids+@patch("products.slack_app.backend.api.handle_posthog_link_unfurl")@override_settings(DEBUG=False)def test_link_shared_routes_to_unfurl(self, mock_unfurl):diff --git a/products/slack_app/backend/tests/test_project_directive_parser.py b/products/slack_app/backend/tests/test_project_directive_parser.pynew file mode 100644index 000000000000..1329fd6ab7f2--- /dev/null+++ b/products/slack_app/backend/tests/test_project_directive_parser.py@@ -0,0 +1,75 @@+from parameterized import parameterized++from products.slack_app.backend.api import RulesCommand, _parse_rules_command+++class TestParseProjectCommand:+ @parameterized.expand(+ [+ (+ "set_plain",+ "project 2",+ RulesCommand(action="project_set", project_team_id=2),+ ),+ (+ "set_with_request",+ "project 2 fix auth",+ RulesCommand(action="project_set", project_team_id=2),+ ),+ (+ "set_uppercase",+ "PROJECT 17",+ RulesCommand(action="project_set", project_team_id=17),+ ),+ (+ "set_mixed_case",+ "Project 5 set up flag",+ RulesCommand(action="project_set", project_team_id=5),+ ),+ (+ "set_leading_bot_mention",+ "<@U123BOT> project 9 do thing",+ RulesCommand(action="project_set", project_team_id=9),+ ),+ (+ "set_trailing_whitespace",+ "project 4 fix auth ",+ RulesCommand(action="project_set", project_team_id=4),+ ),+ (+ "set_multiline_remaining",+ "project 4 fix the\nlogin bug",+ RulesCommand(action="project_set", project_team_id=4),+ ),+ (+ "set_extra_internal_whitespace",+ "project 12 build feature",+ RulesCommand(action="project_set", project_team_id=12),+ ),+ ("show_plain", "project", RulesCommand(action="project_show")),+ ("show_uppercase", "PROJECT", RulesCommand(action="project_show")),+ ("show_trailing_whitespace", "project ", RulesCommand(action="project_show")),+ ("show_with_bot_mention", "<@U123BOT> project", RulesCommand(action="project_show")),+ ]+ )+ def test_recognized(self, _name: str, text: str, expected: RulesCommand) -> None:+ assert _parse_rules_command(text) == expected++ @parameterized.expand(+ [+ ("empty", ""),+ ("whitespace_only", " "),+ ("just_bot_mention", "<@U123>"),+ ("non_numeric_id", "project abc"),+ ("prefix_word", "projector 2"),+ ("not_at_head", "fix project 2"),+ ("similar_command", "projects 2"),+ ("regular_message", "hey can you set up a feature flag"),+ ]+ )+ 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)+ if result is not None:+ assert result.action not in {"project_show", "project_set"}diff --git a/products/slack_app/backend/tests/test_slack_settings.py b/products/slack_app/backend/tests/test_slack_settings.pynew file mode 100644index 000000000000..37492fb3878e--- /dev/null+++ b/products/slack_app/backend/tests/test_slack_settings.py@@ -0,0 +1,141 @@+import pytest++from django.db import IntegrityError++from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.slack_app.backend.models import SlackSettings+++class TestSlackSettings:+ @pytest.fixture(autouse=True)+ def setup(self, db):+ self.organization = Organization.objects.create(name="Org")+ self.team_a = Team.objects.create(organization=self.organization, name="Team A")+ self.team_b = Team.objects.create(organization=self.organization, name="Team B")+ self.integration_a = Integration.objects.create(+ team=self.team_a,+ kind="slack-posthog-code",+ integration_id="T_WS",+ sensitive_config={"access_token": "xoxb-a"},+ )+ self.integration_b = Integration.objects.create(+ team=self.team_b,+ kind="slack-posthog-code",+ integration_id="T_WS",+ sensitive_config={"access_token": "xoxb-b"},+ )++ # --- per-user rows ---------------------------------------------------------++ def test_uniqueness_per_workspace_and_slack_user(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ )++ with pytest.raises(IntegrityError):+ SlackSettings.objects.create(+ default_integration=self.integration_b,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ )++ def test_distinct_workspaces_allow_same_slack_user(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ )+ SlackSettings.objects.create(+ default_integration=self.integration_b,+ slack_workspace_id="T_OTHER",+ slack_user_id="U001",+ )++ assert SlackSettings.objects.filter(slack_user_id="U001").count() == 2++ def test_distinct_slack_users_in_same_workspace(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ )+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id="U002",+ )++ assert SlackSettings.objects.filter(slack_workspace_id="T_WS").count() == 2++ # --- workspace-wide rows ---------------------------------------------------++ def test_workspace_default_row_with_null_user(self):+ row = SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ )+ assert row.slack_user_id is None++ def test_uniqueness_workspace_default_per_workspace(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ )++ # A second workspace-wide row for the same workspace must not be allowed+ # — partial uniqueness applies even though Postgres treats NULL as distinct.+ with pytest.raises(IntegrityError):+ SlackSettings.objects.create(+ default_integration=self.integration_b,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ )++ def test_workspace_default_coexists_with_user_rows(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ )+ SlackSettings.objects.create(+ default_integration=self.integration_b,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ )++ rows = SlackSettings.objects.filter(slack_workspace_id="T_WS")+ assert rows.count() == 2+ assert rows.filter(slack_user_id__isnull=True).count() == 1+ assert rows.filter(slack_user_id="U001").count() == 1++ def test_distinct_workspaces_each_allow_their_own_workspace_default(self):+ SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ )+ SlackSettings.objects.create(+ default_integration=self.integration_b,+ slack_workspace_id="T_OTHER",+ slack_user_id=None,+ )++ assert SlackSettings.objects.filter(slack_user_id__isnull=True).count() == 2++ # --- cascade behavior ------------------------------------------------------++ def test_cascade_when_integration_deleted(self):+ row = SlackSettings.objects.create(+ default_integration=self.integration_a,+ slack_workspace_id="T_WS",+ slack_user_id="U001",+ )+ self.integration_a.delete()+ assert not SlackSettings.objects.filter(pk=row.pk).exists()