:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(slack_app): unify the slack onboarding into one per-person flow (#128128)
Vojta Bartoš30fb54b4c3e6
diff --git a/docs/internal/slack-local-setup-guide.md b/docs/internal/slack-local-setup-guide.mdindex 36e174d154c5..3868e284b2c7 100644--- a/docs/internal/slack-local-setup-guide.md+++ b/docs/internal/slack-local-setup-guide.md@@ -92,7 +92,7 @@ features:always_online: trueapp_home:home_tab_enabled: true- messages_tab_enabled: false+ messages_tab_enabled: truemessages_tab_read_only_enabled: falseoauth_config:redirect_urls:@@ -140,7 +140,13 @@ Django must be up at that moment.> `link_shared` is left out on purpose — it needs the `links:read` scope (the manifest won't save> otherwise) and the coding agent doesn't use it.-> The `app_home` block + `app_home_opened` bot event power the App Home tab; the+> The `app_home` block + `app_home_opened` bot event power the App Home tab. With the+> `slack-app-onboarding` flag on, the same event, an install, a reinstall and a `team_join` start the+> `slack-app-onboarding` Temporal workflow, which posts a person's onboarding thread in the PostHog DM+> once. It needs the Temporal worker running. The thread checks each step again before it shows it,+> so a person who already linked their account or chose a model sees that step as already set.+> To see the thread again in a dev workspace, clear the `onboarding` field of your row in+> `slack_app_slacksettings`. The> Sign in with Slack (OpenID Connect) flow needs `user` scopes `openid` + `email` + `profile` and> the second redirect URL (`/complete/slack-link/`). Drop those if you don't want either feature> locally. Neither is behind a feature flag: the App Home tab renders for every install, and thediff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex d57625abd378..287c1faff66a 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -51,12 +51,16 @@ from products.slack_app.backend.feature_flags import (ASSISTANT_REQUIRED_SCOPES,is_slack_app_assistant_enabled,is_slack_app_oauth_enabled,+ is_slack_app_onboarding_enabled,)from products.slack_app.backend.helpers import local_dev_slack_emailfrom products.slack_app.backend.logic import interview_recruitment, reply_suggestionsfrom products.slack_app.backend.logic.feature_tips import interactivity as feature_tip_interactivityfrom products.slack_app.backend.logic.feature_tips.features import SlackFeaturefrom products.slack_app.backend.logic.feature_tips.state import record_feature_used+from products.slack_app.backend.logic.onboarding import interactivity as onboarding_interactivity+from products.slack_app.backend.logic.onboarding.actions import is_onboarding_action+from products.slack_app.backend.logic.onboarding.dispatch import request_onboardingfrom products.slack_app.backend.logic.untagged_question import is_untagged_question_candidatefrom products.slack_app.backend.models import (ChannelWelcomeMode,@@ -2472,6 +2476,8 @@ def _route_app_home_opened(_handle_app_home_opened(event, slack_team_id, integration=integration)except Exception:logger.exception("slack_app_home_opened_failed", slack_team_id=slack_team_id, event_id=event_id)+ # Opening the Home tab or the DM is often a person's first contact with the app.+ request_onboarding(integration, slack_user_id, may_start=True)return ROUTE_HANDLED_LOCALLY@@ -3727,6 +3733,11 @@ def _route_team_join(if integration is None:return ROUTE_HANDLED_LOCALLY+ if is_slack_app_onboarding_enabled(integration):+ # The onboarding thread opens with the same welcome, and its stored state replaces the dedupe below.+ request_onboarding(integration, slack_user_id, may_start=True, spread_burst=True)+ return ROUTE_HANDLED_LOCALLY+if not _claim_once(_team_join_onboarding_cache_key(slack_team_id, slack_user_id)):logger.info("slack_app_team_join_welcome_skipped_duplicate",@@ -6283,6 +6294,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:or (clicked_reply_suggestion.integration_id if clicked_reply_suggestion else None)or feature_tip_interactivity.feature_tip_integration_hint(payload)or interview_recruitment.interview_integration_hint(payload)+ or onboarding_interactivity.onboarding_integration_hint(payload))requesting_user = payload.get("user", {}).get("id", "")slack_team_id = payload.get("team", {}).get("id")@@ -6425,6 +6437,8 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return feature_tip_interactivity.handle_feature_tip_action(payload)if interview_recruitment.is_interview_action(action_id):return interview_recruitment.handle_interview_action(payload)+ if is_onboarding_action(action_id):+ return onboarding_interactivity.handle_onboarding_action(payload)if reply_suggestions.is_reply_suggestion_action(action_id) and clicked_reply_suggestion:return _handle_reply_suggestion_click(payload, clicked_reply_suggestion)if action_id == CHANNEL_APPROVAL_ACTION_APPROVE:diff --git a/products/slack_app/backend/facade/temporal.py b/products/slack_app/backend/facade/temporal.pyindex 5cfa6eb753d7..09c0514bac5f 100644--- a/products/slack_app/backend/facade/temporal.py+++ b/products/slack_app/backend/facade/temporal.py@@ -11,6 +11,7 @@ from products.slack_app.backend.temporal.posthog_slack_inbox_onboarding import Pfrom products.slack_app.backend.temporal.slack_app_fork import SlackAppForkThreadWorkflowfrom products.slack_app.backend.temporal.slack_app_mention import SlackAppMentionWorkflowfrom products.slack_app.backend.temporal.slack_app_mention_processing import SlackAppMentionProcessingWorkflow+from products.slack_app.backend.temporal.slack_app_onboarding import SlackAppOnboardingWorkflowfrom products.slack_app.backend.temporal.slack_app_unfurl_charts import SlackAppUnfurlChartsWorkflowWORKFLOWS = [@@ -20,6 +21,7 @@ WORKFLOWS = [SlackAppForkThreadWorkflow,PostHogSlackInboxOnboardingWorkflow,SlackAppUnfurlChartsWorkflow,+ SlackAppOnboardingWorkflow,]ACTIVITIES = [*SLACK_APP_ACTIVITIES]diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex 6035c3abd2bb..65d927e90f2f 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -50,6 +50,7 @@ SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"SLACK_APP_FORKING_FLAG = "slack-app-forking"SLACK_APP_BYOS_FLAG = "slack-app-byos"SLACK_APP_FOOTER_COST_FLAG = "slack-app-footer-cost"+SLACK_APP_ONBOARDING_FLAG = "slack-app-onboarding"# Linking a Slack identity to a PostHog user resolves the Slack profile and its email.@@ -192,3 +193,13 @@ def is_slack_app_forking_enabled(integration: IntegrationRecord) -> bool:integration,failure_log_key="slack_app_forking_feature_flag_check_failed",)+++def is_slack_app_onboarding_enabled(integration: IntegrationRecord) -> bool:+ """Keyed on the workspace, because most people who get the onboarding thread are not linked to a PostHog user+ yet. Each step checks its own scopes."""+ return _workspace_flag_enabled(+ SLACK_APP_ONBOARDING_FLAG,+ integration,+ failure_log_key="slack_app_onboarding_feature_flag_check_failed",+ )diff --git a/products/slack_app/backend/inbox_channel.py b/products/slack_app/backend/inbox_channel.pyindex 4da031ca0cd5..28cd3b72185f 100644--- a/products/slack_app/backend/inbox_channel.py+++ b/products/slack_app/backend/inbox_channel.py@@ -23,6 +23,7 @@ INBOX_ONBOARDING_REQUIRED_SCOPES: frozenset[str] = INBOX_CHANNEL_REQUIRED_SCOPES# Just long enough to absorb a concurrent install/join racing to create the same channel._CHANNEL_CLAIM_TTL_SECONDS = 60+_INBOX_MEMBER_TTL_SECONDS = 60 * 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.@@ -220,6 +221,22 @@ def is_inbox_channel(integration: WorkspaceIntegration, channel_id: str) -> boolreturn channel.get("name") == INBOX_CHANNEL_NAME+def is_in_team_inbox_channel(integration: WorkspaceIntegration, slack_user_id: str) -> bool:+ """Whether the person is in the channel the team reports to. False while the team has none."""+ configured = _get_team_channel(integration.team_id)+ if configured is None:+ return False+ channel_id = channel_id_from_target(configured)+ key = f"slack_app:inbox_member:v1:{integration.integration_id}:{channel_id}:{slack_user_id}"+ if cache.get(key):+ return True+ if not _is_channel_member(SlackIntegration(integration), channel_id, slack_user_id):+ return False+ # The member scan can take many Slack calls, and people seldom leave the channel, so a yes holds a while.+ cache.set(key, True, timeout=_INBOX_MEMBER_TTL_SECONDS)+ return True++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 = Nonediff --git a/products/slack_app/backend/logic/feature_tips/offer.py b/products/slack_app/backend/logic/feature_tips/offer.pyindex 5c074c61acf6..5be6769542b8 100644--- a/products/slack_app/backend/logic/feature_tips/offer.py+++ b/products/slack_app/backend/logic/feature_tips/offer.py@@ -31,6 +31,7 @@ from products.slack_app.backend.logic.feature_tips.picker import choose_tipfrom products.slack_app.backend.logic.feature_tips.state import FeatureTipsState, mark_shown, parse_statefrom products.slack_app.backend.models import SlackSettings, SlackThreadTaskMappingfrom products.slack_app.backend.services.slack_messages import post_slack_ephemeral, section_block+from products.slack_app.backend.services.slack_settings import parse_onboardingfrom products.slack_app.backend.services.workspace_integrations import WorkspaceIntegrationif TYPE_CHECKING:@@ -70,11 +71,16 @@ class _Reservation:def offer_feature_tip(request: TipRequest) -> SlackFeature | None:integration = request.integration- stored = list(+ rows = list(SlackSettings.objects.filter(slack_workspace_id=integration.integration_id, slack_user_id=request.slack_user_id- ).values_list("feature_tips", flat=True)[:1]+ ).values_list("feature_tips", "onboarding")[:1])+ stored = [rows[0][0]] if rows else []+ # The onboarding thread already teaches the basics, so a tip during it would be a second message to read.+ onboarding = parse_onboarding(rows[0][1]) if rows else None+ if onboarding is not None and not onboarding.completed:+ return None# Most answers come from a reader who opted out or already got today's tip. They stop here,# before the lock. Their interaction count no longer gates anything.if stored and _skip_without_counting(parse_state(stored[0]), timezone.now()):diff --git a/products/slack_app/backend/logic/onboarding/__init__.py b/products/slack_app/backend/logic/onboarding/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/slack_app/backend/logic/onboarding/actions.py b/products/slack_app/backend/logic/onboarding/actions.pynew file mode 100644index 000000000000..cf3876f72fe7--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/actions.py@@ -0,0 +1,41 @@+import json++from products.slack_app.backend.logic.onboarding.step import OnboardingContext, OnboardingStepKey++# pinned: Slack action ids on cards that people already have in their DMs+MODEL_ACTION_ID = "slack_onboarding:model"+AUTO_MODEL_ACTION_ID = "slack_onboarding:auto_model"+# Each reply mode button needs its own id inside one actions block, so the mode is a suffix.+REPLIES_ACTION_ID = "slack_onboarding:replies"+SKIP_ACTION_ID = "slack_onboarding:skip"+CONTINUE_ACTION_ID = "slack_onboarding:continue"+AI_CONSENT_ACTION_ID = "slack_onboarding:ai_consent"+INBOX_JOIN_ACTION_ID = "slack_onboarding:inbox_join"+SOURCES_ACTION_ID = "slack_onboarding:sources"+SOURCES_BLOCK_PREFIX = "slack_onboarding_sources"+ONBOARDING_ACTION_PREFIX = "slack_onboarding:"+++def is_onboarding_action(action_id: object) -> bool:+ return isinstance(action_id, str) and action_id.startswith(ONBOARDING_ACTION_PREFIX)+++def action_value(ctx: OnboardingContext, **fields: str) -> str:+ # The integration id lets the interactivity webhook route the click to the region that owns the install.+ return json.dumps({"integration_id": ctx.integration.id, **fields}, separators=(",", ":"))+++def button(ctx: OnboardingContext, label: str, action_id: str, *, primary: bool = False, **fields: str) -> dict:+ element = {+ "type": "button",+ "text": {"type": "plain_text", "text": label},+ "action_id": action_id,+ "value": action_value(ctx, **fields),+ }+ if primary:+ element["style"] = "primary"+ return element+++def skip_button(ctx: OnboardingContext, step: OnboardingStepKey) -> dict:+ return button(ctx, "Skip", SKIP_ACTION_ID, step=step)diff --git a/products/slack_app/backend/logic/onboarding/ai_consent_step.py b/products/slack_app/backend/logic/onboarding/ai_consent_step.pynew file mode 100644index 000000000000..650aebd48665--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/ai_consent_step.py@@ -0,0 +1,58 @@+from typing import Any++from products.slack_app.backend.logic.onboarding.actions import (+ AI_CONSENT_ACTION_ID,+ CONTINUE_ACTION_ID,+ button,+ skip_button,+)+from products.slack_app.backend.logic.onboarding.checks import approve_ai_data_processing_for_team, has_ai_approval+from products.slack_app.backend.logic.onboarding.step import (+ OnboardingContext,+ OnboardingStep,+ OnboardingStepKey,+ StepClick,+)+from products.slack_app.backend.services.slack_messages import section_block+from products.slack_app.backend.services.slack_welcome_messages import AI_DATA_PROCESSING_TEXT+++class AiConsentStep(OnboardingStep):+ key = OnboardingStepKey.AI_CONSENT+ title = "AI data processing"+ done_text = "AI data processing allowed"+ action_ids = frozenset({AI_CONSENT_ACTION_ID})++ def applies(self, ctx: OnboardingContext) -> bool:+ # A Slack admin is often the one to ask an org admin for it, even when they cannot allow it.+ return ctx.is_workspace_admin or ctx.is_org_admin++ def is_done(self, ctx: OnboardingContext) -> bool:+ return has_ai_approval(ctx.integration.team_id)++ def render(self, ctx: OnboardingContext) -> list[dict]:+ if not ctx.is_org_admin:+ return [+ section_block(+ f"*Allow AI data processing*\n{AI_DATA_PROCESSING_TEXT}\n"+ "Only an organization admin can allow it. Ask one to allow it in PostHog, then press Continue."+ ),+ {"type": "actions", "elements": [button(ctx, "Continue", CONTINUE_ACTION_ID, step=self.key)]},+ ]+ return [+ section_block(f"*Allow AI data processing*\n{AI_DATA_PROCESSING_TEXT}"),+ {+ "type": "actions",+ "elements": [+ button(ctx, "Allow AI data processing", AI_CONSENT_ACTION_ID, primary=True),+ skip_button(ctx, self.key),+ ],+ },+ ]++ def apply_action(self, ctx: OnboardingContext, action_id: str, value: dict[str, Any]) -> StepClick:+ if not ctx.is_org_admin:+ return StepClick(message="Only an organization admin can allow AI data processing.", refresh=False)+ approve_ai_data_processing_for_team(ctx.integration.team_id)+ self.record_completed(ctx)+ return StepClick()diff --git a/products/slack_app/backend/logic/onboarding/card.py b/products/slack_app/backend/logic/onboarding/card.pynew file mode 100644index 000000000000..5c6d2df5f74f--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/card.py@@ -0,0 +1,293 @@+"""Only the per-person workflow calls these, through activities, so renders for one person never overlap."""++from dataclasses import replace+from typing import Literal++from slack_sdk.errors import SlackApiError++from posthog.dataclasses import frozen+from posthog.models.integration import SlackIntegration++from products.slack_app.backend.analytics import capture_slack_event+from products.slack_app.backend.logic.onboarding.dispatch import request_onboarding+from products.slack_app.backend.logic.onboarding.step import OnboardingContext, OnboardingStep+from products.slack_app.backend.logic.onboarding.steps import ONBOARDING_STEPS, STEPS_BY_KEY+from products.slack_app.backend.services.slack_messages import context_block, section_block+from products.slack_app.backend.services.slack_settings import resolve_onboarding, update_onboarding+from products.slack_app.backend.services.slack_welcome_messages import ONBOARDING_INTRO_TEXT, build_onboarding_ready+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration+from products.slack_app.backend.temporal.types import (+ ONBOARDING_DONE_PLAN,+ SlackAppOnboardingMessage,+ SlackAppOnboardingPlan,+)++# pinned: analytics event names, renaming breaks dashboards+SETUP_STARTED_EVENT = "slack app onboarding started"+STEP_SHOWN_EVENT = "slack app onboarding step shown"+SETUP_COMPLETED_EVENT = "slack app onboarding completed"+++StepStatus = Literal["done", "already_set", "not_needed", "skipped", "pending"]+++@frozen+class _PlannedStep:+ number: int+ step: OnboardingStep+ status: StepStatus+ # Whether the step has a reply in the thread.+ shown: bool+++def _check_planned(+ ctx: OnboardingContext, planned: tuple[str, ...], step_ts: dict[str, str], skipped: tuple[str, ...]+) -> list[_PlannedStep]:+ steps = [STEPS_BY_KEY[key] for key in planned if key in STEPS_BY_KEY]+ checked = []+ for number, step in enumerate(steps, start=1):+ shown = step.key in step_ts+ status: StepStatus+ if not step.applies(ctx):+ status = "not_needed"+ elif step.is_done(ctx):+ status = "done" if shown else "already_set"+ elif step.skippable and step.key in skipped:+ status = "skipped"+ else:+ status = "pending"+ checked.append(_PlannedStep(number=number, step=step, status=status, shown=shown))+ return checked+++def _current(checked: list[_PlannedStep]) -> _PlannedStep | None:+ return next((item for item in checked if item.status == "pending"), None)+++def _progress(checked: list[_PlannedStep]) -> str:+ finished = sum(1 for item in checked if item.status != "pending")+ return f"{finished} of {len(checked)} {'step' if len(checked) == 1 else 'steps'} done"+++_CHECKLIST_LINES: dict[StepStatus, str] = {+ "done": ":white_check_mark: {done_text}",+ "already_set": ":white_check_mark: {title}: already set",+ "not_needed": ":heavy_minus_sign: {title}: not needed",+ "skipped": ":heavy_minus_sign: {title}: skipped",+ "pending": ":white_small_square: {title}",+}+++def _checklist(checked: list[_PlannedStep]) -> str:+ current = _current(checked)+ lines = []+ for item in checked:+ if item is current:+ line = f":arrow_right: *{item.step.title}*"+ else:+ line = _CHECKLIST_LINES[item.status].format(title=item.step.title, done_text=item.step.done_text)+ lines.append(f"{item.number}. {line}")+ return "\n".join(lines)+++def _root_status(checked: list[_PlannedStep]) -> str:+ """Stored so the thread can tell when any checklist line changes, even when the count stays the same."""+ return f"{_progress(checked)}\n{_checklist(checked)}"+++def _root_message(checked: list[_PlannedStep], *, ready: bool, ts: str | None = None) -> SlackAppOnboardingMessage:+ return SlackAppOnboardingMessage(+ kind="root",+ text="PostHog is set up" if ready else "Set up PostHog in Slack",+ blocks=[+ section_block(ONBOARDING_INTRO_TEXT),+ context_block(":white_check_mark: Setup done" if ready else _progress(checked)),+ context_block(_checklist(checked)),+ ],+ ts=ts,+ root_status=_root_status(checked),+ )+++def _passed_notes(checked: list[_PlannedStep], current: _PlannedStep) -> list[str]:+ """The steps that were set elsewhere after the previous reply, so the thread jumps over them."""+ notes = []+ for item in reversed(checked[: current.number - 1]):+ if item.shown:+ break+ reason = "is already set" if item.status == "already_set" else "is not needed anymore"+ notes.append(f"Step {item.number}, {item.step.title}, {reason}, so I skipped it.")+ return list(reversed(notes))+++def _step_message(+ ctx: OnboardingContext, checked: list[_PlannedStep], current: _PlannedStep+) -> SlackAppOnboardingMessage:+ position = f"Step {current.number} of {len(checked)}"+ # The mention makes the person follow the thread, so each new step reply notifies them.+ return SlackAppOnboardingMessage(+ kind="step",+ step=current.step.key,+ text=f"{position}: {current.step.title}",+ blocks=[+ context_block(f"<@{ctx.slack_user_id}> {position}"),+ *(context_block(note) for note in _passed_notes(checked, current)),+ *current.step.render(ctx),+ ],+ )+++_SUMMARY_LINES: dict[StepStatus, str] = {+ "done": ":white_check_mark: {done_text}",+ "not_needed": "Not needed: {title}",+ "skipped": "Skipped: {title}",+}+++def _summary_message(item: _PlannedStep, ts: str) -> SlackAppOnboardingMessage:+ line = _SUMMARY_LINES[item.status].format(title=item.step.title, done_text=item.step.done_text)+ return SlackAppOnboardingMessage(+ kind="step", step=item.step.key, text=line, blocks=[context_block(line)], ts=ts, summarizes_step=True+ )+++def _ready_message(ctx: OnboardingContext, checked: list[_PlannedStep]) -> SlackAppOnboardingMessage:+ skipped = [item.step.title for item in checked if item.status == "skipped"]+ text, blocks = build_onboarding_ready(ctx.integration, ctx.slack_user_id, skipped)+ return SlackAppOnboardingMessage(kind="ready", text=text, blocks=blocks)+++def _status(checked: list[_PlannedStep]) -> str:+ current = _current(checked)+ skips = ", ".join(item.step.key for item in checked if item.status == "skipped") or "none"+ return f"{_progress(checked)} · {f'current step: {current.step.key}' if current else 'ready'} · skipped: {skips}"+++def plan_onboarding(integration: WorkspaceIntegration, slack_user_id: str) -> SlackAppOnboardingPlan:+ """Reads only, except that it stores steps that join the thread and that there is nothing to set up."""+ slack_workspace_id = integration.integration_id+ state = resolve_onboarding(slack_workspace_id, slack_user_id)+ if state is not None and state.completed:+ return ONBOARDING_DONE_PLAN++ ctx = OnboardingContext(integration=integration, slack_user_id=slack_user_id)+ skipped = state.skipped if state else ()+ if state is None or state.root_ts is None:+ # The thread promises these steps at its start.+ steps = [+ step for step in ONBOARDING_STEPS if step.key not in skipped and step.applies(ctx) and not step.is_done(ctx)+ ]+ if not steps:+ # Storing this saves a workflow run on each later open of the DM.+ update_onboarding(slack_workspace_id, slack_user_id, completed_reason="nothing_to_set_up")+ return ONBOARDING_DONE_PLAN+ checked = [+ _PlannedStep(number=number, step=step, status="pending", shown=False)+ for number, step in enumerate(steps, start=1)+ ]+ root = replace(_root_message(checked, ready=False), planned=[step.key for step in steps])+ return SlackAppOnboardingPlan(edits=[], post=root, finished=False, status=_status(checked))++ # A step can apply only after the account link, such as AI consent for an org admin. It joins at the end,+ # so the replies already in the thread keep their numbers.+ joining = [+ step.key+ for step in ONBOARDING_STEPS+ if step.key not in state.planned and step.key not in skipped and step.applies(ctx) and not step.is_done(ctx)+ ]+ planned = (*state.planned, *joining)+ if joining:+ update_onboarding(slack_workspace_id, slack_user_id, planned=list(planned))+ checked = _check_planned(ctx, planned, state.step_ts, skipped)+ status = _status(checked)+ edits = [+ _summary_message(item, state.step_ts[item.step.key])+ for item in checked+ if item.shown and item.status != "pending" and item.step.key not in state.summarized+ ]+ current = _current(checked)+ if current is None:+ edits.append(_root_message(checked, ready=True, ts=state.root_ts))+ return SlackAppOnboardingPlan(edits=edits, post=_ready_message(ctx, checked), finished=True, status=status)++ if state.root_status != _root_status(checked):+ edits.append(_root_message(checked, ready=False, ts=state.root_ts))+ message = _step_message(ctx, checked, current)+ current_ts = state.step_ts.get(current.step.key)+ if current_ts is None:+ return SlackAppOnboardingPlan(edits=edits, post=message, finished=False, status=status)+ # Rendering the shown step again keeps its content fresh, such as the 15-minute account link.+ edits.append(replace(message, ts=current_ts))+ return SlackAppOnboardingPlan(edits=edits, post=None, finished=False, status=status)+++def post_onboarding_message(+ integration: WorkspaceIntegration, slack_user_id: str, message: SlackAppOnboardingMessage+) -> None:+ slack_workspace_id = integration.integration_id+ client = SlackIntegration(integration).client+ if message.kind == "root":+ response = client.chat_postMessage(channel=slack_user_id, text=message.text, blocks=message.blocks)+ update_onboarding(+ slack_workspace_id,+ slack_user_id,+ root=(str(response["channel"]), str(response["ts"])),+ planned=message.planned,+ root_status=message.root_status,+ )+ capture_slack_event(integration, SETUP_STARTED_EVENT, slack_user_id=slack_user_id)+ return++ state = resolve_onboarding(slack_workspace_id, slack_user_id)+ if state is None or state.channel is None or state.root_ts is None:+ # The top message was deleted earlier in this refresh. The next plan starts a new thread.+ return+ response = client.chat_postMessage(+ channel=state.channel, thread_ts=state.root_ts, text=message.text, blocks=message.blocks+ )+ if message.kind == "step" and message.step:+ update_onboarding(slack_workspace_id, slack_user_id, step_ts=(message.step, str(response["ts"])))+ capture_slack_event(integration, STEP_SHOWN_EVENT, slack_user_id=slack_user_id, step=message.step)+ elif message.kind == "ready":+ update_onboarding(slack_workspace_id, slack_user_id, completed_reason="finished")+ capture_slack_event(+ integration, SETUP_COMPLETED_EVENT, slack_user_id=slack_user_id, skipped_steps=list(state.skipped)+ )+++def _forget_deleted_message(+ integration: WorkspaceIntegration, slack_user_id: str, message: SlackAppOnboardingMessage+) -> None:+ """Slack retention or an admin can delete a message. The thread then posts it again, or starts over+ when the top message is gone, instead of failing on each refresh."""+ slack_workspace_id = integration.integration_id+ if message.kind == "root":+ update_onboarding(slack_workspace_id, slack_user_id, reset_thread=True)+ elif message.summarizes_step and message.step:+ update_onboarding(slack_workspace_id, slack_user_id, summarized_step=message.step)+ elif message.step:+ update_onboarding(slack_workspace_id, slack_user_id, forget_step=message.step)+ # The rest of this refresh was planned for the old messages, so plan again.+ request_onboarding(integration, slack_user_id, may_start=False)+++def edit_onboarding_message(+ integration: WorkspaceIntegration, slack_user_id: str, message: SlackAppOnboardingMessage+) -> None:+ slack_workspace_id = integration.integration_id+ state = resolve_onboarding(slack_workspace_id, slack_user_id)+ if state is None or state.channel is None or message.ts is None:+ return+ try:+ SlackIntegration(integration).client.chat_update(+ channel=state.channel, ts=message.ts, text=message.text, blocks=message.blocks+ )+ except SlackApiError as error:+ if error.response.get("error") != "message_not_found":+ raise+ _forget_deleted_message(integration, slack_user_id, message)+ return+ if message.kind == "root" and message.root_status:+ update_onboarding(slack_workspace_id, slack_user_id, root_status=message.root_status)+ if message.summarizes_step and message.step:+ update_onboarding(slack_workspace_id, slack_user_id, summarized_step=message.step)diff --git a/products/slack_app/backend/logic/onboarding/checks.py b/products/slack_app/backend/logic/onboarding/checks.pynew file mode 100644index 000000000000..0313fb62ccc5--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/checks.py@@ -0,0 +1,55 @@+"""Workspace and person checks shared by the onboarding steps and the old installer DM."""++from posthog.integrations import IntegrationManager+from posthog.models import OrganizationMembership, Team+from posthog.models.organization import Organization+from posthog.models.user_integration import UserIntegration+++def has_team_github(team_id: int) -> bool:+ return IntegrationManager.github.oauth.exists(team_id)+++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 as signals_has_enabled_source, # noqa: PLC0415 — keeps the signals stack off the slack import path+ )++ return signals_has_enabled_source(team_id)+++def approve_ai_data_processing_for_team(team_id: int) -> bool:+ """Set the org consent for the team's organization. The caller checks that the person is an org admin."""+ org_id = Team.objects.filter(id=team_id).values_list("organization_id", flat=True).first()+ organization = Organization.objects.filter(id=org_id).first() if org_id is not None else None+ if organization is None:+ return False+ # Save the instance (not a queryset .update()) so ModelActivityMixin records the consent change+ # in the activity log and updated_at is bumped.+ organization.is_ai_data_processing_approved = True+ organization.save(update_fields=["is_ai_data_processing_approved", "updated_at"])+ return Truediff --git a/products/slack_app/backend/logic/onboarding/dispatch.py b/products/slack_app/backend/logic/onboarding/dispatch.pynew file mode 100644index 000000000000..2aadef335ace--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/dispatch.py@@ -0,0 +1,83 @@+"""Callers run inside Slack's 3-second limit, so they only check the stored state and send a signal."""++import asyncio++from django.conf import settings+from django.core.cache import cache++import structlog++from products.slack_app.backend.feature_flags import is_slack_app_onboarding_enabled+from products.slack_app.backend.services.slack_settings import resolve_onboarding, update_onboarding+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration++logger = structlog.get_logger(__name__)++# A bulk import of members sends many team_join events at once. Each onboarding posts two messages+# right away, so starts past this rate wait, and the app keeps room for its other Slack calls.+BURST_STARTS_PER_MINUTE = 20+BURST_WINDOW_SECONDS = 60 * 60+++def request_onboarding(+ integration: WorkspaceIntegration, slack_user_id: str, *, may_start: bool, spread_burst: bool = False+) -> None:+ """Start the person's onboarding, or refresh the one in progress. Only a ``may_start`` trigger can start+ one, and only for a person with no onboarding state. Never raises: the onboarding catches up on the next trigger."""+ try:+ slack_workspace_id = integration.integration_id+ state = resolve_onboarding(slack_workspace_id, slack_user_id)+ if state is not None and state.completed:+ return+ start_delay_seconds = 0+ if state is None:+ if not may_start or not is_slack_app_onboarding_enabled(integration):+ return+ update_onboarding(slack_workspace_id, slack_user_id, start=True)+ if spread_burst:+ start_delay_seconds = _burst_delay_seconds(slack_workspace_id)+ _signal_with_start(integration, slack_user_id, start_delay_seconds=start_delay_seconds)+ except Exception:+ logger.warning("slack_app_onboarding_dispatch_failed", slack_user_id=slack_user_id, exc_info=True)+++def _burst_delay_seconds(slack_workspace_id: str) -> int:+ key = f"slack_app:onboarding:burst_starts:{slack_workspace_id}"+ try:+ position = 1 if cache.add(key, 1, BURST_WINDOW_SECONDS) else cache.incr(key)+ except ValueError:+ # The counter expired between the add and the incr, so this start opens a new window.+ position = 1+ return ((position - 1) // BURST_STARTS_PER_MINUTE) * 60+++def _signal_with_start(integration: WorkspaceIntegration, slack_user_id: str, *, start_delay_seconds: int) -> None:+ # Deferred so temporalio stays off the import path of the webhook and view modules.+ from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy # noqa: PLC0415++ from posthog.temporal.common.client import sync_connect # noqa: PLC0415++ from products.slack_app.backend.temporal.slack_app_onboarding import ( # noqa: PLC0415+ SlackAppOnboardingWorkflow,+ slack_app_onboarding_workflow_id,+ )+ from products.slack_app.backend.temporal.types import SlackAppOnboardingInputs # noqa: PLC0415++ slack_team_id = integration.integration_id+ client = sync_connect()+ asyncio.run(+ client.start_workflow(+ SlackAppOnboardingWorkflow.run,+ SlackAppOnboardingInputs(+ integration_id=integration.id,+ slack_team_id=slack_team_id,+ slack_user_id=slack_user_id,+ start_delay_seconds=start_delay_seconds,+ ),+ id=slack_app_onboarding_workflow_id(slack_team_id, slack_user_id),+ task_queue=settings.TASKS_TASK_QUEUE,+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ start_signal="refresh",+ )+ )diff --git a/products/slack_app/backend/logic/onboarding/github_step.py b/products/slack_app/backend/logic/onboarding/github_step.pynew file mode 100644index 000000000000..5e1ee93e2e03--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/github_step.py@@ -0,0 +1,36 @@+from products.slack_app.backend.logic.onboarding.actions import CONTINUE_ACTION_ID, button, skip_button+from products.slack_app.backend.logic.onboarding.checks import has_personal_github, has_team_github+from products.slack_app.backend.logic.onboarding.step import OnboardingContext, OnboardingStep, OnboardingStepKey+from products.slack_app.backend.services.slack_messages import section_block+from products.slack_app.backend.services.slack_welcome_messages import github_connect_button+++class GithubStep(OnboardingStep):+ key = OnboardingStepKey.GITHUB+ title = "GitHub"+ done_text = "GitHub connected"++ def applies(self, ctx: OnboardingContext) -> bool:+ # A member's personal GitHub only helps once the team has the GitHub app, which an admin installs.+ return ctx.can_link and (ctx.is_workspace_admin or has_team_github(ctx.integration.team_id))++ def is_done(self, ctx: OnboardingContext) -> bool:+ user = ctx.posthog_user+ return user is not None and has_personal_github(user.id) and has_team_github(ctx.integration.team_id)++ def render(self, ctx: OnboardingContext) -> list[dict]:+ return [+ section_block(+ "*Connect GitHub*\nThen I can fix things, not only flag them: I open a pull request with the fix "+ "for you to review. Press Continue when GitHub is connected."+ ),+ {+ "type": "actions",+ "elements": [+ github_connect_button(ctx.integration.team_id),+ # GitHub tells Slack nothing when the connection finishes, so the person moves the thread on.+ button(ctx, "Continue", CONTINUE_ACTION_ID, step=self.key),+ skip_button(ctx, self.key),+ ],+ },+ ]diff --git a/products/slack_app/backend/logic/onboarding/inbox_channel_step.py b/products/slack_app/backend/logic/onboarding/inbox_channel_step.pynew file mode 100644index 000000000000..a8b013000be0--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/inbox_channel_step.py@@ -0,0 +1,56 @@+from typing import Any++from products.slack_app.backend.inbox_channel import (+ ensure_inbox_channel,+ has_inbox_scopes,+ invite_user_to_inbox,+ is_in_team_inbox_channel,+)+from products.slack_app.backend.logic.feature_tips.features import SlackFeature+from products.slack_app.backend.logic.feature_tips.state import record_feature_used+from products.slack_app.backend.logic.onboarding.actions import INBOX_JOIN_ACTION_ID, button, skip_button+from products.slack_app.backend.logic.onboarding.step import (+ OnboardingContext,+ OnboardingStep,+ OnboardingStepKey,+ StepClick,+)+from products.slack_app.backend.services.slack_messages import section_block+++class InboxChannelStep(OnboardingStep):+ key = OnboardingStepKey.INBOX_CHANNEL+ title = "#posthog-inbox"+ done_text = "You're in #posthog-inbox"+ action_ids = frozenset({INBOX_JOIN_ACTION_ID})++ def applies(self, ctx: OnboardingContext) -> bool:+ return ctx.is_workspace_admin and has_inbox_scopes(ctx.integration)++ def is_done(self, ctx: OnboardingContext) -> bool:+ return is_in_team_inbox_channel(ctx.integration, ctx.slack_user_id)++ def render(self, ctx: OnboardingContext) -> list[dict]:+ return [+ section_block(+ "*Join #posthog-inbox*\nEverything I find lands in one shared channel, so the team stays in the loop."+ ),+ {+ "type": "actions",+ "elements": [+ button(ctx, "Join #posthog-inbox", INBOX_JOIN_ACTION_ID, primary=True),+ skip_button(ctx, self.key),+ ],+ },+ ]++ def apply_action(self, ctx: OnboardingContext, action_id: str, value: dict[str, Any]) -> StepClick:+ channel = ensure_inbox_channel(ctx.integration)+ if channel is None or not invite_user_to_inbox(ctx.integration, channel[0], ctx.slack_user_id):+ return StepClick(+ message="I couldn't add you to #posthog-inbox. Create the channel, then invite me with /invite @PostHog.",+ refresh=False,+ )+ record_feature_used(ctx.integration.integration_id, ctx.slack_user_id, SlackFeature.INBOX_CHANNEL)+ self.record_completed(ctx)+ return StepClick()diff --git a/products/slack_app/backend/logic/onboarding/interactivity.py b/products/slack_app/backend/logic/onboarding/interactivity.pynew file mode 100644index 000000000000..073d14ff9e1f--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/interactivity.py@@ -0,0 +1,81 @@+"""Clicks save at once and only signal the workflow, to answer Slack within 3 seconds."""++from typing import Any++from django.http import HttpResponse++from products.slack_app.backend.analytics import capture_slack_event+from products.slack_app.backend.logic.onboarding.actions import CONTINUE_ACTION_ID, SKIP_ACTION_ID, is_onboarding_action+from products.slack_app.backend.logic.onboarding.dispatch import request_onboarding+from products.slack_app.backend.logic.onboarding.step import (+ OnboardingContext,+ OnboardingStep,+ StepClick,+ read_action_value,+)+from products.slack_app.backend.logic.onboarding.steps import ONBOARDING_STEPS, STEPS_BY_KEY+from products.slack_app.backend.services.inbox_interactivity import post_response_url+from products.slack_app.backend.services.slack_settings import update_onboarding+from products.slack_app.backend.services.workspace_integrations import get_workspace_integration++# pinned: analytics event name, renaming breaks dashboards+STEP_SKIPPED_EVENT = "slack app onboarding step skipped"+++def _handling_step(action_id: str) -> OnboardingStep | None:+ return next((step for step in ONBOARDING_STEPS if step.handles(action_id)), None)+++def _clicked_action(payload: dict[str, Any]) -> tuple[str, dict[str, Any]] | None:+ for action in payload.get("actions") or []:+ action_id = action.get("action_id")+ if is_onboarding_action(action_id):+ step = _handling_step(action_id)+ value = step.read_value(action) if step else read_action_value(action)+ if value is not None:+ return action_id, value+ return None+++def _integration_id(clicked: tuple[str, dict[str, Any]] | None) -> int | None:+ integration_id = clicked[1].get("integration_id") if clicked else None+ return integration_id if isinstance(integration_id, int) else None+++def onboarding_integration_hint(payload: dict[str, Any]) -> int | None:+ return _integration_id(_clicked_action(payload))+++def _apply(ctx: OnboardingContext, action_id: str, value: dict[str, Any]) -> StepClick:+ if action_id in (SKIP_ACTION_ID, CONTINUE_ACTION_ID):+ step = STEPS_BY_KEY.get(str(value.get("step")))+ if step is None or not step.skippable:+ return StepClick(refresh=False)+ # Continue closes the step. When the person did nothing in it, that counts as a skip.+ if action_id == SKIP_ACTION_ID or not step.is_done(ctx):+ update_onboarding(ctx.integration.integration_id, ctx.slack_user_id, skip_step=step.key)+ capture_slack_event(ctx.integration, STEP_SKIPPED_EVENT, slack_user_id=ctx.slack_user_id, step=step.key)+ return StepClick()+ step = _handling_step(action_id)+ return step.apply_action(ctx, action_id, value) if step else StepClick(refresh=False)+++def handle_onboarding_action(payload: dict[str, Any]) -> HttpResponse:+ clicked = _clicked_action(payload)+ integration_id = _integration_id(clicked)+ slack_team_id = (payload.get("team") or {}).get("id", "")+ # The thread sits in the person's own DM with PostHog, so the clicker is the person it is for.+ slack_user_id = (payload.get("user") or {}).get("id", "")+ integration = get_workspace_integration(integration_id, slack_team_id) if integration_id else None+ if clicked is None or integration is None or not slack_user_id:+ return HttpResponse(status=200)++ result = _apply(OnboardingContext(integration=integration, slack_user_id=slack_user_id), *clicked)+ if result.message is not None:+ post_response_url(+ payload.get("response_url") or "",+ {"response_type": "ephemeral", "replace_original": False, "text": result.message},+ )+ if result.refresh:+ request_onboarding(integration, slack_user_id, may_start=False)+ return HttpResponse(status=200)diff --git a/products/slack_app/backend/logic/onboarding/link_account_step.py b/products/slack_app/backend/logic/onboarding/link_account_step.pynew file mode 100644index 000000000000..44a53ff07a84--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/link_account_step.py@@ -0,0 +1,43 @@+from products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled+from products.slack_app.backend.logic.onboarding.step import OnboardingContext, OnboardingStep, OnboardingStepKey+from products.slack_app.backend.services.slack_messages import section_block+from products.slack_app.backend.services.slack_user_oauth import build_invite_url+++class LinkAccountStep(OnboardingStep):+ key = OnboardingStepKey.LINK_ACCOUNT+ title = "Link your PostHog account"+ done_text = "PostHog account linked"+ skippable = False++ def applies(self, ctx: OnboardingContext) -> bool:+ return is_slack_app_oauth_enabled(ctx.integration)++ def is_done(self, ctx: OnboardingContext) -> bool:+ return ctx.posthog_user is not None++ def render(self, ctx: OnboardingContext) -> list[dict]:+ link_url = build_invite_url(+ slack_user_id=ctx.slack_user_id,+ slack_team_id=ctx.integration.integration_id,+ posthog_team_id=ctx.integration.team_id,+ channel=None,+ thread_ts=None,+ )+ return [+ section_block(+ "*Link your PostHog account*\n"+ "PostHog answers you in Slack from your projects, with the access you have in PostHog."+ ),+ {+ "type": "actions",+ "elements": [+ {+ "type": "button",+ "text": {"type": "plain_text", "text": "Link account"},+ "style": "primary",+ "url": link_url,+ }+ ],+ },+ ]diff --git a/products/slack_app/backend/logic/onboarding/model_step.py b/products/slack_app/backend/logic/onboarding/model_step.pynew file mode 100644index 000000000000..ab26a0024260--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/model_step.py@@ -0,0 +1,88 @@+from typing import Any++from django.core.exceptions import ValidationError++from products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled+from products.slack_app.backend.logic.feature_tips.features import SlackFeature+from products.slack_app.backend.logic.feature_tips.state import record_feature_used+from products.slack_app.backend.logic.onboarding.actions import (+ AUTO_MODEL_ACTION_ID,+ MODEL_ACTION_ID,+ action_value,+ button,+ skip_button,+)+from products.slack_app.backend.logic.onboarding.step import (+ OnboardingContext,+ OnboardingStep,+ OnboardingStepKey,+ StepClick,+)+from products.slack_app.backend.services.model_catalogue import offered_model_choices+from products.slack_app.backend.services.slack_app_home import has_personal_model, set_personal_model+from products.slack_app.backend.services.slack_messages import section_block+from products.slack_app.backend.services.slack_settings import resolve_auto_model_choice, set_auto_model_choice++# Slack refuses a static_select with more options than this.+SLACK_SELECT_MAX_OPTIONS = 100+++class ModelStep(OnboardingStep):+ key = OnboardingStepKey.MODEL+ title = "Your model"+ done_text = "Model chosen"+ action_ids = frozenset({AUTO_MODEL_ACTION_ID, MODEL_ACTION_ID})++ def applies(self, ctx: OnboardingContext) -> bool:+ # The model is saved for the linked PostHog user, so the step needs an install that can link.+ return is_slack_app_oauth_enabled(ctx.integration)++ def is_done(self, ctx: OnboardingContext) -> bool:+ return resolve_auto_model_choice(ctx.integration.integration_id, ctx.slack_user_id) or has_personal_model(+ ctx.integration, ctx.slack_user_id+ )++ def render(self, ctx: OnboardingContext) -> list[dict]:+ options = [+ {+ "text": {"type": "plain_text", "text": choice.label[:75]},+ "value": action_value(ctx, model=choice.model),+ }+ for choice in offered_model_choices()[:SLACK_SELECT_MAX_OPTIONS]+ ]+ elements: list[dict] = [button(ctx, "Let PostHog choose", AUTO_MODEL_ACTION_ID, primary=True)]+ if options:+ elements.append(+ {+ "type": "static_select",+ "placeholder": {"type": "plain_text", "text": "Pick a model"},+ "action_id": MODEL_ACTION_ID,+ "options": options,+ }+ )+ elements.append(skip_button(ctx, self.key))+ return [+ section_block(+ "*Choose your model*\n"+ "PostHog can pick the model for each task you start, or you can pick one model for all of them. "+ "You can change this later in the Home tab."+ ),+ {"type": "actions", "elements": elements},+ ]++ def apply_action(self, ctx: OnboardingContext, action_id: str, value: dict[str, Any]) -> StepClick:+ slack_workspace_id = ctx.integration.integration_id+ if action_id == AUTO_MODEL_ACTION_ID:+ set_auto_model_choice(slack_workspace_id, ctx.slack_user_id, True)+ record_feature_used(slack_workspace_id, ctx.slack_user_id, SlackFeature.AUTO_MODEL_CHOICE)+ self.record_completed(ctx, choice="auto")+ return StepClick()+ model = value.get("model")+ if model not in {choice.model for choice in offered_model_choices()}:+ return StepClick(message="That model is no longer available. Pick another one.", refresh=False)+ try:+ set_personal_model(ctx.integration, ctx.slack_user_id, str(model))+ except ValidationError as error:+ return StepClick(message=error.messages[0], refresh=False)+ self.record_completed(ctx, choice="model", model=str(model))+ return StepClick()diff --git a/products/slack_app/backend/logic/onboarding/replies_step.py b/products/slack_app/backend/logic/onboarding/replies_step.pynew file mode 100644index 000000000000..8e03112a2a7c--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/replies_step.py@@ -0,0 +1,50 @@+from typing import Any++from products.slack_app.backend.logic.onboarding.actions import REPLIES_ACTION_ID, button, skip_button+from products.slack_app.backend.logic.onboarding.step import (+ OnboardingContext,+ OnboardingStep,+ OnboardingStepKey,+ StepClick,+)+from products.slack_app.backend.models import UntaggedFollowupMode+from products.slack_app.backend.services.slack_app_home import UNTAGGED_FOLLOWUP_MODE_LABELS+from products.slack_app.backend.services.slack_messages import section_block+from products.slack_app.backend.services.slack_settings import (+ has_chosen_untagged_followup_mode,+ set_untagged_followup_mode,+)+++class RepliesInThreadsStep(OnboardingStep):+ key = OnboardingStepKey.REPLIES_IN_THREADS+ title = "Replies in threads"+ done_text = "Replies in threads set"++ def is_done(self, ctx: OnboardingContext) -> bool:+ return has_chosen_untagged_followup_mode(ctx.integration.integration_id, ctx.slack_user_id)++ def render(self, ctx: OnboardingContext) -> list[dict]:+ buttons = [+ button(ctx, UNTAGGED_FOLLOWUP_MODE_LABELS[mode], f"{REPLIES_ACTION_ID}:{mode}", mode=mode)+ for mode in (UntaggedFollowupMode.AUTO, UntaggedFollowupMode.ASK, UntaggedFollowupMode.NEVER)+ ]+ return [+ section_block(+ "*Replies in threads you start*\n"+ "When someone replies in a thread you started and doesn't tag @PostHog, what should PostHog do? "+ "This applies to your own replies too."+ ),+ {"type": "actions", "elements": [*buttons, skip_button(ctx, self.key)]},+ ]++ def handles(self, action_id: str) -> bool:+ return action_id.startswith(f"{REPLIES_ACTION_ID}:")++ def apply_action(self, ctx: OnboardingContext, action_id: str, value: dict[str, Any]) -> StepClick:+ mode = value.get("mode")+ if mode not in UntaggedFollowupMode.values:+ return StepClick(refresh=False)+ set_untagged_followup_mode(ctx.integration.integration_id, ctx.slack_user_id, UntaggedFollowupMode(mode))+ self.record_completed(ctx, choice=str(mode))+ return StepClick()diff --git a/products/slack_app/backend/logic/onboarding/sources_step.py b/products/slack_app/backend/logic/onboarding/sources_step.pynew file mode 100644index 000000000000..6daa94770756--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/sources_step.py@@ -0,0 +1,74 @@+from typing import Any++from products.slack_app.backend.logic.onboarding.actions import (+ CONTINUE_ACTION_ID,+ SOURCES_ACTION_ID,+ SOURCES_BLOCK_PREFIX,+ button,+ skip_button,+)+from products.slack_app.backend.logic.onboarding.checks import has_enabled_source+from products.slack_app.backend.logic.onboarding.step import (+ OnboardingContext,+ OnboardingStep,+ OnboardingStepKey,+ StepClick,+)+from products.slack_app.backend.services.slack_welcome_messages import sources_blocks++NO_PROJECT_ACCESS_TEXT = (+ "You don't have access to the PostHog project connected to this Slack workspace. "+ "Ask an admin of your PostHog organization for access."+)+++class SourcesStep(OnboardingStep):+ key = OnboardingStepKey.SOURCES+ title = "Signals to watch"+ done_text = "Watching your signals"+ action_ids = frozenset({SOURCES_ACTION_ID})++ def applies(self, ctx: OnboardingContext) -> bool:+ # Turning sources on is recorded for a PostHog user, so it needs a linked account with access to the project.+ return ctx.is_workspace_admin and ctx.can_link and (ctx.posthog_user is None or ctx.has_project_access)++ def is_done(self, ctx: OnboardingContext) -> bool:+ return has_enabled_source(ctx.integration.team_id)++ def render(self, ctx: OnboardingContext) -> list[dict]:+ return [+ *sources_blocks(+ ctx.integration,+ title="*Choose what I watch*\nTick the signals I should monitor and investigate. Press Continue when you're done.",+ action_id=SOURCES_ACTION_ID,+ block_id=f"{SOURCES_BLOCK_PREFIX}:{ctx.integration.id}",+ ),+ {+ "type": "actions",+ "elements": [+ button(ctx, "Continue", CONTINUE_ACTION_ID, primary=True, step=self.key),+ skip_button(ctx, self.key),+ ],+ },+ ]++ def read_value(self, action: dict[str, Any]) -> dict[str, Any] | None:+ # Checkbox options carry the source key as their value, so the integration id rides on the block id.+ prefix, _, integration_id = str(action.get("block_id") or "").partition(":")+ if prefix != SOURCES_BLOCK_PREFIX or not integration_id.isdigit():+ return None+ selected = [str(option.get("value")) for option in action.get("selected_options") or []]+ return {"integration_id": int(integration_id), "selected": selected}++ def apply_action(self, ctx: OnboardingContext, action_id: str, value: dict[str, Any]) -> StepClick:+ from products.signals.backend.facade.api import ( # noqa: PLC0415 — keeps the signals stack off the slack import path+ set_sources,+ )++ user = ctx.posthog_user+ if user is None:+ return StepClick(message="Link your PostHog account first.", refresh=False)+ if not ctx.has_project_access:+ return StepClick(message=NO_PROJECT_ACCESS_TEXT, refresh=False)+ set_sources(ctx.integration.team_id, user.id, value.get("selected") or [])+ return StepClick(refresh=False)diff --git a/products/slack_app/backend/logic/onboarding/step.py b/products/slack_app/backend/logic/onboarding/step.pynew file mode 100644index 000000000000..f2e565ed6658--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/step.py@@ -0,0 +1,130 @@+import json+from enum import StrEnum+from functools import cached_property+from typing import Any++from posthog.dataclasses import frozen+from posthog.models import User+from posthog.models.integration import SlackIntegration+from posthog.user_permissions import UserPermissions++from products.slack_app.backend.analytics import capture_slack_event+from products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled+from products.slack_app.backend.logic.onboarding.checks import is_org_admin+from products.slack_app.backend.onboarding import installer_slack_user_id+from products.slack_app.backend.services.slack_app_home import linked_posthog_user+from products.slack_app.backend.services.slack_user_info import is_slack_workspace_admin+from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration++# pinned: analytics event name, renaming breaks dashboards+STEP_COMPLETED_EVENT = "slack app onboarding step completed"+++class OnboardingStepKey(StrEnum):+ # pinned: analytics property values and stored step keys, renaming breaks both+ LINK_ACCOUNT = "link_account"+ AI_CONSENT = "ai_consent"+ GITHUB = "github"+ INBOX_CHANNEL = "inbox_channel"+ SOURCES = "sources"+ MODEL = "model"+ REPLIES_IN_THREADS = "replies_in_threads"+++@frozen(slots=False)+class OnboardingContext:+ """Each check runs at most once per plan, because several steps ask the same question."""++ integration: WorkspaceIntegration+ slack_user_id: str++ @cached_property+ def posthog_user(self) -> User | None:+ return linked_posthog_user(self.integration, self.slack_user_id)++ @cached_property+ def can_link(self) -> bool:+ """Whether the person has, or can get, a linked PostHog account."""+ return self.posthog_user is not None or is_slack_app_oauth_enabled(self.integration)++ @cached_property+ def is_workspace_admin(self) -> bool:+ """The person who installed the app, or a Slack workspace admin or owner."""+ if installer_slack_user_id(self.integration) == self.slack_user_id:+ return True+ return is_slack_workspace_admin(SlackIntegration(self.integration), self.integration, self.slack_user_id)++ @cached_property+ def has_project_access(self) -> bool:+ """The link can name a member of another organization in the workspace, so check this project too."""+ user = self.posthog_user+ if user is None:+ return False+ permissions = UserPermissions(user=user, team=self.integration.team)+ return permissions.current_team.effective_membership_level is not None++ @cached_property+ def is_org_admin(self) -> bool:+ user = self.posthog_user+ return user is not None and is_org_admin(user.id, self.integration.team_id)+++def read_action_value(action: dict[str, Any]) -> dict[str, Any] | None:+ raw = action.get("value") or (action.get("selected_option") or {}).get("value")+ try:+ value = json.loads(raw or "")+ except json.JSONDecodeError:+ return None+ return value if isinstance(value, dict) else None+++@frozen+class StepClick:+ """What a click on a step button did. The person gets ``message`` as a reply that only they see."""++ message: str | None = None+ # A tick on a signal checkbox saves at once but keeps the step open, so the person can tick more.+ refresh: bool = True+++class OnboardingStep:+ """One step of the onboarding thread. The thread decides the steps when it starts, from ``applies`` and+ ``is_done``. It asks both again on every refresh, so it never stores whether a step is done.++ ``applies`` must not depend on the account link: the link is the first step, and the thread promises+ the person a number of steps before they link."""++ key: OnboardingStepKey+ title: str+ done_text: str+ skippable: bool = True+ # The buttons that ``apply_action`` handles. Skip and Continue are the same for each step.+ action_ids: frozenset[str] = frozenset()++ def applies(self, ctx: OnboardingContext) -> bool:+ return True++ def is_done(self, ctx: OnboardingContext) -> bool:+ raise NotImplementedError++ def render(self, ctx: OnboardingContext) -> list[dict]:+ raise NotImplementedError++ def handles(self, action_id: str) -> bool:+ return action_id in self.action_ids++ def read_value(self, action: dict[str, Any]) -> dict[str, Any] | None:+ return read_action_value(action)++ def apply_action(self, ctx: OnboardingContext, action_id: str, value: dict[str, Any]) -> StepClick:+ raise NotImplementedError++ def record_completed(self, ctx: OnboardingContext, *, choice: str | None = None, model: str | None = None) -> None:+ capture_slack_event(+ ctx.integration,+ STEP_COMPLETED_EVENT,+ slack_user_id=ctx.slack_user_id,+ step=self.key,+ choice=choice,+ model=model,+ )diff --git a/products/slack_app/backend/logic/onboarding/steps.py b/products/slack_app/backend/logic/onboarding/steps.pynew file mode 100644index 000000000000..6d0fc7a6916d--- /dev/null+++ b/products/slack_app/backend/logic/onboarding/steps.py@@ -0,0 +1,20 @@+from products.slack_app.backend.logic.onboarding.ai_consent_step import AiConsentStep+from products.slack_app.backend.logic.onboarding.github_step import GithubStep+from products.slack_app.backend.logic.onboarding.inbox_channel_step import InboxChannelStep+from products.slack_app.backend.logic.onboarding.link_account_step import LinkAccountStep+from products.slack_app.backend.logic.onboarding.model_step import ModelStep+from products.slack_app.backend.logic.onboarding.replies_step import RepliesInThreadsStep+from products.slack_app.backend.logic.onboarding.sources_step import SourcesStep+from products.slack_app.backend.logic.onboarding.step import OnboardingStep++# In display order. The account link comes first, because the steps after it act for the linked user.+ONBOARDING_STEPS: tuple[OnboardingStep, ...] = (+ LinkAccountStep(),+ AiConsentStep(),+ GithubStep(),+ InboxChannelStep(),+ SourcesStep(),+ ModelStep(),+ RepliesInThreadsStep(),+)+STEPS_BY_KEY: dict[str, OnboardingStep] = {step.key: step for step in ONBOARDING_STEPS}diff --git a/products/slack_app/backend/migrations/0024_slacksettings_onboarding.py b/products/slack_app/backend/migrations/0024_slacksettings_onboarding.pynew file mode 100644index 000000000000..5cffee4c100d--- /dev/null+++ b/products/slack_app/backend/migrations/0024_slacksettings_onboarding.py@@ -0,0 +1,21 @@+# Generated by Django 6.1.2 on 2026-11-04 11:04++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("slack_app", "0023_slacksettings_feature_tips"),+ ]++ operations = [+ migrations.AddField(+ model_name="slacksettings",+ name="onboarding",+ field=models.JSONField(+ blank=True,+ help_text="This user's onboarding thread in the PostHog DM, and whether they finished it.",+ null=True,+ ),+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex 054ba3619f39..71fc26fa06aa 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0023_slacksettings_feature_tips+0024_slacksettings_onboardingdiff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex 04c1c5e60062..14ce71734738 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -255,6 +255,12 @@ class SlackSettings(UUIDModel):blank=True,help_text="Which Slack app features this user used, saw as a tip, or dismissed.",)+ # Only read on a personal row. The shape is ``OnboardingState`` in ``services/slack_settings.py``.+ onboarding = models.JSONField(+ null=True,+ blank=True,+ help_text="This user's onboarding thread in the PostHog DM, and whether they finished it.",+ )created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/products/slack_app/backend/onboarding.py b/products/slack_app/backend/onboarding.pyindex 2a50a44ef2a5..5eb7cd8cdce7 100644--- a/products/slack_app/backend/onboarding.py+++ b/products/slack_app/backend/onboarding.py@@ -12,13 +12,11 @@ from enum import StrEnumimport structlogfrom slack_sdk.errors import SlackApiError-from posthog.integrations import IntegrationManager-from posthog.models import OrganizationMembership, Teamfrom posthog.models.integration import SlackIntegration-from posthog.models.user_integration import UserIntegrationfrom posthog.slack.formatting import channel_id_from_targetfrom products.slack_app.backend.analytics import capture_slack_event+from products.slack_app.backend.feature_flags import is_slack_app_onboarding_enabledfrom products.slack_app.backend.inbox_channel import (_get_team_channel,_is_channel_member,@@ -26,6 +24,15 @@ from products.slack_app.backend.inbox_channel import (has_inbox_scopes,invite_user_to_inbox,)+from products.slack_app.backend.logic.onboarding.checks import (+ approve_ai_data_processing_for_team,+ has_ai_approval as _has_ai_approval,+ has_enabled_source as _has_enabled_source,+ has_personal_github as _has_personal_github,+ has_team_github as _has_team_github,+ is_org_admin as _is_org_admin,+)+from products.slack_app.backend.logic.onboarding.dispatch import request_onboardingfrom products.slack_app.backend.services.slack_messages import context_blockfrom products.slack_app.backend.services.slack_welcome_messages import (INBOX_CREATE_ACTION_ID,@@ -70,42 +77,6 @@ def _replace_actions_with_context(blocks: list[dict], action_ids: set[str], text# =====================================================================-def _has_team_github(team_id: int) -> bool:- return IntegrationManager.github.oauth.exists(team_id)---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: WorkspaceIntegration, slack_user_id: str) -> int | None:@@ -255,18 +226,8 @@ def approve_ai_data_processing(integration: WorkspaceIntegration, slack_user_id: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:+ if not approve_ai_data_processing_for_team(integration.team_id):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))@@ -289,4 +250,8 @@ def run_install_onboarding(integration: WorkspaceIntegration) -> None:returnif channel is not None:invite_user_to_inbox(integration, channel[0], installer)+ # The DM setup thread takes over the installer's setup, so it starts here in place of the old DM.+ if is_slack_app_onboarding_enabled(integration):+ request_onboarding(integration, installer, may_start=True)+ returnsend_onboarding_dm(integration, installer)diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex 65ec740a59b9..40792e5a92dc 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -2188,6 +2188,21 @@ def _apply_personal_preferences()+def set_personal_model(integration: WorkspaceIntegration, slack_user_id: str, model: str) -> None:+ """Raises ``ValidationError`` with a message for the person, like the Home tab editor."""+ _apply_personal_preferences(+ integration,+ slack_user_id,+ runtime_adapter=runtime_adapter_for(model),+ model=model,+ reasoning_effort=None,+ )+++def has_personal_model(integration: WorkspaceIntegration, slack_user_id: str) -> bool:+ return _stored_personal_preferences(integration, slack_user_id) != AIPreferences()++def _reset_personal_preferences(integration: WorkspaceIntegration, slack_user_id: str) -> None:"""Clear the viewer's central per-(user, project) preference, which resetsthem to the project default. The reset button only renders for viewers with@@ -2580,17 +2595,22 @@ def _auto_model_choice_offered(integration: WorkspaceIntegration, slack_user_id:return _resolve_home_user(integration, slack_user_id) is not None+def linked_posthog_user(integration: WorkspaceIntegration, slack_user_id: str) -> User | None:+ """The PostHog user this Slack user linked, the check behind "Connected as" on the Home tab."""+ slack_team_id = integration.integration_id+ return find_linked_posthog_user(+ slack_user_id=slack_user_id,+ slack_team_id=slack_team_id,+ candidate_org_ids=_workspace_org_ids(slack_team_id),+ )++def _resolve_account_state(integration: WorkspaceIntegration, slack_user_id: str) -> AccountState:slack_team_id = integration.integration_idif not is_slack_app_oauth_enabled(integration):return AccountState(enabled=False)- candidate_org_ids = _workspace_org_ids(slack_team_id)- linked_user = find_linked_posthog_user(- slack_user_id=slack_user_id,- slack_team_id=slack_team_id,- candidate_org_ids=candidate_org_ids,- )+ linked_user = linked_posthog_user(integration, slack_user_id)if linked_user is not None:return AccountState(enabled=True, linked_email=linked_user.email)diff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.pyindex 109ae8ac4e6b..034bc0c235c9 100644--- a/products/slack_app/backend/services/slack_settings.py+++ b/products/slack_app/backend/services/slack_settings.py@@ -1,7 +1,6 @@"""Read helpers for per-(Slack workspace, Slack user) settings backed by`models.SlackSettings` (today: the untagged follow-up and question modes, the thread-join mode, the channel welcome mode and the automatic model choice), plus the shared-AI-triple value object.+join mode, the channel welcome mode, the automatic model choice and the onboarding thread), plus the shared AI-triple value object.Model preferences themselves live in the central tasks config(`products.tasks.backend.facade.ai_run_defaults`); `AIPreferences` keeps the@@ -12,9 +11,12 @@ layer with zero translation.from __future__ import annotationsfrom dataclasses import dataclass-from typing import TypeVar+from typing import Literal, TypeVar-from django.db import models+from django.db import models, transaction+from django.utils import timezone++from posthog.dataclasses import frozenfrom products.slack_app.backend.models import ChannelWelcomeMode, ThreadJoinMode, UntaggedFollowupModefrom products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration@@ -188,6 +190,133 @@ def set_auto_model_choice(slack_workspace_id: str, slack_user_id: str, enabled:)+# Stored with each onboarding, so a later version can find people who finished an earlier one.+ONBOARDING_VERSION = 1++OnboardingCompletedReason = Literal["finished", "nothing_to_set_up"]+++@frozen(slots=False)+class OnboardingState:+ """A person's onboarding thread in the PostHog DM. ``root_ts`` is None until the top message is posted,+ and stays None when there was nothing to set up. ``planned`` holds the step keys the thread promised at+ its start, in display order."""++ channel: str | None+ root_ts: str | None+ root_status: str | None+ planned: tuple[str, ...]+ step_ts: dict[str, str]+ summarized: tuple[str, ...]+ skipped: tuple[str, ...]+ started_at: str | None+ completed_at: str | None+ completed_reason: OnboardingCompletedReason | None++ @property+ def completed(self) -> bool:+ return self.completed_at is not None+++def _keys(value: object) -> tuple[str, ...]:+ return tuple(str(key) for key in value) if isinstance(value, list) else ()+++def parse_onboarding(stored: object) -> OnboardingState | None:+ if not isinstance(stored, dict):+ return None+ step_ts = stored.get("step_ts")+ reason = stored.get("completed_reason")+ return OnboardingState(+ channel=stored.get("channel") or None,+ root_ts=stored.get("root_ts") or None,+ root_status=stored.get("root_status") or None,+ planned=_keys(stored.get("planned")),+ step_ts={str(key): str(ts) for key, ts in step_ts.items()} if isinstance(step_ts, dict) else {},+ summarized=_keys(stored.get("summarized")),+ skipped=_keys(stored.get("skipped")),+ started_at=stored.get("started_at") or None,+ completed_at=stored.get("completed_at") or None,+ completed_reason=reason if reason in ("finished", "nothing_to_set_up") else None,+ )+++def resolve_onboarding(slack_workspace_id: str, slack_user_id: str) -> OnboardingState | None:+ from products.slack_app.backend.models import SlackSettings++ stored = (+ SlackSettings.objects.filter(slack_workspace_id=slack_workspace_id, slack_user_id=slack_user_id)+ .values_list("onboarding", flat=True)+ .first()+ )+ return parse_onboarding(stored)+++def _append_key(card: dict, field: str, key: str) -> None:+ card[field] = [*(existing for existing in card.get(field) or [] if existing != key), key]+++def update_onboarding(+ slack_workspace_id: str,+ slack_user_id: str,+ *,+ start: bool = False,+ root: tuple[str, str] | None = None,+ planned: list[str] | None = None,+ root_status: str | None = None,+ step_ts: tuple[str, str] | None = None,+ summarized_step: str | None = None,+ skip_step: str | None = None,+ forget_step: str | None = None,+ reset_thread: bool = False,+ completed_reason: OnboardingCompletedReason | None = None,+) -> None:+ """``root`` is (channel, ts) and ``step_ts`` is (step key, ts). The row lock stops a skip click and a+ workflow write from losing each other's change."""+ from products.slack_app.backend.models import SlackSettings++ now = timezone.now().isoformat()+ with transaction.atomic():+ row, _ = SlackSettings.objects.select_for_update().get_or_create(+ slack_workspace_id=slack_workspace_id, slack_user_id=slack_user_id+ )+ card = dict(row.onboarding) if isinstance(row.onboarding, dict) else {}+ if start:+ card.setdefault("started_at", now)+ card.setdefault("version", ONBOARDING_VERSION)+ if root is not None:+ card["channel"], card["root_ts"] = root+ if planned is not None:+ card["planned"] = planned+ if root_status is not None:+ card["root_status"] = root_status+ if step_ts is not None:+ card["step_ts"] = {**(card.get("step_ts") or {}), step_ts[0]: step_ts[1]}+ if summarized_step is not None:+ _append_key(card, "summarized", summarized_step)+ if skip_step is not None:+ _append_key(card, "skipped", skip_step)+ if forget_step is not None:+ card["step_ts"] = {key: ts for key, ts in (card.get("step_ts") or {}).items() if key != forget_step}+ if reset_thread:+ # Skips stay, so a new thread does not ask again for what the person turned down.+ for field in ("channel", "root_ts", "root_status", "planned", "step_ts", "summarized"):+ card.pop(field, None)+ if completed_reason is not None:+ card["completed_at"], card["completed_reason"] = now, completed_reason+ row.onboarding = card+ row.save(update_fields=["onboarding", "updated_at"])+++def has_chosen_untagged_followup_mode(slack_workspace_id: str, slack_user_id: str) -> bool:+ """Whether this person picked a mode, as opposed to getting the ``ASK`` default."""+ from products.slack_app.backend.models import SlackSettings++ return SlackSettings.objects.filter(+ slack_workspace_id=slack_workspace_id, slack_user_id=slack_user_id, untagged_followup_mode__isnull=False+ ).exists()++def resolve_workspace_default_integration_id(slack_workspace_id: str) -> int | None:"""The integration that the workspace-wide row routes mentions to."""@@ -213,6 +342,12 @@ def set_workspace_default_integration(slack_workspace_id: str, integration_id: i__all__ = [+ "ONBOARDING_VERSION",+ "OnboardingState",+ "parse_onboarding",+ "has_chosen_untagged_followup_mode",+ "resolve_onboarding",+ "update_onboarding","AIPreferences","resolve_auto_model_choice","resolve_channel_welcome_mode",diff --git a/products/slack_app/backend/services/slack_welcome_messages.py b/products/slack_app/backend/services/slack_welcome_messages.pyindex cfdea8493ac8..5c48260bb2ef 100644--- a/products/slack_app/backend/services/slack_welcome_messages.py+++ b/products/slack_app/backend/services/slack_welcome_messages.py@@ -147,18 +147,10 @@ def build_channel_welcome(integration: WorkspaceIntegration) -> tuple[str, list[return "Hey, I'm PostHog. Tag me with @PostHog to get started.", blocks-def build_team_join_welcome(integration: WorkspaceIntegration) -> tuple[str, list[dict[str, Any]]]:- """DM'd to someone who just joined a workspace that already has the app.-- They inherited a tool nobody introduced them to, so this says what it is before it- says what it can do. The examples drop the `@PostHog` prefix because a DM needs none.- """- blocks: list[dict[str, Any]] = [- section_block(- ":wave: Hey, welcome! I'm PostHog, an AI agent your team already uses here. Message me, or tag "- "`@PostHog` in any channel, and I'll dig into your product data or open a pull request in a "- "connected repo."- ),+def _member_welcome_tail(integration: WorkspaceIntegration) -> list[dict[str, Any]]:+ """Examples, tips and links for someone new to the app. The examples drop the `@PostHog` prefix+ because a DM needs none."""+ return [_bullets("Try asking me",(@@ -181,6 +173,45 @@ def build_team_join_welcome(integration: WorkspaceIntegration) -> tuple[str, lis),_docs_button_block(),]+++ONBOARDING_INTRO_TEXT = (+ ":wave: Hey, I'm PostHog, an AI agent your team uses here. I dig into your product data and open "+ "pull requests in connected repos. A few short steps in this thread set me up for you."+)+++def build_onboarding_ready(+ integration: WorkspaceIntegration, slack_user_id: str, skipped_titles: list[str]+) -> tuple[str, list[dict[str, Any]]]:+ """The last reply of the onboarding thread."""+ text = (+ f"<@{slack_user_id}> *You're all set.* Message me here, or tag `@PostHog` in any channel, and I'll dig "+ "into your product data or open a pull request in a connected repo."+ )+ if skipped_titles:+ text += f"\nYou skipped: {', '.join(skipped_titles)}. You can set these up later in {_home_tab(integration)}."+ blocks: list[dict[str, Any]] = [+ section_block(text),+ *_member_welcome_tail(integration),+ ]+ return "You're all set with PostHog", blocks+++def build_team_join_welcome(integration: WorkspaceIntegration) -> tuple[str, list[dict[str, Any]]]:+ """DM'd to someone who just joined a workspace that already has the app.++ They inherited a tool nobody introduced them to, so this says what it is before it+ says what it can do.+ """+ blocks: list[dict[str, Any]] = [+ section_block(+ ":wave: Hey, welcome! I'm PostHog, an AI agent your team already uses here. Message me, or tag "+ "`@PostHog` in any channel, and I'll dig into your product data or open a pull request in a "+ "connected repo."+ ),+ *_member_welcome_tail(integration),+ ]return "Hey, welcome! I'm PostHog. Message me to get started.", blocks@@ -210,11 +241,22 @@ def _done(text: str) -> dict:return context_block(f":white_check_mark: {text}")-def _github_connect_url(team_id: int) -> str:+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_connect_button(team_id: int) -> dict:+ # 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.+ return {+ "type": "button",+ "text": {"type": "plain_text", "text": "Connect GitHub"},+ "url": github_connect_url(team_id),+ "style": "primary",+ }++def _github_blocks(integration: WorkspaceIntegration, *, done: bool) -> list[dict]:blocks: list[dict] = [section_block(@@ -225,19 +267,11 @@ def _github_blocks(integration: WorkspaceIntegration, *, done: bool) -> list[dicif 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]})+ blocks.append({"type": "actions", "elements": [github_connect_button(integration.team_id)]})return blocks-def _sources_blocks(integration: WorkspaceIntegration) -> list[dict]:+def sources_blocks(integration: WorkspaceIntegration, *, title: str, action_id: str, block_id: str) -> 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@@ -252,14 +286,11 @@ def _sources_blocks(integration: WorkspaceIntegration) -> list[dict]:}for source in tickable]- checkboxes: dict = {"type": "checkboxes", "action_id": INBOX_SOURCES_CHECKBOXES_ACTION, "options": options}+ checkboxes: dict = {"type": "checkboxes", "action_id": action_id, "options": options}initial = [option for option, source in zip(options, tickable) if source.enabled]if initial:checkboxes["initial_options"] = initial- blocks = [- section_block("*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]},- ]+ blocks = [section_block(title), {"type": "actions", "block_id": block_id, "elements": [checkboxes]}]# Sources set up elsewhere have no checkbox, so say what's already watching. Without this the# step reads as done with nothing ticked.elsewhere = [source.label for source in sources if not source.togglable and source.enabled]@@ -268,6 +299,15 @@ def _sources_blocks(integration: WorkspaceIntegration) -> list[dict]:return blocks+def _sources_blocks(integration: WorkspaceIntegration) -> list[dict]:+ return sources_blocks(+ integration,+ title="*2. Choose what I watch* :eyes:\nTick the signals I should monitor and investigate.",+ action_id=INBOX_SOURCES_CHECKBOXES_ACTION,+ block_id=f"{INBOX_SOURCES_BLOCK_PREFIX}:{integration.id}",+ )++def _channel_blocks(integration: WorkspaceIntegration, slack: SlackIntegration, *, done: bool) -> list[dict]:blocks: list[dict] = [section_block(@@ -297,17 +337,17 @@ def _channel_blocks(integration: WorkspaceIntegration, slack: SlackIntegration,return blocks+AI_DATA_PROCESSING_TEXT = (+ "To 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."+)++def _ai_approval_blocks(integration: WorkspaceIntegration, *, 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_block(- "*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."- )- ]+ blocks: list[dict] = [section_block(f"*4. Approve AI data processing*\n{AI_DATA_PROCESSING_TEXT}")]if not is_admin:blocks.append(context_block(":warning: Ask an org admin to approve. Until then I can't get started."))return blocksdiff --git a/products/slack_app/backend/signals.py b/products/slack_app/backend/signals.pyindex e6f7a7a983f0..aaeba18e4c04 100644--- a/products/slack_app/backend/signals.py+++ b/products/slack_app/backend/signals.py@@ -27,22 +27,34 @@ def invalidate_repo_list_on_user_github_change(sender: Any, instance: UserIntegrdef onboard_slack_inbox_on_install(sender: Any, instance: WorkspaceIntegration, created: bool, **kwargs) -> None:"""Fresh Slack install -> capture ``slack app installed`` and enqueue the #posthog-inbox onboardingTemporal workflow on commit (the enqueue runs inline; the workflow itself runs on a Temporal- worker). Onboarding is gated on ``channels:manage``. Re-auth uses update_or_create- (created=False), so only first installs are captured and onboard."""- if not created or instance.kind != "slack":+ worker), which also starts the installer's onboarding thread. An install without+ ``channels:manage``, and a re-auth (update_or_create, so created=False), start the installer's+ onboarding thread directly. Its stored state keeps it from running twice."""+ if 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 created:+ # 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- inbox_scopes = has_inbox_scopes(instance)- # Robust, so a failed capture cannot stop the onboarding callback queued after it.- transaction.on_commit(lambda: _capture_install(instance, has_inbox_scopes=inbox_scopes), robust=True)- if not inbox_scopes:- return+ inbox_scopes = has_inbox_scopes(instance)+ # Robust, so a failed capture cannot stop the onboarding callback queued after it.+ transaction.on_commit(lambda: _capture_install(instance, has_inbox_scopes=inbox_scopes), robust=True)+ if inbox_scopes:+ integration_id = instance.id+ transaction.on_commit(lambda: _start_inbox_onboarding_workflow(integration_id))+ return++ transaction.on_commit(lambda: _start_installer_onboarding(instance), robust=True)+++def _start_installer_onboarding(integration: WorkspaceIntegration) -> None:+ from products.slack_app.backend.logic.onboarding.dispatch import request_onboarding # noqa: PLC0415+ from products.slack_app.backend.onboarding import installer_slack_user_id # noqa: PLC0415- integration_id = instance.id- transaction.on_commit(lambda: _start_inbox_onboarding_workflow(integration_id))+ installer = installer_slack_user_id(integration)+ if installer:+ request_onboarding(integration, installer, may_start=True)def _capture_install(integration: WorkspaceIntegration, *, has_inbox_scopes: bool) -> None:diff --git a/products/slack_app/backend/temporal/__init__.py b/products/slack_app/backend/temporal/__init__.pyindex a1f8072285d9..bcdb08f52f84 100644--- a/products/slack_app/backend/temporal/__init__.py+++ b/products/slack_app/backend/temporal/__init__.py@@ -23,15 +23,18 @@ from products.slack_app.backend.temporal.activities import (create_posthog_code_task_for_repo_activity,derive_mention_workflow_id,discover_posthog_code_repository_via_agent_activity,+ edit_slack_app_onboarding_message_activity,enforce_posthog_code_billing_quota_activity,forward_posthog_code_followup_activity,handle_posthog_code_slack_mention_command_activity,mark_slack_app_message_processing_activity,mark_slack_app_message_queued_activity,+ plan_slack_app_onboarding_activity,post_posthog_code_internal_error_activity,post_posthog_code_no_repos_activity,post_posthog_code_picker_timeout_activity,post_posthog_code_repo_picker_activity,+ post_slack_app_onboarding_message_activity,post_slack_unfurl_charts_activity,posthog_code_thread_has_task_activity,prepare_slack_unfurl_charts_activity,@@ -86,6 +89,9 @@ SLACK_APP_ACTIVITIES = [handle_posthog_code_slack_mention_command_activity,mark_slack_app_message_processing_activity,mark_slack_app_message_queued_activity,+ edit_slack_app_onboarding_message_activity,+ plan_slack_app_onboarding_activity,+ post_slack_app_onboarding_message_activity,run_posthog_slack_inbox_onboarding_activity,prepare_slack_unfurl_charts_activity,post_slack_unfurl_charts_activity,@@ -139,6 +145,9 @@ __all__ = ["request_untagged_followup_confirmation_activity","resolve_posthog_code_slack_command_user_activity","classify_slack_app_model_router_activity",+ "edit_slack_app_onboarding_message_activity",+ "plan_slack_app_onboarding_activity",+ "post_slack_app_onboarding_message_activity","run_posthog_slack_inbox_onboarding_activity","post_slack_unfurl_charts_activity","prepare_slack_unfurl_charts_activity",diff --git a/products/slack_app/backend/temporal/activities/__init__.py b/products/slack_app/backend/temporal/activities/__init__.pyindex 3d4a5cd6de8a..8a3975eca832 100644--- a/products/slack_app/backend/temporal/activities/__init__.py+++ b/products/slack_app/backend/temporal/activities/__init__.py@@ -36,6 +36,11 @@ from products.slack_app.backend.temporal.activities.rules import (create_posthog_code_routing_rule_activity,handle_posthog_code_slack_mention_command_activity,)+from products.slack_app.backend.temporal.activities.slack_app_onboarding import (+ edit_slack_app_onboarding_message_activity,+ plan_slack_app_onboarding_activity,+ post_slack_app_onboarding_message_activity,+)from products.slack_app.backend.temporal.activities.task_creation import (create_posthog_code_task_for_repo_activity,derive_mention_workflow_id,@@ -91,6 +96,9 @@ __all__ = ["resolve_posthog_code_slack_command_user_activity","classify_slack_app_model_router_activity","run_posthog_slack_inbox_onboarding",+ "edit_slack_app_onboarding_message_activity",+ "plan_slack_app_onboarding_activity",+ "post_slack_app_onboarding_message_activity","run_posthog_slack_inbox_onboarding_activity","post_slack_unfurl_charts_activity","prepare_slack_unfurl_charts_activity",diff --git a/products/slack_app/backend/temporal/activities/slack_app_onboarding.py b/products/slack_app/backend/temporal/activities/slack_app_onboarding.pynew file mode 100644index 000000000000..28fb71beb2a1--- /dev/null+++ b/products/slack_app/backend/temporal/activities/slack_app_onboarding.py@@ -0,0 +1,53 @@+from typing import TYPE_CHECKING++import structlog+from temporalio import activity++from products.slack_app.backend.temporal.types import (+ ONBOARDING_DONE_PLAN,+ SlackAppOnboardingInputs,+ SlackAppOnboardingMessageInputs,+ SlackAppOnboardingPlan,+)++if TYPE_CHECKING:+ from products.slack_app.backend.services.workspace_integrations import WorkspaceIntegration++logger = structlog.get_logger(__name__)+++def _integration(inputs: SlackAppOnboardingInputs) -> "WorkspaceIntegration | None":+ from products.slack_app.backend.services.workspace_integrations import get_workspace_integration++ integration = get_workspace_integration(inputs.integration_id, inputs.slack_team_id)+ if integration is None:+ logger.info("slack_app_onboarding_integration_gone", integration_id=inputs.integration_id)+ return integration+++def plan_slack_app_onboarding_activity(inputs: SlackAppOnboardingInputs) -> SlackAppOnboardingPlan:+ from products.slack_app.backend.logic.onboarding.card import plan_onboarding++ integration = _integration(inputs)+ if integration is None:+ return ONBOARDING_DONE_PLAN+ return plan_onboarding(integration, inputs.slack_user_id)+++def post_slack_app_onboarding_message_activity(inputs: SlackAppOnboardingMessageInputs) -> None:+ from products.slack_app.backend.logic.onboarding.card import post_onboarding_message++ integration = _integration(inputs.setup)+ if integration is not None:+ post_onboarding_message(integration, inputs.setup.slack_user_id, inputs.message)+++def edit_slack_app_onboarding_message_activity(inputs: SlackAppOnboardingMessageInputs) -> None:+ from products.slack_app.backend.logic.onboarding.card import edit_onboarding_message++ integration = _integration(inputs.setup)+ if integration is not None:+ edit_onboarding_message(integration, inputs.setup.slack_user_id, inputs.message)diff --git a/products/slack_app/backend/temporal/slack_app_onboarding.py b/products/slack_app/backend/temporal/slack_app_onboarding.pynew file mode 100644index 000000000000..2991356317c3--- /dev/null+++ b/products/slack_app/backend/temporal/slack_app_onboarding.py@@ -0,0 +1,111 @@+import json+from dataclasses import replace+from datetime import timedelta++from temporalio import workflow+from temporalio.common import RetryPolicy+from temporalio.exceptions import ActivityError++from posthog.temporal.common.base import PostHogWorkflow++from products.slack_app.backend.temporal.activities.slack_app_onboarding import (+ edit_slack_app_onboarding_message_activity,+ plan_slack_app_onboarding_activity,+ post_slack_app_onboarding_message_activity,+)+from products.slack_app.backend.temporal.types import SlackAppOnboardingInputs, SlackAppOnboardingMessageInputs++SLACK_APP_ONBOARDING_IDLE_TIMEOUT = timedelta(days=7)+SLACK_APP_ONBOARDING_ACTIVITY_TIMEOUT = timedelta(seconds=60)+# Two plans cover a refresh (the top message, then the first step under it); the third is headroom.+SLACK_APP_ONBOARDING_MAX_PLANS_PER_REFRESH = 3+# Plans and edits can run again safely. A post cannot: a retry after a post could send the message twice.+_SAFE_TO_RETRY = RetryPolicy(maximum_attempts=3)+_ONE_ATTEMPT = RetryPolicy(maximum_attempts=1)+++def slack_app_onboarding_workflow_id(slack_team_id: str, slack_user_id: str) -> str:+ return f"slack-app-onboarding-{slack_team_id}-{slack_user_id}"++[email protected](name="slack-app-onboarding")+class SlackAppOnboardingWorkflow(PostHogWorkflow):+ """One run per person. The plan activity decides everything from the database, so adding or+ reordering setup steps changes no workflow command and needs no ``workflow.patched``."""++ @staticmethod+ def parse_inputs(inputs: list[str]) -> SlackAppOnboardingInputs:+ return SlackAppOnboardingInputs(**json.loads(inputs[0]))++ @workflow.init+ def __init__(self, inputs: SlackAppOnboardingInputs) -> None:+ # The first render needs no signal. Set here and not in run(), because buffered signals run first.+ self._render_requested = True++ @workflow.signal+ async def refresh(self) -> None:+ self._render_requested = True++ async def _render(self, inputs: SlackAppOnboardingInputs) -> bool:+ """Returns True when the setup is finished."""+ for _ in range(SLACK_APP_ONBOARDING_MAX_PLANS_PER_REFRESH):+ plan = await workflow.execute_activity(+ plan_slack_app_onboarding_activity,+ inputs,+ start_to_close_timeout=SLACK_APP_ONBOARDING_ACTIVITY_TIMEOUT,+ retry_policy=_SAFE_TO_RETRY,+ summary="plan",+ )+ # Summaries and details are metadata, not commands, so changing them needs no workflow.patched.+ workflow.set_current_details(plan.status)+ for edit in plan.edits:+ await workflow.execute_activity(+ edit_slack_app_onboarding_message_activity,+ SlackAppOnboardingMessageInputs(setup=inputs, message=edit),+ start_to_close_timeout=SLACK_APP_ONBOARDING_ACTIVITY_TIMEOUT,+ retry_policy=_SAFE_TO_RETRY,+ summary=f"edit {edit.summary}",+ )+ if plan.post is not None:+ await workflow.execute_activity(+ post_slack_app_onboarding_message_activity,+ SlackAppOnboardingMessageInputs(setup=inputs, message=plan.post),+ start_to_close_timeout=SLACK_APP_ONBOARDING_ACTIVITY_TIMEOUT,+ retry_policy=_ONE_ATTEMPT,+ summary=f"post {plan.post.summary}",+ )+ if not plan.plan_again:+ return plan.finished+ return False++ @workflow.run+ async def run(self, inputs: SlackAppOnboardingInputs) -> None:+ if inputs.start_delay_seconds > 0:+ await workflow.sleep(timedelta(seconds=inputs.start_delay_seconds))+ while True:+ try:+ await workflow.wait_condition(lambda: self._render_requested, timeout=SLACK_APP_ONBOARDING_IDLE_TIMEOUT)+ except TimeoutError:+ # A refresh that lands between the timeout and the return must not be dropped.+ await workflow.wait_condition(workflow.all_handlers_finished)+ if self._render_requested:+ continue+ return++ self._render_requested = False+ try:+ finished = await self._render(inputs)+ except ActivityError:+ # The next refresh plans again from the database, so a failed step is not lost.+ workflow.logger.warning(+ "slack_app_onboarding_render_failed", extra={"slack_user_id": inputs.slack_user_id}+ )+ continue++ if finished:+ await workflow.wait_condition(workflow.all_handlers_finished)+ return++ if workflow.info().is_continue_as_new_suggested():+ await workflow.wait_condition(workflow.all_handlers_finished)+ workflow.continue_as_new(replace(inputs, start_delay_seconds=0))diff --git a/products/slack_app/backend/temporal/tests/test_slack_app_onboarding_workflow.py b/products/slack_app/backend/temporal/tests/test_slack_app_onboarding_workflow.pynew file mode 100644index 000000000000..fc8f98f63963--- /dev/null+++ b/products/slack_app/backend/temporal/tests/test_slack_app_onboarding_workflow.py@@ -0,0 +1,188 @@+import os+import uuid+import asyncio+from collections.abc import AsyncIterator+from dataclasses import replace+from datetime import timedelta++import pytest++from temporalio import activity+from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from products.slack_app.backend.temporal.slack_app_onboarding import SlackAppOnboardingWorkflow+from products.slack_app.backend.temporal.types import (+ SlackAppOnboardingInputs,+ SlackAppOnboardingMessage,+ SlackAppOnboardingMessageInputs,+ SlackAppOnboardingPlan,+)++INPUTS = SlackAppOnboardingInputs(integration_id=1, slack_team_id="T1", slack_user_id="U1")+++def _message(kind: str, ts: str | None = None) -> SlackAppOnboardingMessage:+ return SlackAppOnboardingMessage(+ kind=kind, # type: ignore[arg-type]+ text=kind,+ blocks=[],+ ts=ts,+ step="model" if kind == "step" else None,+ root_status="1 of 3 steps done" if kind == "root" else None,+ summarizes_step=kind == "step" and ts is not None,+ )+++ROOT_PLAN = SlackAppOnboardingPlan(edits=[], post=_message("root"), finished=False)+FIRST_STEP_PLAN = SlackAppOnboardingPlan(edits=[], post=_message("step"), finished=False)+NEXT_STEP_PLAN = SlackAppOnboardingPlan(+ edits=[_message("step", ts="1"), _message("root", ts="0")], post=_message("step"), finished=False+)+READY_PLAN = SlackAppOnboardingPlan(edits=[_message("root", ts="0")], post=_message("ready"), finished=True)+++class _Slack:+ def __init__(self, plans: list[SlackAppOnboardingPlan], failing_posts: int = 0) -> None:+ self.plans = plans+ self.failing_posts = failing_posts+ self.calls: list[str] = []+ self.refreshed = asyncio.Event()++ def activities(self) -> list:+ @activity.defn(name="plan_slack_app_onboarding_activity")+ async def plan(_: SlackAppOnboardingInputs) -> SlackAppOnboardingPlan:+ self.calls.append("plan")+ return self.plans[min(self.calls.count("plan") - 1, len(self.plans) - 1)]++ @activity.defn(name="edit_slack_app_onboarding_message_activity")+ async def edit(inputs: SlackAppOnboardingMessageInputs) -> None:+ self.calls.append(f"edit:{inputs.message.kind}")++ @activity.defn(name="post_slack_app_onboarding_message_activity")+ async def post(inputs: SlackAppOnboardingMessageInputs) -> None:+ self.calls.append(f"post:{inputs.message.kind}")+ # A root post is followed by a step post in the same refresh, so only the step post ends it.+ if inputs.message.kind != "root":+ self.refreshed.set()+ if self.failing_posts:+ self.failing_posts -= 1+ raise ApplicationError("slack down")++ return [plan, edit, post]+++async def env() -> AsyncIterator[WorkflowEnvironment]:+ async with await WorkflowEnvironment.start_time_skipping(+ test_server_existing_path=os.environ.get("TEMPORAL_TEST_SERVER_PATH")+ ) as environment:+ yield environment+++async def _run(+ env: WorkflowEnvironment, slack: _Slack, *, refreshes: int, inputs: SlackAppOnboardingInputs = INPUTS+) -> list[str]:+ task_queue = str(uuid.uuid4())+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[SlackAppOnboardingWorkflow],+ activities=slack.activities(),+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ handle = await env.client.start_workflow(+ SlackAppOnboardingWorkflow.run,+ inputs,+ id=f"slack-app-onboarding-test-{uuid.uuid4()}",+ task_queue=task_queue,+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ start_signal="refresh",+ )+ for _ in range(refreshes):+ # Each refresh goes in after the previous one posted, so it plans against the new state.+ await asyncio.wait_for(slack.refreshed.wait(), timeout=10)+ slack.refreshed.clear()+ await handle.signal(SlackAppOnboardingWorkflow.refresh)+ await asyncio.wait_for(handle.result(), timeout=60)+ summaries: list[str] = []+ async for event in handle.fetch_history_events():+ if event.HasField("activity_task_scheduled_event_attributes") and event.HasField("user_metadata"):+ summary = env.client.data_converter.payload_converter.from_payload(event.user_metadata.summary, str)+ summaries.append(summary)+ return summaries+++ "plans, failing_posts, refreshes, expected_calls",+ [+ pytest.param(+ [ROOT_PLAN, FIRST_STEP_PLAN, NEXT_STEP_PLAN, READY_PLAN],+ 0,+ 2,+ [+ *["plan", "post:root", "plan", "post:step"],+ *["plan", "edit:step", "edit:root", "post:step"],+ *["plan", "edit:root", "post:ready"],+ ],+ id="each refresh plans, edits, then posts once, until ready ends the run",+ ),+ pytest.param(+ [FIRST_STEP_PLAN, READY_PLAN],+ 1,+ 1,+ ["plan", "post:step", "plan", "edit:root", "post:ready"],+ id="a failed post is not retried and the next refresh plans again",+ ),+ pytest.param(+ [FIRST_STEP_PLAN],+ 0,+ 0,+ ["plan", "post:step"],+ id="without a refresh for a week the run ends",+ ),+ ],+)+async def test_workflow_applies_one_plan_per_refresh(+ env: WorkflowEnvironment,+ plans: list[SlackAppOnboardingPlan],+ failing_posts: int,+ refreshes: int,+ expected_calls: list[str],+) -> None:+ slack = _Slack(plans, failing_posts=failing_posts)++ summaries = await _run(env, slack, refreshes=refreshes)++ assert slack.calls == expected_calls+ assert len(summaries) == len(expected_calls)+++async def test_each_activity_names_the_message_it_sends_in_the_history(env: WorkflowEnvironment) -> None:+ slack = _Slack([ROOT_PLAN, FIRST_STEP_PLAN, NEXT_STEP_PLAN, READY_PLAN])++ summaries = await _run(env, slack, refreshes=2)++ assert summaries == [+ *["plan", "post top message: 1 of 3 steps done", "plan", "post model: show step"],+ *["plan", "edit model: shrink to one line", "edit top message: 1 of 3 steps done", "post model: show step"],+ *["plan", "edit top message: 1 of 3 steps done", "post ready message"],+ ]+++async def test_a_delayed_start_waits_before_its_first_plan(env: WorkflowEnvironment) -> None:+ slack = _Slack([FIRST_STEP_PLAN])+ delayed = replace(INPUTS, start_delay_seconds=300)++ started_at = await env.get_current_time()+ summaries = await _run(env, slack, refreshes=0, inputs=delayed)++ assert slack.calls == ["plan", "post:step"]+ assert summaries == ["plan", "post model: show step"]+ assert await env.get_current_time() - started_at >= timedelta(seconds=300)diff --git a/products/slack_app/backend/temporal/types.py b/products/slack_app/backend/temporal/types.pyindex e1c1bed84e93..488ac2b2d498 100644--- a/products/slack_app/backend/temporal/types.py+++ b/products/slack_app/backend/temporal/types.py@@ -20,6 +20,65 @@ class PostHogSlackInboxOnboardingInputs:integration_id: int+@dataclass(frozen=True)+class SlackAppOnboardingInputs:+ integration_id: int+ slack_team_id: str+ slack_user_id: str+ # Spreads a burst of new members over time. Only a fresh run waits; continue_as_new resets it to 0.+ start_delay_seconds: int = 0+++@frozen+class SlackAppOnboardingMessage:+ """One message of a person's onboarding thread. For an edit, ``ts`` names the message. ``planned``,+ ``root_status`` and ``summarizes_step`` say what to store after it."""++ kind: Literal["root", "step", "ready"]+ text: str+ blocks: list[dict[str, Any]]+ step: str | None = None+ ts: str | None = None+ root_status: str | None = None+ planned: list[str] | None = None+ summarizes_step: bool = False++ @property+ def summary(self) -> str:+ """The label of the activity that sends this message, shown in the Temporal UI."""+ if self.kind == "step" and self.summarizes_step:+ return f"{self.step}: shrink to one line"+ if self.kind == "step":+ return f"{self.step}: show step"+ if self.kind == "root":+ progress, _, _ = (self.root_status or "").partition("\n")+ return f"top message: {progress}"+ return "ready message"+++@frozen+class SlackAppOnboardingPlan:+ edits: list[SlackAppOnboardingMessage]+ post: SlackAppOnboardingMessage | None+ finished: bool+ # Shown as the workflow's current details in the Temporal UI.+ status: str = ""++ @property+ def plan_again(self) -> bool:+ # The first step reply goes under the top message, so it needs one more plan after the top post.+ return self.post is not None and self.post.kind == "root"+++ONBOARDING_DONE_PLAN = SlackAppOnboardingPlan(edits=[], post=None, finished=True, status="Done")+++@frozen+class SlackAppOnboardingMessageInputs:+ setup: SlackAppOnboardingInputs+ message: SlackAppOnboardingMessage++def insight_render_key(insight_id: int) -> str:return f"insight:{insight_id}"diff --git a/products/slack_app/backend/tests/logic/onboarding/__init__.py b/products/slack_app/backend/tests/logic/onboarding/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/slack_app/backend/tests/logic/onboarding/conftest.py b/products/slack_app/backend/tests/logic/onboarding/conftest.pynew file mode 100644index 000000000000..1d57f99f2303--- /dev/null+++ b/products/slack_app/backend/tests/logic/onboarding/conftest.py@@ -0,0 +1,12 @@+from collections.abc import Iterator++import pytest+from unittest.mock import MagicMock, patch++[email protected](autouse=True)+def slack_workspace_admin() -> Iterator[MagicMock]:+ with patch(+ "products.slack_app.backend.logic.onboarding.step.is_slack_workspace_admin", return_value=False+ ) as admin:+ yield admindiff --git a/products/slack_app/backend/tests/logic/onboarding/test_checks.py b/products/slack_app/backend/tests/logic/onboarding/test_checks.pynew file mode 100644index 000000000000..d822e23750eb--- /dev/null+++ b/products/slack_app/backend/tests/logic/onboarding/test_checks.py@@ -0,0 +1,29 @@+import pytest++from posthog.models import Organization, OrganizationMembership++from products.slack_app.backend.logic.onboarding.checks import is_org_admin+++ "level, expected",+ [+ (OrganizationMembership.Level.MEMBER, False),+ (OrganizationMembership.Level.ADMIN, True),+ (OrganizationMembership.Level.OWNER, True),+ (None, False),+ ],+)+def test_only_an_admin_of_the_teams_organization_is_an_org_admin(+ level: OrganizationMembership.Level | None, expected: bool, org_team_user+) -> None:+ org, team, user = org_team_user+ if level is None:+ OrganizationMembership.objects.filter(user=user, organization=org).delete()+ other = Organization.objects.create(name="Other Org")+ OrganizationMembership.objects.create(user=user, organization=other, level=OrganizationMembership.Level.ADMIN)+ else:+ OrganizationMembership.objects.filter(user=user, organization=org).update(level=level)++ assert is_org_admin(user.id, team.id) is expecteddiff --git a/products/slack_app/backend/tests/logic/onboarding/test_steps.py b/products/slack_app/backend/tests/logic/onboarding/test_steps.pynew file mode 100644index 000000000000..c921d5466a85--- /dev/null+++ b/products/slack_app/backend/tests/logic/onboarding/test_steps.py@@ -0,0 +1,105 @@+from typing import Any++import pytest+from unittest.mock import patch++from posthog.models import Organization, OrganizationMembership+from posthog.models.integration import Integration++from products.slack_app.backend.logic.onboarding.actions import CONTINUE_ACTION_ID, SKIP_ACTION_ID+from products.slack_app.backend.logic.onboarding.card import plan_onboarding+from products.slack_app.backend.logic.onboarding.step import OnboardingContext, OnboardingStep, read_action_value+from products.slack_app.backend.logic.onboarding.steps import ONBOARDING_STEPS+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ require_workspace_integration,+)+from products.slack_app.backend.tests.conftest import SLACK_TEAM_ID, SLACK_USER_ID++GITHUB_STEP = "products.slack_app.backend.logic.onboarding.github_step"+ADMIN_SCOPES = "chat:write,users:read,users:read.email,channels:manage,channels:read,groups:read"+++def _install(team, *, installer: str | None = None) -> WorkspaceIntegration:+ config: dict[str, Any] = {"scope": ADMIN_SCOPES}+ if installer:+ config["authed_user"] = {"id": installer}+ row = Integration.objects.create(+ team=team,+ kind="slack",+ integration_id=SLACK_TEAM_ID,+ config=config,+ sensitive_config={"access_token": "xoxb-test"},+ )+ return require_workspace_integration(row.id, SLACK_TEAM_ID)+++def _clickable(blocks: list[dict]) -> list[dict[str, Any]]:+ # Each clickable element, shaped like the action Slack sends back when someone clicks it.+ actions = []+ for block in blocks:+ for element in block.get("elements") or []:+ if "action_id" not in element:+ continue+ option = (element.get("options") or [None])[0]+ actions.append(+ {+ "action_id": element["action_id"],+ "block_id": block.get("block_id"),+ "value": element.get("value"),+ "selected_option": option,+ "selected_options": [option] if option else [],+ }+ )+ return actions++[email protected]("step", ONBOARDING_STEPS, ids=lambda step: step.key)+def test_each_button_on_a_step_reaches_a_handler(step: OnboardingStep, org_team_user, link_user) -> None:+ org, team, user = org_team_user+ OrganizationMembership.objects.filter(user=user, organization=org).update(level=OrganizationMembership.Level.ADMIN)+ link_user(user)+ integration = _install(team)+ ctx = OnboardingContext(integration=integration, slack_user_id=SLACK_USER_ID)++ clicked = _clickable(step.render(ctx))++ assert (SKIP_ACTION_ID in [action["action_id"] for action in clicked]) is step.skippable+ for action in clicked:+ if action["action_id"] in (SKIP_ACTION_ID, CONTINUE_ACTION_ID):+ value = read_action_value(action)+ assert value is not None and value["step"] == step.key+ else:+ assert step.handles(action["action_id"])+ value = step.read_value(action)+ assert value is not None and value["integration_id"] == integration.id+++ "role, expected",+ [+ ("member", ["link_account", "model", "replies_in_threads"]),+ ("member_with_team_github", ["link_account", "github", "model", "replies_in_threads"]),+ (+ "installer",+ ["link_account", "ai_consent", "github", "inbox_channel", "sources", "model", "replies_in_threads"],+ ),+ ("linked_org_admin", ["ai_consent", "model", "replies_in_threads"]),+ ],+)+def test_the_planned_steps_depend_on_the_role(role: str, expected: list[str], org_team_user, link_user) -> None:+ org, team, user = org_team_user+ Organization.objects.filter(id=org.id).update(is_ai_data_processing_approved=False)+ if role == "linked_org_admin":+ OrganizationMembership.objects.filter(user=user, organization=org).update(+ level=OrganizationMembership.Level.ADMIN+ )+ link_user(user)+ integration = _install(team, installer=SLACK_USER_ID if role == "installer" else None)++ with patch(f"{GITHUB_STEP}.has_team_github", return_value=role == "member_with_team_github"):+ plan = plan_onboarding(integration, SLACK_USER_ID)++ assert plan.post is not None and plan.post.planned == expecteddiff --git a/products/slack_app/backend/tests/logic/onboarding/test_thread.py b/products/slack_app/backend/tests/logic/onboarding/test_thread.pynew file mode 100644index 000000000000..bc484de92dad--- /dev/null+++ b/products/slack_app/backend/tests/logic/onboarding/test_thread.py@@ -0,0 +1,503 @@+import json+from collections.abc import Iterator++import pytest+from unittest.mock import MagicMock, patch++from django.core.exceptions import ValidationError++from slack_sdk.errors import SlackApiError++from posthog.models import Organization, OrganizationMembership, Team+from posthog.models.integration import Integration++from products.slack_app.backend.logic.feature_tips.state import get_state+from products.slack_app.backend.logic.onboarding import dispatch+from products.slack_app.backend.logic.onboarding.card import (+ edit_onboarding_message,+ plan_onboarding,+ post_onboarding_message,+)+from products.slack_app.backend.logic.onboarding.interactivity import (+ handle_onboarding_action,+ onboarding_integration_hint,+)+from products.slack_app.backend.logic.onboarding.sources_step import NO_PROJECT_ACCESS_TEXT+from products.slack_app.backend.models import UntaggedFollowupMode+from products.slack_app.backend.services.slack_settings import (+ resolve_auto_model_choice,+ resolve_onboarding,+ resolve_untagged_followup_mode,+ set_auto_model_choice,+ set_untagged_followup_mode,+ update_onboarding,+)+from products.slack_app.backend.services.workspace_integrations import (+ WorkspaceIntegration,+ require_workspace_integration,+)+from products.slack_app.backend.temporal.slack_app_onboarding import SLACK_APP_ONBOARDING_MAX_PLANS_PER_REFRESH+from products.slack_app.backend.tests.conftest import SLACK_TEAM_ID, SLACK_USER_ID+from products.slack_app.backend.tests.helpers import all_block_text++CARD = "products.slack_app.backend.logic.onboarding.card"+CLICKS = "products.slack_app.backend.logic.onboarding.interactivity"+STEP = "products.slack_app.backend.logic.onboarding.step"+MODEL_STEP = "products.slack_app.backend.logic.onboarding.model_step"+INBOX_STEP = "products.slack_app.backend.logic.onboarding.inbox_channel_step"+LINK_SCOPES = "chat:write,users:read,users:read.email"+ADMIN_SCOPES = f"{LINK_SCOPES},channels:manage,channels:read,groups:read"+++def _install(team, scope: str = LINK_SCOPES) -> WorkspaceIntegration:+ row = Integration.objects.create(+ team=team,+ kind="slack",+ integration_id=SLACK_TEAM_ID,+ config={"scope": scope},+ sensitive_config={"access_token": "xoxb-test"},+ )+ return require_workspace_integration(row.id, SLACK_TEAM_ID)+++def _click(integration: WorkspaceIntegration, action_id: str, **value: str) -> dict:+ encoded = json.dumps({"integration_id": integration.id, **value})+ action = (+ {"action_id": action_id, "selected_option": {"value": encoded}}+ if action_id == "slack_onboarding:model"+ else {"action_id": action_id, "value": encoded}+ )+ return {+ "type": "block_actions",+ "team": {"id": SLACK_TEAM_ID},+ "user": {"id": SLACK_USER_ID},+ "response_url": "https://hooks.slack.example/response",+ "actions": [action],+ }+++def slack_client() -> Iterator[MagicMock]:+ with patch("posthog.models.integration.slack.WebClient") as web_client:+ client = web_client.return_value+ posted = iter(range(1, 100))+ client.chat_postMessage.side_effect = lambda **_: {"channel": "D1", "ts": f"100.{next(posted)}"}+ yield client+++def capture() -> Iterator[MagicMock]:+ with patch(f"{CARD}.capture_slack_event") as mock_capture:+ yield mock_capture+++def _refresh(integration: WorkspaceIntegration) -> bool:+ for _ in range(SLACK_APP_ONBOARDING_MAX_PLANS_PER_REFRESH):+ plan = plan_onboarding(integration, SLACK_USER_ID)+ for edit in plan.edits:+ edit_onboarding_message(integration, SLACK_USER_ID, edit)+ if plan.post is not None:+ post_onboarding_message(integration, SLACK_USER_ID, plan.post)+ if not plan.plan_again:+ return plan.finished+ return False+++def _posts(slack_client: MagicMock) -> list[dict]:+ return [call.kwargs for call in slack_client.chat_postMessage.call_args_list]+++def _edits(slack_client: MagicMock) -> dict[str, str]:+ return {+ call.kwargs["ts"]: all_block_text(call.kwargs["blocks"]) for call in slack_client.chat_update.call_args_list+ }+++def test_first_open_starts_a_thread_with_the_first_step_and_later_refreshes_post_nothing_new(+ org_team_user, slack_client: MagicMock, capture: MagicMock+) -> None:+ _, team, _ = org_team_user+ integration = _install(team)++ assert _refresh(integration) is False+ assert _refresh(integration) is False++ root, step = _posts(slack_client)+ assert root["channel"] == SLACK_USER_ID and "thread_ts" not in root+ assert "0 of 3 steps done" in all_block_text(root["blocks"])+ assert "1. :arrow_right: *Link your PostHog account*" in all_block_text(root["blocks"])+ assert (step["channel"], step["thread_ts"]) == ("D1", "100.1")+ assert f"<@{SLACK_USER_ID}> Step 1 of 3" in all_block_text(step["blocks"])+ assert "Link your PostHog account" in all_block_text(step["blocks"])+ # The second refresh only renders the shown step again, which keeps its link fresh.+ assert list(_edits(slack_client)) == ["100.2"]+ assert [call.args[1] for call in capture.call_args_list] == [+ "slack app onboarding started",+ "slack app onboarding step shown",+ ]+++def test_person_with_nothing_to_set_up_gets_no_thread(+ org_team_user, link_user, slack_client: MagicMock, capture: MagicMock+) -> None:+ _, team, user = org_team_user+ integration = _install(team)+ link_user(user)+ set_auto_model_choice(SLACK_TEAM_ID, SLACK_USER_ID, True)+ set_untagged_followup_mode(SLACK_TEAM_ID, SLACK_USER_ID, UntaggedFollowupMode.ASK)++ assert _refresh(integration) is True++ slack_client.chat_postMessage.assert_not_called()+ state = resolve_onboarding(SLACK_TEAM_ID, SLACK_USER_ID)+ assert state is not None and state.completed and state.root_ts is None+ capture.assert_not_called()+++def test_each_step_is_a_new_reply_and_done_steps_shrink_to_one_line(+ org_team_user, link_user, slack_client: MagicMock, capture: MagicMock+) -> None:+ _, team, user = org_team_user+ integration = _install(team)+ _refresh(integration)++ link_user(user)+ _refresh(integration)+ model_step = _posts(slack_client)[-1]+ edits_after_link = _edits(slack_client)+ update_onboarding(SLACK_TEAM_ID, SLACK_USER_ID, skip_step="model")+ assert plan_onboarding(integration, SLACK_USER_ID).status == (+ "2 of 3 steps done · current step: replies_in_threads · skipped: model"+ )+ set_untagged_followup_mode(SLACK_TEAM_ID, SLACK_USER_ID, UntaggedFollowupMode.AUTO)+ capture.reset_mock()+ finished = _refresh(integration)++ assert "Step 2 of 3" in all_block_text(model_step["blocks"]) and model_step["thread_ts"] == "100.1"+ assert ":white_check_mark: PostHog account linked" in edits_after_link["100.2"]+ assert "Link account" not in edits_after_link["100.2"]+ assert "1 of 3 steps done" in edits_after_link["100.1"]+ ready = _posts(slack_client)[-1]+ edits = _edits(slack_client)+ assert finished is True+ assert ready["thread_ts"] == "100.1"+ assert "You skipped: Your model" in all_block_text(ready["blocks"])+ assert "Skipped: Your model" in edits["100.3"] and "Pick a model" not in edits["100.3"]+ assert "Hey, I'm PostHog" in edits["100.1"] and "Setup done" in edits["100.1"]+ capture.assert_called_once_with(+ integration, "slack app onboarding completed", slack_user_id=SLACK_USER_ID, skipped_steps=["model"]+ )+ posts_before = slack_client.chat_postMessage.call_count+ assert _refresh(integration) is True+ assert slack_client.chat_postMessage.call_count == posts_before+++ "action_id, value, check",+ [+ ("slack_onboarding:auto_model", {}, lambda: resolve_auto_model_choice(SLACK_TEAM_ID, SLACK_USER_ID)),+ (+ "slack_onboarding:replies:never",+ {"mode": "never"},+ lambda: resolve_untagged_followup_mode_for_test() == UntaggedFollowupMode.NEVER,+ ),+ ("slack_onboarding:skip", {"step": "model"}, lambda: _skipped() == ("model",)),+ ],+)+def test_card_clicks_save_the_choice_and_refresh_the_card(action_id: str, value: dict, check, org_team_user) -> None:+ _, team, _ = org_team_user+ integration = _install(team)++ with patch(f"{CLICKS}.request_onboarding") as refresh, patch(f"{CLICKS}.capture_slack_event"):+ response = handle_onboarding_action(_click(integration, action_id, **value))++ assert response.status_code == 200+ assert check()+ refresh.assert_called_once_with(integration, SLACK_USER_ID, may_start=False)+++def test_the_link_step_cannot_be_skipped(org_team_user) -> None:+ _, team, _ = org_team_user+ integration = _install(team)++ with patch(f"{CLICKS}.request_onboarding"):+ handle_onboarding_action(_click(integration, "slack_onboarding:skip", step="link_account"))++ assert resolve_onboarding(SLACK_TEAM_ID, SLACK_USER_ID) is None+++def test_a_model_that_cannot_be_saved_tells_the_person_why(org_team_user) -> None:+ _, team, _ = org_team_user+ integration = _install(team)+ model = "claude-opus-example"++ with (+ patch(f"{MODEL_STEP}.offered_model_choices", return_value=[MagicMock(model=model)]),+ patch(f"{MODEL_STEP}.set_personal_model", side_effect=ValidationError("Link your PostHog account first.")),+ patch(f"{CLICKS}.request_onboarding") as refresh,+ patch(f"{CLICKS}.post_response_url") as reply,+ ):+ payload = _click(integration, "slack_onboarding:model", model=model)+ assert onboarding_integration_hint(payload) == integration.id+ handle_onboarding_action(payload)++ assert reply.call_args.args[1]["text"] == "Link your PostHog account first."+ assert reply.call_args.args[1]["response_type"] == "ephemeral"+ refresh.assert_not_called()+++ "stored, may_start, flag_on, starts",+ [+ ("none", True, True, True),+ ("none", True, False, False),+ ("none", False, True, False),+ ("open", False, False, True),+ ("completed", True, True, False),+ ],+)+def test_only_people_with_onboarding_left_start_the_workflow(+ stored: str, may_start: bool, flag_on: bool, starts: bool, org_team_user+) -> None:+ _, team, _ = org_team_user+ integration = _install(team)+ if stored == "open":+ update_onboarding(SLACK_TEAM_ID, SLACK_USER_ID, root=("D1", "100.1"))+ elif stored == "completed":+ update_onboarding(SLACK_TEAM_ID, SLACK_USER_ID, completed_reason="finished")++ with (+ patch.object(dispatch, "is_slack_app_onboarding_enabled", return_value=flag_on),+ patch.object(dispatch, "_signal_with_start") as start,+ ):+ dispatch.request_onboarding(integration, SLACK_USER_ID, may_start=may_start)++ assert start.called is starts+ if stored == "none":+ state = resolve_onboarding(SLACK_TEAM_ID, SLACK_USER_ID)+ assert (state is not None and state.started_at is not None) is starts+++def test_a_burst_of_new_members_spreads_the_starts_over_time(org_team_user) -> None:+ _, team, _ = org_team_user+ integration = _install(team)+ people = [f"U{index}" for index in range(dispatch.BURST_STARTS_PER_MINUTE + 1)]++ with (+ patch.object(dispatch, "is_slack_app_onboarding_enabled", return_value=True),+ patch.object(dispatch, "_signal_with_start") as start,+ ):+ for person in people:+ dispatch.request_onboarding(integration, person, may_start=True, spread_burst=True)+ dispatch.request_onboarding(integration, "U_OPENED_THE_DM", may_start=True)++ delays = [call.kwargs["start_delay_seconds"] for call in start.call_args_list]+ assert delays == [*[0] * dispatch.BURST_STARTS_PER_MINUTE, 60, 0]+++def resolve_untagged_followup_mode_for_test() -> UntaggedFollowupMode:+ integration = require_workspace_integration(Integration.objects.get(integration_id=SLACK_TEAM_ID).id, SLACK_TEAM_ID)+ return resolve_untagged_followup_mode(integration, SLACK_USER_ID)+++def _skipped() -> tuple[str, ...]:+ state = resolve_onboarding(SLACK_TEAM_ID, SLACK_USER_ID)+ return state.skipped if state else ()+++def test_a_workspace_admin_also_gets_the_workspace_steps_after_linking(+ org_team_user, link_user, slack_workspace_admin: MagicMock, slack_client: MagicMock, capture: MagicMock+) -> None:+ org, team, user = org_team_user+ OrganizationMembership.objects.filter(user=user, organization=org).update(level=OrganizationMembership.Level.ADMIN)+ Organization.objects.filter(id=org.id).update(is_ai_data_processing_approved=False)+ integration = _install(team, scope=ADMIN_SCOPES)+ slack_workspace_admin.return_value = True++ _refresh(integration)+ link_user(user)+ _refresh(integration)++ assert plan_onboarding(integration, SLACK_USER_ID).status == (+ "1 of 7 steps done · current step: ai_consent · skipped: none"+ )+ second_step = all_block_text(_posts(slack_client)[-1]["blocks"])+ assert f"<@{SLACK_USER_ID}> Step 2 of 7" in second_step and "Allow AI data processing" in second_step+++def test_steps_done_before_the_thread_are_left_out_of_the_numbering(+ org_team_user, link_user, slack_client: MagicMock, capture: MagicMock+) -> None:+ _, team, user = org_team_user+ integration = _install(team)+ set_auto_model_choice(SLACK_TEAM_ID, SLACK_USER_ID, True)+ set_untagged_followup_mode(SLACK_TEAM_ID, SLACK_USER_ID, UntaggedFollowupMode.ASK)++ _refresh(integration)+ link_user(user)+ finished = _refresh(integration)++ root, link_step, ready = _posts(slack_client)+ assert "0 of 1 step done" in all_block_text(root["blocks"])+ assert f"<@{SLACK_USER_ID}> Step 1 of 1" in all_block_text(link_step["blocks"])+ assert finished is True and ready["thread_ts"] == "100.1"+ assert "Setup done" in _edits(slack_client)["100.1"]+++def test_a_step_set_elsewhere_keeps_its_number_and_says_it_is_already_set(+ org_team_user, link_user, slack_client: MagicMock, capture: MagicMock+) -> None:+ _, team, user = org_team_user+ integration = _install(team)++ _refresh(integration)+ link_user(user)+ set_auto_model_choice(SLACK_TEAM_ID, SLACK_USER_ID, True)+ _refresh(integration)++ replies_step = all_block_text(_posts(slack_client)[-1]["blocks"])+ assert f"<@{SLACK_USER_ID}> Step 3 of 3" in replies_step+ assert "Step 2, Your model, is already set, so I skipped it." in replies_step+ root = _edits(slack_client)["100.1"]+ assert "2 of 3 steps done" in root and "2. :white_check_mark: Your model: already set" in root+++def test_the_top_message_follows_a_skipped_step_set_later(+ org_team_user, link_user, slack_client: MagicMock, capture: MagicMock+) -> None:+ _, team, user = org_team_user+ integration = _install(team)+ _refresh(integration)+ link_user(user)+ _refresh(integration)+ update_onboarding(SLACK_TEAM_ID, SLACK_USER_ID, skip_step="model")+ _refresh(integration)+ slack_client.chat_update.reset_mock()++ set_auto_model_choice(SLACK_TEAM_ID, SLACK_USER_ID, True)+ _refresh(integration)++ root = _edits(slack_client)["100.1"]+ assert "2 of 3 steps done" in root and "2. :white_check_mark: Model chosen" in root+++def test_a_deleted_top_message_starts_a_new_thread(+ org_team_user, link_user, slack_client: MagicMock, capture: MagicMock+) -> None:+ _, team, user = org_team_user+ integration = _install(team)+ _refresh(integration)+ slack_client.chat_update.side_effect = SlackApiError(+ "message_not_found", {"ok": False, "error": "message_not_found"}+ )+ link_user(user)++ with patch(f"{CARD}.request_onboarding") as plan_again:+ _refresh(integration)+ slack_client.chat_update.side_effect = None+ _refresh(integration)++ assert plan_again.called+ old_root, _, new_root, next_step = _posts(slack_client)+ assert "thread_ts" not in new_root and "0 of 2 steps done" in all_block_text(new_root["blocks"])+ assert next_step["thread_ts"] == "100.3" and "Choose your model" in all_block_text(next_step["blocks"])+++def test_an_org_admin_who_links_later_gets_ai_consent_at_the_end(+ org_team_user, link_user, slack_client: MagicMock, capture: MagicMock+) -> None:+ org, team, user = org_team_user+ OrganizationMembership.objects.filter(user=user, organization=org).update(level=OrganizationMembership.Level.ADMIN)+ Organization.objects.filter(id=org.id).update(is_ai_data_processing_approved=False)+ integration = _install(team)++ _refresh(integration)+ link_user(user)+ _refresh(integration)++ state = resolve_onboarding(SLACK_TEAM_ID, SLACK_USER_ID)+ assert state is not None and state.planned == ("link_account", "model", "replies_in_threads", "ai_consent")+ assert f"<@{SLACK_USER_ID}> Step 2 of 4" in all_block_text(_posts(slack_client)[-1]["blocks"])+++ "action, org_admin, refreshes, message",+ [+ ("ai_consent", True, True, None),+ ("ai_consent", False, False, "Only an organization admin can allow AI data processing."),+ ("inbox_join", True, True, None),+ ("inbox_join_fails", True, False, "I couldn't add you to #posthog-inbox."),+ ("sources", True, False, None),+ ("sources_no_access", True, False, NO_PROJECT_ACCESS_TEXT),+ ("continue", True, True, None),+ ],+)+def test_workspace_step_clicks(+ action: str, org_admin: bool, refreshes: bool, message: str | None, org_team_user, link_user+) -> None:+ org, team, user = org_team_user+ Organization.objects.filter(id=org.id).update(is_ai_data_processing_approved=False)+ if org_admin:+ OrganizationMembership.objects.filter(user=user, organization=org).update(+ level=OrganizationMembership.Level.ADMIN+ )+ if action == "sources_no_access":+ other_org = Organization.objects.create(name="Other Org")+ other_team = Team.objects.create(organization=other_org, name="Other Team")+ Integration.objects.create(team=other_team, kind="slack", integration_id=SLACK_TEAM_ID, config={})+ OrganizationMembership.objects.filter(user=user, organization=org).update(organization=other_org)+ link_user(user)+ integration = _install(team, scope=ADMIN_SCOPES)+ if action.startswith("sources"):+ payload = _click(integration, "slack_onboarding:sources")+ payload["actions"] = [+ {+ "action_id": "slack_onboarding:sources",+ "block_id": f"slack_onboarding_sources:{integration.id}",+ "selected_options": [{"value": "session_replay"}],+ }+ ]+ else:+ payload = _click(integration, f"slack_onboarding:{action.removesuffix('_fails')}", step="sources")++ with (+ patch(f"{CLICKS}.request_onboarding") as refresh,+ patch(f"{CLICKS}.post_response_url") as reply,+ patch(f"{CLICKS}.capture_slack_event"),+ patch(f"{STEP}.capture_slack_event"),+ patch(f"{INBOX_STEP}.ensure_inbox_channel", return_value=("C_INBOX", "#posthog-inbox")),+ patch(f"{INBOX_STEP}.invite_user_to_inbox", return_value=action != "inbox_join_fails") as invite,+ patch("products.signals.backend.facade.api.set_sources") as set_sources,+ ):+ handle_onboarding_action(payload)++ assert refresh.called is refreshes+ assert (reply.call_args.args[1]["text"].split(" Create")[0] if reply.called else None) == message+ if action == "ai_consent":+ org.refresh_from_db()+ assert org.is_ai_data_processing_approved is org_admin+ if action == "inbox_join":+ invite.assert_called_once_with(integration, "C_INBOX", SLACK_USER_ID)+ assert "inbox_channel" in get_state(SLACK_TEAM_ID, SLACK_USER_ID).used+ if action == "sources":+ set_sources.assert_called_once_with(team.id, user.id, ["session_replay"])+ if action == "sources_no_access":+ set_sources.assert_not_called()+ if action == "continue":+ # Continue with no signal ticked closes the step, so the thread moves on.+ assert _skipped() == ("sources",)diff --git a/products/slack_app/backend/tests/logic/test_feature_tips.py b/products/slack_app/backend/tests/logic/test_feature_tips.pyindex 88d6254b82b5..9a96b8e839eb 100644--- a/products/slack_app/backend/tests/logic/test_feature_tips.py+++ b/products/slack_app/backend/tests/logic/test_feature_tips.py@@ -100,28 +100,41 @@ class TestOfferFeatureTip:@parameterized.expand([- ("opted out", {"opted_out_at": "2026-01-01T00:00:00Z"}, None, None),+ ("opted out", {"opted_out_at": "2026-01-01T00:00:00Z"}, None, None, None),("chose a follow-up mode before tips existed",{},UntaggedFollowupMode.NEVER,+ None,SlackFeature.FILE_ATTACHMENTS,),("used a feature that leaves no setting",{"used": {"file_attachments": "2026-01-01T00:00:00Z"}},UntaggedFollowupMode.NEVER,+ None,SlackFeature.MODEL_IN_MENTION,),+ ("is in the middle of onboarding", {}, None, {"started_at": "2026-01-01T00:00:00Z"}, None),+ (+ "finished onboarding",+ {},+ None,+ {"started_at": "2026-01-01T00:00:00Z", "completed_at": "2026-01-02T00:00:00Z"},+ SlackFeature.THREAD_FOLLOWUP,+ ),])- def test_skips_what_the_reader_turned_off_or_already_uses(self, _name, stored_state, followup_mode, expected):+ def test_skips_what_the_reader_turned_off_or_already_uses(+ self, _name, stored_state, followup_mode, onboarding, expected+ ):self._threads(3)SlackSettings.objects.create(slack_workspace_id=WORKSPACE,slack_user_id=SLACK_USER,untagged_followup_mode=followup_mode,feature_tips={"backfilled_at": "2026-01-01T00:00:00Z", "interaction_count": 5, **stored_state},+ onboarding=onboarding,)assert self._offer() == expecteddiff --git a/products/slack_app/backend/tests/test_channel_onboarding_routing.py b/products/slack_app/backend/tests/test_channel_onboarding_routing.pyindex feaa757214c2..a7c9cc264451 100644--- a/products/slack_app/backend/tests/test_channel_onboarding_routing.py+++ b/products/slack_app/backend/tests/test_channel_onboarding_routing.py@@ -244,6 +244,22 @@ class TestTeamJoinRouting(_SlackRoutingTestBase):assert instance.client.chat_postMessage.call_args.kwargs["channel"] == self.JOINER_IDassert cache.get(_team_join_onboarding_cache_key(self.SLACK_TEAM_ID, self.JOINER_ID)) is True+ @patch("products.slack_app.backend.api.request_onboarding")+ @patch("products.slack_app.backend.api.is_slack_app_onboarding_enabled", return_value=True)+ @patch("products.slack_app.backend.api.is_slack_app_assistant_enabled", return_value=True)+ @patch("products.slack_app.backend.api.SlackIntegration")+ def test_with_onboarding_on_a_new_member_gets_the_onboarding_thread_instead(+ self, slack_cls, _flag, _onboarding_flag, start_onboarding+ ):+ instance = self._mock_slack(slack_cls)++ result = route_posthog_code_event_to_relevant_region(self._request(), self._event(), self.SLACK_TEAM_ID)++ assert result == ROUTE_HANDLED_LOCALLY+ instance.client.chat_postMessage.assert_not_called()+ assert start_onboarding.call_args.args[1] == self.JOINER_ID+ assert start_onboarding.call_args.kwargs == {"may_start": True, "spread_burst": True}+@parameterized.expand([("bot", {"is_bot": True}),diff --git a/products/slack_app/backend/tests/test_onboarding.py b/products/slack_app/backend/tests/test_onboarding.pyindex 56d340539498..5ca6aa1ec3eb 100644--- a/products/slack_app/backend/tests/test_onboarding.py+++ b/products/slack_app/backend/tests/test_onboarding.py@@ -58,8 +58,9 @@ class TestOnboarding:assert onboarding.send_onboarding_dm(self.integration, "") is Falseclient.chat_postMessage.assert_not_called()+ @pytest.mark.parametrize("setup_thread_enabled", [False, True])@patch("posthog.models.integration.slack.WebClient")- def test_run_install_onboarding_creates_invites_and_dms(self, mock_webclient_class):+ def test_run_install_onboarding_creates_invites_and_dms(self, mock_webclient_class, setup_thread_enabled):client = self._client(mock_webclient_class)self.integration.config = {"scope": "channels:manage,chat:write", "authed_user": {"id": "U_INSTALL"}}self.integration.save()@@ -67,11 +68,19 @@ class TestOnboarding:client.conversations_create.return_value = {"channel": {"id": "C_NEW"}}client.conversations_info.return_value = {"channel": {"id": "C_NEW"}}- onboarding.run_install_onboarding(self.integration)+ with (+ patch.object(onboarding, "is_slack_app_onboarding_enabled", return_value=setup_thread_enabled),+ patch.object(onboarding, "request_onboarding") as start_setup_thread,+ ):+ 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 client.chat_postMessage.called is not setup_thread_enabled+ assert start_setup_thread.called is setup_thread_enabled+ if setup_thread_enabled:+ assert start_setup_thread.call_args.args[1] == "U_INSTALL"+ assert start_setup_thread.call_args.kwargs == {"may_start": True}assert get_default_slack_notification_channel(self.team.id) == "C_NEW|#posthog-inbox"@patch("posthog.models.integration.slack.WebClient")@@ -303,12 +312,14 @@ class TestOnboarding:("T12345", "chat:write", True, False),],)+ @patch("products.slack_app.backend.signals._start_installer_onboarding")@patch("products.slack_app.backend.signals._start_inbox_onboarding_workflow")@patch("products.slack_app.backend.analytics.capture_slack_event")def test_install_captures_installed_for_every_fresh_install(self,mock_capture,mock_start,+ mock_start_installer_onboarding,django_capture_on_commit_callbacks,slack_team_id,scope,@@ -335,6 +346,23 @@ class TestOnboarding:"workspace_already_linked": workspace_already_linked,}assert mock_start.called is onboards+ # Without the inbox scopes there is no inbox workflow to start it, so the installer's onboarding starts directly.+ assert mock_start_installer_onboarding.called is not onboards++ @patch("products.slack_app.backend.signals._start_installer_onboarding")+ @patch("products.slack_app.backend.signals._start_inbox_onboarding_workflow")+ @patch("products.slack_app.backend.analytics.capture_slack_event")+ def test_reinstall_starts_only_the_installers_onboarding(+ self, mock_capture, mock_start, mock_start_installer_onboarding, django_capture_on_commit_callbacks+ ):+ self.integration.config = {"scope": "channels:manage,chat:write", "authed_user": {"id": "U_INSTALL"}}++ with django_capture_on_commit_callbacks(execute=True):+ self.integration.save()++ mock_capture.assert_not_called()+ mock_start.assert_not_called()+ mock_start_installer_onboarding.assert_called_once()@patch("products.slack_app.backend.onboarding.run_install_onboarding")def test_onboarding_workflow_activity_runs_for_integration(self, mock_run):diff --git a/products/slack_app/backend/tests/test_zz_app_home_routing.py b/products/slack_app/backend/tests/test_zz_app_home_routing.pyindex 83b926975073..b526d9c79fe3 100644--- a/products/slack_app/backend/tests/test_zz_app_home_routing.py+++ b/products/slack_app/backend/tests/test_zz_app_home_routing.py@@ -14,6 +14,8 @@ from unittest.mock import MagicMock, patchfrom django.test import RequestFactory, TestCase+from parameterized import parameterized+from posthog.models.integration import Integrationfrom posthog.models.organization import Organizationfrom posthog.models.team import Team@@ -44,10 +46,10 @@ class TestAppHomeOpenedRegionRouting(TestCase):write_auth_state_ok(integration.id, bot_user_id=None)return integration- def _route(self, host: str = "eu.posthog.com") -> str:+ def _route(self, host: str = "eu.posthog.com", tab: str = "home") -> str:request = self.factory.post("/slack/event-callback/", HTTP_HOST=host)return route_posthog_code_event_to_relevant_region(- request, {"type": "app_home_opened", "user": "U001"}, self.SLACK_TEAM_ID+ request, {"type": "app_home_opened", "user": "U001", "tab": tab}, self.SLACK_TEAM_ID)@patch("products.slack_app.backend.api.get_instance_region", return_value="EU")@@ -62,15 +64,25 @@ class TestAppHomeOpenedRegionRouting(TestCase):assert mock_proxy.calledassert not mock_publish.called+ @parameterized.expand([("home",), ("messages",)])@patch("products.slack_app.backend.api.does_other_region_claim_workspace", return_value=False)@patch("products.slack_app.backend.api.get_instance_region", return_value="EU")@patch("products.slack_app.backend.api._proxy_event_to_region")+ @patch("products.slack_app.backend.api.request_onboarding")@patch("products.slack_app.backend.api._handle_app_home_opened")def test_publishes_locally_when_workspace_is_local(- self, mock_publish: MagicMock, mock_proxy: MagicMock, _region: MagicMock, _claims: MagicMock+ self,+ tab: str,+ mock_publish: MagicMock,+ mock_setup_card: MagicMock,+ mock_proxy: MagicMock,+ _region: MagicMock,+ _claims: MagicMock,) -> None:integration = self._create_local_integration()- assert self._route() == ROUTE_HANDLED_LOCALLY+ assert self._route(tab=tab) == ROUTE_HANDLED_LOCALLYassert not mock_proxy.calledassert mock_publish.call_args.kwargs["integration"] == integration+ assert mock_setup_card.called+ assert mock_setup_card.call_args.kwargs == {"may_start": True}diff --git a/products/slack_app/backend/tests/views/test_slack_user_link.py b/products/slack_app/backend/tests/views/test_slack_user_link.pyindex c387fee877fd..e0bd065b35a2 100644--- a/products/slack_app/backend/tests/views/test_slack_user_link.py+++ b/products/slack_app/backend/tests/views/test_slack_user_link.py@@ -176,10 +176,12 @@ class TestCallbackView:patch("products.slack_app.backend.views.slack_user_link.exchange_code", return_value=self._identity()),patch("posthog.models.integration.slack.WebClient"),patch("products.slack_app.backend.analytics.ph_background_capture") as mock_ph,+ patch("products.slack_app.backend.views.slack_user_link.request_onboarding") as mock_refresh_card,):response = client.get(f"/complete/slack-link/?code=abc&state={state}")self._assert_settings_redirect_success(response)+ assert mock_refresh_card.call_args.args[1] == SLACK_USER_IDmock_ph.return_value.alias.assert_called_once_with(previous_id=user.distinct_id, distinct_id=f"slack:{SLACK_TEAM_ID}:{SLACK_USER_ID}")diff --git a/products/slack_app/backend/views/slack_user_link.py b/products/slack_app/backend/views/slack_user_link.pyindex d4c4efae0d62..4efbf67d172a 100644--- a/products/slack_app/backend/views/slack_user_link.py+++ b/products/slack_app/backend/views/slack_user_link.py@@ -46,6 +46,7 @@ from posthog.views import login_requiredfrom products.slack_app.backend.analytics import alias_slack_user, capture_slack_eventfrom products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled+from products.slack_app.backend.logic.onboarding.dispatch import request_onboardingfrom products.slack_app.backend.services.slack_user_oauth import (CallbackState,InviteToken,@@ -270,6 +271,7 @@ def slack_user_link_callback(request: HttpRequest) -> HttpResponse:channel=state.channel,thread_ts=state.thread_ts,)+ request_onboarding(workspace_integration, identity.slack_user_id, may_start=False)return _settings_redirect()