: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): onboarding message for self-driving (#64629)
Joshua Snyder1475822a76ad
diff --git a/frontend/src/scenes/authentication/account/AccountConnected.tsx b/frontend/src/scenes/authentication/account/AccountConnected.tsxindex 8adf8c6057f2..9a0366434260 100644--- a/frontend/src/scenes/authentication/account/AccountConnected.tsx+++ b/frontend/src/scenes/authentication/account/AccountConnected.tsx@@ -2,7 +2,7 @@ import { useValues } from 'kea'import { router } from 'kea-router'import { useEffect } from 'react'-import { IconCheckCircle } from '@posthog/icons'+import { IconCheckCircle, IconWarning } from '@posthog/icons'import { BridgePage } from 'lib/components/BridgePage/BridgePage'import { SSO_PROVIDER_NAMES } from 'lib/constants'@@ -93,19 +93,24 @@ export const scene: SceneExport<AccountConnectedProps> = {/*** Unified return page for PostHog Code / web: social SSO link (`github-login`), personal GitHub* integration (`github-integration`), or team Slack integration (`slack-integration`). Navigates- * to the matching `posthog-code://…` deep link so the desktop app refreshes its integrations.+ * to the matching `posthog-code://…` deep link so the desktop app refreshes its integrations —+ * except when started from Slack (`connect_from=slack`), where it shows a terminal success state+ * and the user returns to Slack manually (no deep link).*/export function AccountConnected({ kind }: AccountConnectedProps): JSX.Element {const { searchParams } = useValues(router)const provider = typeof searchParams.provider === 'string' ? searchParams.provider : undefinedconst label = providerLabel(provider)const isError = typeof searchParams.error === 'string' && searchParams.error.length > 0+ // The Slack flow has no deep link back — the user just returns to Slack themselves, so we only+ // show the success state. PostHog Code refreshes its integrations via a desktop deep link.+ const startedFromSlack = searchParams.connect_from === 'slack'useEffect(() => {- if (kind !== 'invalid') {+ if (kind !== 'invalid' && !startedFromSlack) {window.location.href = posthogCodeDeepUrl(kind, searchParams)}- }, [kind, searchParams])+ }, [kind, searchParams, startedFromSlack])if (kind === 'invalid') {return (@@ -124,14 +129,26 @@ export function AccountConnected({ kind }: AccountConnectedProps): JSX.Element {return (<BridgePage view="account-connected"><div className="flex flex-col items-center gap-4 text-center max-w-lg mx-auto">- <IconCheckCircle className="text-success text-5xl shrink-0" />+ {isError ? (+ <IconWarning className="text-danger text-5xl shrink-0" />+ ) : (+ <IconCheckCircle className="text-success text-5xl shrink-0" />+ )}<h2 className="text-xl font-semibold m-0">{headline(kind, label, isError)}</h2>{showLoginLine && <p className="text-muted mb-0">You can now log into PostHog using {label}.</p>}- <p className="text-muted mb-0">- <strong>Returning to PostHog Code…</strong>- <br />- <em>If this hasn't happened automatically, get back to the PostHog Code app manually.</em>- </p>+ {startedFromSlack ? (+ <p className="text-muted mb-0">+ {isError+ ? 'Something went wrong. Head back to Slack and try again.'+ : 'You can head back to Slack now.'}+ </p>+ ) : (+ <p className="text-muted mb-0">+ <strong>Returning to PostHog Code…</strong>+ <br />+ <em>If this hasn't happened automatically, get back to the PostHog Code app manually.</em>+ </p>+ )}</div></BridgePage>)diff --git a/posthog/api/github_callback/redirects.py b/posthog/api/github_callback/redirects.pyindex e3b422e5adf2..a940695e3197 100644--- a/posthog/api/github_callback/redirects.py+++ b/posthog/api/github_callback/redirects.py@@ -34,9 +34,14 @@ def final_github_redirect(connect_from: str | None, *, error: str | None = None)app_base_urls: dict[str, str] = {"posthog_mobile": MOBILE_GITHUB_CALLBACK_URL,"posthog_code": ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,+ # Slack lands on the same web page; the ``connect_from`` marker tells it to bounce back+ # to the Slack app (deep link) rather than the desktop app.+ "slack": ACCOUNT_CONNECTED_GITHUB_INTEGRATION_PATH,}if connect_from in app_base_urls:params = {"provider": "github"}+ if connect_from == "slack":+ params["connect_from"] = "slack"if error:params["error"] = errorreturn AppDeepLinkRedirect(f"{app_base_urls[connect_from]}?{urlencode(params)}")diff --git a/posthog/api/github_callback/types.py b/posthog/api/github_callback/types.pyindex c3775e9c9954..fcfaf47ac4b5 100644--- a/posthog/api/github_callback/types.py+++ b/posthog/api/github_callback/types.py@@ -23,7 +23,7 @@ MOBILE_GITHUB_CALLBACK_URL = "posthog://github/callback"# ``connect_from`` values for first-party clients that use the lightweight app# linking flow (OAuth-only when the team already has the GitHub App installed,# otherwise discover/install) and return to a client-specific destination.-APP_CONNECT_FROM_VALUES = ("posthog_code", "posthog_mobile")+APP_CONNECT_FROM_VALUES = ("posthog_code", "posthog_mobile", "slack")# GitHub App installation IDs are always positive integers. Reject anything else# before it touches URL construction.diff --git a/posthog/temporal/ai/__init__.py b/posthog/temporal/ai/__init__.pyindex d900b1cf82d8..b417e3ae1019 100644--- a/posthog/temporal/ai/__init__.py+++ b/posthog/temporal/ai/__init__.py@@ -13,6 +13,7 @@ from posthog.temporal.ai.slack_app.posthog_code_slack_interactivity import ()from posthog.temporal.ai.slack_app.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflowfrom posthog.temporal.ai.slack_app.posthog_code_slack_mention_command import PostHogCodeSlackMentionCommandWorkflow+from posthog.temporal.ai.slack_app.posthog_slack_inbox_onboarding import PostHogSlackInboxOnboardingWorkflowfrom posthog.temporal.ai.slack_conversation import (SlackConversationRunnerWorkflow,SlackConversationRunnerWorkflowInputs,@@ -40,6 +41,7 @@ POSTHOG_CODE_SLACK_WORKFLOWS = [PostHogCodeSlackMentionWorkflow,PostHogCodeSlackMentionCommandWorkflow,PostHogCodeSlackTerminateTaskWorkflow,+ PostHogSlackInboxOnboardingWorkflow,]POSTHOG_CODE_SLACK_ACTIVITIES = [diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.pyindex ece478dae9ab..93013df01b8c 100644--- a/posthog/temporal/ai/slack_app/__init__.py+++ b/posthog/temporal/ai/slack_app/__init__.py@@ -29,6 +29,7 @@ from posthog.temporal.ai.slack_app.activities import (post_posthog_code_repo_picker_activity,resolve_posthog_code_slack_command_user_activity,resolve_posthog_code_slack_user_activity,+ run_posthog_slack_inbox_onboarding_activity,)from posthog.temporal.ai.slack_app.types import (PostHogCodeRepoCascadeOutcome,@@ -36,6 +37,7 @@ from posthog.temporal.ai.slack_app.types import (PostHogCodeSlackMentionCommandResult,PostHogCodeSlackMentionCommandWorkflowInputs,PostHogCodeSlackMentionWorkflowInputs,+ PostHogSlackInboxOnboardingInputs,SlackRepoSelectionOutcome,)@@ -58,6 +60,7 @@ SLACK_APP_ACTIVITIES = [handle_posthog_code_rules_command_activity,create_posthog_code_routing_rule_activity,handle_posthog_code_slack_mention_command_activity,+ run_posthog_slack_inbox_onboarding_activity,]__all__ = [@@ -69,6 +72,7 @@ __all__ = ["PostHogCodeSlackMentionCommandResult","PostHogCodeSlackMentionCommandWorkflowInputs","PostHogCodeSlackMentionWorkflowInputs",+ "PostHogSlackInboxOnboardingInputs","SLACK_APP_ACTIVITIES","SlackRepoSelectionOutcome","block_posthog_code_task_if_no_personal_github_activity",@@ -91,4 +95,5 @@ __all__ = ["post_posthog_code_repo_picker_activity","resolve_posthog_code_slack_command_user_activity","resolve_posthog_code_slack_user_activity",+ "run_posthog_slack_inbox_onboarding_activity",]diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.pyindex e926a587c7e6..78b5eaa6287a 100644--- a/posthog/temporal/ai/slack_app/activities/__init__.py+++ b/posthog/temporal/ai/slack_app/activities/__init__.py@@ -15,6 +15,10 @@ from posthog.temporal.ai.slack_app.activities.messaging import (post_posthog_code_picker_timeout_activity,post_posthog_code_repo_picker_activity,)+from posthog.temporal.ai.slack_app.activities.onboarding import (+ run_posthog_slack_inbox_onboarding,+ run_posthog_slack_inbox_onboarding_activity,+)from posthog.temporal.ai.slack_app.activities.repo_selection import (cascade_posthog_code_repository_activity,discover_posthog_code_repository_via_agent_activity,@@ -60,4 +64,6 @@ __all__ = ["post_posthog_code_repo_picker_activity","resolve_posthog_code_slack_command_user_activity","resolve_posthog_code_slack_user_activity",+ "run_posthog_slack_inbox_onboarding",+ "run_posthog_slack_inbox_onboarding_activity",]diff --git a/posthog/temporal/ai/slack_app/activities/onboarding.py b/posthog/temporal/ai/slack_app/activities/onboarding.pynew file mode 100644index 000000000000..67c749457f64--- /dev/null+++ b/posthog/temporal/ai/slack_app/activities/onboarding.py@@ -0,0 +1,28 @@+import structlog+from temporalio import activity++from posthog.temporal.ai.slack_app.types import PostHogSlackInboxOnboardingInputs++logger = structlog.get_logger(__name__)+++def run_posthog_slack_inbox_onboarding_activity(inputs: PostHogSlackInboxOnboardingInputs) -> None:+ run_posthog_slack_inbox_onboarding(inputs.integration_id)+++def run_posthog_slack_inbox_onboarding(integration_id: int) -> None:+ """Create #posthog-inbox and DM the installer for a fresh Slack install. Plain function so it's+ callable outside the Temporal worker (and unit-testable without an activity environment)."""+ from posthog.models.integration import Integration++ from products.slack_app.backend.onboarding import run_install_onboarding++ try:+ integration = Integration.objects.select_related("team", "team__organization").get(+ id=integration_id, kind="slack"+ )+ except Integration.DoesNotExist:+ logger.info("slack_app_inbox_onboarding_integration_gone", integration_id=integration_id)+ return+ run_install_onboarding(integration)diff --git a/posthog/temporal/ai/slack_app/posthog_slack_inbox_onboarding.py b/posthog/temporal/ai/slack_app/posthog_slack_inbox_onboarding.pynew file mode 100644index 000000000000..dc26e25feca6--- /dev/null+++ b/posthog/temporal/ai/slack_app/posthog_slack_inbox_onboarding.py@@ -0,0 +1,32 @@+import json+from datetime import timedelta++import structlog+from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.ai.slack_app.activities.onboarding import run_posthog_slack_inbox_onboarding_activity+from posthog.temporal.ai.slack_app.types import PostHogSlackInboxOnboardingInputs+from posthog.temporal.common.base import PostHogWorkflow++POSTHOG_SLACK_INBOX_ONBOARDING_TIMEOUT_SECONDS = 5 * 60+logger = structlog.get_logger(__name__)++[email protected](name="posthog-slack-inbox-onboarding")+class PostHogSlackInboxOnboardingWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> PostHogSlackInboxOnboardingInputs:+ loaded = json.loads(inputs[0])+ return PostHogSlackInboxOnboardingInputs(**loaded)++ @workflow.run+ async def run(self, inputs: PostHogSlackInboxOnboardingInputs) -> None:+ await workflow.execute_activity(+ run_posthog_slack_inbox_onboarding_activity,+ args=(inputs,),+ start_to_close_timeout=timedelta(seconds=POSTHOG_SLACK_INBOX_ONBOARDING_TIMEOUT_SECONDS),+ # Single attempt: the onboarding DM isn't idempotent, so a retry after a post-then-crash+ # would re-DM the installer. Onboarding is best-effort, so we accept "no retry" over a dup DM.+ retry_policy=RetryPolicy(maximum_attempts=1),+ )diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.pyindex 049dcee51664..1186e49dfe06 100644--- a/posthog/temporal/ai/slack_app/types.py+++ b/posthog/temporal/ai/slack_app/types.py@@ -9,6 +9,11 @@ from dataclasses import dataclassfrom typing import Any, Literal+@dataclass+class PostHogSlackInboxOnboardingInputs:+ integration_id: int++@dataclassclass PostHogCodeSlackMentionWorkflowInputs:event: dict[str, Any]diff --git a/posthog/test/setup_receivers_baseline.txt b/posthog/test/setup_receivers_baseline.txtindex 5641204e7059..b7fad90170b0 100644--- a/posthog/test/setup_receivers_baseline.txt+++ b/posthog/test/setup_receivers_baseline.txt@@ -168,6 +168,7 @@ post_save:products.product_analytics.backend.models.insight_caching_state.sync_dpost_save:products.product_analytics.backend.models.insight_caching_state.sync_insightpost_save:products.product_analytics.backend.models.insight_caching_state.sync_sharing_configurationpost_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change+post_save:products.slack_app.backend.signals.onboard_slack_inbox_on_installpost_save:products.surveys.backend.models.survey_changedpost_save:products.tasks.backend.models.track_task_run_completionpost_save:products.workflows.backend.models.hog_flow.hog_flow.action_saved_for_hog_flowsdiff --git a/posthog/test/test_urls.py b/posthog/test/test_urls.pyindex bdf5bb604ae5..fbc249704445 100644--- a/posthog/test/test_urls.py+++ b/posthog/test/test_urls.py@@ -31,6 +31,31 @@ class TestUrls(APIBaseTest):fetch_redirect_response=False,)+ def test_integration_connect_redirect_authenticated(self):+ response = self.client.get(+ f"/integrations/connect/github/?project_id={self.team.id}&connect_from=slack", follow=False+ )+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ location = response["Location"]+ self.assertIn(f"/api/environments/{self.team.id}/integrations/authorize/", location)+ self.assertIn("kind=github", location)+ self.assertIn("account-connected", location)+ self.assertIn("connect_from%3Dslack", location)++ def test_integration_connect_redirect_requires_login(self):+ self.client.logout()+ response = self.client.get("/integrations/connect/github/?project_id=1&connect_from=slack", follow=False)+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ self.assertIn("/login", response["Location"])++ def test_integration_connect_redirect_rejects_bad_kind(self):+ response = self.client.get(f"/integrations/connect/notreal/?project_id={self.team.id}&connect_from=slack")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_integration_connect_redirect_rejects_bad_connect_from(self):+ response = self.client.get(f"/integrations/connect/github/?project_id={self.team.id}&connect_from=evil")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+def test_unauthenticated_routes_get_loaded_on_the_frontend(self):self.client.logout()diff --git a/posthog/urls.py b/posthog/urls.pyindex 4824a4a21804..438feb83ab00 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -164,6 +164,36 @@ def home(request, *args, **kwargs):return render_template("index.html", request)+_CONNECT_REDIRECT_ALLOWED_KINDS = {"github", "slack", "linear"}+# Surfaces allowed to start a connect flow and be returned to afterwards (see+# posthog/api/github_callback/types.py APP_CONNECT_FROM_VALUES, plus Slack).+_CONNECT_REDIRECT_ALLOWED_SURFACES = {"posthog_code", "posthog_mobile", "slack"}+++def integration_connect_redirect(request: HttpRequest, kind: str) -> HttpResponse:+ """Login-gated entry point for starting an integration OAuth connect from an external surface+ (a Slack message, the desktop app, etc.). Wrapped in ``login_required`` so unauthenticated users+ are bounced to login and resume here, then redirected into the existing ``integrations/authorize``+ flow with a ``connect_from``-tagged return page. ``next`` is constructed internally (never taken+ from the query) so this can't be used as an open redirect."""+ if kind not in _CONNECT_REDIRECT_ALLOWED_KINDS:+ return HttpResponse("Unsupported integration kind", status=400)+ connect_from = request.GET.get("connect_from", "")+ if connect_from not in _CONNECT_REDIRECT_ALLOWED_SURFACES:+ return HttpResponse("Unsupported connect_from", status=400)+ project_id = request.GET.get("project_id") or getattr(request.user, "current_team_id", None)+ if not project_id or not str(project_id).isdigit():+ return HttpResponse("Missing or invalid project_id", status=400)++ next_path = "/account-connected/{}-integration?{}".format(+ kind, urlencode({"provider": kind, "project_id": project_id, "connect_from": connect_from})+ )+ authorize_url = "/api/environments/{}/integrations/authorize/?{}".format(+ project_id, urlencode({"kind": kind, "next": next_path})+ )+ return HttpResponseRedirect(authorize_url)++def authorize_and_redirect(request: HttpRequest) -> HttpResponse:if not request.GET.get("redirect"):return HttpResponse("You need to pass a url to ?redirect=", status=400)@@ -376,6 +406,7 @@ urlpatterns = [),re_path(r"^api.+", api_not_found),path("authorize_and_redirect/", login_required(authorize_and_redirect)),+ path("integrations/connect/<str:kind>/", login_required(integration_connect_redirect)),path("shared_dashboard/<str:access_token>",sharing.SharingViewerPageViewSet.as_view({"get": "retrieve"}),diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex a1b71e33e409..26fce666d6a5 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -1,4 +1,5 @@import enum+import dataclassesfrom datetime import timedeltafrom typing import get_args@@ -40,6 +41,140 @@ def dismiss_report_from_slack(return suppress_report_from_slack(team_id, report_id, slack_user_id=slack_user_id, user_id=user_id)+def get_default_slack_notification_channel(team_id: int) -> str | None:+ """Team-default Slack channel for signal notifications, stored as "<channel_id>|#name"."""+ from products.signals.backend.models import (+ SignalTeamConfig, # noqa: PLC0415 — avoids importing model layer at facade import time+ )++ config = SignalTeamConfig.objects.filter(team_id=team_id).only("default_slack_notification_channel").first()+ if config is None:+ return None+ value = (config.default_slack_notification_channel or "").strip()+ return value or None+++def set_default_slack_notification_channel(team_id: int, value: str | None) -> None:+ """Idempotently set the team-default Slack channel for signal notifications."""+ from products.signals.backend.models import (+ SignalTeamConfig, # noqa: PLC0415 — avoids importing model layer at facade import time+ )++ SignalTeamConfig.objects.update_or_create(+ team_id=team_id,+ defaults={"default_slack_notification_channel": value or None},+ )+++# ---------------------------------------------------------------------------+# Slack onboarding: the signal sources offered in the inbox onboarding flow.+# One catalog drives the list, the toggles, and the "connected" checks.+# ---------------------------------------------------------------------------++_DEFAULT_SESSION_ANALYSIS_SAMPLE_RATE = 0.1++[email protected](frozen=True)+class OnboardingSource:+ """A signal source offered as a checkbox in the Slack onboarding flow, with current state."""++ key: str+ label: str+ description: str+ enabled: bool++[email protected](frozen=True)+class _SourceSpec:+ key: str+ label: str+ description: str+ # The SignalSourceConfig (source_product, source_type) rows ticking this source enables.+ pairs: tuple[tuple[str, str], ...]+ needs_ai_approval: bool = False+++_SOURCE_CATALOG: tuple[_SourceSpec, ...] = (+ _SourceSpec(+ "error_tracking",+ "Error tracking",+ "new, reopened & spiking issues",+ (+ ("error_tracking", "issue_created"),+ ("error_tracking", "issue_reopened"),+ ("error_tracking", "issue_spiking"),+ ),+ ),+ _SourceSpec(+ "session_replay",+ "Session replay analysis",+ "problems real users hit",+ (("session_replay", "session_analysis_cluster"),),+ needs_ai_approval=True,+ ),+)+_SOURCE_BY_KEY: dict[str, _SourceSpec] = {spec.key: spec for spec in _SOURCE_CATALOG}+++def _ai_data_processing_approved(team_id: int) -> bool:+ return bool(+ Team.objects.filter(id=team_id).values_list("organization__is_ai_data_processing_approved", flat=True).first()+ )+++def has_enabled_source(team_id: int) -> bool:+ """True once the team has at least one enabled signal source — i.e. there's something to respond to."""+ return SignalSourceConfig.objects.filter(team_id=team_id, enabled=True).exists()+++def onboarding_sources(team_id: int) -> list[OnboardingSource]:+ """The onboarding sources, in order, with current enabled state (for pre-checking the checkboxes)."""+ enabled_pairs = set(+ SignalSourceConfig.objects.filter(team_id=team_id, enabled=True).values_list("source_product", "source_type")+ )+ return [+ OnboardingSource(+ key=spec.key,+ label=spec.label,+ description=spec.description,+ enabled=any(pair in enabled_pairs for pair in spec.pairs),+ )+ for spec in _SOURCE_CATALOG+ ]+++def set_sources(team_id: int, user_id: int | None, selected_keys: list[str]) -> list[str]:+ """Sync the team's onboarding sources to ``selected_keys`` (tick = enable, untick = disable;+ enabling a source sets up its SignalSourceConfig). Returns the labels of any that couldn't be+ enabled because AI data processing isn't approved (session replay analysis)."""+ selected = set(selected_keys)+ ai_approved = _ai_data_processing_approved(team_id)+ blocked: list[str] = []+ for spec in _SOURCE_CATALOG:+ want_on = spec.key in selected+ if want_on and spec.needs_ai_approval and not ai_approved:+ # Wanted but AI-gated: leave the source as-is. Disabling here would silently turn off a+ # previously-approved source when the full checkbox snapshot is re-submitted.+ blocked.append(spec.label)+ continue+ for source_product, source_type in spec.pairs:+ if want_on:+ defaults: dict = {"enabled": True, "created_by_id": user_id}+ if source_type == "session_analysis_cluster":+ defaults["config"] = {"sample_rate": _DEFAULT_SESSION_ANALYSIS_SAMPLE_RATE}+ obj, created = SignalSourceConfig.objects.get_or_create(+ team_id=team_id, source_product=source_product, source_type=source_type, defaults=defaults+ )+ if not created and not obj.enabled:+ obj.enabled = True+ obj.save(update_fields=["enabled", "updated_at"])+ else:+ SignalSourceConfig.objects.filter(+ team_id=team_id, source_product=source_product, source_type=source_type, enabled=True+ ).update(enabled=False)+ return blocked++def _get_field_values(field: pydantic.fields.FieldInfo) -> tuple[str, ...]:"""Extract all possible values for a Pydantic field (Literal, StrEnum, or default)."""args = get_args(field.annotation)diff --git a/products/slack_app/backend/analytics.py b/products/slack_app/backend/analytics.pynew file mode 100644index 000000000000..ce722b646671--- /dev/null+++ b/products/slack_app/backend/analytics.py@@ -0,0 +1,49 @@+"""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.+"""++from __future__ import annotations++import structlog++from posthog.event_usage import groups+from posthog.models.integration import Integration+from posthog.ph_client import ph_scoped_capture++logger = structlog.get_logger(__name__)+++def slack_event_props(integration: Integration, *, slack_user_id: str | None = None, **extra: object) -> dict:+ """The standard property bundle attached to every Slack app event, plus any ``extra`` props."""+ props: dict = {+ "integration_id": integration.id,+ "slack_team_id": integration.integration_id,+ "team_id": integration.team_id,+ "organization_id": str(integration.team.organization_id),+ }+ if slack_user_id:+ props["slack_user_id"] = slack_user_id+ props.update(extra)+ return props+++def capture_slack_event(+ integration: Integration, event: str, *, slack_user_id: str | 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."""+ 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),+ )+ 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.+ logger.warning("slack_analytics_capture_failed", slack_event=event, exc_info=True)diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex 2726200c6fa7..6155248c52f3 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -51,7 +51,9 @@ from posthog.temporal.common.client import sync_connectfrom posthog.user_permissions import UserPermissionsfrom posthog.utils import get_instance_region+from products.slack_app.backend import inbox_channel, onboardingfrom products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping+from products.slack_app.backend.services import inbox_interactivityfrom products.slack_app.backend.services.integration_resolver import (UserResolutionFailure,format_project_candidate_list,@@ -1968,6 +1970,10 @@ def _route_member_joined_channel(# event for every channel-membership change, so the volume is high.return ROUTE_HANDLED_LOCALLY+ # The onboarding flow has its own messaging for the inbox channel — skip the generic welcome here.+ if inbox_channel.is_inbox_channel(integration, channel_id):+ return ROUTE_HANDLED_LOCALLY+if not _claim_channel_onboarding(slack_team_id, channel_id):logger.info("slack_app_channel_onboarding_skipped_duplicate",@@ -2730,19 +2736,9 @@ def _handle_no_repo_needed_submit(payload: dict) -> HttpResponse:def _delete_ephemeral_via_response_url(response_url: str) -> None:- """Remove the original ephemeral prompt via the interactivity ``response_url``.-- Every click outcome is recorded as a public threaded message — the- ephemeral prompt has done its job by then and only the public message- should remain. Failures are logged but never raised: a click handler- that can't reach Slack still finished its DB work.- """- if not response_url:- return- try:- requests.post(response_url, json={"delete_original": True}, timeout=3)- except Exception:- logger.warning("slack_app_channel_approval_response_url_failed", exc_info=True)+ """Remove the original ephemeral prompt via the interactivity ``response_url`` once its public+ threaded outcome has been posted."""+ inbox_interactivity.post_response_url(response_url, {"delete_original": True})def _post_channel_approval_outcome(@@ -3094,6 +3090,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:hinted_integration_id, hinted_user_id = _extract_picker_hints(payload)terminate_integration_id, terminate_user_id = _extract_terminate_hints(payload)dismiss_integration_id = _extract_dismiss_hints(payload)+ inbox_integration_id = inbox_interactivity.extract_inbox_hints(payload)requesting_user = payload.get("user", {}).get("id", "")slack_team_id = payload.get("team", {}).get("id")@@ -3127,6 +3124,14 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:kind=SLACK_INTEGRATION_KIND,integration_id=slack_team_id,).exists()+ elif slack_team_id and inbox_integration_id:+ # Inbox onboarding buttons (create/join) are DMed to a user; any clicker may act, so this+ # is gated only on owning the integration locally.+ local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ id=inbox_integration_id, # nosemgrep: idor-taint-user-input-to-model-get+ kind=SLACK_INTEGRATION_KIND,+ integration_id=slack_team_id,+ ).exists()proxied = _was_proxied(request)incoming_host = request.get_host()@@ -3214,5 +3219,13 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return _handle_channel_approval_deny(payload)if action.get("action_id") == SIGNALS_DISMISS_REPORT_ACTION_ID:return _handle_signals_dismiss_report(payload)+ if action.get("action_id") == onboarding.INBOX_CREATE_ACTION_ID:+ return inbox_interactivity.handle_inbox_create(payload)+ if action.get("action_id") == onboarding.INBOX_JOIN_ACTION_ID:+ return inbox_interactivity.handle_inbox_join(payload)+ if action.get("action_id") == onboarding.INBOX_SOURCES_CHECKBOXES_ACTION:+ return inbox_interactivity.handle_inbox_sources(payload)+ if action.get("action_id") == onboarding.INBOX_AI_APPROVAL_ACTION_ID:+ return inbox_interactivity.handle_inbox_ai_approval(payload)return HttpResponse(status=200)diff --git a/products/slack_app/backend/inbox_channel.py b/products/slack_app/backend/inbox_channel.pynew file mode 100644index 000000000000..32a569bc2533--- /dev/null+++ b/products/slack_app/backend/inbox_channel.py@@ -0,0 +1,215 @@+"""Find-or-create the ``#posthog-inbox`` channel and persist it as the team's signal notification channel."""++from __future__ import annotations++from django.core.cache import cache++import structlog+from slack_sdk.errors import SlackApiError++from posthog.models.integration import Integration, SlackIntegration++logger = structlog.get_logger(__name__)++INBOX_CHANNEL_NAME = "posthog-inbox"+# Creating a public channel and inviting members both require this scope.+INBOX_CHANNEL_REQUIRED_SCOPES: frozenset[str] = frozenset({"channels:manage"})+# Onboarding also DMs the installer and posts reports, both needing chat:write. Gated on scopes, not a flag.+INBOX_ONBOARDING_REQUIRED_SCOPES: frozenset[str] = INBOX_CHANNEL_REQUIRED_SCOPES | frozenset({"chat:write"})++# Just long enough to absorb a concurrent install/join racing to create the same channel.+_CHANNEL_CLAIM_TTL_SECONDS = 60++# Cap the channel scan so a huge workspace (or a non-advancing cursor) can't loop unbounded.+# 50 * 200 = 10k channels; past that we bail to create / manual instructions.+_MAX_CHANNEL_LIST_PAGES = 50+++def has_inbox_scopes(integration: Integration) -> bool:+ """Whether the install granted the onboarding scopes. Gated on this rather than a feature flag."""+ return not SlackIntegration(integration).missing_scopes(INBOX_ONBOARDING_REQUIRED_SCOPES)+++def _get_team_channel(team_id: int) -> str | None:+ from products.signals.backend.facade.api import (+ get_default_slack_notification_channel, # noqa: PLC0415 — keeps the signals temporal stack off the slack import path+ )++ return get_default_slack_notification_channel(team_id)+++def _set_team_channel(team_id: int, value: str) -> None:+ from products.signals.backend.facade.api import (+ set_default_slack_notification_channel, # noqa: PLC0415 — keeps the signals temporal stack off the slack import path+ )++ set_default_slack_notification_channel(team_id, value)+++def _channel_target(channel_id: str, channel_name: str) -> str:+ """Serialize to the "<id>|#name" form the signals notifier expects."""+ name = channel_name if channel_name.startswith("#") else f"#{channel_name}"+ return f"{channel_id}|{name}"+++def channel_id_from_target(value: str) -> str:+ return value.split("|", 1)[0].strip()+++def channel_name_from_target(value: str) -> str:+ pipe = value.find("|")+ return value[pipe + 1 :].strip() if pipe != -1 else f"#{INBOX_CHANNEL_NAME}"+++def _channel_exists(slack: SlackIntegration, channel_id: str) -> bool:+ try:+ channel = slack.client.conversations_info(channel=channel_id).get("channel") or {}+ except SlackApiError as e:+ # Fail safe: only a definitive "gone" answer replaces a configured channel; a transient error+ # (ratelimited, network) must not clobber the team's existing default notification channel.+ return e.response.get("error") not in ("channel_not_found", "channel_is_archived")+ return bool(channel.get("id")) and not channel.get("is_archived", False)+++def _find_inbox_channel(slack: SlackIntegration) -> tuple[str, str] | None:+ """Return (channel_id, "#name") for an existing #posthog-inbox public channel, else None.++ Bounded by ``_MAX_CHANNEL_LIST_PAGES`` and fails closed (None) on any Slack error.+ """+ cursor: str | None = None+ for _ in range(_MAX_CHANNEL_LIST_PAGES):+ try:+ response = slack.client.conversations_list(+ exclude_archived=True, types="public_channel", limit=200, cursor=cursor or None+ )+ except SlackApiError as e:+ logger.warning("slack_app_inbox_channel_list_failed", error=e.response.get("error"))+ return None+ channels: list[dict] = response.get("channels", [])+ for channel in channels:+ if channel.get("name") == INBOX_CHANNEL_NAME:+ return channel["id"], f"#{INBOX_CHANNEL_NAME}"+ cursor = (response.get("response_metadata") or {}).get("next_cursor") or ""+ if not cursor:+ return None+ logger.warning("slack_app_inbox_channel_scan_exhausted")+ return None+++def _claim_channel_creation(slack_team_id: str) -> bool:+ return bool(+ cache.add(f"slack_app:inbox_channel_create:v1:{slack_team_id}", True, timeout=_CHANNEL_CLAIM_TTL_SECONDS)+ )+++def ensure_inbox_channel(integration: Integration) -> tuple[str, str] | None:+ """Find-or-create #posthog-inbox, persist it as the team's default notification channel,+ and return (channel_id, "#name"). Returns None when the channel must be created but the+ install lacks ``channels:manage`` — callers fall back to manual instructions.++ Idempotent: reuses the configured channel, then any existing #posthog-inbox, before creating.+ """+ slack = SlackIntegration(integration)+ team_id = integration.team_id++ configured = _get_team_channel(team_id)+ if configured:+ channel_id = channel_id_from_target(configured)+ if _channel_exists(slack, channel_id):+ return channel_id, channel_name_from_target(configured)++ # Without channels:manage we can't create, so the only option is to find an already-created channel.+ if slack.missing_scopes(INBOX_CHANNEL_REQUIRED_SCOPES):+ existing = _find_inbox_channel(slack)+ if existing:+ _set_team_channel(team_id, _channel_target(*existing))+ return existing+ return None++ if not _claim_channel_creation(integration.integration_id):+ # Another actor holds the create claim. Reuse what they made; if not visible yet, bail rather+ # than racing a second create — the claim holder will finish and persist it.+ existing = _find_inbox_channel(slack)+ if existing:+ _set_team_channel(team_id, _channel_target(*existing))+ return existing+ return None++ # Create straight away instead of scanning every channel first — a full conversations_list sweep is+ # heavy and rate-limit-hungry, and on a fresh install (the common case) it finds nothing. If the+ # channel already exists Slack answers name_taken; only then do we pay for a scan to resolve its id.+ try:+ channel: dict = slack.client.conversations_create(name=INBOX_CHANNEL_NAME, is_private=False)["channel"]+ result: tuple[str, str] = (channel["id"], f"#{INBOX_CHANNEL_NAME}")+ except SlackApiError as e:+ if e.response.get("error") != "name_taken":+ logger.warning("slack_app_inbox_create_failed", integration_id=integration.id, error=str(e))+ return None+ found = _find_inbox_channel(slack)+ if found is None:+ logger.warning("slack_app_inbox_name_taken_but_not_found", integration_id=integration.id)+ return None+ result = found++ _set_team_channel(team_id, _channel_target(*result))+ return result+++def invite_user_to_inbox(integration: Integration, channel_id: str, slack_user_id: str) -> bool:+ """Invite a Slack user into the inbox channel; existing membership counts as success.++ A bot isn't auto-added to a channel it creates and can't invite others to one it's not in, so on+ ``not_in_channel`` the bot joins and retries.+ """+ slack = SlackIntegration(integration)+ for attempt in range(2):+ try:+ slack.client.conversations_invite(channel=channel_id, users=slack_user_id)+ return True+ except SlackApiError as e:+ error = e.response.get("error")+ if error == "already_in_channel":+ return True+ if error == "not_in_channel" and attempt == 0:+ try:+ slack.client.conversations_join(channel=channel_id)+ except SlackApiError as join_error:+ logger.warning(+ "slack_app_inbox_join_failed",+ integration_id=integration.id,+ error=join_error.response.get("error"),+ )+ return False+ continue+ logger.warning("slack_app_inbox_invite_failed", integration_id=integration.id, error=error)+ return False+ return False+++def is_inbox_channel(integration: Integration, channel_id: str) -> bool:+ """True when ``channel_id`` is this team's inbox channel — by configured id, else by name+ (the name fallback covers the window before the team default is written)."""+ configured = _get_team_channel(integration.team_id)+ if configured and channel_id_from_target(configured) == channel_id:+ return True+ try:+ channel = SlackIntegration(integration).client.conversations_info(channel=channel_id).get("channel") or {}+ except SlackApiError:+ return False+ return channel.get("name") == INBOX_CHANNEL_NAME+++def _is_channel_member(slack: SlackIntegration, channel_id: str, slack_user_id: str) -> bool:+ """Whether ``slack_user_id`` is already in ``channel_id``. Bounded + fails closed (False)."""+ cursor: str | None = None+ for _ in range(_MAX_CHANNEL_LIST_PAGES):+ try:+ response = slack.client.conversations_members(channel=channel_id, limit=200, cursor=cursor or None)+ except SlackApiError:+ return False+ if slack_user_id in (response.get("members") or []):+ return True+ cursor = (response.get("response_metadata") or {}).get("next_cursor") or ""+ if not cursor:+ return False+ return Falsediff --git a/products/slack_app/backend/onboarding.py b/products/slack_app/backend/onboarding.pynew file mode 100644index 000000000000..15072d431f4e--- /dev/null+++ b/products/slack_app/backend/onboarding.py@@ -0,0 +1,482 @@+"""Inbox onboarding DM: a product intro built from four steps (GitHub, sources, reports/channel, AI approval).++Block builders assemble the message, ``send_onboarding_dm`` delivers it, and the interactivity helpers+(called from ``api.py``) handle each click. ``run_install_onboarding`` is the install entrypoint.+"""++from __future__ import annotations++import json+from enum import StrEnum++from django.conf import settings++import structlog+from slack_sdk.errors import SlackApiError++from posthog.models import OrganizationMembership, Team+from posthog.models.integration import Integration, SlackIntegration+from posthog.models.user_integration import UserIntegration+from posthog.utils import absolute_uri++from products.slack_app.backend.analytics import capture_slack_event+from products.slack_app.backend.inbox_channel import (+ INBOX_CHANNEL_REQUIRED_SCOPES,+ _channel_exists,+ _get_team_channel,+ _is_channel_member,+ channel_id_from_target,+ channel_name_from_target,+ ensure_inbox_channel,+ has_inbox_scopes,+ invite_user_to_inbox,+)++logger = structlog.get_logger(__name__)++# Block Kit action ids for the onboarding DM, kept in sync with the interactivity router.+INBOX_CREATE_ACTION_ID = "slack_inbox_create"+INBOX_JOIN_ACTION_ID = "slack_inbox_join"+# The block_id carries the integration id so the checkbox interaction can be region-routed.+INBOX_SOURCES_CHECKBOXES_ACTION = "slack_inbox_sources_select"+INBOX_SOURCES_BLOCK_PREFIX = "slack_inbox_sources_block"+# AI approval is a hard prerequisite — without it no signals are emitted. block_id carries the integration id.+INBOX_AI_APPROVAL_ACTION_ID = "slack_inbox_ai_approval"+INBOX_AI_APPROVAL_BLOCK_PREFIX = "slack_inbox_ai_approval_block"+++class OnboardingStep(StrEnum):+ AI_APPROVAL = "ai_approval"+ CHANNEL = "channel"+ GITHUB = "github"+ SOURCES = "sources"+++EVENT_DM_SENT = "slack_onboarding_dm_sent"+EVENT_STEP_COMPLETED = "slack_onboarding_step_completed"+EVENT_COMPLETED = "slack_onboarding_completed"+EVENT_SOURCE_ENABLED = "slack_onboarding_source_enabled"++_REQUIRED_STEPS = (OnboardingStep.AI_APPROVAL, OnboardingStep.CHANNEL, OnboardingStep.GITHUB, OnboardingStep.SOURCES)+++# =====================================================================+# Block Kit primitives + per-step block builders+# =====================================================================+++def _section(text: str) -> dict:+ return {"type": "section", "text": {"type": "mrkdwn", "text": text}}+++def _button(label: str, action_id: str, value: str) -> dict:+ return {+ "type": "button",+ "text": {"type": "plain_text", "text": label},+ "action_id": action_id,+ "value": value,+ "style": "primary",+ }+++def _public_url(path: str) -> str:+ """Public base URL for links delivered to Slack. In local dev, prefer the ngrok tunnel so the link+ is reachable from outside (mirrors ``OauthIntegration.redirect_uri``)."""+ if settings.DEBUG and settings.NGROK_URL:+ return f"{settings.NGROK_URL.rstrip('/')}{path}"+ return absolute_uri(path)+++def _done(text: str) -> dict:+ return _context(f":white_check_mark: {text}")+++def _context(text: str) -> dict:+ return {"type": "context", "elements": [{"type": "mrkdwn", "text": text}]}+++def _github_connect_url(team_id: int) -> str:+ """GitHub OAuth entry that returns to Slack — one flow connects the team install and the user's personal GitHub."""+ return _public_url(f"/integrations/connect/github/?project_id={team_id}&connect_from=slack")+++def _github_blocks(integration: Integration, *, done: bool) -> list[dict]:+ blocks: list[dict] = [+ _section(+ "*1. Connect your codebase* :wrench:\nConnect GitHub so I can fix things, not just flag them - "+ "when I spot a problem in your product I'll proactively open a pull request with the fix for you to review."+ )+ ]+ if done:+ blocks.append(_done("Connected"))+ return blocks+ # Pure URL button (no action_id): clicking just opens OAuth in the browser and fires no+ # interaction. The callback returns to Slack; the message updates next time it's rebuilt.+ button = {+ "type": "button",+ "text": {"type": "plain_text", "text": "Connect GitHub"},+ "url": _github_connect_url(integration.team_id),+ "style": "primary",+ }+ blocks.append({"type": "actions", "elements": [button]})+ return blocks+++def _sources_blocks(integration: Integration) -> list[dict]:+ """Inline checkboxes (current state pre-checked) — ticking sets a source up immediately, unticking turns it off."""+ from products.signals.backend.facade.api import (+ onboarding_sources, # noqa: PLC0415 — keeps the signals stack off the slack import path+ )++ sources = onboarding_sources(integration.team_id)+ options = [+ {+ "text": {"type": "mrkdwn", "text": f"*{source.label}*: {source.description}"},+ "value": source.key,+ }+ for source in sources+ ]+ checkboxes: dict = {"type": "checkboxes", "action_id": INBOX_SOURCES_CHECKBOXES_ACTION, "options": options}+ initial = [option for option, source in zip(options, sources) if source.enabled]+ if initial:+ checkboxes["initial_options"] = initial+ return [+ _section("*2. Choose what I watch* :eyes:\nTick the signals I should monitor and investigate."),+ {"type": "actions", "block_id": f"{INBOX_SOURCES_BLOCK_PREFIX}:{integration.id}", "elements": [checkboxes]},+ ]+++def _channel_blocks(integration: Integration, slack: SlackIntegration, *, done: bool) -> list[dict]:+ blocks: list[dict] = [+ _section(+ "*3. Where I report* :inbox_tray:\nEverything I find lands in one shared channel so the team stays in the loop."+ )+ ]+ if done:+ blocks.append(_done("Posting to #posthog-inbox"))+ return blocks+ configured = _get_team_channel(integration.team_id)+ channel_exists = configured is not None and _channel_exists(slack, channel_id_from_target(configured))+ has_scope = not slack.missing_scopes(INBOX_CHANNEL_REQUIRED_SCOPES)+ value = json.dumps({"integration_id": integration.id})+ name = channel_name_from_target(configured or "") if channel_exists else "#posthog-inbox"+ if channel_exists and has_scope:+ blocks.append({"type": "actions", "elements": [_button(f"Join {name}", INBOX_JOIN_ACTION_ID, value)]})+ elif channel_exists:+ blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": f"Join {name} in your workspace."}]})+ elif has_scope:+ blocks.append(+ {"type": "actions", "elements": [_button("Create #posthog-inbox", INBOX_CREATE_ACTION_ID, value)]}+ )+ else:+ blocks.append(+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": f"Create a #posthog-inbox channel, then set it in your <{_public_url('/inbox')}|inbox>.",+ }+ ],+ }+ )+ return blocks+++def _ai_approval_blocks(integration: Integration, *, is_admin: bool) -> list[dict]:+ """The approval prompt — only rendered when not yet approved. Admins tick a checkbox to approve;+ non-admins get an 'ask an admin' note, since only ADMIN+ can toggle org settings."""+ blocks: list[dict] = [+ _section(+ "*4. Approve AI data processing*\nTo investigate your product I use external AI "+ "providers (Anthropic, OpenAI, Google, Microsoft). This can involve transferring identifying user data, "+ "and is never used to train third-party models. FYI it's not HIPAA-compliant yet, and any BAA you have "+ "with PostHog won't cover these features."+ )+ ]+ if not is_admin:+ blocks.append(+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": ":warning: Ask an org admin to approve. Until then I can't get started.",+ }+ ],+ }+ )+ return blocks+ blocks.append(+ {+ "type": "actions",+ "block_id": f"{INBOX_AI_APPROVAL_BLOCK_PREFIX}:{integration.id}",+ "elements": [+ {+ "type": "checkboxes",+ "action_id": INBOX_AI_APPROVAL_ACTION_ID,+ "options": [+ {"text": {"type": "plain_text", "text": "Approve AI data processing"}, "value": "approve"}+ ],+ }+ ],+ }+ )+ return blocks+++# Slack has no disabled buttons; a context block is the idiomatic greyed/done state.+def _replace_actions_with_context(blocks: list[dict], action_ids: set[str], text: str) -> list[dict]:+ return [+ _context(text)+ if (+ block.get("type") == "actions"+ and any(el.get("action_id") in action_ids for el in block.get("elements", []))+ )+ else block+ for block in blocks+ ]+++# =====================================================================+# Assembly, delivery, status, completion+# =====================================================================+++def build_onboarding_dm(+ integration: Integration,+ slack: SlackIntegration,+ *,+ needs_ai_approval: bool = False,+ ai_approval_is_admin: bool = True,+ needs_github: bool = False,+ already_in_channel: bool = False,+) -> tuple[str, list[dict]]:+ """Return (fallback_text, Block Kit blocks) for the inbox onboarding DM.++ Every step is always shown with its state (done steps render a '✅' line). AI approval is the one+ exception: omitted once approved. Always returns a full message — the DM is posted unconditionally.+ """+ intro = _section(+ "👋 *Hi, I'm PostHog - self-driving for your product*\nI'm an AI agent on autopilot: I watch your product "+ "for problems, investigate them myself, and open pull requests to fix them - so issues get handled before "+ "they reach your backlog."+ )+ blocks: list[dict] = [intro, {"type": "divider"}]+ blocks += _github_blocks(integration, done=not needs_github)+ blocks += _sources_blocks(integration)+ blocks += _channel_blocks(integration, slack, done=already_in_channel)+ if needs_ai_approval:+ blocks += _ai_approval_blocks(integration, is_admin=ai_approval_is_admin)+ blocks.append(+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": "🎉 Once you're set up, I'll start watching your product and send your first report to #posthog-inbox as soon as I spot something.",+ }+ ],+ }+ )+ return "Set up PostHog - self-driving for your product", blocks+++def _has_team_github(team_id: int) -> bool:+ return Integration.objects.filter(team_id=team_id, kind="github").exists()+++def _has_personal_github(user_id: int) -> bool:+ return UserIntegration.objects.filter(user_id=user_id, kind=UserIntegration.IntegrationKind.GITHUB).exists()+++def _has_ai_approval(team_id: int) -> bool:+ org_approved = (+ Team.objects.filter(id=team_id).values_list("organization__is_ai_data_processing_approved", flat=True).first()+ )+ return bool(org_approved)+++def _is_org_admin(user_id: int, team_id: int) -> bool:+ """Whether the user can toggle org settings (AI consent needs ADMIN+)."""+ org_id = Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()+ if org_id is None:+ return False+ level = (+ OrganizationMembership.objects.filter(organization_id=org_id, user_id=user_id)+ .values_list("level", flat=True)+ .first()+ )+ return level is not None and level >= OrganizationMembership.Level.ADMIN+++def _has_enabled_source(team_id: int) -> bool:+ from products.signals.backend.facade.api import (+ has_enabled_source, # noqa: PLC0415 — keeps the signals stack off the slack import path+ )++ return has_enabled_source(team_id)+++def _resolve_onboarding_user(slack: SlackIntegration, integration: Integration, slack_user_id: str) -> int | None:+ """Resolve the Slack user to a PostHog user id (org-member email match), or None."""+ from products.slack_app.backend.api import (+ resolve_slack_user, # noqa: PLC0415 — api.py imports this module; defer to break the cycle+ )++ context = resolve_slack_user(slack, integration, slack_user_id, "", "", post_feedback=False)+ return context.user.id if context else None+++def _onboarding_status(+ integration: Integration, slack: SlackIntegration, slack_user_id: str, user_id: int | None = None+) -> tuple[int | None, dict[OnboardingStep, bool]]:+ """Resolve the user and evaluate each step's done/not-done — the source of truth for what's left.+ Pass ``user_id`` when the caller already resolved it, to skip the repeat lookup."""+ # GitHub is done only when both the team install and the user's personal GitHub exist.+ if user_id is None:+ user_id = _resolve_onboarding_user(slack, integration, slack_user_id)+ team_id = integration.team_id+ configured = _get_team_channel(team_id)+ in_channel = configured is not None and _is_channel_member(slack, channel_id_from_target(configured), slack_user_id)+ return user_id, {+ OnboardingStep.AI_APPROVAL: _has_ai_approval(team_id),+ OnboardingStep.CHANNEL: in_channel,+ OnboardingStep.GITHUB: (user_id is None or _has_personal_github(user_id)) and _has_team_github(team_id),+ OnboardingStep.SOURCES: _has_enabled_source(team_id),+ }+++def _build_from_status(+ integration: Integration, slack: SlackIntegration, user_id: int | None, status: dict[OnboardingStep, bool]+) -> tuple[str, list[dict]]:+ is_admin = user_id is not None and _is_org_admin(user_id, integration.team_id)+ return build_onboarding_dm(+ integration,+ slack,+ needs_ai_approval=not status[OnboardingStep.AI_APPROVAL],+ ai_approval_is_admin=is_admin,+ needs_github=not status[OnboardingStep.GITHUB],+ already_in_channel=status[OnboardingStep.CHANNEL],+ )+++def send_onboarding_dm(integration: Integration, slack_user_id: str) -> bool:+ """DM a user the inbox onboarding. Returns True when sent, False when the post failed.++ Always posts (no dedupe, no all-done shortcut) — the install hook already fires only once.+ """+ if not slack_user_id:+ return False+ slack = SlackIntegration(integration)+ user_id, status = _onboarding_status(integration, slack, slack_user_id)+ text, blocks = _build_from_status(integration, slack, user_id, status)+ try:+ slack.client.chat_postMessage(channel=slack_user_id, text=text, blocks=blocks)+ except SlackApiError as e:+ logger.warning("slack_inbox_onboarding_dm_failed", integration_id=integration.id, error=e.response.get("error"))+ return False+ capture_slack_event(+ integration,+ EVENT_DM_SENT,+ slack_user_id=slack_user_id,+ steps_needed=[str(step) for step, done in status.items() if not done],+ steps_total=len(status),+ is_admin=user_id is not None and _is_org_admin(user_id, integration.team_id),+ )+ return True+++def _maybe_complete(integration: Integration, slack_user_id: str, user_id: int | None = None) -> None:+ """Fire 'completed' once every required step is done. Pass ``user_id`` when already resolved."""+ _, status = _onboarding_status(integration, SlackIntegration(integration), slack_user_id, user_id)+ if all(status[step] for step in _REQUIRED_STEPS):+ capture_slack_event(integration, EVENT_COMPLETED, slack_user_id=slack_user_id)+++# =====================================================================+# Interactivity: click handlers (called from api.py's router)+# =====================================================================+++def _chat_update_blocks(integration: Integration, channel: str, message_ts: str, text: str, blocks: list[dict]) -> None:+ try:+ SlackIntegration(integration).client.chat_update(channel=channel, ts=message_ts, text=text, blocks=blocks)+ except SlackApiError as e:+ logger.warning(+ "slack_inbox_connect_update_failed", integration_id=integration.id, error=e.response.get("error")+ )+++def mark_channel_joined(+ integration: Integration, slack_user_id: str, channel: str, message_ts: str, original_blocks: list[dict]+) -> None:+ """After create/join: flip just the channel block to a '✅' line in place, then record completion."""+ swapped = _replace_actions_with_context(+ original_blocks,+ {INBOX_CREATE_ACTION_ID, INBOX_JOIN_ACTION_ID},+ ":white_check_mark: You're in your #posthog-inbox channel",+ )+ _chat_update_blocks(integration, channel, message_ts, "You're in your #posthog-inbox channel", swapped)+ capture_slack_event(+ integration, EVENT_STEP_COMPLETED, slack_user_id=slack_user_id, step=str(OnboardingStep.CHANNEL)+ )+ _maybe_complete(integration, slack_user_id)+++def apply_sources_selection(integration: Integration, slack_user_id: str, selected_keys: list[str]) -> list[str]:+ """Sync the team's sources to the new selection. Returns the labels of any that couldn't be turned+ on (AI data processing not approved yet)."""+ from products.signals.backend.facade.api import (+ set_sources, # noqa: PLC0415 — keeps the signals stack off the slack import path+ )++ user_id = _resolve_onboarding_user(SlackIntegration(integration), integration, slack_user_id)+ if user_id is None:+ # Can't tie the clicker to an org member — don't mutate team state.+ return []+ blocked = set_sources(integration.team_id, user_id, selected_keys)+ capture_slack_event(+ integration, EVENT_SOURCE_ENABLED, slack_user_id=slack_user_id, selected=list(selected_keys), blocked=blocked+ )+ _maybe_complete(integration, slack_user_id, user_id)+ return blocked+++def approve_ai_data_processing(integration: Integration, slack_user_id: str) -> bool:+ """Admin-only approval: re-checks ADMIN+ server-side, sets org consent, records completion.+ Returns False if the clicker isn't an admin."""+ user_id = _resolve_onboarding_user(SlackIntegration(integration), integration, slack_user_id)+ if user_id is None or not _is_org_admin(user_id, integration.team_id):+ return False+ org_id = Team.objects.filter(id=integration.team_id).values_list("organization_id", flat=True).first()+ if org_id is None:+ return False+ from posthog.models.organization import Organization # noqa: PLC0415++ # Save the instance (not a queryset .update()) so ModelActivityMixin records the consent change+ # in the activity log and updated_at is bumped.+ organization = Organization.objects.filter(id=org_id).first()+ if organization is None:+ return False+ organization.is_ai_data_processing_approved = True+ organization.save(update_fields=["is_ai_data_processing_approved", "updated_at"])+ capture_slack_event(+ integration, EVENT_STEP_COMPLETED, slack_user_id=slack_user_id, step=str(OnboardingStep.AI_APPROVAL)+ )+ _maybe_complete(integration, slack_user_id, user_id)+ return True+++def run_install_onboarding(integration: Integration) -> None:+ """On a fresh install: create the inbox channel, invite the installer, and DM them the onboarding.+ Gated on the install having ``channels:manage``; best-effort."""+ if not has_inbox_scopes(integration):+ return+ channel = ensure_inbox_channel(integration)+ installer = ((integration.config or {}).get("authed_user") or {}).get("id")+ if not installer:+ return+ if channel is not None:+ invite_user_to_inbox(integration, channel[0], installer)+ send_onboarding_dm(integration, installer)diff --git a/products/slack_app/backend/services/inbox_interactivity.py b/products/slack_app/backend/services/inbox_interactivity.pynew file mode 100644index 000000000000..e647d70fdf8e--- /dev/null+++ b/products/slack_app/backend/services/inbox_interactivity.py@@ -0,0 +1,179 @@+"""Slack interactivity handlers for the inbox onboarding DM (create/join channel, sources, AI approval).++Kept out of ``api.py`` to keep that module focused on routing — the interactivity dispatcher there+imports ``extract_inbox_hints`` (for region-ownership routing) and the ``handle_inbox_*`` entrypoints.+"""++from __future__ import annotations++import json+from typing import Any++from django.conf import settings+from django.http import HttpResponse++import requests+import structlog++from posthog.models.integration import Integration++from products.slack_app.backend import inbox_channel, onboarding++logger = structlog.get_logger(__name__)++SLACK_INTEGRATION_KIND = "slack"+++def extract_inbox_hints(payload: dict) -> int | None:+ """Integration id carried by an inbox onboarding interaction, used for region-ownership routing.+ Buttons carry it in their ``value``; the sources/AI checkboxes carry it in their block_id."""+ for action in payload.get("actions", []):+ action_id = action.get("action_id")+ if action_id in (+ onboarding.INBOX_CREATE_ACTION_ID,+ onboarding.INBOX_JOIN_ACTION_ID,+ ):+ try:+ value = json.loads(action.get("value") or "{}")+ except json.JSONDecodeError:+ continue+ integration_id = value.get("integration_id")+ if isinstance(integration_id, int):+ return integration_id+ continue+ block_id = action.get("block_id", "")+ for prefix in (onboarding.INBOX_SOURCES_BLOCK_PREFIX, onboarding.INBOX_AI_APPROVAL_BLOCK_PREFIX):+ if block_id.startswith(f"{prefix}:"):+ suffix = block_id.split(":", 1)[1]+ return int(suffix) if suffix.isdigit() else None+ return None+++def post_response_url(response_url: str, body: dict[str, Any]) -> None:+ """POST a body to a Slack interactivity ``response_url``. Best-effort: failures are logged, never+ raised, so a handler that already did its DB work isn't broken by a Slack hiccup."""+ if not response_url:+ return+ try:+ requests.post(response_url, json=body, timeout=3)+ except Exception:+ logger.warning("slack_app_response_url_post_failed", exc_info=True)+++def _replace_message_via_response_url(response_url: str, text: str, blocks: list[dict] | None = None) -> None:+ body: dict[str, Any] = {"replace_original": True, "text": text}+ if blocks is not None:+ body["blocks"] = blocks+ post_response_url(response_url, body)+++def _post_ephemeral_via_response_url(response_url: str, text: str) -> None:+ """Post a transient note next to the message (doesn't touch the message itself)."""+ post_response_url(response_url, {"response_type": "ephemeral", "replace_original": False, "text": text})+++def _inbox_integration_from_payload(payload: dict) -> Integration | None:+ integration_id = extract_inbox_hints(payload)+ slack_team_id = payload.get("team", {}).get("id")+ if not integration_id or not slack_team_id:+ return None+ return 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,+ ).first()+++def _reconnect_hint() -> str:+ return (+ "PostHog needs the `channels:manage` permission for this. "+ f"Ask a project admin to reconnect Slack ({settings.SITE_URL}/settings/project-integrations), then try again."+ )+++def handle_inbox_create(payload: dict) -> HttpResponse:+ """'Create the PostHog inbox channel' button: create #posthog-inbox and invite the clicker."""+ integration = _inbox_integration_from_payload(payload)+ slack_user_id = payload.get("user", {}).get("id", "")+ response_url = payload.get("response_url", "")+ if integration is None or not slack_user_id:+ return HttpResponse(status=200)++ channel = inbox_channel.ensure_inbox_channel(integration)+ if channel is None:+ _replace_message_via_response_url(response_url, f"I couldn't create the channel. {_reconnect_hint()}")+ return HttpResponse(status=200)++ inbox_channel.invite_user_to_inbox(integration, channel[0], slack_user_id)+ dm_channel = payload.get("channel", {}).get("id") or payload.get("container", {}).get("channel_id")+ message_ts = payload.get("message", {}).get("ts")+ if dm_channel and message_ts:+ onboarding.mark_channel_joined(+ integration, slack_user_id, dm_channel, message_ts, payload.get("message", {}).get("blocks", [])+ )+ return HttpResponse(status=200)+++def handle_inbox_join(payload: dict) -> HttpResponse:+ """'Join' button: invite the clicker into the team's existing inbox channel."""+ integration = _inbox_integration_from_payload(payload)+ slack_user_id = payload.get("user", {}).get("id", "")+ response_url = payload.get("response_url", "")+ if integration is None or not slack_user_id:+ return HttpResponse(status=200)++ channel = inbox_channel.ensure_inbox_channel(integration)+ if channel is None:+ _replace_message_via_response_url(+ response_url, "Your team's inbox channel isn't available right now — please try again shortly."+ )+ return HttpResponse(status=200)++ if inbox_channel.invite_user_to_inbox(integration, channel[0], slack_user_id):+ dm_channel = payload.get("channel", {}).get("id") or payload.get("container", {}).get("channel_id")+ message_ts = payload.get("message", {}).get("ts")+ if dm_channel and message_ts:+ onboarding.mark_channel_joined(+ integration, slack_user_id, dm_channel, message_ts, payload.get("message", {}).get("blocks", [])+ )+ else:+ _replace_message_via_response_url(response_url, f"I couldn't add you. {_reconnect_hint()}")+ return HttpResponse(status=200)+++def handle_inbox_ai_approval(payload: dict) -> HttpResponse:+ """'Approve AI data processing' checkbox: ticking it approves. The approve helper re-checks ADMIN+ server-side."""+ integration = _inbox_integration_from_payload(payload)+ slack_user_id = payload.get("user", {}).get("id", "")+ action = next(+ (a for a in payload.get("actions", []) if a.get("action_id") == onboarding.INBOX_AI_APPROVAL_ACTION_ID),+ None,+ )+ ticked = any(o.get("value") == "approve" for o in (action or {}).get("selected_options", []))+ if integration and slack_user_id and ticked:+ if not onboarding.approve_ai_data_processing(integration, slack_user_id):+ _post_ephemeral_via_response_url(+ payload.get("response_url", ""),+ ":warning: Only an organization admin can approve AI data processing.",+ )+ return HttpResponse(status=200)+++def handle_inbox_sources(payload: dict) -> HttpResponse:+ """Sources checkbox toggled: sync the team's sources to the new selection, in place."""+ integration = _inbox_integration_from_payload(payload)+ slack_user_id = payload.get("user", {}).get("id", "")+ if integration is None or not slack_user_id:+ return HttpResponse(status=200)+ action = next(+ (a for a in payload.get("actions", []) if a.get("action_id") == onboarding.INBOX_SOURCES_CHECKBOXES_ACTION),+ None,+ )+ selected = [o.get("value") for o in (action or {}).get("selected_options", []) if o.get("value")]+ blocked = onboarding.apply_sources_selection(integration, slack_user_id, selected)+ if blocked:+ _post_ephemeral_via_response_url(+ payload.get("response_url", ""),+ f":warning: Approve AI data processing first to turn on *{', '.join(blocked)}*.",+ )+ return HttpResponse(status=200)diff --git a/products/slack_app/backend/signals.py b/products/slack_app/backend/signals.pyindex a584fbaf96b4..589b72a8b4c0 100644--- a/products/slack_app/backend/signals.py+++ b/products/slack_app/backend/signals.py@@ -1,8 +1,10 @@from typing import Any+from django.db import transactionfrom django.db.models.signals import post_delete, post_savefrom django.dispatch import receiver+from posthog.models.integration import Integrationfrom posthog.models.user_integration import UserIntegration@@ -11,10 +13,58 @@ from posthog.models.user_integration import UserIntegrationdef invalidate_repo_list_on_user_github_change(sender: Any, instance: UserIntegration, **kwargs) -> None:if instance.kind != UserIntegration.IntegrationKind.GITHUB:return- # Deferred: products.slack_app.backend.api imports posthog.temporal.ai workflows at module- # scope, which pulls the whole ee.hogai chat-agent core. This receiver is wired from- # AppConfig.ready(), so a module-level import would drag the AI core into every process's- # startup. The cache helper is only needed when a GitHub integration actually changes.+ # Deferred: api.py imports the temporal.ai workflows (the whole ee.hogai core) at module scope.+ # This receiver is wired from AppConfig.ready(), so a module-level import would drag that onto+ # every process's startup path.from products.slack_app.backend.api import _invalidate_user_repo_list_cache # noqa: PLC0415_invalidate_user_repo_list_cache(instance.user_id)+++@receiver(post_save, sender=Integration)+def onboard_slack_inbox_on_install(sender: Any, instance: Integration, created: bool, **kwargs) -> None:+ """Fresh Slack install -> enqueue the #posthog-inbox onboarding Temporal workflow on commit (the+ enqueue runs inline; the workflow itself runs on a Temporal worker). Gated on ``channels:manage``.+ Re-auth uses update_or_create (created=False), so only first installs onboard."""+ if not created or instance.kind != "slack":+ return++ # Deferred: keep the import lazy since this receiver is wired from AppConfig.ready().+ from products.slack_app.backend.inbox_channel import has_inbox_scopes # noqa: PLC0415++ if not has_inbox_scopes(instance):+ return++ integration_id = instance.id+ transaction.on_commit(lambda: _start_inbox_onboarding_workflow(integration_id))+++def _start_inbox_onboarding_workflow(integration_id: int) -> None:+ # Deferred imports keep the Temporal stack off the signals (AppConfig.ready) import path.+ import asyncio++ from django.conf import settings++ import structlog+ from temporalio.common import WorkflowIDReusePolicy++ from posthog.temporal.ai.slack_app.posthog_slack_inbox_onboarding import ( # noqa: PLC0415+ PostHogSlackInboxOnboardingWorkflow,+ )+ from posthog.temporal.ai.slack_app.types import PostHogSlackInboxOnboardingInputs # noqa: PLC0415+ from posthog.temporal.common.client import sync_connect # noqa: PLC0415++ log = structlog.get_logger(__name__)+ try:+ client = sync_connect()+ asyncio.run(+ client.start_workflow(+ PostHogSlackInboxOnboardingWorkflow.run,+ PostHogSlackInboxOnboardingInputs(integration_id=integration_id),+ id=f"posthog-slack-inbox-onboarding-{integration_id}",+ task_queue=settings.TASKS_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ )+ )+ except Exception:+ log.warning("slack_app_inbox_onboarding_dispatch_failed", integration_id=integration_id, exc_info=True)diff --git a/products/slack_app/backend/tests/test_inbox_channel.py b/products/slack_app/backend/tests/test_inbox_channel.pynew file mode 100644index 000000000000..00c0ab0de9dd--- /dev/null+++ b/products/slack_app/backend/tests/test_inbox_channel.py@@ -0,0 +1,239 @@+import pytest+from unittest.mock import MagicMock, patch++from django.core.cache import cache++from slack_sdk.errors import SlackApiError++from posthog.models.integration import Integration, SlackIntegration+from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.models.user import User++from products.signals.backend.facade.api import (+ get_default_slack_notification_channel,+ set_default_slack_notification_channel,+)+from products.slack_app.backend import inbox_channel+++class TestInboxChannel:+ @pytest.fixture(autouse=True)+ def setup(self, db):+ cache.clear()+ self.organization = Organization.objects.create(name="Org")+ self.team = Team.objects.create(organization=self.organization, name="Team")+ self.user = User.objects.create(email="[email protected]", first_name="Installer")+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T12345",+ config={"scope": "channels:manage,chat:write"},+ sensitive_config={"access_token": "xoxb-test"},+ )++ def _client(self, mock_webclient_class):+ client = MagicMock()+ # Default: empty membership so onboarding DMs render normally unless a test says otherwise.+ client.conversations_members.return_value = {"members": [], "response_metadata": {"next_cursor": ""}}+ mock_webclient_class.return_value = client+ return client++ @patch("posthog.models.integration.WebClient")+ def test_creates_channel_and_sets_team_default(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}+ client.conversations_create.return_value = {"channel": {"id": "C999"}}++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result == ("C999", "#posthog-inbox")+ client.conversations_create.assert_called_once_with(name="posthog-inbox", is_private=False)+ assert get_default_slack_notification_channel(self.team.id) == "C999|#posthog-inbox"++ @patch("posthog.models.integration.WebClient")+ def test_reuses_configured_channel(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C777|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C777"}}++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result == ("C777", "#posthog-inbox")+ client.conversations_create.assert_not_called()+ client.conversations_list.assert_not_called()++ @patch("posthog.models.integration.WebClient")+ def test_reuses_existing_channel_by_name_without_manage_scope(self, mock_webclient_class):+ # Without channels:manage we can't create, so the only path is to find an existing channel by name.+ client = self._client(mock_webclient_class)+ self.integration.config = {"scope": "chat:write"}+ self.integration.save()+ client.conversations_list.return_value = {+ "channels": [{"id": "C555", "name": "posthog-inbox"}],+ "response_metadata": {"next_cursor": ""},+ }++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result == ("C555", "#posthog-inbox")+ client.conversations_create.assert_not_called()+ assert get_default_slack_notification_channel(self.team.id) == "C555|#posthog-inbox"++ @patch("posthog.models.integration.WebClient")+ def test_create_name_taken_falls_back_to_lookup(self, mock_webclient_class):+ # Create-first: we attempt to create straight away; name_taken triggers the lookup to resolve the id.+ client = self._client(mock_webclient_class)+ client.conversations_list.return_value = {+ "channels": [{"id": "C111", "name": "posthog-inbox"}],+ "response_metadata": {"next_cursor": ""},+ }+ client.conversations_create.side_effect = SlackApiError("name_taken", {"error": "name_taken"})++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result == ("C111", "#posthog-inbox")+ assert get_default_slack_notification_channel(self.team.id) == "C111|#posthog-inbox"++ @patch("posthog.models.integration.WebClient")+ def test_missing_scope_and_no_channel_returns_none(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ self.integration.config = {"scope": "chat:write"}+ self.integration.save()+ client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result is None+ client.conversations_create.assert_not_called()+ assert get_default_slack_notification_channel(self.team.id) is None++ @patch("posthog.models.integration.WebClient")+ def test_has_inbox_scopes(self, mock_webclient_class):+ self._client(mock_webclient_class)++ self.integration.config = {"scope": "channels:manage,chat:write"}+ self.integration.save()+ assert inbox_channel.has_inbox_scopes(self.integration) is True++ self.integration.config = {"scope": "chat:write"}+ self.integration.save()+ assert inbox_channel.has_inbox_scopes(self.integration) is False++ @patch("posthog.models.integration.WebClient")+ def test_is_inbox_channel_by_configured_id(self, mock_webclient_class):+ self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C222|#posthog-inbox")++ assert inbox_channel.is_inbox_channel(self.integration, "C222") is True++ @patch("posthog.models.integration.WebClient")+ def test_is_inbox_channel_by_name_fallback(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.conversations_info.return_value = {"channel": {"id": "C333", "name": "posthog-inbox"}}++ assert inbox_channel.is_inbox_channel(self.integration, "C333") is True++ @patch("posthog.models.integration.WebClient")+ def test_is_inbox_channel_false_for_other_channel(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.conversations_info.return_value = {"channel": {"id": "C444", "name": "random"}}++ assert inbox_channel.is_inbox_channel(self.integration, "C444") is False++ @patch("posthog.models.integration.WebClient")+ def test_invite_success(self, mock_webclient_class):+ client = self._client(mock_webclient_class)++ assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is True+ client.conversations_invite.assert_called_once_with(channel="C1", users="U1")++ @patch("posthog.models.integration.WebClient")+ def test_invite_already_in_channel_is_success(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.conversations_invite.side_effect = SlackApiError("already_in_channel", {"error": "already_in_channel"})++ assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is True++ @patch("posthog.models.integration.WebClient")+ def test_invite_other_error_returns_false(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.conversations_invite.side_effect = SlackApiError("missing_scope", {"error": "missing_scope"})++ assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is False++ @patch("posthog.models.integration.WebClient")+ def test_invite_joins_and_retries_on_not_in_channel(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.conversations_invite.side_effect = [+ SlackApiError("not_in_channel", {"error": "not_in_channel"}),+ {"ok": True},+ ]++ assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is True+ client.conversations_join.assert_called_once_with(channel="C1")+ assert client.conversations_invite.call_count == 2++ @patch("posthog.models.integration.WebClient")+ def test_invite_returns_false_when_join_fails(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.conversations_invite.side_effect = SlackApiError("not_in_channel", {"error": "not_in_channel"})+ client.conversations_join.side_effect = SlackApiError("missing_scope", {"error": "missing_scope"})++ assert inbox_channel.invite_user_to_inbox(self.integration, "C1", "U1") is False++ @patch("posthog.models.integration.WebClient")+ def test_configured_channel_preserved_on_transient_error(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C_CUSTOM|#alerts")+ client.conversations_info.side_effect = SlackApiError("ratelimited", {"error": "ratelimited"})++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result == ("C_CUSTOM", "#alerts")+ client.conversations_create.assert_not_called()+ client.conversations_list.assert_not_called()+ assert get_default_slack_notification_channel(self.team.id) == "C_CUSTOM|#alerts"++ @patch("posthog.models.integration.WebClient")+ def test_configured_channel_replaced_when_definitely_gone(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C_OLD|#alerts")+ client.conversations_info.side_effect = SlackApiError("channel_not_found", {"error": "channel_not_found"})+ client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}+ client.conversations_create.return_value = {"channel": {"id": "C_NEW"}}++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result == ("C_NEW", "#posthog-inbox")+ assert get_default_slack_notification_channel(self.team.id) == "C_NEW|#posthog-inbox"++ @patch("posthog.models.integration.WebClient")+ def test_ensure_returns_none_when_create_claimed_by_other(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ cache.add("slack_app:inbox_channel_create:v1:T12345", True, timeout=60)+ client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result is None+ client.conversations_create.assert_not_called()++ @patch("posthog.models.integration.WebClient")+ def test_ensure_handles_conversations_list_error(self, mock_webclient_class):+ # name_taken sends us to the lookup; a transient list error there must fail closed (None).+ client = self._client(mock_webclient_class)+ client.conversations_create.side_effect = SlackApiError("name_taken", {"error": "name_taken"})+ client.conversations_list.side_effect = SlackApiError("ratelimited", {"error": "ratelimited"})++ result = inbox_channel.ensure_inbox_channel(self.integration)++ assert result is None++ @patch("posthog.models.integration.WebClient")+ def test_is_channel_member(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.conversations_members.return_value = {"members": ["U1", "U2"], "response_metadata": {"next_cursor": ""}}++ assert inbox_channel._is_channel_member(SlackIntegration(self.integration), "C1", "U1") is True+ assert inbox_channel._is_channel_member(SlackIntegration(self.integration), "C1", "U9") is Falsediff --git a/products/slack_app/backend/tests/test_onboarding.py b/products/slack_app/backend/tests/test_onboarding.pynew file mode 100644index 000000000000..5774c5056f48--- /dev/null+++ b/products/slack_app/backend/tests/test_onboarding.py@@ -0,0 +1,575 @@+import pytest+from unittest.mock import MagicMock, patch++from django.core.cache import cache++from slack_sdk.errors import SlackApiError++from posthog.models.integration import Integration, SlackIntegration+from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.models.user import User++from products.signals.backend.facade.api import (+ get_default_slack_notification_channel,+ set_default_slack_notification_channel,+)+from products.slack_app.backend import onboarding+++class TestOnboarding:+ @pytest.fixture(autouse=True)+ def setup(self, db):+ cache.clear()+ self.organization = Organization.objects.create(name="Org")+ self.team = Team.objects.create(organization=self.organization, name="Team")+ self.user = User.objects.create(email="[email protected]", first_name="Installer")+ self.integration = Integration.objects.create(+ team=self.team,+ kind="slack",+ integration_id="T12345",+ config={"scope": "channels:manage,chat:write"},+ sensitive_config={"access_token": "xoxb-test"},+ )++ def _client(self, mock_webclient_class):+ client = MagicMock()+ # Default: empty membership so onboarding DMs render normally unless a test says otherwise.+ client.conversations_members.return_value = {"members": [], "response_metadata": {"next_cursor": ""}}+ mock_webclient_class.return_value = client+ return client++ def _action_ids(self, blocks):+ ids = [el["action_id"] for b in blocks if b["type"] == "actions" for el in b["elements"] if "action_id" in el]+ ids += [b["accessory"]["action_id"] for b in blocks if (b.get("accessory") or {}).get("action_id")]+ return ids++ def _url_buttons(self, blocks):+ urls = [el["url"] for b in blocks if b["type"] == "actions" for el in b["elements"] if "url" in el]+ urls += [b["accessory"]["url"] for b in blocks if (b.get("accessory") or {}).get("url")]+ return urls++ def _all_text(self, blocks):+ parts: list[str] = []+ for b in blocks:+ if (b.get("text") or {}).get("text"):+ parts.append(b["text"]["text"])+ for f in b.get("fields", []):+ parts.append(f.get("text", ""))+ for el in b.get("elements", []):+ txt = el.get("text")+ parts.append(txt if isinstance(txt, str) else (txt or {}).get("text", ""))+ return " ".join(parts)++ @patch("posthog.models.integration.WebClient")+ def test_dm_join_button_when_channel_exists_with_scope(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}++ _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert onboarding.INBOX_JOIN_ACTION_ID in self._action_ids(blocks)++ @patch("posthog.models.integration.WebClient")+ def test_dm_instructions_when_channel_exists_without_scope(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ self.integration.config = {"scope": "chat:write"}+ self.integration.save()+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}++ _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(blocks)+ assert "workspace" in self._all_text(blocks)++ @patch("posthog.models.integration.WebClient")+ def test_dm_create_button_when_no_channel_with_scope(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert onboarding.INBOX_CREATE_ACTION_ID in self._action_ids(blocks)++ @patch("posthog.models.integration.WebClient")+ def test_dm_instructions_with_inbox_link_when_no_channel_no_scope(self, mock_webclient_class):+ self._client(mock_webclient_class)+ self.integration.config = {"scope": "chat:write"}+ self.integration.save()++ _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert onboarding.INBOX_CREATE_ACTION_ID not in self._action_ids(blocks)+ assert "/inbox" in self._all_text(blocks)++ @patch("posthog.models.integration.WebClient")+ def test_send_onboarding_dm_posts_each_call(self, mock_webclient_class):+ # No per-user dedupe — onboarding is sent once because the install hook fires once, not+ # because send_onboarding_dm suppresses repeats.+ client = self._client(mock_webclient_class)++ assert onboarding.send_onboarding_dm(self.integration, "U1") is True+ assert onboarding.send_onboarding_dm(self.integration, "U1") is True+ assert client.chat_postMessage.call_count == 2++ @patch("posthog.models.integration.WebClient")+ def test_send_onboarding_dm_skips_empty_user(self, mock_webclient_class):+ client = self._client(mock_webclient_class)++ assert onboarding.send_onboarding_dm(self.integration, "") is False+ client.chat_postMessage.assert_not_called()++ @patch("posthog.models.integration.WebClient")+ def test_run_install_onboarding_creates_invites_and_dms(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ self.integration.config = {"scope": "channels:manage,chat:write", "authed_user": {"id": "U_INSTALL"}}+ self.integration.save()+ client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}+ client.conversations_create.return_value = {"channel": {"id": "C_NEW"}}+ client.conversations_info.return_value = {"channel": {"id": "C_NEW"}}++ onboarding.run_install_onboarding(self.integration)++ client.conversations_create.assert_called_once()+ client.conversations_invite.assert_called_once_with(channel="C_NEW", users="U_INSTALL")+ assert client.chat_postMessage.called+ assert get_default_slack_notification_channel(self.team.id) == "C_NEW|#posthog-inbox"++ @patch("posthog.models.integration.WebClient")+ def test_run_install_onboarding_noop_when_missing_scope(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ # No channels:manage scope -> onboarding is gated off for this install.+ self.integration.config = {"scope": "chat:write", "authed_user": {"id": "U_INSTALL"}}+ self.integration.save()++ onboarding.run_install_onboarding(self.integration)++ client.conversations_create.assert_not_called()+ client.chat_postMessage.assert_not_called()++ @patch("posthog.models.integration.WebClient")+ def test_send_onboarding_dm_returns_false_on_post_failure(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ client.chat_postMessage.side_effect = [+ SlackApiError("channel_not_found", {"error": "channel_not_found"}),+ {"ok": True},+ ]++ assert onboarding.send_onboarding_dm(self.integration, "U1") is False+ assert onboarding.send_onboarding_dm(self.integration, "U1") is True+ assert client.chat_postMessage.call_count == 2++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_appends_github_button_when_missing(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = onboarding.build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_github=True+ )++ urls = self._url_buttons(blocks)+ assert any(+ f"/integrations/connect/github/?project_id={self.team.id}" in u and "connect_from=slack" in u for u in urls+ )+ assert onboarding.INBOX_CREATE_ACTION_ID in self._action_ids(blocks)++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_omits_join_when_already_member(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}++ _, blocks = onboarding.build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_github=False, already_in_channel=True+ )++ assert blocks != []+ assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(blocks)++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_already_member_shows_only_github(self, mock_webclient_class):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}++ _, blocks = onboarding.build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_github=True, already_in_channel=True+ )++ assert any("/integrations/connect/github/" in u for u in self._url_buttons(blocks))+ assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(blocks)++ @patch("products.slack_app.backend.onboarding._has_enabled_source", return_value=True)+ @patch("products.slack_app.backend.onboarding._has_team_github", return_value=True)+ @patch("products.slack_app.backend.onboarding._has_personal_github", return_value=True)+ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)+ @patch("posthog.models.integration.WebClient")+ def test_send_onboarding_dm_posts_even_when_all_steps_satisfied(+ self, mock_webclient_class, _resolve, _personal, _team, _responder+ ):+ # Install-only delivery: always post, even if every step is already done (shown as '✅').+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}+ client.conversations_members.return_value = {"members": ["U1"], "response_metadata": {"next_cursor": ""}}++ assert onboarding.send_onboarding_dm(self.integration, "U1") is True+ client.chat_postMessage.assert_called_once()++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_no_github_block_when_connected(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert not any("/integrations/connect/github" in u for u in self._url_buttons(blocks))++ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=123)+ @patch("products.slack_app.backend.onboarding._has_personal_github", return_value=False)+ @patch("products.slack_app.backend.onboarding._has_team_github", return_value=False)+ @patch("posthog.models.integration.WebClient")+ def test_send_onboarding_dm_includes_github_button(+ self, mock_webclient_class, _mock_team, _mock_personal, _mock_resolve+ ):+ client = self._client(mock_webclient_class)++ assert onboarding.send_onboarding_dm(self.integration, "U1") is True++ urls = self._url_buttons(client.chat_postMessage.call_args.kwargs["blocks"])+ assert any("/integrations/connect/github/" in u and "connect_from=slack" in u for u in urls)++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_sources_inline_checkboxes(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = onboarding.build_onboarding_dm(self.integration, SlackIntegration(self.integration))++ assert onboarding.INBOX_SOURCES_CHECKBOXES_ACTION in self._action_ids(blocks)+ checkboxes = next(+ el for b in blocks if b["type"] == "actions" for el in b["elements"] if el.get("type") == "checkboxes"+ )+ # only the two built-in toggle sources, no Linear / GitHub issues+ assert {o["value"] for o in checkboxes["options"]} == {"error_tracking", "session_replay"}+ block = next(b for b in blocks if b.get("block_id", "").startswith(onboarding.INBOX_SOURCES_BLOCK_PREFIX))+ assert block["block_id"] == f"{onboarding.INBOX_SOURCES_BLOCK_PREFIX}:{self.integration.id}"+ assert "Choose what I watch" in self._all_text(blocks)++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_shows_done_steps_as_checks(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = onboarding.build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), already_in_channel=True+ )++ # done steps render as '✅' lines, not pruned+ text = self._all_text(blocks)+ assert "Connected" in text+ assert "Posting to #posthog-inbox" in text+ assert onboarding.INBOX_SOURCES_CHECKBOXES_ACTION in self._action_ids(blocks)++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_omits_ai_approval_when_done(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = onboarding.build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_github=True+ )++ assert "AI data processing" not in " ".join(str(b) for b in blocks)++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_always_returns_message_even_when_all_done(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, all_done = onboarding.build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), already_in_channel=True+ )++ assert all_done != [] # posted unconditionally on install+ assert onboarding.INBOX_JOIN_ACTION_ID not in self._action_ids(all_done)+ assert not any("/integrations/connect/github" in u for u in self._url_buttons(all_done))++ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)+ @patch("posthog.models.integration.WebClient")+ def test_apply_sources_selection_syncs_checkboxes(self, mock_webclient_class, _resolve):+ from products.signals.backend.facade.api import has_enabled_source++ self._client(mock_webclient_class)+ _resolve.return_value = self.user.id++ assert onboarding.apply_sources_selection(self.integration, "U1", ["error_tracking"]) == []+ assert has_enabled_source(self.team.id) is True++ # unticking everything turns them back off (set-semantics)+ onboarding.apply_sources_selection(self.integration, "U1", [])+ assert has_enabled_source(self.team.id) is False++ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)+ @patch("posthog.models.integration.WebClient")+ def test_apply_sources_blocks_session_replay_without_ai_approval(self, mock_webclient_class, _resolve):+ from products.signals.backend.facade.api import has_enabled_source++ self._client(mock_webclient_class)+ _resolve.return_value = self.user.id+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])++ blocked = onboarding.apply_sources_selection(self.integration, "U1", ["session_replay"])++ assert blocked == ["Session replay analysis"] # surfaced so the handler can nudge the user+ assert has_enabled_source(self.team.id) is False++ @patch("products.slack_app.backend.services.inbox_interactivity._post_ephemeral_via_response_url")+ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)+ @patch("posthog.models.integration.WebClient")+ def test_sources_handler_nudges_when_session_replay_blocked(self, mock_webclient_class, _resolve, mock_ephemeral):+ from products.slack_app.backend.services import inbox_interactivity++ self._client(mock_webclient_class)+ _resolve.return_value = self.user.id+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ payload = {+ "team": {"id": "T12345"},+ "user": {"id": "U1"},+ "response_url": "https://hook",+ "actions": [+ {+ "action_id": onboarding.INBOX_SOURCES_CHECKBOXES_ACTION,+ "block_id": f"{onboarding.INBOX_SOURCES_BLOCK_PREFIX}:{self.integration.id}",+ "selected_options": [{"value": "session_replay"}],+ }+ ],+ }++ inbox_interactivity.handle_inbox_sources(payload)++ mock_ephemeral.assert_called_once()+ assert "Approve AI data processing" in mock_ephemeral.call_args.args[1]++ def test_set_sources_error_tracking_no_approval_needed(self):+ from products.signals.backend.facade.api import has_enabled_source, set_sources++ assert has_enabled_source(self.team.id) is False+ assert set_sources(self.team.id, None, ["error_tracking"]) == []+ assert has_enabled_source(self.team.id) is True++ def test_set_sources_session_replay_blocked_without_ai_approval(self):+ from products.signals.backend.facade.api import has_enabled_source, set_sources++ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])++ assert set_sources(self.team.id, None, ["session_replay"]) == ["Session replay analysis"]+ assert has_enabled_source(self.team.id) is False++ def test_set_sources_keeps_enabled_source_when_ai_later_revoked(self):+ from products.signals.backend.facade.api import has_enabled_source, set_sources++ self.organization.is_ai_data_processing_approved = True+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ assert set_sources(self.team.id, None, ["session_replay"]) == []+ assert has_enabled_source(self.team.id) is True++ # AI revoked: re-submitting the still-ticked selection must leave it enabled, not disable it.+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ assert set_sources(self.team.id, None, ["session_replay"]) == ["Session replay analysis"]+ assert has_enabled_source(self.team.id) is True++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_ai_approval_checkbox_for_admin_and_trails(self, mock_webclient_class):+ self._client(mock_webclient_class)++ text, blocks = onboarding.build_onboarding_dm(+ self.integration,+ SlackIntegration(self.integration),+ needs_ai_approval=True,+ ai_approval_is_admin=True,+ needs_github=True,+ )++ # Admin gets an inline checkbox (no browser/url) — approval happens in Slack.+ assert onboarding.INBOX_AI_APPROVAL_ACTION_ID in self._action_ids(blocks)+ assert not any("organization-details" in u for u in self._url_buttons(blocks))+ ai_block = next(+ b for b in blocks if b.get("block_id", "").startswith(onboarding.INBOX_AI_APPROVAL_BLOCK_PREFIX)+ )+ assert ai_block["elements"][0]["type"] == "checkboxes"+ assert "AI data processing" not in text # fixed notification text, not the step copy++ @patch("posthog.models.integration.WebClient")+ def test_build_dm_ai_approval_note_for_non_admin_no_button(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = onboarding.build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_ai_approval=True, ai_approval_is_admin=False+ )++ assert onboarding.INBOX_AI_APPROVAL_ACTION_ID not in self._action_ids(blocks)+ assert "Ask an org admin" in self._all_text(blocks)++ def test_has_ai_approval_reflects_org(self):+ assert onboarding._has_ai_approval(self.team.id) is True # default-approved org+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])+ assert onboarding._has_ai_approval(self.team.id) is False++ @patch("products.slack_app.backend.onboarding._is_org_admin", return_value=True)+ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)+ @patch("posthog.models.integration.WebClient")+ def test_approve_ai_data_processing_admin_sets_org_flag(self, mock_webclient_class, _resolve, _admin):+ self._client(mock_webclient_class)+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])++ ok = onboarding.approve_ai_data_processing(self.integration, "U1")++ assert ok is True+ self.organization.refresh_from_db()+ assert self.organization.is_ai_data_processing_approved is True++ @patch("products.slack_app.backend.onboarding._is_org_admin", return_value=False)+ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)+ @patch("posthog.models.integration.WebClient")+ def test_approve_ai_data_processing_non_admin_rejected(self, mock_webclient_class, _resolve, _admin):+ self._client(mock_webclient_class)+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])++ ok = onboarding.approve_ai_data_processing(self.integration, "U1")++ assert ok is False+ self.organization.refresh_from_db()+ assert self.organization.is_ai_data_processing_approved is False++ @patch("products.slack_app.backend.onboarding._is_org_admin", return_value=True)+ @patch("products.slack_app.backend.onboarding._has_enabled_source", return_value=True)+ @patch("products.slack_app.backend.onboarding._has_team_github", return_value=True)+ @patch("products.slack_app.backend.onboarding._has_personal_github", return_value=True)+ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)+ @patch("posthog.models.integration.WebClient")+ def test_send_onboarding_dm_gates_on_ai_approval_admin(+ self, mock_webclient_class, _resolve, _personal, _team, _responder, _admin+ ):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}+ client.conversations_members.return_value = {"members": ["U1"], "response_metadata": {"next_cursor": ""}}+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])++ # Everything else satisfied, but the unapproved org still triggers a DM — admin gets the button.+ assert onboarding.send_onboarding_dm(self.integration, "U1") is True+ blocks = client.chat_postMessage.call_args.kwargs["blocks"]+ assert onboarding.INBOX_AI_APPROVAL_ACTION_ID in self._action_ids(blocks)++ @patch("products.slack_app.backend.onboarding._is_org_admin", return_value=False)+ @patch("products.slack_app.backend.onboarding._has_enabled_source", return_value=True)+ @patch("products.slack_app.backend.onboarding._has_team_github", return_value=True)+ @patch("products.slack_app.backend.onboarding._has_personal_github", return_value=True)+ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=7)+ @patch("posthog.models.integration.WebClient")+ def test_send_onboarding_dm_non_admin_gets_note_not_button(+ self, mock_webclient_class, _resolve, _personal, _team, _responder, _admin+ ):+ client = self._client(mock_webclient_class)+ set_default_slack_notification_channel(self.team.id, "C1|#posthog-inbox")+ client.conversations_info.return_value = {"channel": {"id": "C1"}}+ client.conversations_members.return_value = {"members": ["U1"], "response_metadata": {"next_cursor": ""}}+ self.organization.is_ai_data_processing_approved = False+ self.organization.save(update_fields=["is_ai_data_processing_approved"])++ # A member can't approve, so they get an informational note (no button) and aren't blocked.+ assert onboarding.send_onboarding_dm(self.integration, "U1") is True+ blocks = client.chat_postMessage.call_args.kwargs["blocks"]+ assert onboarding.INBOX_AI_APPROVAL_ACTION_ID not in self._action_ids(blocks)+ assert "Ask an org admin" in self._all_text(blocks)++ def test_slack_event_props_bundle(self):+ from products.slack_app.backend.analytics import slack_event_props++ props = slack_event_props(self.integration, slack_user_id="U1", foo="bar")++ assert props["integration_id"] == self.integration.id+ assert props["slack_team_id"] == "T12345"+ assert props["team_id"] == self.team.id+ assert props["organization_id"] == str(self.organization.id)+ assert props["slack_user_id"] == "U1"+ assert props["foo"] == "bar"++ @patch("products.slack_app.backend.onboarding.capture_slack_event")+ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)+ @patch("posthog.models.integration.WebClient")+ def test_send_onboarding_dm_captures_dm_sent(self, mock_webclient_class, _resolve, mock_capture):+ client = self._client(mock_webclient_class)+ client.conversations_list.return_value = {"channels": [], "response_metadata": {"next_cursor": ""}}++ assert onboarding.send_onboarding_dm(self.integration, "U1") is True+ assert onboarding.EVENT_DM_SENT in [c.args[1] for c in mock_capture.call_args_list]++ @patch("products.slack_app.backend.onboarding.capture_slack_event")+ @patch("products.slack_app.backend.onboarding._resolve_onboarding_user", return_value=None)+ @patch("posthog.models.integration.WebClient")+ def test_apply_sources_captures_source_enabled(self, mock_webclient_class, _resolve, mock_capture):+ self._client(mock_webclient_class)+ _resolve.return_value = self.user.id++ onboarding.apply_sources_selection(self.integration, "U1", ["error_tracking"])++ assert onboarding.EVENT_SOURCE_ENABLED in [c.args[1] for c in mock_capture.call_args_list]++ @patch("products.slack_app.backend.onboarding.capture_slack_event")+ @patch("products.slack_app.backend.onboarding._onboarding_status")+ @patch("posthog.models.integration.WebClient")+ def test_maybe_complete_fires_completed_when_all_done(self, mock_webclient_class, mock_status, mock_capture):+ self._client(mock_webclient_class)+ mock_status.return_value = (7, dict.fromkeys(onboarding.OnboardingStep, True))++ onboarding._maybe_complete(self.integration, "U1")++ assert onboarding.EVENT_COMPLETED in [c.args[1] for c in mock_capture.call_args_list]++ @patch("products.slack_app.backend.onboarding.capture_slack_event")+ @patch("products.slack_app.backend.onboarding._onboarding_status")+ @patch("posthog.models.integration.WebClient")+ def test_maybe_complete_no_completed_when_remaining(self, mock_webclient_class, mock_status, mock_capture):+ self._client(mock_webclient_class)+ status = dict.fromkeys(onboarding.OnboardingStep, True)+ status[onboarding.OnboardingStep.GITHUB] = False+ mock_status.return_value = (7, status)++ onboarding._maybe_complete(self.integration, "U1")++ assert onboarding.EVENT_COMPLETED not in [c.args[1] for c in mock_capture.call_args_list]++ @patch("posthog.models.integration.WebClient")+ def test_dm_leads_with_self_driving_intro(self, mock_webclient_class):+ self._client(mock_webclient_class)++ _, blocks = onboarding.build_onboarding_dm(+ self.integration, SlackIntegration(self.integration), needs_github=True+ )++ assert blocks[0]["type"] == "section"+ assert "self-driving" in blocks[0]["text"]["text"]+ assert "first report" in self._all_text(blocks)++ @patch("products.slack_app.backend.onboarding.run_install_onboarding")+ def test_onboarding_workflow_activity_runs_for_integration(self, mock_run):+ from posthog.temporal.ai.slack_app.activities.onboarding import run_posthog_slack_inbox_onboarding++ run_posthog_slack_inbox_onboarding(self.integration.id)++ mock_run.assert_called_once()+ assert mock_run.call_args.args[0].id == self.integration.id++ @patch("products.slack_app.backend.onboarding.run_install_onboarding")+ def test_onboarding_workflow_activity_noop_for_missing_integration(self, mock_run):+ from posthog.temporal.ai.slack_app.activities.onboarding import run_posthog_slack_inbox_onboarding++ run_posthog_slack_inbox_onboarding(99999999)++ mock_run.assert_not_called()