: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): invite users to book a research interview (#123273)
Vojta Bartoš438a841198ed
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex f7d947f534dd..7f14ea79e7bf 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -53,7 +53,7 @@ from products.slack_app.backend.feature_flags import (is_slack_app_unprompted_answers_enabled,)from products.slack_app.backend.helpers import local_dev_slack_email-from products.slack_app.backend.logic import reply_suggestions+from products.slack_app.backend.logic import interview_recruitment, reply_suggestionsfrom products.slack_app.backend.logic.feature_tips import interactivity as feature_tip_interactivityfrom products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.state import record_feature_used@@ -6301,6 +6301,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:or turn_feedback.extract_modal_hint(payload)or (clicked_reply_suggestion.integration_id if clicked_reply_suggestion else None)or feature_tip_interactivity.feature_tip_integration_hint(payload)+ or interview_recruitment.interview_integration_hint(payload))requesting_user = payload.get("user", {}).get("id", "")slack_team_id = payload.get("team", {}).get("id")@@ -6468,6 +6469,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return turn_feedback.handle_turn_feedback_click(payload)if feature_tip_interactivity.is_feature_tip_action(action_id):return feature_tip_interactivity.handle_feature_tip_action(payload)+ if interview_recruitment.is_interview_action(action_id):+ return interview_recruitment.handle_interview_action(payload)if reply_suggestions.is_reply_suggestion_action(action_id) and clicked_reply_suggestion:return _handle_reply_suggestion_click(payload, clicked_reply_suggestion)if action_id == CHANNEL_APPROVAL_ACTION_APPROVE:diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex 38615173fb15..8bea45500f9e 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -52,6 +52,7 @@ SLACK_APP_FORKING_FLAG = "slack-app-forking"SLACK_APP_MULTIPLAYER_APPROVALS_FLAG = "slack-app-multiplayer-approvals"SLACK_APP_BYOS_FLAG = "slack-app-byos"SLACK_APP_UNPROMPTED_ANSWERS_FLAG = "slack-app-unprompted-answers"+SLACK_APP_INTERVIEW_RECRUITMENT_FLAG = "slack-app-interview-recruitment"# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.@@ -204,6 +205,20 @@ def is_slack_app_unprompted_answers_enabled(integration: Integration) -> bool:)+def is_slack_app_interview_recruitment_enabled(integration: Integration, distinct_id: str) -> bool:+ """Gate for the interview invitations on the Home tab and after a frustration signal.++ ``distinct_id`` is the reader's PostHog distinct id, or their Slack-derived id when no+ PostHog user is linked. A rule on email or a cohort only matches a linked reader.+ """+ return _workspace_flag_enabled(+ SLACK_APP_INTERVIEW_RECRUITMENT_FLAG,+ integration,+ failure_log_key="slack_app_interview_recruitment_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/logic/interview_recruitment.py b/products/slack_app/backend/logic/interview_recruitment.pynew file mode 100644index 000000000000..0693c7684a3c--- /dev/null+++ b/products/slack_app/backend/logic/interview_recruitment.py@@ -0,0 +1,149 @@+"""Invitations to book a research interview with the Slack app team.++Every invitation links to ``BOOKING_URL``. A click arrives as a ``block_actions`` payload, which is+how the click is counted.++- The bad-rating modal always shows the link, because the reader already chose to tell us what went wrong.+- The Home tab shows a button when the ``slack-app-interview-recruitment`` flag selects the reader.+"""++from __future__ import annotations++import json+from typing import TYPE_CHECKING, Any, Literal, get_args++from django.http import HttpResponse++import structlog++from posthog.dataclasses import frozen+from posthog.models.integration import Integration++from products.slack_app.backend.analytics import capture_slack_event, slack_distinct_id+from products.slack_app.backend.feature_flags import is_slack_app_interview_recruitment_enabled+from products.slack_app.backend.services.slack_messages import section_block+from products.slack_app.backend.services.slack_user_oauth import find_linked_posthog_user++if TYPE_CHECKING:+ from posthog.models.user import User++logger = structlog.get_logger(__name__)++InterviewSurface = Literal["home", "bad_rating_modal"]+INTERVIEW_SURFACES: frozenset[str] = frozenset(get_args(InterviewSurface))++BOOKING_URL = "https://cal.com/vojta-bartos-wye08f/posthog-slack-app"+INVITE_MESSAGE = "Got 30 minutes to tell us how the PostHog Slack app works for you? Book a chat with the team."+MODAL_INVITE_MESSAGE = "Want to talk it through? Book 30 minutes with the team."++INTERVIEW_BOOK_ACTION_ID = "slack_app_interview:book"+INTERVIEW_ACTION_IDS: frozenset[str] = frozenset({INTERVIEW_BOOK_ACTION_ID})+_CLICK_EVENTS: dict[str, str] = {INTERVIEW_BOOK_ACTION_ID: "slack app interview invite clicked"}+++def linked_posthog_user(integration: Integration, slack_user_id: str) -> User | None:+ """The PostHog user behind this Slack identity. Best-effort, because the result only targets the flag and labels events."""+ try:+ return find_linked_posthog_user(+ slack_user_id=slack_user_id,+ slack_team_id=integration.integration_id or "",+ candidate_org_ids={integration.team.organization_id},+ )+ except Exception:+ logger.warning("slack_app_interview_user_lookup_failed", integration_id=integration.id, exc_info=True)+ return None+++def is_recruiting(integration: Integration, slack_user_id: str, posthog_user: User | None) -> bool:+ distinct_id = (+ posthog_user.distinct_id+ if posthog_user is not None and posthog_user.distinct_id+ else slack_distinct_id(integration, slack_user_id)+ )+ return is_slack_app_interview_recruitment_enabled(integration, distinct_id)+++def book_button(integration_id: int, surface: InterviewSurface, **extra: str | None) -> dict[str, Any]:+ # The integration id lets the cross-region interactivity router find the region that owns the click.+ value = {"integration_id": integration_id, "surface": surface, **{key: item for key, item in extra.items() if item}}+ return {+ "type": "button",+ "action_id": INTERVIEW_BOOK_ACTION_ID,+ "text": {"type": "plain_text", "text": "Book a chat"},+ "style": "primary",+ "url": BOOKING_URL,+ "value": json.dumps(value),+ }+++def invite_section(text: str, button: dict[str, Any]) -> dict[str, Any]:+ return {**section_block(text), "accessory": button}+++@frozen+class _InterviewClick:+ action_id: str+ value: dict[str, Any]+++def _clicked(payload: dict[str, Any]) -> _InterviewClick | None:+ for action in payload.get("actions", []) or ():+ action_id = action.get("action_id")+ if not is_interview_action(action_id):+ continue+ try:+ value = json.loads(action.get("value") or "")+ except json.JSONDecodeError:+ return None+ return _InterviewClick(action_id=action_id, value=value) if isinstance(value, dict) else None+ return None+++def is_interview_action(action_id: object) -> bool:+ return action_id in INTERVIEW_ACTION_IDS+++def _integration_id(clicked: _InterviewClick | None) -> int | None:+ integration_id = clicked.value.get("integration_id") if clicked is not None else None+ return integration_id if isinstance(integration_id, int) else None+++def interview_integration_hint(payload: dict[str, Any]) -> int | None:+ return _integration_id(_clicked(payload))+++def handle_interview_action(payload: dict[str, Any]) -> HttpResponse:+ """Record a click on an invitation's booking button.++ Slack opens the booking page itself and sends this payload only so the click can be counted.+ """+ clicked = _clicked(payload)+ slack_user_id = (payload.get("user") or {}).get("id")+ slack_team_id = (payload.get("team") or {}).get("id")+ integration_id = _integration_id(clicked)+ if clicked is None or integration_id is None or not slack_user_id or not slack_team_id:+ return HttpResponse(status=200)+ value = clicked.value+ integration = (+ Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get+ kind="slack",+ integration_id=slack_team_id,+ )+ .select_related("team__organization")+ .first()+ )+ surface = value.get("surface")+ if integration is None or surface not in INTERVIEW_SURFACES:+ return HttpResponse(status=200)++ capture_slack_event(+ integration,+ _CLICK_EVENTS[clicked.action_id],+ slack_user_id=slack_user_id,+ posthog_user=linked_posthog_user(integration, slack_user_id),+ surface=surface,+ task_run_id=value.get("run_id"),+ ai_trace_id=value.get("trace_id"),+ )+ return HttpResponse(status=200)diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex f7602ed0112b..910e94ff22b8 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -41,6 +41,12 @@ from products.slack_app.backend.feature_flags import ()from products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.state import record_feature_used+from products.slack_app.backend.logic.interview_recruitment import (+ INVITE_MESSAGE,+ book_button,+ invite_section,+ is_recruiting,+)from products.slack_app.backend.models import (ChannelWelcomeMode,SlackSettings,@@ -473,6 +479,7 @@ def render_home_view(thread_join_mode: ThreadJoinMode | None = None,has_project_access: bool = True,account_settings_url: str | None = None,+ interview_invite: dict | None = None,) -> dict:"""Render the Block Kit payload for `views.publish` on the App Home tab."""@@ -544,6 +551,13 @@ def render_home_view(blocks.append({"type": "divider"})blocks.extend(_linked_accounts_section_blocks(account_state, github_state))+ # Section 6a — interview invitation. `interview_invite` is the section block, present only+ # for a viewer the recruitment flag selects.+ if interview_invite is not None:+ blocks.append({"type": "divider"})+ blocks.append(_section_title("💬 Talk to the team"))+ blocks.append(interview_invite)+# Section 7 — your tasks: a quiet list of tasks the calling user# started via @PostHog mentions, so they can see status without# the bot pinging the activity feed for every transition.@@ -2307,6 +2321,7 @@ def _build_home_view(has_project_access=bool(accessible),# The same settings page the GitHub card deep-links to.account_settings_url=github_state.settings_url,+ interview_invite=_resolve_interview_invite(integration, slack_user_id, home_user),)return _HomeRender(view=view,@@ -2316,6 +2331,17 @@ def _build_home_view()+def _resolve_interview_invite(integration: Integration, slack_user_id: str, home_user: User | None) -> dict | None:+ """The invitation section for a viewer the recruitment flag selects. Best-effort, like every card."""+ try:+ if not is_recruiting(integration, slack_user_id, home_user):+ return None+ except Exception:+ logger.warning("slack_app_home_interview_invite_failed", exc_info=True)+ return None+ return invite_section(INVITE_MESSAGE, book_button(integration.id, "home"))++def _republish_home(integration: Integration,slack_user_id: str,diff --git a/products/slack_app/backend/services/turn_feedback.py b/products/slack_app/backend/services/turn_feedback.pyindex 41badbba9a14..482cb3a6f3ea 100644--- a/products/slack_app/backend/services/turn_feedback.py+++ b/products/slack_app/backend/services/turn_feedback.py@@ -34,6 +34,7 @@ from posthog.models.integration import Integration, SlackIntegrationfrom products.slack_app.backend.analytics import slack_event_propsfrom products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.state import record_feature_used+from products.slack_app.backend.logic.interview_recruitment import MODAL_INVITE_MESSAGE, book_button, invite_sectionfrom products.slack_app.backend.services.slack_messages import SLACK_WEBHOOK_TIMEOUT_SECONDS, TURN_FEEDBACK_ACTION_IDfrom products.slack_app.backend.services.slack_user_info import get_cached_bot_user_id@@ -312,7 +313,7 @@ def _capture(target: _FeedbackTarget, event: str, properties: dict[str, Any]) ->logger.warning("slack_app_turn_feedback_capture_failed", captured_event=event, exc_info=True)-def _render_reason_modal(private_metadata: str) -> dict[str, Any]:+def _render_reason_modal(private_metadata: str, invite_button: dict[str, Any]) -> dict[str, Any]:return {"type": "modal","callback_id": TURN_FEEDBACK_MODAL_CALLBACK_ID,@@ -332,7 +333,9 @@ def _render_reason_modal(private_metadata: str) -> dict[str, Any]:"max_length": FEEDBACK_TEXT_MAX_LENGTH,"placeholder": {"type": "plain_text", "text": "What did you expect instead?"},},- }+ },+ {"type": "divider"},+ invite_section(MODAL_INVITE_MESSAGE, invite_button),],}@@ -350,9 +353,12 @@ def _open_reason_modal(payload: dict, target: _FeedbackTarget) -> None:"trace_id": target.trace_id,})+ invite_button = book_button(+ target.integration.id, "bad_rating_modal", run_id=target.run_id, trace_id=target.trace_id+ )try:SlackIntegration(target.integration).client.views_open(- trigger_id=trigger_id, view=_render_reason_modal(private_metadata)+ trigger_id=trigger_id, view=_render_reason_modal(private_metadata, invite_button))except Exception:logger.warning("slack_app_turn_feedback_modal_open_failed", run_id=target.run_id, exc_info=True)diff --git a/products/slack_app/backend/tests/test_turn_feedback.py b/products/slack_app/backend/tests/test_turn_feedback.pyindex 181f4e9fe35b..c42cfc905d40 100644--- a/products/slack_app/backend/tests/test_turn_feedback.py+++ b/products/slack_app/backend/tests/test_turn_feedback.py@@ -13,6 +13,8 @@ from posthog.models.organization import Organizationfrom posthog.models.team.team import Teamfrom posthog.models.user import User+from products.slack_app.backend.logic import interview_recruitment+from products.slack_app.backend.logic.interview_recruitment import BOOKING_URLfrom products.slack_app.backend.services.slack_messages import TURN_FEEDBACK_ACTION_ID, turn_feedback_blockfrom products.slack_app.backend.services.slack_user_info import cache_workspace_bot_user_idfrom products.slack_app.backend.services.turn_feedback import (@@ -174,6 +176,32 @@ class TestTurnFeedback(TestCase):assert kwargs["event"] == "$ai_feedback"assert kwargs["properties"]["$ai_trace_id"] == trace_id+ def test_every_thumbs_down_modal_links_to_the_interview_booking(self):+ client = self.mock_slack.return_value.client+ with patch.object(interview_recruitment, "capture_slack_event") as capture:+ self._pick(self._thumb_value("negative"))+ self._pick(self._thumb_value("negative"))+ view = client.views_open.call_args.kwargs["view"]+ button = view["blocks"][-1]["accessory"]++ response = self._post(+ {+ "type": "block_actions",+ "team": {"id": self.slack_team_id},+ "user": {"id": "U_ALICE"},+ "view": {"id": "V_MODAL", "type": "modal"},+ "actions": [{"type": "button", "action_id": button["action_id"], "value": button["value"]}],+ }+ )++ assert client.views_open.call_count == 2+ assert view["blocks"][0]["block_id"] == _MODAL_TEXT_BLOCK_ID+ assert button["url"] == BOOKING_URL+ assert response.status_code == 200+ assert capture.call_args.args[1] == "slack app interview invite clicked"+ assert capture.call_args.kwargs["surface"] == "bad_rating_modal"+ assert capture.call_args.kwargs["task_run_id"] == str(self.task_run.id)+def test_a_run_from_another_project_is_not_rated(self):other_org = Organization.objects.create(name="OtherOrg")other_team = Team.objects.create(organization=other_org, name="OtherTeam")