: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
fix(slack_app): list projects and offer the Home tab when routing is ambiguous (#103637)
Vojta Bartoš81f7f342aa00
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 54faaabdf8ea..a029c37c49dc 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -66,10 +66,11 @@ from products.slack_app.backend.feature_flags import (from products.slack_app.backend.helpers import local_dev_slack_emailfrom products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping, UntaggedFollowupModefrom products.slack_app.backend.services import inbox_interactivity, turn_feedback+from products.slack_app.backend.services.commands import SLASH_COMMAND_PREFIXfrom products.slack_app.backend.services.integration_resolver import (UserResolutionFailure,- format_project_candidate_list,load_integrations,+ pick_a_project_message,resolve_from_candidates,resolve_user_for_workspace,user_resolution_failure_reply,@@ -89,6 +90,7 @@ from products.slack_app.backend.services.slack_messages import (SLACK_WEBHOOK_TIMEOUT_SECONDS,TURN_FEEDBACK_ACTION_ID,SlackThreadMessage,+ app_home_url,parse_slack_file_refs,post_slack_thread_reply,)@@ -1644,11 +1646,11 @@ def _post_pick_a_project_hint(event: dict[str, Any],) -> bool:"""Tell the user that this workspace is connected to multiple PostHog- projects, and that they should pick one.+ projects, list the ones they can reach, and point at the two ways to pick one.- The selection command differs by surface: in a channel the user mentions the app- (`@PostHog project <id>`), but in a DM there is no app to mention, so they just reply- with `project <id>`.+ The slash command is offered rather than the `@PostHog project <id>` mention because it+ reads the same on both surfaces this runs on: a channel mention and a DM, where there+ is no app to mention.Returns whether the hint was posted, so callers can record whether the user wasleft with an explanation or with silence.@@ -1658,11 +1660,11 @@ def _post_pick_a_project_hint(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 False- pick_command = "`project <id>`" if event.get("channel_type") == "im" else "`@PostHog project <id>`"- text = (- "This Slack workspace is connected to multiple PostHog projects:\n"- f"{format_project_candidate_list(candidates)}\n\n"- f"Use {pick_command} to pick one — that also saves it as your default."+ text = pick_a_project_message(+ "This Slack workspace is connected to multiple PostHog projects. You can work in any of these:",+ candidates,+ set_command=SLASH_COMMAND_PREFIX,+ home_tab_url=app_home_url(probe.integration),)return _post_slack_user_feedback(probe, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.pyindex f9486ab55bc3..4005ccf26ed7 100644--- a/products/slack_app/backend/services/commands.py+++ b/products/slack_app/backend/services/commands.py@@ -3,16 +3,18 @@ from typing import TYPE_CHECKINGfrom posthog.models.integration import Integration, SlackIntegrationfrom posthog.models.repo_routing_rule import RepoRoutingRule-from products.slack_app.backend.services.slack_messages import post_slack_ephemeral+from products.slack_app.backend.services.slack_messages import app_home_url, post_slack_ephemeralif TYPE_CHECKING:from products.slack_app.backend.api import RulesCommandfrom products.slack_app.backend.services.integration_resolver import ResolutionResultMENTION_COMMAND_PREFIX = "@PostHog"+SLASH_COMMAND_PREFIX = "/posthog"MENTION_HELP_REDIRECT = (- "Run `/posthog help` to see the available commands. To start a task, mention me with a description of the work."+ f"Run `{SLASH_COMMAND_PREFIX} help` to see the available commands. "+ "To start a task, mention me with a description of the work.")@@ -255,8 +257,8 @@ def _handle_project_show(from posthog.models.user import Userfrom products.slack_app.backend.services.integration_resolver import (- format_project_candidate_list,load_integrations,+ pick_a_project_message,resolve_from_candidates,)@@ -301,17 +303,16 @@ def _handle_project_show()return- lines = format_project_candidate_list(result.candidates)post_slack_ephemeral(slack.client,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"- f"Set one with `{command_prefix} project <id>`."+ text=pick_a_project_message(+ "You haven't set a default project for this Slack workspace yet. You can pick from:",+ result.candidates,+ set_command=command_prefix,+ home_tab_url=app_home_url(slack.integration),),)diff --git a/products/slack_app/backend/services/integration_resolver.py b/products/slack_app/backend/services/integration_resolver.pyindex 9d6a3e0a0a24..4a101669edee 100644--- a/products/slack_app/backend/services/integration_resolver.py+++ b/products/slack_app/backend/services/integration_resolver.py@@ -5,6 +5,7 @@ from django.db.models import Qimport structlog+from posthog.comment.formatting import escape_slack_mrkdwnfrom posthog.helpers.slack_scopes import bot_is_readyfrom posthog.models.integration import Integrationfrom posthog.models.user import User@@ -90,6 +91,35 @@ def format_project_candidate_list(candidates: list[Integration]) -> str:return "\n".join(f"• `{c.team_id}` — {project_label(c)}" for c in candidates)+def pick_a_project_message(+ intro: str,+ candidates: list[Integration],+ *,+ set_command: str,+ home_tab_url: str | None,+) -> str:+ """A "which project?" reply: every project the caller can route to, then the two ways+ to choose one.++ The Home tab leads because it is one click on a dropdown, against a command that asks+ the reader to copy an id out of the list above it. ``home_tab_url`` degrades to plain+ text for an install that carries no app id, which is the one case ``app_home_url``+ cannot build a deep link for.+ """+ # Organization and team names are tenant text, and this reply lands in a channel+ # thread, so an unescaped `<!channel>` in a name broadcasts to everyone reading it and+ # `<url|label>` renders a link they read as the bot's. Escaped on the way out rather+ # than inside `format_project_candidate_list`, because that helper also builds an LLM+ # prompt, which needs the plain name.+ projects = escape_slack_mrkdwn(format_project_candidate_list(candidates))+ home_tab = f"<{home_tab_url}|Home tab>" if home_tab_url else "Home tab"+ return (+ f"{intro}\n"+ f"{projects}\n\n"+ f"Pick one on the app's {home_tab}, or set your default with `{set_command} project <id>`."+ )++def resolve_from_candidates(candidates: list[Integration],*,diff --git a/products/slack_app/backend/tests/test_integration_resolver.py b/products/slack_app/backend/tests/test_integration_resolver.pyindex 2ee7612cb301..89160484315e 100644--- a/products/slack_app/backend/tests/test_integration_resolver.py+++ b/products/slack_app/backend/tests/test_integration_resolver.py@@ -10,7 +10,11 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping, SlackUserProfileCache-from products.slack_app.backend.services.integration_resolver import load_integrations, resolve_user_for_workspace+from products.slack_app.backend.services.integration_resolver import (+ load_integrations,+ pick_a_project_message,+ resolve_user_for_workspace,+)WORKSPACE = "T_WS"SLACK_USER = "U001"@@ -719,3 +723,52 @@ class TestLoadIntegrationsAuthStateFilter:assert {c.id for c in result.candidates} == {self.integration_new.id}assert result.integration == self.integration_newassert result.source == "sole_candidate"+++class TestPickAProjectMessage:+ # No database: the message builder only reads names and ids off the objects handed to+ # it, so unsaved instances exercise it exactly as saved ones would.+ @staticmethod+ def _candidate(team_id: int, org_name: str, team_name: str) -> Integration:+ organization = Organization(name=org_name)+ team = Team(id=team_id, organization=organization, name=team_name)+ return Integration(team=team, kind="slack", integration_id=WORKSPACE)++ def test_lists_every_project_and_both_ways_to_set_one(self):+ message = pick_a_project_message(+ "You can route your mentions to:",+ [self._candidate(1, "Acme", "Production"), self._candidate(2, "Acme", "Staging")],+ set_command="/posthog",+ home_tab_url="slack://app?team=T_WS&id=A1&tab=home",+ )++ assert "`1` — Acme · Production" in message+ assert "`2` — Acme · Staging" in message+ # The Home tab is the one-click route, so it leads and the command follows.+ assert message.index("<slack://app?team=T_WS&id=A1&tab=home|Home tab>") < message.index(+ "`/posthog project <id>`"+ )++ def test_home_tab_stays_plain_text_when_the_install_has_no_deep_link(self):+ message = pick_a_project_message(+ "You can route your mentions to:",+ [self._candidate(1, "Acme", "Production")],+ set_command="/posthog",+ home_tab_url=None,+ )++ assert "the app's Home tab," in message+ assert "|Home tab>" not in message+ assert "None" not in message++ def test_project_names_cannot_inject_slack_control_syntax(self):+ message = pick_a_project_message(+ "You can route your mentions to:",+ [self._candidate(1, "<!channel>", "<https://evil.example|Open PostHog>")],+ set_command="/posthog",+ home_tab_url=None,+ )++ assert "<!channel>" not in message+ assert "<!channel>" in message+ assert "<https://evil.example|Open PostHog>" not in messagediff --git a/products/slack_app/backend/views/slack_command.py b/products/slack_app/backend/views/slack_command.pyindex 2ca85aa3edf7..6dfb3b8baa3c 100644--- a/products/slack_app/backend/views/slack_command.py+++ b/products/slack_app/backend/views/slack_command.py@@ -36,12 +36,11 @@ from products.slack_app.backend.api import (resolve_region_or_terminal_route,was_proxied,)+from products.slack_app.backend.services.commands import SLASH_COMMAND_PREFIXfrom products.slack_app.backend.services.integration_resolver import load_integrationslogger = structlog.get_logger(__name__)-SLASH_COMMAND_NAME = "/posthog"-@csrf_exemptdef slack_app_command_handler(request: HttpRequest) -> HttpResponse:@@ -69,7 +68,7 @@ def slack_app_command_handler(request: HttpRequest) -> HttpResponse:# Present only when invoked inside a thread; forwarding it keeps the reply in-thread.thread_ts = payload.get("thread_ts", "")raw_text = (payload.get("text") or "").strip()- command_name = payload.get("command", SLASH_COMMAND_NAME)+ command_name = payload.get("command", SLASH_COMMAND_PREFIX)# Unique per invocation — used to derive a distinct workflow id since slash# payloads carry no message ``ts`` or event id to key on.trigger_id = payload.get("trigger_id", "")