: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 `project workspace <id>` command for admins (#60874)
Vojta Bartoša8ce30cd4f1d
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 6e3298520a5b..4a656eb788e9 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -165,6 +165,7 @@ class RulesCommand:"deprecated_default_repo","project_show","project_set",+ "project_set_workspace",]rule_text: str | None = Nonerepository: str | None = None@@ -265,6 +266,13 @@ def _get_slack_user_info(slack: SlackIntegration, integration: Integration, slacreturn {}+def is_slack_workspace_admin(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> bool:+ """Whether the Slack user is a workspace admin or owner."""+ user_info = _get_slack_user_info(slack, integration, slack_user_id)+ slack_user = user_info.get("user", {}) if isinstance(user_info, dict) else {}+ return bool(slack_user.get("is_admin") or slack_user.get("is_owner"))++def _get_slack_user_id_by_email_from_db(integration: Integration, normalized_email: str) -> str | None:try:profile = SlackUserProfileCache.objects.filter(@@ -765,6 +773,14 @@ def _parse_rules_command(text: str) -> RulesCommand | None:if numbers:return RulesCommand(action="remove", rule_numbers=numbers)+ # `project workspace <id>` sets the workspace-wide default and must be tested+ # before the generic `project` branch. Trailing text after the id is ignored.+ project_workspace_match = re.fullmatch(+ r"project\s+workspace\s+(\d+)(?:\s+.*)?", cleaned, flags=re.IGNORECASE | re.DOTALL+ )+ if project_workspace_match is not None:+ return RulesCommand(action="project_set_workspace", project_team_id=int(project_workspace_match.group(1)))+# 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:diff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex 1b6ae221881e..998663938fe6 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -73,8 +73,10 @@ class SlackSettings(UUIDModel):Written by the Slack `@PostHog project <id>` directive or the user-levelsettings 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).+ inbound event's Slack user has no personal row yet. Written via the+ PostHog project-level settings UI by a team admin, or via the Slack+ `@PostHog project workspace <id>` directive by a Slack workspace+ admin/owner.A user-specific row, if present, always wins over the workspace-wide row atresolution time.diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.pyindex b9794694fb7f..1934827d19fe 100644--- a/products/slack_app/backend/services/commands.py+++ b/products/slack_app/backend/services/commands.py@@ -7,23 +7,32 @@ if TYPE_CHECKING: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_help(+ slack: SlackIntegration, integration: Integration, channel: str, thread_ts: str, slack_user_id: str+) -> None:+ from products.slack_app.backend.api 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",+ ]++ # 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)"+ )++ 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.")++ 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:@@ -272,6 +281,83 @@ def _handle_project_set()+def _handle_project_set_workspace(+ slack: SlackIntegration,+ integration: Integration,+ 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:+ """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.+ Restricted to Slack workspace admins and owners.+ """+ from posthog.models.user import User++ from products.slack_app.backend.api import is_slack_workspace_admin+ from products.slack_app.backend.models import SlackSettings++ if not is_slack_workspace_admin(slack, integration, slack_user_id):+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ text="Only Slack workspace admins or owners can set the workspace-wide default project.",+ )+ return++ 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",+ 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=None,+ defaults={"default_integration": target},+ )+ slack.client.chat_postEphemeral(+ channel=channel,+ user=slack_user_id,+ thread_ts=thread_ts,+ 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."+ ),+ )++def resolve_command_target(*,slack_team_id: str,@@ -304,9 +390,9 @@ def resolve_command_target(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"):+ # text, and ``project_*`` commands enforce access inside the handler. They+ # run against any workspace integration as a probe.+ if command.action in ("project_show", "project_set", "project_set_workspace", "help"):return candidates, ResolutionResult(integration=candidates[0], source="sole_candidate", candidates=candidates)# Team-scoped commands (``list``/``add``/``remove``) must go through the@@ -345,7 +431,7 @@ def dispatch_rules_command(*before* calling this dispatcher."""if command.action == "help":- _handle_help(slack, channel, thread_ts)+ _handle_help(slack, integration, channel, thread_ts, slack_user_id)elif command.action == "list":_handle_rules_list(slack, integration, channel, thread_ts)elif command.action == "add":@@ -384,3 +470,17 @@ def dispatch_rules_command(command.project_team_id,workspace_candidates=workspace_candidates,)+ elif command.action == "project_set_workspace":+ if command.project_team_id is None:+ return+ _handle_project_set_workspace(+ slack,+ integration,+ 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/tests/test_project_directive_parser.py b/products/slack_app/backend/tests/test_project_directive_parser.pyindex 1329fd6ab7f2..3a28efc4c4e5 100644--- a/products/slack_app/backend/tests/test_project_directive_parser.py+++ b/products/slack_app/backend/tests/test_project_directive_parser.py@@ -50,6 +50,31 @@ class TestParseProjectCommand:("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")),+ (+ "workspace_set_plain",+ "project workspace 3",+ RulesCommand(action="project_set_workspace", project_team_id=3),+ ),+ (+ "workspace_set_uppercase",+ "PROJECT WORKSPACE 8",+ RulesCommand(action="project_set_workspace", project_team_id=8),+ ),+ (+ "workspace_set_with_bot_mention",+ "<@U123BOT> project workspace 11 go",+ RulesCommand(action="project_set_workspace", project_team_id=11),+ ),+ (+ "workspace_set_trailing_text",+ "project workspace 4 fix auth",+ RulesCommand(action="project_set_workspace", project_team_id=4),+ ),+ (+ "workspace_set_extra_whitespace",+ "project workspace 6",+ RulesCommand(action="project_set_workspace", project_team_id=6),+ ),])def test_recognized(self, _name: str, text: str, expected: RulesCommand) -> None:@@ -72,4 +97,4 @@ class TestParseProjectCommand:# 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"}+ assert result.action not in {"project_show", "project_set", "project_set_workspace"}diff --git a/products/slack_app/backend/tests/test_project_set_workspace.py b/products/slack_app/backend/tests/test_project_set_workspace.pynew file mode 100644index 000000000000..5dc4093da602--- /dev/null+++ b/products/slack_app/backend/tests/test_project_set_workspace.py@@ -0,0 +1,141 @@+import pytest+from unittest.mock import MagicMock, patch++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 products.slack_app.backend.models import SlackSettings+from products.slack_app.backend.services.commands import _handle_help, _handle_project_set_workspace++WORKSPACE_HELP_LINE = "`@PostHog project workspace <id>`"+++def _slack_user_info(*, is_admin: bool = False, is_owner: bool = False) -> dict:+ return {"user": {"is_admin": is_admin, "is_owner": is_owner, "profile": {"email": "[email protected]"}}}+++class TestHandleProjectSetWorkspace:+ @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.other_team = Team.objects.create(organization=Organization.objects.create(name="Other"), name="Team B")+ 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")+ self.slack = MagicMock()++ def _run(self, target_team_id: int) -> None:+ _handle_project_set_workspace(+ self.slack,+ self.integration,+ channel="C1",+ thread_ts="111.1",+ slack_user_id="U1",+ slack_workspace_id="T_WS",+ user_id=self.user.id,+ target_team_id=target_team_id,+ workspace_candidates=[self.integration],+ )++ @patch("products.slack_app.backend.api._get_slack_user_info")+ def test_admin_sets_workspace_default(self, mock_info):+ mock_info.return_value = _slack_user_info(is_admin=True)++ self._run(self.team.id)++ row = SlackSettings.objects.get(slack_workspace_id="T_WS", slack_user_id__isnull=True)+ assert row.default_integration_id == self.integration.id+ self.slack.client.chat_postEphemeral.assert_called_once()++ @patch("products.slack_app.backend.api._get_slack_user_info")+ def test_owner_sets_workspace_default(self, mock_info):+ mock_info.return_value = _slack_user_info(is_owner=True)++ self._run(self.team.id)++ assert SlackSettings.objects.filter(slack_workspace_id="T_WS", slack_user_id__isnull=True).exists()++ @patch("products.slack_app.backend.api._get_slack_user_info")+ def test_non_admin_is_refused(self, mock_info):+ mock_info.return_value = _slack_user_info(is_admin=False, is_owner=False)++ self._run(self.team.id)++ assert not SlackSettings.objects.filter(slack_workspace_id="T_WS").exists()+ text = self.slack.client.chat_postEphemeral.call_args.kwargs["text"]+ assert "admins or owners" in text++ @patch("products.slack_app.backend.api._get_slack_user_info")+ def test_admin_without_team_access_is_refused(self, mock_info):+ mock_info.return_value = _slack_user_info(is_admin=True)++ self._run(self.other_team.id)++ assert not SlackSettings.objects.filter(slack_workspace_id="T_WS").exists()+ text = self.slack.client.chat_postEphemeral.call_args.kwargs["text"]+ assert "don't have access" in text++ @patch("products.slack_app.backend.api._get_slack_user_info")+ def test_workspace_default_replaces_existing(self, mock_info):+ mock_info.return_value = _slack_user_info(is_admin=True)+ second_team = Team.objects.create(organization=self.organization, name="Team C")+ second_integration = Integration.objects.create(+ team=second_team,+ kind="slack",+ integration_id="T_WS",+ sensitive_config={"access_token": "xoxb-c"},+ )+ SlackSettings.objects.create(+ default_integration=second_integration,+ slack_workspace_id="T_WS",+ slack_user_id=None,+ )++ self._run(self.team.id)++ rows = SlackSettings.objects.filter(slack_workspace_id="T_WS", slack_user_id__isnull=True)+ assert rows.count() == 1+ assert rows.get().default_integration_id == self.integration.id+++class TestHandleHelp:+ @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.slack = MagicMock()++ def _help_text(self) -> str:+ _handle_help(self.slack, self.integration, "C1", "111.1", "U1")+ return self.slack.client.chat_postMessage.call_args.kwargs["text"]++ @patch("products.slack_app.backend.api._get_slack_user_info")+ def test_admin_sees_workspace_line(self, mock_info):+ mock_info.return_value = _slack_user_info(is_admin=True)+ assert WORKSPACE_HELP_LINE in self._help_text()++ @patch("products.slack_app.backend.api._get_slack_user_info")+ def test_owner_sees_workspace_line(self, mock_info):+ mock_info.return_value = _slack_user_info(is_owner=True)+ assert WORKSPACE_HELP_LINE in self._help_text()++ @patch("products.slack_app.backend.api._get_slack_user_info")+ def test_non_admin_does_not_see_workspace_line(self, mock_info):+ mock_info.return_value = _slack_user_info(is_admin=False, is_owner=False)+ text = self._help_text()+ assert WORKSPACE_HELP_LINE not in text+ # The rest of the help is still posted.+ assert "Available commands" in text