: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): capture usage events across bot surfaces (#98127)
Vojta Bartošaa46fc0e65fb
diff --git a/products/slack_app/backend/analytics.py b/products/slack_app/backend/analytics.pyindex ce722b646671..5d852cb33346 100644--- a/products/slack_app/backend/analytics.py+++ b/products/slack_app/backend/analytics.py@@ -1,16 +1,23 @@"""Reusable analytics helpers for the Slack app.-Uses ``ph_scoped_capture`` (not ``posthoganalytics.capture``) so events survive being emitted from a-Temporal worker, where the global client's background flush may never run before the worker exits.+Uses ``ph_background_capture`` (not ``posthoganalytics.capture``) so events survive being emitted+from a Temporal worker, where the global client's background flush may never run before the worker+exits. Unlike ``ph_scoped_capture`` it doesn't block on a per-call flush, so the same helper is+safe on the Slack webhook request path and its 3-second ack budget."""from __future__ import annotations+from typing import TYPE_CHECKING+import structlogfrom posthog.event_usage import groupsfrom posthog.models.integration import Integration-from posthog.ph_client import ph_scoped_capture+from posthog.ph_client import ph_background_capture++if TYPE_CHECKING:+ from posthog.models.user import Userlogger = structlog.get_logger(__name__)@@ -30,19 +37,38 @@ def slack_event_props(integration: Integration, *, slack_user_id: str | None = Ndef capture_slack_event(- integration: Integration, event: str, *, slack_user_id: str | None = None, **props: object+ integration: Integration,+ event: str,+ *,+ slack_user_id: str | None = None,+ posthog_user: User | None = None,+ **props: object,) -> None:- """Capture a Slack app event, keyed on the team (``distinct_id`` = team uuid) with org/team groups.- Best-effort: analytics never breaks the flow."""+ """Capture a Slack app event with org/team groups. Best-effort: analytics never breaks the flow.++ ``distinct_id`` ladder: a resolved PostHog user's distinct id, else a stable Slack-derived id+ (``slack:{team}:{user}``) when the acting Slack user is known, else the team uuid — matching+ the mention funnel's attribution so per-user analysis works across every Slack app event.+ """try:team = integration.team- with ph_scoped_capture() as capture:- capture(- distinct_id=str(team.uuid),- event=event,- properties=slack_event_props(integration, slack_user_id=slack_user_id, **props),- groups=groups(team.organization, team),- )+ if posthog_user is not None:+ distinct_id = posthog_user.distinct_id+ elif slack_user_id:+ distinct_id = f"slack:{integration.integration_id}:{slack_user_id}"+ else:+ distinct_id = str(team.uuid)+ properties = slack_event_props(integration, slack_user_id=slack_user_id, **props)+ properties["posthog_user_identified"] = posthog_user is not None+ if posthog_user is not None:+ properties["$set"] = posthog_user.get_analytics_metadata()+ capture = ph_background_capture()+ capture(+ distinct_id=distinct_id,+ event=event,+ properties=properties,+ groups=groups(team.organization, team),+ )except Exception:# NB: structlog's first positional arg is named ``event``, so pass the Slack event under a# different key — otherwise this best-effort handler itself raises and defeats the swallow.diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 65c929cbf40a..54faaabdf8ea 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -56,6 +56,7 @@ from posthog.user_permissions import UserPermissionsfrom posthog.utils import get_instance_regionfrom products.slack_app.backend import inbox_channel, onboarding+from products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.discussion_replies import try_ingest_discussion_replyfrom products.slack_app.backend.feature_flags import (ASSISTANT_REQUIRED_SCOPES,@@ -88,6 +89,7 @@ from products.slack_app.backend.services.slack_messages import (SLACK_WEBHOOK_TIMEOUT_SECONDS,TURN_FEEDBACK_ACTION_ID,SlackThreadMessage,+ parse_slack_file_refs,post_slack_thread_reply,)from products.slack_app.backend.services.slack_settings import resolve_untagged_followup_mode@@ -1326,6 +1328,24 @@ def _thread_message_event_has_files(event: dict[str, Any]) -> bool:return isinstance(files, list) and len(files) > 0+def _slack_attachment_props(event: dict[str, Any]) -> dict[str, Any]:+ """Analytics context for whatever a message carried alongside its text.++ The agent reads images now, so how often people send one is the question the mention+ event has to answer, and it can only do that by counting the uploads as they arrive.+ Distinct mimetypes ride along so a screenshot is separable from a log or a CSV without+ a second event.+ """+ files = parse_slack_file_refs(event.get("files"))+ image_count = sum(1 for file in files if file.mimetype.startswith("image/"))+ return {+ "slack_attachment_count": len(files),+ "slack_image_count": image_count,+ "slack_has_image": image_count > 0,+ "slack_attachment_mimetypes": sorted({file.mimetype for file in files if file.mimetype}),+ }++def _thread_message_ignore_reason(event: dict[str, Any]) -> str | None:"""Return a short reason if this ``message`` event shouldn't be considered as anuntagged thread follow-up, else None.@@ -1971,6 +1991,9 @@ def _route_assistant_event(posthog_user = resolution.userif event_type == "assistant_thread_started":+ capture_slack_event(+ probe, "slack app assistant thread started", slack_user_id=fields.slack_user_id, posthog_user=posthog_user+ )return _handle_assistant_thread_started(SlackIntegration(probe), fields.dm_channel_id, fields.thread_ts)if event_type == "assistant_thread_context_changed":_store_assistant_channel_context(probe.id, fields.dm_channel_id, fields.thread_ts, fields.viewed_channel_id)@@ -2114,6 +2137,21 @@ def _handle_app_uninstalled(request: HttpRequest, slack_team_id: str) -> str:"""deleted = clear_workspace_profile_cache(slack_team_id)logger.info("slack_app_uninstalled_profile_cache_cleared", slack_team_id=slack_team_id, rows_deleted=deleted)+ # A workspace linked to several projects matches several rows, but the uninstall is+ # one act: capture once per region so plain event counts stay honest, with+ # `linked_project_count` carrying how many links it severed.+ linked_integrations = list(+ Integration.objects.filter(kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id)+ .select_related("team", "team__organization")+ .order_by("id")+ )+ if linked_integrations:+ capture_slack_event(+ linked_integrations[0],+ "slack app uninstalled",+ was_proxied=was_proxied(request),+ linked_project_count=len(linked_integrations),+ )if not was_proxied(request) and cross_region_routing_enabled():_proxy_event_to_region(request, other_region_domain(request.get_host()))return ROUTE_HANDLED_LOCALLY@@ -3315,6 +3353,12 @@ def _handle_untagged_followup_run(payload: dict) -> HttpResponse:slack_channel_id=context.get("slack_channel_id"),slack_user_id=clicker_slack_user_id,)+ capture_slack_event(+ integration,+ "slack app untagged followup confirmed",+ slack_user_id=clicker_slack_user_id,+ posthog_user=posthog_user,+ )_delete_ephemeral_via_response_url(response_url)return HttpResponse(status=200)@@ -3323,9 +3367,34 @@ def _handle_untagged_followup_dismiss(payload: dict) -> HttpResponse:"""Drop the message the replier declined. Nothing is persisted — the choicecovers this one message, not the thread."""context_token = _extract_context_token(payload)+ context = _decode_picker_context(context_token) if context_token else Noneif context_token:cache.delete(_picker_context_cache_key(context_token))_delete_ephemeral_via_response_url(payload.get("response_url", ""))+ # Only a live untagged-followup context names the integration that raised the prompt,+ # so resolving it there matches the confirm path's attribution instead of an+ # arbitrary row of a multi-project workspace.+ if not context or context.get("kind") != UNTAGGED_FOLLOWUP_CONTEXT_KIND:+ return HttpResponse(status=200)+ slack_team_id = payload.get("team", {}).get("id", "")+ integration_id = context.get("integration_id")+ dismissing_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", "team__organization")+ .first()+ if integration_id and slack_team_id+ else None+ )+ if dismissing_integration is not None:+ capture_slack_event(+ dismissing_integration,+ "slack app untagged followup dismissed",+ slack_user_id=payload.get("user", {}).get("id"),+ )return HttpResponse(status=200)@@ -3381,8 +3450,20 @@ def _report_slack_mention_received("slack_team_id": slack_team_id,"slack_channel": channel,"slack_thread_ts": thread_ts,+ # Identifies the individual message, so an accepted mention can be ordered against+ # the drops in its thread and joined to the agent turn that answered it.+ "slack_message_ts": message_ts,"slack_user_id": slack_user_id,+ # Whether the message tagged the bot. ``app_mention`` is a tagged message;+ # ``message`` is an untagged thread reply that the follow-up mode let through,+ # because the ``message`` copy of a tagged reply drops earlier as ``tagged_reply``.+ # ``posthog code slack mention dropped`` reports the same field, so the two sides+ # add up to a funnel.+ "slack_event_type": event.get("type"),+ # "im" marks an assistant DM; channel mentions carry "channel"/"group" or no type at all.+ "slack_channel_type": event.get("channel_type"),"posthog_user_identified": identified_distinct_id is not None,+ **_slack_attachment_props(event),}if posthog_user is not None and identified_distinct_id is not None:properties["$set"] = posthog_user.get_analytics_metadata()diff --git a/products/slack_app/backend/services/commands.py b/products/slack_app/backend/services/commands.pyindex 976c33305f4c..f9486ab55bc3 100644--- a/products/slack_app/backend/services/commands.py+++ b/products/slack_app/backend/services/commands.py@@ -545,6 +545,19 @@ def dispatch_rules_command(defaults, the help listing. The answer concerns whoever ran the command, soevery reply below goes out ephemerally, on both surfaces."""+ from posthog.models.user import User++ from products.slack_app.backend.analytics import capture_slack_event++ capture_slack_event(+ integration,+ "slack app command used",+ slack_user_id=slack_user_id,+ posthog_user=User.objects.filter(id=user_id).first(),+ action=command.action,+ source="mention" if command_prefix == MENTION_COMMAND_PREFIX else "slash_command",+ )+if command.action == "help":# The slash command owns the listing, so a mention only points at it. Answering here# rather than inside the handler keeps the Slack users.info call the listing needs offdiff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex 86e966eda7ca..6433bfbf5625 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -32,6 +32,7 @@ from posthog.models.user import Userfrom posthog.models.user_integration import UserIntegrationfrom posthog.user_permissions import UserPermissions+from products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.feature_flags import is_slack_app_oauth_enabledfrom products.slack_app.backend.models import SlackSettings, SlackUserProfileCache, UntaggedFollowupModefrom products.slack_app.backend.services.integration_resolver import load_integrations, resolve_from_candidates@@ -90,6 +91,10 @@ ACTION_TASKS_PAGE_NEXT = "slack_app_home:tasks_page_next"ACTION_STATS_WINDOW = "slack_app_home:stats_window"ACTION_STATS_REFRESH = "slack_app_home:stats_refresh"ACTION_SET_UNTAGGED_FOLLOWUP_MODE = "slack_app_home:set_untagged_followup_mode"+# URL buttons: Slack opens the link itself and posts a block_actions payload we+# only ack — the ids exist so the clicks still reach the usage-analytics capture.+ACTION_GITHUB_SETTINGS = "slack_app_home:github_settings"+ACTION_CONNECT_ACCOUNT = "slack_app_home:connect_account"# Every control the Home tab renders, in one place. The interactivity endpoint reads# this to claim region ownership and to dispatch, so a control that isn't listed here@@ -111,6 +116,8 @@ HOME_ACTION_IDS: frozenset[str] = frozenset(ACTION_STATS_WINDOW,ACTION_STATS_REFRESH,ACTION_SET_UNTAGGED_FOLLOWUP_MODE,+ ACTION_GITHUB_SETTINGS,+ ACTION_CONNECT_ACCOUNT,})@@ -790,6 +797,7 @@ def _posthog_account_button(account_state: AccountState) -> dict | None:return Nonereturn {"type": "button",+ "action_id": ACTION_CONNECT_ACCOUNT,"url": account_state.link_url,"text": {"type": "plain_text", "text": "Connect to PostHog", "emoji": True},"style": "primary",@@ -819,6 +827,8 @@ def _github_account_button(github_state: GitHubState) -> dict | None:label, style = "Manage GitHub", ""button: dict[str, Any] = {"type": "button",+ "action_id": ACTION_GITHUB_SETTINGS,+ "value": label.lower().replace(" ", "_"),"url": github_state.settings_url,"text": {"type": "plain_text", "text": label, "emoji": True},}@@ -1550,6 +1560,13 @@ def handle_app_home_opened(event: dict, slack_team_id: str, *, integration: Inteslack_user_id=slack_user_id,slack_team_id=slack_team_id,)+ capture_slack_event(+ integration,+ "slack app home opened",+ slack_user_id=slack_user_id,+ account_linked=bool(account_state.linked_email),+ has_project_access=bool(accessible),+ )def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpResponse:@@ -1564,6 +1581,16 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpRespoif integration is None:return HttpResponse(status=200)+ capture_slack_event(+ integration,+ "slack app home action clicked",+ slack_user_id=slack_user_id,+ action=action_id,+ # Which option the control carried: the follow-up mode, the picked project id,+ # the stats window, the tasks page, or the GitHub button's connect/manage state.+ value=(action.get("selected_option") or {}).get("value") or action.get("value"),+ )+# The Home tab keeps no server-side view state — every payload carries the whole# view's inputs instead. Read them all back once so any action republishes with the# controls the user had dialled in, rather than resetting its neighbours' cards.@@ -1676,6 +1703,15 @@ def handle_app_home_view_submission(payload: dict) -> HttpResponse | JsonResponsreasoning_effort=reasoning_effort,)+ capture_slack_event(+ integration,+ "slack app ai preferences saved",+ slack_user_id=slack_user_id,+ runtime_adapter=runtime_adapter,+ model=model,+ reasoning_effort=reasoning_effort,+ )+_republish_home(integration, slack_user_id)return JsonResponse({"response_action": "clear"})diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.pyindex 2daf5d657e50..d7ffdde7deb4 100644--- a/products/slack_app/backend/slack_link_unfurl.py+++ b/products/slack_app/backend/slack_link_unfurl.py@@ -23,6 +23,7 @@ from products.access_control.backend.facade.user_access_control import (from products.conversations.backend.models.ticket import Ticketfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.product_analytics.backend.facade.models import Insight+from products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.services.slack_messages import UNFURL_OPT_OUT_PARAMfrom products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.contracts import TaskSlackUnfurlDTO@@ -427,6 +428,7 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:uac = UserAccessControl(user, team=team)unfurls: dict[str, dict] = {}+ unfurled_kinds: list[str] = []# Every resource we recognized but chose not to unfurl, so a report of "no unfurl appeared"# can be answered from logs instead of by re-deriving the path by hand.skipped: list[dict[str, str]] = []@@ -531,6 +533,9 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:except Exception:logger.exception("slack_task_reference_attach_failed", task_id=str(task.id), team_id=team.pk)+ if raw_url in unfurls:+ unfurled_kinds.append(kind)+logger.info("slack_app_link_unfurl_result",team_id=team.pk,@@ -553,3 +558,13 @@ def handle_posthog_link_unfurl(event: dict, integration: Integration) -> None:slack.client.chat_unfurl(**unfurl_kwargs)except Exception:logger.exception("slack_link_unfurl_chat_unfurl_failed", team_id=team.pk)+ else:+ capture_slack_event(+ integration,+ "slack app link unfurled",+ slack_user_id=slack_user_id,+ posthog_user=user,+ kinds=sorted(set(unfurled_kinds)),+ unfurled_count=len(unfurls),+ skipped_count=len(skipped),+ )diff --git a/products/slack_app/backend/tests/services/test_slack_app_home.py b/products/slack_app/backend/tests/services/test_slack_app_home.pyindex 937a4e19a042..edd5656e901e 100644--- a/products/slack_app/backend/tests/services/test_slack_app_home.py+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py@@ -283,6 +283,9 @@ def _action_ids(view: dict) -> list[str]:for el in block.get("elements", []) or []:if "action_id" in el:out.append(el["action_id"])+ accessory = block.get("accessory")+ if accessory and "action_id" in accessory:+ out.append(accessory["action_id"])return out@@ -448,6 +451,7 @@ class TestRenderHomeView:user_row=_make_row(runtime_adapter="claude", model="claude-opus-4-7"),is_admin=True,account_state=AccountState(enabled=True, link_url="https://app/link"),+ github_state=GitHubState(user_resolved=True, settings_url="https://app/settings"),project_state=ProjectState(candidates=(ProjectChoice(team_id=1, label="Org · Team"),),personal_team_id=1,diff --git a/products/slack_app/backend/tests/test_analytics.py b/products/slack_app/backend/tests/test_analytics.pynew file mode 100644index 000000000000..7ec872683724--- /dev/null+++ b/products/slack_app/backend/tests/test_analytics.py@@ -0,0 +1,61 @@+import pytest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++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.analytics import capture_slack_event+++class TestCaptureSlackEvent:+ @pytest.fixture(autouse=True)+ def setup(self, db):+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.user = User.objects.create(email="[email protected]", distinct_id="user-distinct-1")+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T12345",+ sensitive_config={"access_token": "xoxb-test"},+ )++ @parameterized.expand(+ [+ # name, with_posthog_user, slack_user_id, expected_distinct_id, expected_identified+ ("resolved_user_wins", True, "U123", "user-distinct-1", True),+ ("slack_user_fallback", False, "U123", "slack:T12345:U123", False),+ ("team_fallback", False, None, None, False), # expected_distinct_id filled in from team uuid+ ]+ )+ @patch("products.slack_app.backend.analytics.ph_background_capture")+ def test_distinct_id_ladder(+ self, _name, with_posthog_user, slack_user_id, expected_distinct_id, expected_identified, mock_background+ ):+ capture = MagicMock()+ mock_background.return_value = capture++ capture_slack_event(+ self.integration,+ "slack app test event",+ slack_user_id=slack_user_id,+ posthog_user=self.user if with_posthog_user else None,+ extra_prop="value",+ )++ kwargs = capture.call_args.kwargs+ assert kwargs["distinct_id"] == (expected_distinct_id or str(self.team.uuid))+ assert kwargs["event"] == "slack app test event"+ properties = kwargs["properties"]+ assert properties["posthog_user_identified"] is expected_identified+ assert properties["team_id"] == self.team.id+ assert properties["extra_prop"] == "value"+ assert ("$set" in properties) is with_posthog_user++ @patch("products.slack_app.backend.analytics.ph_background_capture", side_effect=RuntimeError("boom"))+ def test_capture_failure_is_swallowed(self, _mock_background):+ capture_slack_event(self.integration, "slack app test event")diff --git a/products/slack_app/backend/tests/test_mention_analytics.py b/products/slack_app/backend/tests/test_mention_analytics.pyindex 31dfdeebba10..f178714140f6 100644--- a/products/slack_app/backend/tests/test_mention_analytics.py+++ b/products/slack_app/backend/tests/test_mention_analytics.py@@ -30,42 +30,55 @@ class TestReportSlackMentionReceived:@parameterized.expand([- # name, event, user_resolved, thread_reply_count, exp_first, exp_count, exp_identified+ # name, event, user_resolved, thread_reply_count, exp_first, exp_count, exp_identified,+ # exp_event_type("first_message_resolved",- {"channel": "C001", "ts": "1700.0001", "user": "U123"},+ {"type": "app_mention", "channel": "C001", "ts": "1700.0001", "user": "U123"},True,None,True,1,True,+ "app_mention",),("thread_root_is_the_mention_itself",- {"channel": "C001", "ts": "1700.0001", "thread_ts": "1700.0001", "user": "U123"},+ {+ "type": "app_mention",+ "channel": "C001",+ "ts": "1700.0001",+ "thread_ts": "1700.0001",+ "user": "U123",+ },True,None,True,1,True,+ "app_mention",),+ # An untagged reply the follow-up mode let through arrives as ``message``, and is the+ # only shape here whose own ts differs from its thread's.(- "followup_counts_thread_messages",- {"channel": "C001", "ts": "1700.0009", "thread_ts": "1700.0001", "user": "U123"},+ "untagged_followup_counts_thread_messages",+ {"type": "message", "channel": "C001", "ts": "1700.0009", "thread_ts": "1700.0001", "user": "U123"},True,3,False,3,True,+ "message",),("first_message_unresolved_user",- {"channel": "C001", "ts": "1700.0001", "user": "U999"},+ {"type": "app_mention", "channel": "C001", "ts": "1700.0001", "user": "U999"},False,None,True,1,False,+ "app_mention",),])@@ -81,6 +94,7 @@ class TestReportSlackMentionReceived:exp_first,exp_count,exp_identified,+ exp_event_type,mock_resolve,mock_capture,mock_slack_integration,@@ -108,10 +122,54 @@ class TestReportSlackMentionReceived:assert props["session_message_count"] == exp_countassert props["slack_session_id"] == f"T12345:{event['channel']}:{thread_ts}"assert props["slack_thread_ts"] == thread_ts+ # Must track the message, not its thread: the two only diverge on a follow-up, so wiring+ # this to ``thread_ts`` would still look right on every thread-opening mention.+ assert props["slack_message_ts"] == event["ts"]+ assert props["slack_event_type"] == exp_event_typeassert props["slack_user_id"] == event["user"]assert props["posthog_user_identified"] is exp_identifiedassert ("$set" in props) is exp_identified+ @parameterized.expand(+ [+ # name, files, exp_attachments, exp_images, exp_mimetypes+ ("no_files_key", None, 0, 0, []),+ ("empty_list", [], 0, 0, []),+ ("one_screenshot", [{"id": "F1", "name": "shot.png", "mimetype": "image/png"}], 1, 1, ["image/png"]),+ (+ "image_and_log",+ [+ {"id": "F1", "name": "shot.png", "mimetype": "image/png"},+ {"id": "F2", "name": "server.log", "mimetype": "text/plain"},+ ],+ 2,+ 1,+ ["image/png", "text/plain"],+ ),+ ("non_image_only", [{"id": "F1", "name": "rows.csv", "mimetype": "text/csv"}], 1, 0, ["text/csv"]),+ ("two_images_one_mimetype", [{"mimetype": "image/png"}, {"mimetype": "image/png"}], 2, 2, ["image/png"]),+ # Slack omits ``mimetype`` on some uploads; the file still counts, unlabeled.+ ("mimetype_missing", [{"id": "F1", "name": "unknown"}], 1, 0, []),+ ]+ )+ @patch("products.slack_app.backend.api.posthoganalytics.capture")+ @patch("products.slack_app.backend.api.resolve_posthog_user_from_event")+ def test_capture_attachment_properties(+ self, _name, files, exp_attachments, exp_images, exp_mimetypes, mock_resolve, mock_capture+ ):+ mock_resolve.return_value = self.user+ event: dict = {"channel": "C001", "ts": "1700.0001", "user": "U123"}+ if files is not None:+ event["files"] = files++ _report_slack_mention_received(event, self.integration, "T12345")++ props = mock_capture.call_args.kwargs["properties"]+ assert props["slack_attachment_count"] == exp_attachments+ assert props["slack_image_count"] == exp_images+ assert props["slack_has_image"] is (exp_images > 0)+ assert props["slack_attachment_mimetypes"] == exp_mimetypes+@patch("products.slack_app.backend.api.posthoganalytics.capture")@patch("products.slack_app.backend.api.resolve_posthog_user_from_event")def test_capture_failure_is_swallowed(self, mock_resolve, mock_capture):diff --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 d247423e50dc..cc3d10384150 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@@ -286,6 +286,29 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):assert Integration.objects.filter(id=self.posthog_code_integration.id).exists()assert mock_proxy.call_count == expected_proxy_calls+ @patch("products.slack_app.backend.api.capture_slack_event")+ @patch("products.slack_app.backend.api._proxy_event_to_region")+ @override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")+ def test_app_uninstalled_captures_once_for_multi_project_workspace(self, _mock_proxy, mock_capture):+ # A workspace linked to several projects has several rows here; capturing per+ # row would let one uninstall inflate a plain count of the event.+ second_team = Team.objects.create(organization=self.organization, name="Second Team")+ Integration.objects.create(+ team=second_team,+ kind="slack",+ integration_id="T12345",+ sensitive_config={"access_token": "xoxb-second"},+ )++ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region++ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")+ route_posthog_code_event_to_relevant_region(request, {"type": "app_uninstalled"}, "T12345")++ mock_capture.assert_called_once()+ assert mock_capture.call_args.args[1] == "slack app uninstalled"+ assert mock_capture.call_args.kwargs["linked_project_count"] == 2+@patch("products.slack_app.backend.api._proxy_event_to_region")@patch("products.slack_app.backend.services.slack_user_info.SlackUserProfileCache.objects.filter")@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")diff --git a/products/slack_app/backend/tests/test_untagged_followup_interactivity.py b/products/slack_app/backend/tests/test_untagged_followup_interactivity.pyindex 5ae72a52981d..8bca9508c4b0 100644--- a/products/slack_app/backend/tests/test_untagged_followup_interactivity.py+++ b/products/slack_app/backend/tests/test_untagged_followup_interactivity.py@@ -167,6 +167,29 @@ class TestUntaggedFollowupInteractivity(TestCase):assert cache.get(_picker_context_cache_key(self.context_token)) is Noneassert mock_post.call_args.kwargs["json"] == {"delete_original": True}+ def test_dismissal_attributes_to_the_prompts_integration(self, mock_slack_cls, mock_post):+ # A workspace can be linked to several projects; the dismissal must land on the+ # integration that raised the prompt, not on whichever row a lookup returns first.+ mock_slack_cls.slack_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}+ second_team = Team.objects.create(organization=self.organization, name="Second Team")+ second_integration = Integration.objects.create(+ team=second_team,+ kind="slack",+ integration_id=self.slack_team_id,+ sensitive_config={"access_token": "xoxb-second"},+ )+ context = cache.get(_picker_context_cache_key(self.context_token))+ context["integration_id"] = second_integration.id+ cache.set(_picker_context_cache_key(self.context_token), context, timeout=900)++ with patch("products.slack_app.backend.api.capture_slack_event") as mock_capture:+ response = self._click(UNTAGGED_FOLLOWUP_ACTION_DISMISS, "U_BOB")++ assert response.status_code == 200+ mock_capture.assert_called_once()+ assert mock_capture.call_args.args[0].id == second_integration.id+ assert mock_capture.call_args.args[1] == "slack app untagged followup dismissed"+def test_click_from_anyone_but_the_message_author_dispatches_nothing(self, mock_slack_cls, mock_post):# The prompt is ephemeral, so this shouldn't be reachable — but the run# would execute as the clicker against somebody else's message.diff --git a/products/slack_app/backend/tests/views/test_slack_user_link.py b/products/slack_app/backend/tests/views/test_slack_user_link.pyindex e3874a80b9c3..9f0b0daf537a 100644--- a/products/slack_app/backend/tests/views/test_slack_user_link.py+++ b/products/slack_app/backend/tests/views/test_slack_user_link.py@@ -259,8 +259,13 @@ class TestCallbackView:with (patch("products.slack_app.backend.views.slack_user_link.is_slack_app_oauth_enabled", return_value=True),patch("products.slack_app.backend.views.slack_user_link.exchange_code", return_value=self._identity()),+ patch("products.slack_app.backend.views.slack_user_link.capture_slack_event") as mock_capture,):response = client.get(f"/complete/slack-link/?code=abc&state={state}")self._assert_settings_redirect_error(response, "org_mismatch")assert not UserIntegration.objects.filter(user=outsider).exists()+ # The session check has passed here, so the failure keys to the same distinct id+ # a later success would use; otherwise one person's linking funnel splits in two.+ mock_capture.assert_called_once()+ assert mock_capture.call_args.kwargs["posthog_user"] == outsiderdiff --git a/products/slack_app/backend/views/slack_user_link.py b/products/slack_app/backend/views/slack_user_link.pyindex 6149a497121b..b769ffcec9ee 100644--- a/products/slack_app/backend/views/slack_user_link.py+++ b/products/slack_app/backend/views/slack_user_link.py@@ -44,6 +44,7 @@ from posthog.models.user import Userfrom posthog.models.user_integration import user_slack_integration_from_identityfrom posthog.views import login_required+from products.slack_app.backend.analytics import capture_slack_eventfrom products.slack_app.backend.feature_flags import is_slack_app_oauth_enabledfrom products.slack_app.backend.services.slack_user_oauth import (CallbackState,@@ -77,6 +78,27 @@ def _settings_redirect(*, error: str | None = None) -> HttpResponseRedirect:return redirect(f"{PERSONAL_INTEGRATIONS_SETTINGS_PATH}?{urlencode(param)}")+def _link_failed(+ integration: Integration,+ reason: str,+ *,+ slack_user_id: str | None = None,+ posthog_user: User | None = None,+) -> HttpResponseRedirect:+ """Report a link attempt that got far enough to name a workspace, then bounce to settings.++ Failures before the workspace lookup stay uncaptured — there is no integration to+ attribute them to. ``posthog_user`` keys the failure to the same distinct id a later+ success would use, so one person's linking funnel doesn't split across ids; pass it+ only once the state's session check has proven the requester initiated the flow,+ because before that ``request.user`` may be a victim of a forwarded callback URL.+ """+ capture_slack_event(+ integration, "slack app user link failed", slack_user_id=slack_user_id, posthog_user=posthog_user, reason=reason+ )+ return _settings_redirect(error=reason)++def _load_workspace_integration(posthog_team_id: int, slack_team_id: str) -> Integration | None:return (Integration.objects.filter(team_id=posthog_team_id, kind="slack", integration_id=slack_team_id)@@ -154,13 +176,13 @@ def slack_user_link_callback(request: HttpRequest) -> HttpResponse:if workspace_integration is None:return _settings_redirect(error="workspace_not_found")if not is_slack_app_oauth_enabled(workspace_integration):- return _settings_redirect(error="flag_off")+ return _link_failed(workspace_integration, "flag_off", slack_user_id=state.slack_user_id)try:identity = exchange_code(code=code, redirect_uri=_callback_redirect_uri())except SlackUserOAuthError as exc:logger.warning("slack_app_user_link_callback_exchange_failed", error=str(exc))- return _settings_redirect(error="exchange_failed")+ return _link_failed(workspace_integration, "exchange_failed", slack_user_id=state.slack_user_id)# Hard-bind to the workspace from the original invite: if the user# authorized in a different Slack workspace tab, refuse rather than@@ -171,7 +193,7 @@ def slack_user_link_callback(request: HttpRequest) -> HttpResponse:expected=state.slack_team_id,actual=identity.slack_team_id,)- return _settings_redirect(error="team_mismatch")+ return _link_failed(workspace_integration, "team_mismatch", slack_user_id=identity.slack_user_id)# `state.slack_user_id` is informational — if the user clicks an invite# meant for a different person but authorizes as themselves, that's fine@@ -202,7 +224,7 @@ def slack_user_link_callback(request: HttpRequest) -> HttpResponse:state_posthog_user_id=state.posthog_user_id,request_posthog_user_id=posthog_user.id,)- return _settings_redirect(error="session_mismatch")+ return _link_failed(workspace_integration, "session_mismatch", slack_user_id=identity.slack_user_id)# Refuse to write a link row for a PostHog user who isn't a member of# the workspace's org. The org-scope filter in `find_linked_posthog_user`@@ -219,7 +241,9 @@ def slack_user_link_callback(request: HttpRequest) -> HttpResponse:posthog_team_id=workspace_integration.team_id,organization_id=workspace_integration.team.organization_id,)- return _settings_redirect(error="org_mismatch")+ return _link_failed(+ workspace_integration, "org_mismatch", slack_user_id=identity.slack_user_id, posthog_user=posthog_user+ )user_slack_integration_from_identity(posthog_user,@@ -232,6 +256,13 @@ def slack_user_link_callback(request: HttpRequest) -> HttpResponse:user_scopes=identity.user_scopes,)+ capture_slack_event(+ workspace_integration,+ "slack app user linked",+ slack_user_id=identity.slack_user_id,+ posthog_user=posthog_user,+ )+_post_link_success_followup(workspace_integration=workspace_integration,slack_user_id=identity.slack_user_id,