: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): pick the project for a mention from the thread (#108369)
Vojta Bartoš682c580417dd
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex a481bb071369..119b65f99c8f 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -61,10 +61,16 @@ from products.slack_app.backend.feature_flags import (ASSISTANT_REQUIRED_SCOPES,is_slack_app_assistant_enabled,is_slack_app_oauth_enabled,+ is_slack_app_project_picker_enabled,)from products.slack_app.backend.helpers import local_dev_slack_email-from products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping, UntaggedFollowupMode-from products.slack_app.backend.services import inbox_interactivity, slack_welcome_messages, turn_feedback+from products.slack_app.backend.models import SlackChannel, SlackSettings, SlackThreadTaskMapping, UntaggedFollowupMode+from products.slack_app.backend.services import (+ inbox_interactivity,+ project_picker,+ slack_welcome_messages,+ turn_feedback,+)from products.slack_app.backend.services.commands import SLASH_COMMAND_PREFIX, mention_command_redirectfrom products.slack_app.backend.services.integration_resolver import (UserResolutionFailure,@@ -92,6 +98,7 @@ from products.slack_app.backend.services.slack_messages import (SlackThreadMessage,app_home_url,parse_slack_file_refs,+ post_slack_ephemeral,post_slack_thread_reply,)from products.slack_app.backend.services.slack_scopes import REQUIRED_SLACK_SCOPES@@ -1731,6 +1738,162 @@ def _post_pick_a_project_hint(return _post_slack_user_feedback(probe, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)+def _post_project_picker(+ candidates: list[Integration],+ event: dict[str, Any],+ event_id: str | None,+ *,+ posthog_user: User,+ is_ext_shared_channel: bool,+ mention_is_threaded: bool,+) -> bool:+ """Offer the projects as choices. Returns whether the picker reached Slack."""+ probe = candidates[0]+ slack_user_id = event.get("user")+ channel = event.get("channel")+ message_ts = event.get("ts")+ if not isinstance(slack_user_id, str) or not isinstance(channel, str) or not isinstance(message_ts, str):+ return False+ if not is_slack_app_project_picker_enabled(probe, posthog_user.distinct_id):+ return False++ context_token = uuid.uuid4().hex+ cache.set(+ _picker_context_cache_key(context_token),+ project_picker.build_project_picker_context(+ event=event,+ event_id=event_id,+ probe=probe,+ candidates=candidates,+ slack_user_id=slack_user_id,+ is_ext_shared_channel=is_ext_shared_channel,+ ),+ timeout=PICKER_TOKEN_MAX_AGE_SECONDS,+ )+ client = SlackIntegration(probe).client+ client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS+ thread_ts = event.get("thread_ts")+ try:+ post_slack_ephemeral(+ client,+ channel=channel,+ user=slack_user_id,+ # Slack renders an ephemeral only on the surface the person is viewing.+ thread_ts=thread_ts if mention_is_threaded and isinstance(thread_ts, str) else None,+ text="Which PostHog project should I use?",+ blocks=project_picker.build_project_picker_blocks(+ candidates,+ context_token=context_token,+ slack_user_id=slack_user_id,+ home_tab_url=app_home_url(probe),+ ),+ )+ except Exception:+ logger.warning(+ "slack_app_project_picker_post_failed",+ integration_id=probe.id,+ slack_workspace_id=probe.integration_id,+ slack_channel_id=channel,+ exc_info=True,+ )+ cache.delete(_picker_context_cache_key(context_token))+ return False+ return True+++def _handle_project_picker_pick(payload: dict) -> HttpResponse:+ """Run the mention the picker was raised for against the project the person picked."""+ response_url = payload.get("response_url", "")+ context_token = _extract_context_token(payload)+ context = _decode_picker_context(context_token) if context_token else None+ if not context or context.get("kind") != project_picker.PROJECT_PICKER_CONTEXT_KIND:+ inbox_interactivity.post_response_url(+ response_url, {"replace_original": True, "text": project_picker.PICKER_EXPIRED_MESSAGE}+ )+ return HttpResponse(status=200)++ slack_team_id = payload.get("team", {}).get("id", "")+ clicker_slack_user_id = payload.get("user", {}).get("id", "")+ event = context.get("event")+ integration_id = project_picker.picked_integration_id(payload)+ rejection: str | None = project_picker.pick_rejection(+ context, clicker_slack_user_id=clicker_slack_user_id, integration_id=integration_id+ )+ integration = None+ if rejection is None and integration_id is not None and slack_team_id:+ integration = (+ Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get+ kind=SLACK_INTEGRATION_KIND,+ integration_id=slack_team_id,+ )+ .select_related("team__organization")+ .first()+ )+ # Access can change between the post and the click.+ posthog_user = _is_org_member(integration, clicker_slack_user_id) if integration is not None else None+ if (+ not isinstance(event, dict)+ or integration is None+ or posthog_user is None+ or not _can_access_team(posthog_user, integration)+ ):+ rejection = rejection or "no_access"+ logger.info(+ "slack_app_project_picker_pick_rejected",+ reason=rejection,+ slack_workspace_id=slack_team_id,+ slack_user_id=clicker_slack_user_id,+ )+ if integration is not None:+ capture_slack_event(+ integration,+ "slack app project picker rejected",+ slack_user_id=clicker_slack_user_id,+ posthog_user=posthog_user,+ reason=rejection,+ )+ inbox_interactivity.post_response_url(+ response_url, {"replace_original": True, "text": project_picker.PICK_REJECTED_MESSAGE}+ )+ return HttpResponse(status=200)++ # The context is single use, so a second click finds none and starts nothing.+ cache.delete(_picker_context_cache_key(context_token))++ SlackSettings.objects.update_or_create(+ slack_workspace_id=slack_team_id,+ slack_user_id=clicker_slack_user_id,+ defaults={"default_integration": integration},+ )+ # The mention never reached the workflow, so its event id is still unused.+ _dispatch_mention_to_target(+ event,+ integration,+ slack_team_id,+ context.get("event_id"),+ posthog_user=posthog_user,+ untagged_followup_mapping=None,+ is_ext_shared_channel=bool(context.get("is_ext_shared_channel")),+ )+ inbox_interactivity.post_response_url(+ response_url,+ {+ "replace_original": True,+ "text": project_picker.project_picked_message(integration, home_tab_url=app_home_url(integration)),+ },+ )+ capture_slack_event(+ integration,+ "slack app project picker picked",+ slack_user_id=clicker_slack_user_id,+ posthog_user=posthog_user,+ candidate_count=len(context.get("candidate_integration_ids") or []),+ seconds_to_pick=int(time.time()) - int(context.get("created_at") or time.time()),+ )+ return HttpResponse(status=200)++def _post_user_resolution_failure_reply(*,probe: Integration,@@ -2198,6 +2361,86 @@ def _handle_app_uninstalled(request: HttpRequest, slack_team_id: str) -> str:return ROUTE_HANDLED_LOCALLY+def _dispatch_mention_to_target(+ event: dict,+ mention_target: Integration,+ slack_team_id: str,+ event_id: str | None,+ *,+ posthog_user: User,+ untagged_followup_mapping: SlackThreadTaskMapping | None,+ is_ext_shared_channel: bool,+) -> str:+ """Run the gates that need a resolved project, then start the mention workflow."""+ slack = SlackIntegration(mention_target)+ missing = slack.missing_scopes(REQUIRED_SLACK_SCOPES)+ if missing:+ if untagged_followup_mapping is not None:+ logger.info(+ "slack_app_thread_message_missing_scopes",+ slack_team_id=slack_team_id,+ integration_id=mention_target.id,+ )+ replied = False+ else:+ replied = _notify_missing_slack_scopes(slack, event, missing)+ _report_slack_mention_dropped(+ event,+ slack_team_id,+ reason="missing_scopes",+ replied=replied,+ integration=mention_target,+ posthog_user=posthog_user,+ )+ return ROUTE_HANDLED_LOCALLY++ channel_id = event.get("channel") if isinstance(event.get("channel"), str) else None+ if channel_id and is_ext_shared_channel and not _channel_is_approved(mention_target.integration_id, channel_id):+ if untagged_followup_mapping is not None:+ logger.info(+ "slack_app_thread_message_channel_unapproved",+ slack_team_id=slack_team_id,+ channel=channel_id,+ )+ replied = False+ else:+ replied = _post_channel_approval_prompt(slack, mention_target, event)+ _report_slack_mention_dropped(+ event,+ slack_team_id,+ reason="channel_not_approved",+ replied=replied,+ integration=mention_target,+ posthog_user=posthog_user,+ )+ return ROUTE_HANDLED_LOCALLY++ # Last gate on the untagged path: a thread whose creator has follow-ups off+ # never reaches the workflow. ``ask`` is decided there instead, once the+ # classifier has judged the reply worth forwarding.+ if untagged_followup_mapping is not None and _untagged_followups_switched_off(+ event,+ mention_target,+ slack_team_id,+ mapping=untagged_followup_mapping,+ posthog_user=posthog_user,+ ):+ return ROUTE_HANDLED_LOCALLY++ if untagged_followup_mapping is not None:+ _mark_message_handled(slack_team_id, event, "untagged_followup")++ return _start_mention_workflow(+ event,+ mention_target,+ slack_team_id,+ event_id,+ posthog_user=posthog_user,+ untagged_followup=untagged_followup_mapping is not None,+ is_ext_shared_channel=is_ext_shared_channel,+ )++def route_posthog_code_event_to_relevant_region(request: HttpRequest,event: dict,@@ -2555,7 +2798,15 @@ def route_posthog_code_event_to_relevant_region(return ROUTE_HANDLED_LOCALLYmention_target = untagged_followup_mapping.integrationelif mention_target is None:- replied = _post_pick_a_project_hint(SlackIntegration(candidates[0]), candidates, event)+ picker_shown = _post_project_picker(+ candidates,+ event,+ event_id,+ posthog_user=posthog_user,+ is_ext_shared_channel=is_ext_shared_channel,+ mention_is_threaded=mention_is_threaded,+ )+ replied = picker_shown or _post_pick_a_project_hint(SlackIntegration(candidates[0]), candidates, event)# No integration is passed on purpose: this drop exists precisely because no# project was picked, and candidate order has nothing to do with what the# user meant. Attributing it to candidates[0] would pin workspace-level@@ -2567,74 +2818,17 @@ def route_posthog_code_event_to_relevant_region(replied=replied,posthog_user=posthog_user,candidate_count=len(candidates),+ picker_shown=picker_shown,)return ROUTE_HANDLED_LOCALLY- slack = SlackIntegration(mention_target)- missing = slack.missing_scopes(REQUIRED_SLACK_SCOPES)- if missing:- if untagged_followup_mapping is not None:- logger.info(- "slack_app_thread_message_missing_scopes",- slack_team_id=slack_team_id,- integration_id=mention_target.id,- )- replied = False- else:- replied = _notify_missing_slack_scopes(slack, event, missing)- _report_slack_mention_dropped(- event,- slack_team_id,- reason="missing_scopes",- replied=replied,- integration=mention_target,- posthog_user=posthog_user,- )- return ROUTE_HANDLED_LOCALLY-- channel_id = event.get("channel") if isinstance(event.get("channel"), str) else None- if channel_id and is_ext_shared_channel and not _channel_is_approved(mention_target.integration_id, channel_id):- if untagged_followup_mapping is not None:- logger.info(- "slack_app_thread_message_channel_unapproved",- slack_team_id=slack_team_id,- channel=channel_id,- )- replied = False- else:- replied = _post_channel_approval_prompt(slack, mention_target, event)- _report_slack_mention_dropped(- event,- slack_team_id,- reason="channel_not_approved",- replied=replied,- integration=mention_target,- posthog_user=posthog_user,- )- return ROUTE_HANDLED_LOCALLY-- # Last gate on the untagged path: a thread whose creator has follow-ups off- # never reaches the workflow. ``ask`` is decided there instead, once the- # classifier has judged the reply worth forwarding.- if untagged_followup_mapping is not None and _untagged_followups_switched_off(- event,- mention_target,- slack_team_id,- mapping=untagged_followup_mapping,- posthog_user=posthog_user,- ):- return ROUTE_HANDLED_LOCALLY-- if untagged_followup_mapping is not None:- _mark_message_handled(slack_team_id, event, "untagged_followup")-- return _start_mention_workflow(+ return _dispatch_mention_to_target(event,mention_target,slack_team_id,event_id,posthog_user=posthog_user,- untagged_followup=untagged_followup_mapping is not None,+ untagged_followup_mapping=untagged_followup_mapping,is_ext_shared_channel=is_ext_shared_channel,)@@ -5022,6 +5216,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:dismiss_integration_id = _extract_dismiss_hints(payload)alert_snooze_uuid = _extract_alert_snooze_hints(payload)inbox_integration_id = inbox_interactivity.extract_inbox_hints(payload)+ project_picker_integration_id = project_picker.picked_integration_id(payload)# Both controls a reply carries, and the modal a thumbs-down opens, claim the same# workspace, so one hint serves all three. Only the modal needs its own extractor:# a view submission carries no action for the generic one to read.@@ -5076,6 +5271,13 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:kind=SLACK_INTEGRATION_KIND,integration_id=slack_team_id,).exists()+ elif slack_team_id and project_picker_integration_id:+ # Reached once the context expired, so that the handler can tell the person.+ local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ id=project_picker_integration_id, # nosemgrep: idor-taint-user-input-to-model-get+ kind=SLACK_INTEGRATION_KIND,+ integration_id=slack_team_id,+ ).exists()elif slack_team_id and _is_ai_preferences_interactivity(payload, payload_type):# App Home AI-settings actions (Edit/Reset/Save) and the modal# re-render dispatched_actions carry no per-row hint — the button is@@ -5195,6 +5397,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return _handle_untagged_followup_run(payload)if action_id == UNTAGGED_FOLLOWUP_ACTION_DISMISS:return _handle_untagged_followup_dismiss(payload)+ if project_picker.is_project_picker_action(action_id):+ return _handle_project_picker_pick(payload)if action_id == SIGNALS_DISMISS_REPORT_ACTION_ID:return _handle_signals_dismiss_report(payload)if action_id in (INSIGHT_ALERT_SNOOZE_ACTION_ID, INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID):diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex a7e89bbebead..fa71a20e1d86 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -47,6 +47,7 @@ logger = structlog.get_logger(__name__)SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"SLACK_APP_FORKING_FLAG = "slack-app-forking"+SLACK_APP_PROJECT_PICKER_FLAG = "slack-app-project-picker"# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.@@ -125,6 +126,17 @@ def is_slack_app_agent_design_enabled(integration: Integration, distinct_id: str)+def is_slack_app_project_picker_enabled(integration: Integration, distinct_id: str | None = None) -> bool:+ """Gate for the in-thread project picker. With the gate closed, a mention that could go+ to more than one project gets the text hint."""+ return _workspace_flag_enabled(+ SLACK_APP_PROJECT_PICKER_FLAG,+ integration,+ failure_log_key="slack_app_project_picker_feature_flag_check_failed",+ distinct_id=distinct_id,+ )++def is_slack_app_assistant_enabled(integration: Integration) -> bool:"""Gate for the DM assistant: the install must hold the scopes the DM surfacecalls — ``im:history`` in particular, without which the assistant would answerdiff --git a/products/slack_app/backend/services/project_picker.py b/products/slack_app/backend/services/project_picker.pynew file mode 100644index 000000000000..48847a4d96d4--- /dev/null+++ b/products/slack_app/backend/services/project_picker.py@@ -0,0 +1,153 @@+import json+import time+from typing import Any, Literal++from posthog.models.integration import Integration+from posthog.slack.formatting import escape_slack_mrkdwn++from products.slack_app.backend.services.integration_resolver import project_label++PROJECT_PICKER_CONTEXT_KIND = "project_picker"+PROJECT_PICKER_BLOCK_ID_PREFIX = "slack_app_project_picker"+PROJECT_PICKER_ACTION_PREFIX = "slack_app_project_picker_pick"++# Slack lays buttons out side by side, so a longer list goes in a dropdown.+MAX_PROJECT_BUTTONS = 5+# Slack rejects the whole message when a button or an option has longer text.+_CHOICE_TEXT_MAX_LENGTH = 75++PickRejection = Literal["not_the_mentioner", "not_a_candidate"]++PICKER_EXPIRED_MESSAGE = "This project picker expired. Mention me again to get a new one."+PICK_REJECTED_MESSAGE = "I couldn't use that project. Mention me again to pick another one."+++def build_project_picker_context(+ *,+ event: dict[str, Any],+ event_id: str | None,+ probe: Integration,+ candidates: list[Integration],+ slack_user_id: str,+ is_ext_shared_channel: bool,+) -> dict[str, Any]:+ return {+ "kind": PROJECT_PICKER_CONTEXT_KIND,+ # The interactivity handler reads this key to decide that the click belongs to this region.+ "integration_id": probe.id,+ "candidate_integration_ids": [candidate.id for candidate in candidates],+ "slack_user_id": slack_user_id,+ "event": event,+ "event_id": event_id,+ "is_ext_shared_channel": is_ext_shared_channel,+ "created_at": int(time.time()),+ }+++def _choice_text(integration: Integration) -> dict[str, Any]:+ label = project_label(integration)+ if len(label) > _CHOICE_TEXT_MAX_LENGTH:+ label = f"{label[: _CHOICE_TEXT_MAX_LENGTH - 1]}…"+ return {"type": "plain_text", "text": label}+++def _choice_value(integration: Integration, slack_user_id: str) -> str:+ return json.dumps({"integration_id": integration.id, "mentioning_slack_user_id": slack_user_id})+++def build_project_picker_blocks(+ candidates: list[Integration],+ *,+ context_token: str,+ slack_user_id: str,+ home_tab_url: str | None,+) -> list[dict[str, Any]]:+ elements: list[dict[str, Any]]+ if len(candidates) <= MAX_PROJECT_BUTTONS:+ elements = [+ {+ "type": "button",+ # Slack requires a unique action id for each element in a block.+ "action_id": f"{PROJECT_PICKER_ACTION_PREFIX}:{candidate.id}",+ "text": _choice_text(candidate),+ "value": _choice_value(candidate, slack_user_id),+ }+ for candidate in candidates+ ]+ else:+ elements = [+ {+ "type": "static_select",+ "action_id": f"{PROJECT_PICKER_ACTION_PREFIX}:select",+ "placeholder": {"type": "plain_text", "text": "Choose a project"},+ "options": [+ {"text": _choice_text(candidate), "value": _choice_value(candidate, slack_user_id)}+ for candidate in candidates+ ],+ }+ ]+ home_tab = f"<{home_tab_url}|Home tab>" if home_tab_url else "Home tab"+ return [+ {+ "type": "section",+ "block_id": f"{PROJECT_PICKER_BLOCK_ID_PREFIX}:{context_token}",+ "text": {+ "type": "mrkdwn",+ "text": "This Slack workspace is connected to more than one PostHog project. Which one should I use?",+ },+ },+ {+ "type": "actions",+ "block_id": f"{PROJECT_PICKER_BLOCK_ID_PREFIX}_actions:{context_token}",+ "elements": elements,+ },+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": (+ "Only you can see this. I'll use your choice for your future mentions too. "+ f"You can change it on the {home_tab}."+ ),+ }+ ],+ },+ ]+++def is_project_picker_action(action_id: object) -> bool:+ return isinstance(action_id, str) and action_id.startswith(f"{PROJECT_PICKER_ACTION_PREFIX}:")+++def picked_integration_id(payload: dict[str, Any]) -> int | None:+ for action in payload.get("actions", []):+ if not is_project_picker_action(action.get("action_id")):+ continue+ raw_value = action.get("value") or (action.get("selected_option") or {}).get("value", "")+ try:+ integration_id = json.loads(raw_value).get("integration_id")+ except (json.JSONDecodeError, AttributeError, TypeError):+ return None+ return integration_id if isinstance(integration_id, int) else None+ return None+++def pick_rejection(+ context: dict[str, Any], *, clicker_slack_user_id: str, integration_id: int | None+) -> PickRejection | None:+ # Slack shows the picker to the mentioner only, but the run starts as that person, so the+ # click must come from them.+ if clicker_slack_user_id != context.get("slack_user_id"):+ return "not_the_mentioner"+ if integration_id not in (context.get("candidate_integration_ids") or []):+ return "not_a_candidate"+ return None+++def project_picked_message(integration: Integration, *, home_tab_url: str | None) -> str:+ home_tab = f"<{home_tab_url}|Home tab>" if home_tab_url else "Home tab"+ return (+ f"Using *{escape_slack_mrkdwn(project_label(integration))}* for this and your future mentions. "+ f"You can change it on the {home_tab}."+ )diff --git a/products/slack_app/backend/tests/services/test_project_picker.py b/products/slack_app/backend/tests/services/test_project_picker.pynew file mode 100644index 000000000000..9a5f75732376--- /dev/null+++ b/products/slack_app/backend/tests/services/test_project_picker.py@@ -0,0 +1,82 @@+import json++import pytest++from posthog.models.integration import Integration+from posthog.models.organization import Organization+from posthog.models.team.team import Team++from products.slack_app.backend.services.project_picker import (+ build_project_picker_blocks,+ pick_rejection,+ picked_integration_id,+)++MENTIONER = "U_ALICE"+++def _candidate(integration_id: int, team_name: str = "Production") -> Integration:+ team = Team(id=integration_id, organization=Organization(name="Acme"), name=team_name)+ return Integration(id=integration_id, team=team, kind="slack", integration_id="T_WS")+++def _click(element: dict, block_id: str) -> dict:+ action = {"action_id": element["action_id"], "block_id": block_id}+ if element["type"] == "static_select":+ action["selected_option"] = element["options"][-1]+ else:+ action["value"] = element["value"]+ return {"actions": [action]}+++ "candidate_count, expected_element_type",+ [+ pytest.param(2, "button", id="few_projects_get_buttons"),+ pytest.param(6, "static_select", id="many_projects_get_a_dropdown"),+ ],+)+def test_every_choice_leads_back_to_its_project(candidate_count, expected_element_type):+ candidates = [_candidate(100 + index) for index in range(candidate_count)]++ blocks = build_project_picker_blocks(+ candidates, context_token="token-1", slack_user_id=MENTIONER, home_tab_url=None+ )++ actions_block = next(block for block in blocks if block["type"] == "actions")+ assert {element["type"] for element in actions_block["elements"]} == {expected_element_type}+ last_element = actions_block["elements"][-1]+ assert picked_integration_id(_click(last_element, actions_block["block_id"])) == candidates[-1].id+++def test_long_project_name_stays_within_the_slack_text_limit():+ blocks = build_project_picker_blocks(+ [_candidate(1, team_name="x" * 200), _candidate(2)],+ context_token="token-1",+ slack_user_id=MENTIONER,+ home_tab_url=None,+ )++ actions_block = next(block for block in blocks if block["type"] == "actions")+ assert all(len(element["text"]["text"]) <= 75 for element in actions_block["elements"])+++ "clicker, integration_id, expected",+ [+ pytest.param(MENTIONER, 101, None, id="the_mentioner_picks_a_listed_project"),+ pytest.param("U_BOB", 101, "not_the_mentioner", id="someone_else_clicks"),+ pytest.param(MENTIONER, 999, "not_a_candidate", id="project_was_not_offered"),+ pytest.param(MENTIONER, None, "not_a_candidate", id="click_names_no_project"),+ ],+)+def test_pick_is_accepted_only_from_the_mentioner_for_an_offered_project(clicker, integration_id, expected):+ context = {"slack_user_id": MENTIONER, "candidate_integration_ids": [101, 102]}++ assert pick_rejection(context, clicker_slack_user_id=clicker, integration_id=integration_id) == expected+++def test_malformed_click_value_names_no_project():+ payload = {"actions": [{"action_id": "slack_app_project_picker_pick:101", "value": json.dumps([101])}]}++ assert picked_integration_id(payload) is Nonediff --git a/products/slack_app/backend/tests/test_feature_flags.py b/products/slack_app/backend/tests/test_feature_flags.pyindex 2ee18885dd5d..083f3d202292 100644--- a/products/slack_app/backend/tests/test_feature_flags.py+++ b/products/slack_app/backend/tests/test_feature_flags.py@@ -32,6 +32,11 @@ def test_gate_stays_closed_when_a_required_scope_is_missing(workspace_integratioassert gate(workspace_integration) is False+ "gate",+ [feature_flags.is_slack_app_agent_design_enabled, feature_flags.is_slack_app_project_picker_enabled],+ ids=["agent design", "project picker"],+)@pytest.mark.parametrize(("distinct_id", "expected_identity"),[@@ -40,8 +45,8 @@ def test_gate_stays_closed_when_a_required_scope_is_missing(workspace_integratio],ids=["known user", "no user"],)-def test_agent_design_gate_resolves_against_the_acting_user(- settings, workspace_integration, org_team_user, distinct_id, expected_identity+def test_user_keyed_gate_resolves_against_the_acting_user(+ settings, workspace_integration, org_team_user, gate, distinct_id, expected_identity):# The identity decides which rules can match at all. Resolving a known user against the# workspace instead would silently stop every person rule, `email ends_with@@ -50,7 +55,7 @@ def test_agent_design_gate_resolves_against_the_acting_user(org, _, _ = org_team_userwith patch("posthoganalytics.feature_enabled", return_value=True) as feature_enabled:- feature_flags.is_slack_app_agent_design_enabled(workspace_integration, distinct_id)+ gate(workspace_integration, distinct_id)assert feature_enabled.call_args.args[1] == expected_identityassert feature_enabled.call_args.kwargs["person_properties"] == {"region": "DEV"}diff --git a/products/slack_app/backend/tests/test_project_picker_flow.py b/products/slack_app/backend/tests/test_project_picker_flow.pynew file mode 100644index 000000000000..38b88aa21587--- /dev/null+++ b/products/slack_app/backend/tests/test_project_picker_flow.py@@ -0,0 +1,217 @@+import json+from typing import Any++from unittest.mock import patch++from django.core.cache import cache+from django.test import TestCase, override_settings+from django.test.client import RequestFactory+from django.utils import timezone++from parameterized import parameterized+from rest_framework.test import APIClient++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.api import ROUTE_HANDLED_LOCALLY, SLACK_MENTION_DROPPED_EVENT+from products.slack_app.backend.models import SlackSettings, SlackUserProfileCache+from products.slack_app.backend.services.project_picker import PICKER_EXPIRED_MESSAGE+from products.slack_app.backend.services.slack_auth import write_auth_state_ok+from products.slack_app.backend.services.slack_scopes import REQUIRED_SLACK_SCOPES+from products.slack_app.backend.tests.helpers import sign_slack_request++WORKSPACE = "T12345"+MENTIONER = "U123"+SIGNING_SECRET = "posthog-code-test-secret"+RESPONSE_URL = "https://hooks.slack.example/response/abc"+++class TestProjectPickerFlow(TestCase):+ def setUp(self):+ cache.clear()+ self.enterContext(patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False))+ self.enterContext(+ patch(+ "products.slack_app.backend.api.SlackIntegration.slack_config",+ return_value={"SLACK_APP_SIGNING_SECRET": SIGNING_SECRET},+ )+ )+ self.mock_start = self.enterContext(+ patch("products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY)+ )+ self.mock_response_url = self.enterContext(+ patch("products.slack_app.backend.services.inbox_interactivity.requests.post")+ )++ self.organization = Organization.objects.create(name="Acme")+ self.user = User.objects.create(email="[email protected]", distinct_id="user-1")+ self.membership = OrganizationMembership.objects.create(organization=self.organization, user=self.user)+ self.production = self._connect_project("Production")+ self.staging = self._connect_project("Staging")+ self.event = {+ "type": "app_mention",+ "channel": "C001",+ "user": MENTIONER,+ "ts": "1234.5678",+ "text": "<@U0BOT> how many signups last week",+ }++ def _connect_project(self, name: str) -> Integration:+ team = Team.objects.create(organization=self.organization, name=name)+ integration = Integration.objects.create(+ team=team,+ kind="slack",+ integration_id=WORKSPACE,+ config={"scope": ",".join(sorted(REQUIRED_SLACK_SCOPES))},+ sensitive_config={"access_token": "xoxb-test"},+ )+ write_auth_state_ok(integration.id, bot_user_id="U0BOT")+ SlackUserProfileCache.objects.create(+ integration=integration,+ slack_user_id=MENTIONER,+ email="[email protected]",+ display_name="Dev",+ real_name="Dev User",+ refreshed_at=timezone.now(),+ )+ return integration++ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def _mention(+ self, *, picker_enabled: bool = True, post_fails: bool = False, is_ext_shared_channel: bool = False+ ) -> dict[str, Any]:+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region++ request = RequestFactory().post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ with (+ patch("products.slack_app.backend.api.is_slack_app_project_picker_enabled", return_value=picker_enabled),+ patch(+ "products.slack_app.backend.api.post_slack_ephemeral",+ side_effect=RuntimeError("slack is down") if post_fails else None,+ ) as mock_picker,+ patch("products.slack_app.backend.api._post_slack_user_feedback", return_value=True) as mock_hint,+ patch("products.slack_app.backend.api.posthoganalytics.capture") as mock_capture,+ ):+ route_posthog_code_event_to_relevant_region(+ request, self.event, WORKSPACE, "Ev001", is_ext_shared_channel=is_ext_shared_channel+ )+ drops = [+ call.kwargs["properties"]+ for call in mock_capture.call_args_list+ if call.kwargs["event"] == SLACK_MENTION_DROPPED_EVENT+ ]+ return {+ "blocks": mock_picker.call_args.kwargs["blocks"] if mock_picker.called else None,+ "hint_posted": mock_hint.called,+ "drop": drops[0],+ }++ @override_settings(DEBUG=True)+ def _click(self, blocks: list[dict], *, project: Integration, slack_user_id: str = MENTIONER) -> None:+ actions_block = next(block for block in blocks if block["type"] == "actions")+ element = next(+ element+ for element in actions_block["elements"]+ if json.loads(element["value"])["integration_id"] == project.id+ )+ payload = {+ "type": "block_actions",+ "team": {"id": WORKSPACE},+ "user": {"id": slack_user_id},+ "response_url": RESPONSE_URL,+ "actions": [+ {"action_id": element["action_id"], "block_id": actions_block["block_id"], "value": element["value"]}+ ],+ }+ body = f"payload={json.dumps(payload)}"+ signed = sign_slack_request(body.encode(), SIGNING_SECRET)+ response = APIClient().post(+ "/slack/interactivity-callback/",+ data=body,+ content_type="application/x-www-form-urlencoded",+ headers={"x-slack-signature": signed.signature, "x-slack-request-timestamp": signed.timestamp},+ )+ assert response.status_code == 200++ def _saved_default(self) -> Integration | None:+ row = SlackSettings.objects.filter(slack_workspace_id=WORKSPACE, slack_user_id=MENTIONER).first()+ return row.default_integration if row else None++ @parameterized.expand(+ [+ ("picker_on", True, False, True),+ ("picker_off", False, False, False),+ ("picker_fails_to_post", True, True, False),+ ]+ )+ def test_mention_with_several_projects_gets_the_picker_or_the_hint(+ self, _name, picker_enabled, post_fails, expect_picker+ ):+ outcome = self._mention(picker_enabled=picker_enabled, post_fails=post_fails)++ assert outcome["hint_posted"] is not expect_picker+ assert outcome["drop"]["drop_reason"] == "multiple_projects"+ assert outcome["drop"]["picker_shown"] is expect_picker+ assert outcome["drop"]["replied"] is True+ self.mock_start.assert_not_called()++ def test_pick_runs_the_original_mention_and_saves_the_default(self):+ blocks = self._mention()["blocks"]++ self._click(blocks, project=self.staging)++ self.mock_start.assert_called_once()+ started = self.mock_start.call_args+ assert started.args[0] == self.event+ assert started.args[1].id == self.staging.id+ assert started.args[3] == "Ev001"+ assert self._saved_default() == self.staging+ assert "Acme · Staging" in self.mock_response_url.call_args.kwargs["json"]["text"]++ @parameterized.expand(+ [+ ("click_by_someone_else", "U_OTHER", False),+ ("access_removed_before_the_click", MENTIONER, True),+ ]+ )+ def test_rejected_pick_starts_nothing_and_saves_nothing(self, _name, clicker, remove_access):+ blocks = self._mention()["blocks"]+ if remove_access:+ self.membership.delete()++ self._click(blocks, project=self.staging, slack_user_id=clicker)++ self.mock_start.assert_not_called()+ assert self._saved_default() is None++ def test_second_click_does_not_start_a_second_run(self):+ blocks = self._mention()["blocks"]++ self._click(blocks, project=self.staging)+ self._click(blocks, project=self.production)++ self.mock_start.assert_called_once()+ assert self._saved_default() == self.staging++ def test_pick_in_an_unapproved_shared_channel_starts_nothing(self):+ blocks = self._mention(is_ext_shared_channel=True)["blocks"]++ with patch(+ "products.slack_app.backend.api._post_channel_approval_prompt", return_value=True+ ) as mock_approval_prompt:+ self._click(blocks, project=self.staging)++ mock_approval_prompt.assert_called_once()+ self.mock_start.assert_not_called()++ def test_click_after_the_picker_expired_tells_the_person(self):+ blocks = self._mention()["blocks"]+ cache.clear()++ self._click(blocks, project=self.staging)++ self.mock_start.assert_not_called()+ assert self.mock_response_url.call_args.kwargs["json"]["text"] == PICKER_EXPIRED_MESSAGE