: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): let thread creators choose who joins their threads (#121142)
Vojta Bartoš54d920d16086
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex 907b095708fb..2ee314924565 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -409,6 +409,7 @@ rules:|SignalProjectProfile|SingleSessionSummary|SlackThreadTaskMapping+ |SlackThreadJoin|SourceBatch|SourceGroupLease|StreamlitApp@@ -875,6 +876,7 @@ rules:|SignalProjectProfile|SingleSessionSummary|SlackThreadTaskMapping+ |SlackThreadJoin|SourceBatch|SourceGroupLease|StreamlitAppdiff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.pyindex bd5891864408..ab124651712b 100644--- a/products/slack_app/backend/api.py+++ b/products/slack_app/backend/api.py@@ -59,6 +59,7 @@ from products.slack_app.backend.models import (ChannelWelcomeMode,SlackChannel,SlackSettings,+ SlackThreadJoin,SlackThreadTaskMapping,UntaggedFollowupMode,)@@ -213,6 +214,13 @@ UNTAGGED_FOLLOWUP_BLOCK_ID_PREFIX = "posthog_code_untagged_followup"UNTAGGED_FOLLOWUP_ACTION_RUN = "posthog_code_untagged_followup_run"UNTAGGED_FOLLOWUP_ACTION_DISMISS = "posthog_code_untagged_followup_dismiss"UNTAGGED_FOLLOWUP_CONTEXT_KIND = "untagged_followup"++THREAD_JOIN_BLOCK_ID_PREFIX = "posthog_code_thread_join"+THREAD_JOIN_ACTION_ALLOW = "posthog_code_thread_join_allow"+THREAD_JOIN_ACTION_DECLINE = "posthog_code_thread_join_decline"+THREAD_JOIN_CONTEXT_KIND = "thread_join"+# The thread creator is often away when someone asks to join, so the prompt outlives a picker.+THREAD_JOIN_PROMPT_MAX_AGE_SECONDS = 24 * 60 * 60UNTAGGED_QUESTION_BLOCK_ID_PREFIX = "posthog_code_untagged_question"UNTAGGED_QUESTION_ACTION_RUN = "posthog_code_untagged_question_run"UNTAGGED_QUESTION_ACTION_DISMISS = "posthog_code_untagged_question_dismiss"@@ -4169,6 +4177,253 @@ def _handle_untagged_question_turn_off(payload: dict) -> HttpResponse:return HttpResponse(status=200)+def _thread_join_pending_key(integration_id: int, channel: str, thread_ts: str, joiner_slack_user_id: str) -> str:+ return f"slack_app_thread_join_pending:{integration_id}:{channel}:{thread_ts}:{joiner_slack_user_id}"+++def post_thread_join_prompt(+ slack: SlackIntegration,+ integration: Integration,+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ *,+ channel: str,+ thread_ts: str,+ owner_slack_user_id: str,+ joiner_slack_user_id: str,+ opens_thread: bool,+) -> None:+ """Ask the thread creator whether someone else may join their thread.++ ``opens_thread`` says that approving lets anyone join the thread, not only this person.++ The whole event is stashed behind a one-off token, so letting them join sends the original+ message rather than a reconstruction of it. The person who asked hears that the creator was+ asked, so their message does not seem lost. While a prompt for this person waits, their+ next messages post no new prompt, so a chatty joiner cannot flood the creator.+ """+ pending_key = _thread_join_pending_key(integration.id, channel, thread_ts, joiner_slack_user_id)+ if not cache.add(pending_key, True, timeout=THREAD_JOIN_PROMPT_MAX_AGE_SECONDS):+ return++ context_token = uuid.uuid4().hex+ cache.set(+ _picker_context_cache_key(context_token),+ {+ "kind": THREAD_JOIN_CONTEXT_KIND,+ "integration_id": integration.id,+ "slack_channel_id": channel,+ "thread_ts": thread_ts,+ "owner_slack_user_id": owner_slack_user_id,+ "joiner_slack_user_id": joiner_slack_user_id,+ "event": inputs.event,+ "untagged_followup": inputs.untagged_followup,+ "untagged_followup_confirmed": inputs.untagged_followup_confirmed,+ "is_ext_shared_channel": inputs.is_ext_shared_channel,+ },+ timeout=THREAD_JOIN_PROMPT_MAX_AGE_SECONDS,+ )+ home_tab_url = app_home_url(integration)+ home_tab_label = f"<{home_tab_url}|PostHog app Home tab>" if home_tab_url else "PostHog app Home tab"+ blocks: list[dict[str, Any]] = [+ {+ "type": "section",+ "block_id": f"{THREAD_JOIN_BLOCK_ID_PREFIX}:{context_token}",+ "text": {+ "type": "mrkdwn",+ "text": f"<@{joiner_slack_user_id}> wants to work with me in your thread. "+ + ("Let anyone join this thread?" if opens_thread else "Let them join?"),+ },+ },+ {+ "type": "actions",+ "block_id": f"{THREAD_JOIN_BLOCK_ID_PREFIX}_actions:{context_token}",+ "elements": [+ {+ "type": "button",+ "action_id": THREAD_JOIN_ACTION_ALLOW,+ "style": "primary",+ "text": {"type": "plain_text", "text": "Let anyone join" if opens_thread else "Let them join"},+ "value": context_token,+ },+ {+ "type": "button",+ "action_id": THREAD_JOIN_ACTION_DECLINE,+ "text": {"type": "plain_text", "text": "Not now"},+ "value": context_token,+ },+ ],+ },+ {+ "type": "context",+ "elements": [+ {+ "type": "mrkdwn",+ "text": f"In the {home_tab_label} you can choose who joins your threads.",+ }+ ],+ },+ ]+ try:+ slack.client.chat_postEphemeral(+ channel=channel,+ user=owner_slack_user_id,+ thread_ts=thread_ts,+ text="Someone wants to join your PostHog thread.",+ blocks=blocks,+ )+ slack.client.chat_postEphemeral(+ channel=channel,+ user=joiner_slack_user_id,+ thread_ts=thread_ts,+ text=f"I asked <@{owner_slack_user_id}> to let you join this thread. I'll pick up your message if they do.",+ )+ except Exception:+ logger.warning(+ "slack_app_thread_join_prompt_failed",+ integration_id=integration.id,+ slack_channel_id=channel,+ exc_info=True,+ )+ cache.delete(pending_key)+ return+ capture_slack_event(integration, "slack app thread join requested", slack_user_id=joiner_slack_user_id)+++def _thread_join_context(payload: dict) -> tuple[str, dict[str, Any]] | None:+ """The live join prompt this click answers, when the thread creator is the one clicking."""+ context_token = _extract_context_token(payload)+ context = _decode_picker_context(context_token) if context_token else None+ if not context or context.get("kind") != THREAD_JOIN_CONTEXT_KIND:+ return None+ # The prompt is ephemeral, so only the creator sees it, but the answer acts for them.+ if payload.get("user", {}).get("id", "") != context.get("owner_slack_user_id"):+ return None+ return context_token, context+++def _close_thread_join_prompt(context_token: str, context: dict[str, Any], response_url: str) -> None:+ """Forget an answered prompt, so the same person can ask again with their next message."""+ cache.delete(_picker_context_cache_key(context_token))+ cache.delete(+ _thread_join_pending_key(+ context["integration_id"],+ context["slack_channel_id"],+ context["thread_ts"],+ context["joiner_slack_user_id"],+ )+ )+ _delete_ephemeral_via_response_url(response_url)+++def _handle_thread_join_allow(payload: dict) -> HttpResponse:+ """Let the person join the thread, then send the message that asked to join.++ The prompt stays open until the message is sent, so a click that fails on a database or+ Temporal error can be repeated. Only an answer that can never succeed closes it early.+ """+ response_url = payload.get("response_url", "")+ found = _thread_join_context(payload)+ slack_team_id = payload.get("team", {}).get("id", "")+ if found is None:+ _delete_ephemeral_via_response_url(response_url)+ return HttpResponse(status=200)+ context_token, context = found+ integration_id = context.get("integration_id")+ if not slack_team_id or not isinstance(integration_id, int):+ _close_thread_join_prompt(context_token, context, response_url)+ return HttpResponse(status=200)+ integration = (+ Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get+ kind=SLACK_INTEGRATION_KIND,+ integration_id=slack_team_id,+ )+ .select_related("team__organization")+ .first()+ )+ joiner_slack_user_id = context.get("joiner_slack_user_id")+ event = context.get("event")+ if integration is None or not isinstance(joiner_slack_user_id, str) or not isinstance(event, dict):+ _close_thread_join_prompt(context_token, context, response_url)+ return HttpResponse(status=200)++ mapping = (+ SlackThreadTaskMapping.objects.filter(+ integration_id=integration.id,+ channel=context.get("slack_channel_id"),+ thread_ts=context.get("thread_ts"),+ )+ .only("id", "team_id")+ .first()+ )+ if mapping is None:+ _close_thread_join_prompt(context_token, context, response_url)+ return HttpResponse(status=200)+ # The message re-enters the pipeline past the webhook's gates, so the joiner's access to the+ # mapped project is checked again here.+ joiner = _is_org_member(integration, joiner_slack_user_id)+ if joiner is None or not _can_access_team(joiner, integration):+ _close_thread_join_prompt(context_token, context, response_url)+ return HttpResponse(status=200)+ # The unique constraint makes a double click or a retry a no-op.+ SlackThreadJoin.objects.for_team(mapping.team_id).get_or_create(+ thread_mapping=mapping,+ slack_user_id=joiner_slack_user_id,+ defaults={"team_id": mapping.team_id},+ )++ _start_mention_workflow(+ event,+ integration,+ slack_team_id,+ None,+ posthog_user=joiner,+ untagged_followup=bool(context.get("untagged_followup")),+ untagged_followup_confirmed=bool(context.get("untagged_followup_confirmed")),+ thread_join_approved=True,+ is_ext_shared_channel=bool(context.get("is_ext_shared_channel")),+ )+ _close_thread_join_prompt(context_token, context, response_url)+ capture_slack_event(+ integration,+ "slack app thread join allowed",+ slack_user_id=payload.get("user", {}).get("id"),+ )+ return HttpResponse(status=200)+++def _handle_thread_join_decline(payload: dict) -> HttpResponse:+ """Drop the message and tell the person who asked. Nothing is stored, so they can ask again later."""+ response_url = payload.get("response_url", "")+ found = _thread_join_context(payload)+ if found is None:+ _delete_ephemeral_via_response_url(response_url)+ return HttpResponse(status=200)+ context_token, context = found+ _close_thread_join_prompt(context_token, context, response_url)+ integration_id = context.get("integration_id")+ if not isinstance(integration_id, int):+ return HttpResponse(status=200)+ integration = Integration.objects.filter( # nosemgrep: idor-lookup-without-team+ id=integration_id, # nosemgrep: idor-taint-user-input-to-model-get+ kind=SLACK_INTEGRATION_KIND,+ integration_id=payload.get("team", {}).get("id", ""),+ ).first()+ if integration is None:+ return HttpResponse(status=200)+ try:+ SlackIntegration(integration).client.chat_postEphemeral(+ channel=context["slack_channel_id"],+ user=context["joiner_slack_user_id"],+ thread_ts=context["thread_ts"],+ text=f"<@{context['owner_slack_user_id']}> didn't let you join this thread, so I won't pick up your message.",+ )+ except Exception:+ logger.warning("slack_app_thread_join_decline_notice_failed", integration_id=integration.id, exc_info=True)+ capture_slack_event(integration, "slack app thread join declined", slack_user_id=context["owner_slack_user_id"])+ return HttpResponse(status=200)++def _can_access_team(posthog_user: User, integration: Integration) -> bool:"""Whether the user can reach the integration's project.@@ -4640,6 +4895,7 @@ def _start_mention_workflow(untagged_followup_confirmed: bool = False,untagged_question: bool = False,untagged_question_confirmed: bool = False,+ thread_join_approved: bool = False,is_ext_shared_channel: bool = False,awaited_request_reply: bool = False,fork_source_channel: str | None = None,@@ -4685,6 +4941,7 @@ def _start_mention_workflow(untagged_followup_confirmed=untagged_followup_confirmed,untagged_question=untagged_question,untagged_question_confirmed=untagged_question_confirmed,+ thread_join_approved=thread_join_approved,is_ext_shared_channel=is_ext_shared_channel,fork_source_channel=fork_source_channel,fork_source_thread_ts=fork_source_thread_ts,@@ -6201,6 +6458,10 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:return _handle_untagged_followup_run(payload)if action_id == UNTAGGED_FOLLOWUP_ACTION_DISMISS:return _handle_untagged_followup_dismiss(payload)+ if action_id == THREAD_JOIN_ACTION_ALLOW:+ return _handle_thread_join_allow(payload)+ if action_id == THREAD_JOIN_ACTION_DECLINE:+ return _handle_thread_join_decline(payload)if action_id == UNTAGGED_QUESTION_ACTION_RUN:return _handle_untagged_question_run(payload)if action_id == UNTAGGED_QUESTION_ACTION_DISMISS:diff --git a/products/slack_app/backend/feature_flags.py b/products/slack_app/backend/feature_flags.pyindex 09fa37197b3c..f9246ecf1c50 100644--- a/products/slack_app/backend/feature_flags.py+++ b/products/slack_app/backend/feature_flags.py@@ -48,6 +48,7 @@ logger = structlog.get_logger(__name__)SLACK_APP_AGENT_DESIGN_FLAG = "slack-app-agent-design"SLACK_APP_CHART_LINKS_FLAG = "slack-app-chart-links"SLACK_APP_FORKING_FLAG = "slack-app-forking"+SLACK_APP_MULTIPLAYER_APPROVALS_FLAG = "slack-app-multiplayer-approvals"SLACK_APP_UNPROMPTED_ANSWERS_FLAG = "slack-app-unprompted-answers"@@ -138,6 +139,20 @@ def is_slack_app_chart_links_enabled(integration: Integration) -> bool:)+def is_slack_app_multiplayer_approvals_enabled(integration: Integration, distinct_id: str | None) -> bool:+ """Gate for the thread creator's choice of who may join their threads.++ ``distinct_id`` is the thread creator's PostHog user. With the gate closed, anyone with+ project access can join, and the Home tab hides the setting.+ """+ return _workspace_flag_enabled(+ SLACK_APP_MULTIPLAYER_APPROVALS_FLAG,+ integration,+ failure_log_key="slack_app_multiplayer_approvals_feature_flag_check_failed",+ distinct_id=distinct_id,+ )++def is_slack_app_unprompted_answers_enabled(integration: Integration) -> bool:"""Gate for answering top-level channel messages nobody tagged the app in.diff --git a/products/slack_app/backend/logic/thread_join.py b/products/slack_app/backend/logic/thread_join.pynew file mode 100644index 000000000000..84d3e5c45f51--- /dev/null+++ b/products/slack_app/backend/logic/thread_join.py@@ -0,0 +1,51 @@+"""Whether someone other than the thread creator may send messages to the thread's task."""++from enum import StrEnum+from typing import TYPE_CHECKING++from products.slack_app.backend.feature_flags import is_slack_app_multiplayer_approvals_enabled+from products.slack_app.backend.models import SlackThreadJoin, ThreadJoinMode+from products.slack_app.backend.services.slack_settings import resolve_thread_join_mode++if TYPE_CHECKING:+ from posthog.models.integration import Integration++ from products.slack_app.backend.models import SlackThreadTaskMapping+++class ThreadJoinDecision(StrEnum):+ ALLOW = "allow"+ # Ask the creator, and let only this person join.+ ASK_FOR_PERSON = "ask_for_person"+ # Ask the creator, and let anyone join the thread once they approve.+ ASK_FOR_THREAD = "ask_for_thread"+ DENY = "deny"+++def decide_thread_join(+ integration: "Integration", mapping: "SlackThreadTaskMapping", slack_user_id: str+) -> ThreadJoinDecision:+ """The creator's join mode applied to one person, given the approvals the thread already has.++ A person's approval holds whatever the mode is now, because a mode change applies to new+ people only. With the rollout flag off for the creator, the stored mode does not apply.+ """+ mode = resolve_thread_join_mode(integration, mapping.mentioning_slack_user_id)+ if mode == ThreadJoinMode.ALLOW:+ return ThreadJoinDecision.ALLOW+ # Checked after the mode, so a creator who lets anyone join costs no flag request.+ creator = mapping.task.created_by+ if not is_slack_app_multiplayer_approvals_enabled(integration, creator.distinct_id if creator else None):+ return ThreadJoinDecision.ALLOW+ approved = set(+ SlackThreadJoin.objects.for_team(mapping.team_id)+ .filter(thread_mapping_id=mapping.id)+ .values_list("slack_user_id", flat=True)+ )+ if slack_user_id in approved or (mode == ThreadJoinMode.ASK_PER_THREAD and approved):+ return ThreadJoinDecision.ALLOW+ if mode == ThreadJoinMode.ASK_PER_PERSON:+ return ThreadJoinDecision.ASK_FOR_PERSON+ if mode == ThreadJoinMode.ASK_PER_THREAD:+ return ThreadJoinDecision.ASK_FOR_THREAD+ return ThreadJoinDecision.DENYdiff --git a/products/slack_app/backend/migrations/0022_thread_join_mode.py b/products/slack_app/backend/migrations/0022_thread_join_mode.pynew file mode 100644index 000000000000..8751c2efdf65--- /dev/null+++ b/products/slack_app/backend/migrations/0022_thread_join_mode.py@@ -0,0 +1,73 @@+# Generated by Django 5.2.18 on 2026-10-21 11:14++import django.db.models.deletion+from django.db import migrations, models++import posthog.uuidt+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1405_user_onboarding_skipped_reason_connector"),+ ("slack_app", "0021_slacksettings_untagged_question_mode"),+ ]++ operations = [+ migrations.AddField(+ model_name="slacksettings",+ name="thread_join_mode",+ field=models.CharField(+ blank=True,+ choices=[+ ("never", "Ignore them"),+ ("ask_per_person", "Ask me for each person"),+ ("ask_per_thread", "Ask me once per thread"),+ ("allow", "Let anyone join"),+ ],+ help_text="What PostHog does when someone else tags it in threads this user started.",+ max_length=16,+ null=True,+ ),+ ),+ migrations.CreateModel(+ name="SlackThreadJoin",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.uuidt.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("slack_user_id", models.CharField(max_length=64)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="+",+ to="posthog.team",+ ),+ ),+ (+ "thread_mapping",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="joins",+ to="slack_app.slackthreadtaskmapping",+ ),+ ),+ ],+ options={+ "constraints": [+ models.UniqueConstraint(+ fields=("thread_mapping", "slack_user_id"),+ name="uniq_slack_thread_join",+ )+ ],+ },+ ),+ ]diff --git a/products/slack_app/backend/migrations/max_migration.txt b/products/slack_app/backend/migrations/max_migration.txtindex 19664f63b5a9..28808c951e4d 100644--- a/products/slack_app/backend/migrations/max_migration.txt+++ b/products/slack_app/backend/migrations/max_migration.txt@@ -1 +1 @@-0021_slacksettings_untagged_question_mode+0022_thread_join_modediff --git a/products/slack_app/backend/models.py b/products/slack_app/backend/models.pyindex b3d4f3bc35c4..46748d24ded5 100644--- a/products/slack_app/backend/models.py+++ b/products/slack_app/backend/models.py@@ -1,6 +1,7 @@from django.db import modelsfrom django.db.models import Q+from posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDModel@@ -76,6 +77,27 @@ class SlackThreadTaskMapping(UUIDModel):]+class SlackThreadJoin(TeamScopedRootMixin, UUIDModel):+ """A person the thread creator let join their thread under an ask join mode.++ Only the thread creator can approve, so the approver is the mapping's+ ``mentioning_slack_user_id``. Joining lets the person send messages to the thread's task, so+ the row keeps when the approval happened.+ """++ # db_constraint=False: a foreign key constraint to posthog_team locks that hot table when the+ # table is created. The mapping cascade removes these rows when a team goes.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+", db_constraint=False)+ thread_mapping = models.ForeignKey(SlackThreadTaskMapping, on_delete=models.CASCADE, related_name="joins")+ slack_user_id = models.CharField(max_length=64)+ created_at = models.DateTimeField(auto_now_add=True)++ class Meta:+ constraints = [+ models.UniqueConstraint(fields=["thread_mapping", "slack_user_id"], name="uniq_slack_thread_join"),+ ]++# A direct message is the only conversation with no audience beyond its author, so a task# started in one stays with its creator. Everything else — group DMs and channels, public or# private — is shared with people who are all on the same team, and anything asked there is@@ -126,6 +148,19 @@ class UntaggedFollowupMode(models.TextChoices):NEVER = "never", "Never pick it up"+class ThreadJoinMode(models.TextChoices):+ """What PostHog does when someone else tags it in a thread a user started.++ Read from the thread creator's settings row. An unset row resolves to ``ASK_PER_THREAD``.+ Under ``ASK_PER_THREAD`` the creator's first approval in a thread lets anyone join it.+ """++ NEVER = "never", "Ignore them"+ ASK_PER_PERSON = "ask_per_person", "Ask me for each person"+ ASK_PER_THREAD = "ask_per_thread", "Ask me once per thread"+ ALLOW = "allow", "Let anyone join"++class ChannelWelcomeMode(models.TextChoices):"""Where the greeting goes when someone adds the app to a channel.@@ -191,6 +226,14 @@ class SlackSettings(UUIDModel):choices=UntaggedFollowupMode.choices,help_text="What PostHog does with this user's top-level channel questions that do not tag the app.",)+ # NULL means the user has never picked, which resolves to ``ASK_PER_THREAD``.+ thread_join_mode = models.CharField(+ max_length=16,+ null=True,+ blank=True,+ choices=ThreadJoinMode.choices,+ help_text="What PostHog does when someone else tags it in threads this user started.",+ )# Only read on the workspace-wide row. NULL resolves to ``CHANNEL``.channel_welcome_mode = models.CharField(max_length=16,diff --git a/products/slack_app/backend/services/slack_app_home.py b/products/slack_app/backend/services/slack_app_home.pyindex a880ec266b63..cdd61755d3c4 100644--- a/products/slack_app/backend/services/slack_app_home.py+++ b/products/slack_app/backend/services/slack_app_home.py@@ -33,11 +33,16 @@ from posthog.models.user_integration import UserIntegrationfrom posthog.user_permissions import UserPermissionsfrom products.slack_app.backend.analytics import capture_slack_event-from products.slack_app.backend.feature_flags import is_slack_app_oauth_enabled, is_slack_app_unprompted_answers_enabled+from products.slack_app.backend.feature_flags import (+ is_slack_app_multiplayer_approvals_enabled,+ is_slack_app_oauth_enabled,+ is_slack_app_unprompted_answers_enabled,+)from products.slack_app.backend.models import (ChannelWelcomeMode,SlackSettings,SlackUserProfileCache,+ ThreadJoinMode,UntaggedFollowupMode,)from products.slack_app.backend.services.integration_resolver import load_integrations, resolve_from_candidates@@ -72,10 +77,12 @@ from products.slack_app.backend.services.slack_settings import (AIPreferences,resolve_auto_model_choice,resolve_channel_welcome_mode,+ resolve_thread_join_mode,resolve_untagged_followup_mode,resolve_untagged_question_mode,set_auto_model_choice,set_channel_welcome_mode,+ set_thread_join_mode,set_untagged_followup_mode,set_untagged_question_mode,)@@ -102,6 +109,7 @@ ACTION_TASKS_REFRESH = "slack_app_home:tasks_refresh"ACTION_TASKS_PAGE_PREV = "slack_app_home:tasks_page_prev"ACTION_TASKS_PAGE_NEXT = "slack_app_home:tasks_page_next"ACTION_STATS_WINDOW = "slack_app_home:stats_window"+ACTION_SET_THREAD_JOIN_MODE = "slack_app_home:set_thread_join_mode"ACTION_STATS_REFRESH = "slack_app_home:stats_refresh"ACTION_SET_UNTAGGED_FOLLOWUP_MODE = "slack_app_home:set_untagged_followup_mode"ACTION_SET_UNTAGGED_QUESTION_MODE = "slack_app_home:set_untagged_question_mode"@@ -129,6 +137,7 @@ HOME_ACTION_IDS: frozenset[str] = frozenset(ACTION_TASKS_REFRESH,ACTION_TASKS_PAGE_PREV,ACTION_TASKS_PAGE_NEXT,+ ACTION_SET_THREAD_JOIN_MODE,ACTION_STATS_WINDOW,ACTION_STATS_REFRESH,ACTION_SET_UNTAGGED_FOLLOWUP_MODE,@@ -449,6 +458,7 @@ def render_home_view(untagged_question_mode: UntaggedFollowupMode | None = None,channel_welcome_mode: ChannelWelcomeMode | None = None,auto_model_choice: bool | None = None,+ thread_join_mode: ThreadJoinMode | None = None,has_project_access: bool = True,account_settings_url: str | None = None,) -> dict:@@ -496,6 +506,11 @@ def render_home_view(blocks.append({"type": "divider"})blocks.extend(_untagged_followups_section_blocks(untagged_followup_mode))+ # Section 4a — multiplayer: who may join the threads you started.+ if thread_join_mode is not None:+ blocks.append({"type": "divider"})+ blocks.extend(_multiplayer_section_blocks(thread_join_mode))+# Section 4b — channel questions. `None` means the flag is off for this workspace.if untagged_question_mode is not None:blocks.append({"type": "divider"})@@ -1025,6 +1040,20 @@ def _untagged_questions_section_blocks(mode: UntaggedFollowupMode) -> list[dict])+def _multiplayer_section_blocks(mode: ThreadJoinMode) -> list[dict]:+ """Picker for what happens when someone else tags PostHog in a thread you started."""+ select = _static_select(+ action_id=ACTION_SET_THREAD_JOIN_MODE,+ placeholder="Choose who can join",+ pairs=ThreadJoinMode.choices,+ selected=mode.value,+ )+ return [+ _section_title("👥 Multiplayer", "What I do when someone else tags @PostHog in a thread you started."),+ {"type": "actions", "elements": [select]},+ ]++CHANNEL_WELCOME_MODE_LABELS: dict[str, str] = {ChannelWelcomeMode.CHANNEL: "Post it in the channel",ChannelWelcomeMode.INVITER: "Show it only to the person who added me",@@ -1739,6 +1768,17 @@ def handle_ai_preferences_block_action(payload: dict, action: dict) -> HttpResporepublish()return HttpResponse(status=200)+ if action_id == ACTION_SET_THREAD_JOIN_MODE:+ picked = (action.get("selected_option") or {}).get("value")+ # An unrecognised value is ignored rather than stored.+ if picked in ThreadJoinMode.values and _thread_join_offered(+ integration, _resolve_home_user(integration, slack_user_id)+ ):+ set_thread_join_mode(integration.integration_id, slack_user_id, ThreadJoinMode(picked))+ capture_slack_event(integration, "slack app thread join mode set", slack_user_id=slack_user_id, mode=picked)+ republish()+ return HttpResponse(status=200)+if action_id == ACTION_SET_UNTAGGED_FOLLOWUP_MODE:if (mode := _picked_untagged_mode(action)) is not None:set_untagged_followup_mode(integration.integration_id, slack_user_id, mode)@@ -2137,7 +2177,12 @@ def _clear_project_personal(integration: Integration, slack_user_id: str) -> Non).first()if row is None:return- if not row.untagged_followup_mode and not row.untagged_question_mode and not row.auto_model_choice:+ if (+ not row.untagged_followup_mode+ and not row.untagged_question_mode+ and not row.auto_model_choice+ and not row.thread_join_mode+ ):row.delete()returnrow.default_integration = None@@ -2209,6 +2254,11 @@ def _build_home_view(if _auto_model_choice_offered(integration, slack_user_id)else None),+ thread_join_mode=(+ resolve_thread_join_mode(integration, slack_user_id)+ if _thread_join_offered(integration, _resolve_home_user(integration, slack_user_id))+ else None+ ),has_project_access=bool(accessible),# The same settings page the GitHub card deep-links to.account_settings_url=github_state.settings_url,@@ -2456,6 +2506,10 @@ def _resolve_run_defaults_state()+def _thread_join_offered(integration: Integration, home_user: User | None) -> bool:+ return home_user is not None and is_slack_app_multiplayer_approvals_enabled(integration, home_user.distinct_id)++def _auto_model_choice_offered(integration: Integration, slack_user_id: str) -> bool:return _resolve_home_user(integration, slack_user_id) is not Nonediff --git a/products/slack_app/backend/services/slack_settings.py b/products/slack_app/backend/services/slack_settings.pyindex d15b37157be9..766567b64053 100644--- a/products/slack_app/backend/services/slack_settings.py+++ b/products/slack_app/backend/services/slack_settings.py@@ -1,6 +1,6 @@"""Read helpers for per-(Slack workspace, Slack user) settings backed by-`models.SlackSettings` (today: the untagged follow-up mode, the channel-welcome mode and the automatic model choice), plus the shared+`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 sharedAI-triple value object.Model preferences themselves live in the central tasks config@@ -12,13 +12,17 @@ layer with zero translation.from __future__ import annotationsfrom dataclasses import dataclass-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, TypeVar-from products.slack_app.backend.models import ChannelWelcomeMode, UntaggedFollowupMode+from django.db import models++from products.slack_app.backend.models import ChannelWelcomeMode, ThreadJoinMode, UntaggedFollowupModeif TYPE_CHECKING:from posthog.models.integration import Integration+_Mode = TypeVar("_Mode", bound=models.TextChoices)+@dataclass(frozen=True)class AIPreferences:@@ -58,20 +62,32 @@ def resolve_untagged_question_mode(slack_workspace_id: str, slack_user_id: str |def _resolve_untagged_mode(slack_workspace_id: str, slack_user_id: str | None, column: str) -> UntaggedFollowupMode:if not slack_user_id:return UntaggedFollowupMode.NEVER+ return _resolve_personal_mode(+ slack_workspace_id,+ slack_user_id,+ column,+ UntaggedFollowupMode,+ unset=UntaggedFollowupMode.ASK,+ unknown=UntaggedFollowupMode.NEVER,+ )++def _resolve_personal_mode(+ slack_workspace_id: str, slack_user_id: str, column: str, mode_type: type[_Mode], *, unset: _Mode, unknown: _Mode+) -> _Mode:+ """One choice from a Slack user's personal settings row, as `mode_type`."""from products.slack_app.backend.models import SlackSettings- row = (+ stored = (SlackSettings.objects.filter(slack_workspace_id=slack_workspace_id, slack_user_id=slack_user_id)- .values(column)+ .values_list(column, flat=True).first())- stored = row[column] if row else Noneif stored is None:- return UntaggedFollowupMode.ASK- if stored in UntaggedFollowupMode.values:- return UntaggedFollowupMode(stored)- return UntaggedFollowupMode.NEVER+ return unset+ if stored in mode_type.values:+ return mode_type(stored)+ return unknowndef set_untagged_followup_mode(slack_workspace_id: str, slack_user_id: str, mode: UntaggedFollowupMode) -> None:@@ -82,7 +98,11 @@ def set_untagged_question_mode(slack_workspace_id: str, slack_user_id: str, mode_set_untagged_mode(slack_workspace_id, slack_user_id, "untagged_question_mode", mode)-def _set_untagged_mode(slack_workspace_id: str, slack_user_id: str, column: str, mode: UntaggedFollowupMode) -> None:+def set_thread_join_mode(slack_workspace_id: str, slack_user_id: str, mode: ThreadJoinMode) -> None:+ _set_untagged_mode(slack_workspace_id, slack_user_id, "thread_join_mode", mode)+++def _set_untagged_mode(slack_workspace_id: str, slack_user_id: str, column: str, mode: models.TextChoices) -> None:from products.slack_app.backend.models import SlackSettingsSlackSettings.objects.update_or_create(@@ -92,6 +112,25 @@ def _set_untagged_mode(slack_workspace_id: str, slack_user_id: str, column: str,)+def resolve_thread_join_mode(integration: Integration, slack_user_id: str | None) -> ThreadJoinMode:+ """Resolve what happens when someone else tags PostHog in a thread this Slack user started.++ An absent row or empty column resolves to `ASK_PER_THREAD`, so the creator approves the first+ person who wants to join a thread, and after that anyone can join it.+ An unknown value resolves to `NEVER`.+ """+ if not slack_user_id:+ return ThreadJoinMode.ALLOW+ return _resolve_personal_mode(+ integration.integration_id,+ slack_user_id,+ "thread_join_mode",+ ThreadJoinMode,+ unset=ThreadJoinMode.ASK_PER_THREAD,+ unknown=ThreadJoinMode.NEVER,+ )++def resolve_channel_welcome_mode(slack_workspace_id: str) -> ChannelWelcomeMode:"""Resolve where the greeting goes when someone adds the app to a channel.@@ -158,5 +197,7 @@ __all__ = ["set_untagged_followup_mode","set_untagged_question_mode","set_channel_welcome_mode",+ "resolve_thread_join_mode",+ "set_thread_join_mode","resolve_untagged_followup_mode",]diff --git a/products/slack_app/backend/temporal/activities/task_creation.py b/products/slack_app/backend/temporal/activities/task_creation.pyindex 54254d820005..10ecbf339a7d 100644--- a/products/slack_app/backend/temporal/activities/task_creation.py+++ b/products/slack_app/backend/temporal/activities/task_creation.py@@ -14,6 +14,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.slack_app.backend.facade.api import slack_artifact_delivery_state_updatesfrom products.slack_app.backend.logic.reply_suggestions import clear_open_suggestions+from products.slack_app.backend.logic.thread_join import ThreadJoinDecision, decide_thread_joinfrom products.slack_app.backend.services.slack_messages import (SlackThreadMessage,context_block,@@ -31,8 +32,12 @@ from products.slack_app.backend.temporal.attachments import (prepare_slack_file_artifacts,prepare_slack_thread_file_artifacts,)-from products.slack_app.backend.temporal.helpers import block_if_team_over_quota, safe_react-from products.slack_app.backend.temporal.types import PostHogCodeSlackMentionWorkflowInputs, SlackAppModelOverride+from products.slack_app.backend.temporal.helpers import block_if_team_over_quota, safe_react, safe_unreact+from products.slack_app.backend.temporal.types import (+ SLACK_APP_PROCESSING_REACTION,+ PostHogCodeSlackMentionWorkflowInputs,+ SlackAppModelOverride,+)if TYPE_CHECKING:from products.slack_app.backend.models import SlackThreadTaskMapping@@ -552,6 +557,8 @@ def derive_mention_workflow_id(inputs: PostHogCodeSlackMentionWorkflowInputs) ->suffix = f"{event.get('channel', '')}:{event.get('ts', '')}"if inputs.untagged_confirmed:suffix = f"{suffix}:confirmed"+ if inputs.thread_join_approved:+ suffix = f"{suffix}:joined"return f"{MENTION_WORKFLOW_ID_PREFIX}{inputs.slack_team_id}:{suffix}"@@ -950,6 +957,14 @@ def forward_posthog_code_followup_activity(actor_user = mapping.task.created_byfollowup_user_text_prefix: str | None = Noneif slack_user_id != mapping.mentioning_slack_user_id:+ # Checked before the Slack lookup below, so a message the creator's mode drops costs+ # no Slack call.+ join = decide_thread_join(integration, mapping, slack_user_id)+ if join == ThreadJoinDecision.DENY:+ # The queue already marked the message as being worked on, and nothing will answer it.+ _clear_processing_reaction(slack, channel, user_message_ts)+ logger.info("slack_app_followup_thread_join_denied", channel=channel, thread_ts=thread_ts)+ return True# The follow-up is from a different Slack user than the one who started the# thread. Try to resolve them to a PostHog user with access to the same team# — if so, let them participate under their own sandbox token, with their@@ -978,6 +993,23 @@ def forward_posthog_code_followup_activity(actor=slack_user_id,actor_user_id=resolved.user.id,)+ if join != ThreadJoinDecision.ALLOW:+ from products.slack_app.backend.api import post_thread_join_prompt # noqa: PLC0415++ # The creator's approval sends this message again, so it stops here. Nothing works on+ # it while it waits, so it loses the reaction that says so.+ _clear_processing_reaction(slack, channel, user_message_ts)+ post_thread_join_prompt(+ slack,+ integration,+ inputs,+ channel=channel,+ thread_ts=thread_ts,+ owner_slack_user_id=mapping.mentioning_slack_user_id,+ joiner_slack_user_id=slack_user_id,+ opens_thread=join == ThreadJoinDecision.ASK_FOR_THREAD,+ )+ return Trueif block_if_team_over_quota(integration=integration,@@ -1618,6 +1650,11 @@ def _delete_followup_progress(pass+def _clear_processing_reaction(slack: Any, channel: str, user_message_ts: str | None) -> None:+ if user_message_ts:+ safe_unreact(slack.client, channel, user_message_ts, SLACK_APP_PROCESSING_REACTION)++def _set_followup_done_reaction(slack: Any, channel: str, user_message_ts: str | None, done_emoji: str) -> None:if not user_message_ts:returndiff --git a/products/slack_app/backend/temporal/helpers.py b/products/slack_app/backend/temporal/helpers.pyindex 47dd0ac6a61e..2919e8125695 100644--- a/products/slack_app/backend/temporal/helpers.py+++ b/products/slack_app/backend/temporal/helpers.py@@ -67,10 +67,15 @@ def safe_react(client: Any, channel: str, timestamp: str, name: str) -> None:raise-def swap_reaction(client: Any, channel: str, timestamp: str, remove: str, add: str) -> None:- """Replace one reaction with another; a missing old reaction is a no-op."""+def safe_unreact(client: Any, channel: str, timestamp: str, name: str) -> None:+ """Remove a reaction; a missing reaction or message is a no-op."""try:- client.reactions_remove(channel=channel, timestamp=timestamp, name=remove)+ client.reactions_remove(channel=channel, timestamp=timestamp, name=name)except Exception:pass+++def swap_reaction(client: Any, channel: str, timestamp: str, remove: str, add: str) -> None:+ """Replace one reaction with another; a missing old reaction is a no-op."""+ safe_unreact(client, channel, timestamp, remove)safe_react(client, channel, timestamp, add)diff --git a/products/slack_app/backend/temporal/tests/activities/test_task_creation.py b/products/slack_app/backend/temporal/tests/activities/test_task_creation.pyindex fb6d69cdf36c..1dc8d47d073d 100644--- a/products/slack_app/backend/temporal/tests/activities/test_task_creation.py+++ b/products/slack_app/backend/temporal/tests/activities/test_task_creation.py@@ -652,11 +652,23 @@ class TestDeriveMentionWorkflowId:}return PostHogCodeSlackMentionWorkflowInputs(**fields)- def test_confirmed_redispatch_gets_its_own_id(self):- original = derive_mention_workflow_id(self._inputs(untagged_followup=True))- confirmed = derive_mention_workflow_id(self._inputs(untagged_followup=True, untagged_followup_confirmed=True))- assert original != confirmed- assert confirmed.startswith(original)+ @pytest.mark.parametrize(+ "earlier, redispatch",+ [+ ({"untagged_followup": True}, {"untagged_followup_confirmed": True}),+ # A confirmed reply that then needed the creator's approval is sent a third time.+ (+ {"untagged_followup": True, "untagged_followup_confirmed": True, "slack_event_id": None},+ {"thread_join_approved": True},+ ),+ ],+ ids=["confirmed", "join_approved"],+ )+ def test_redispatch_gets_its_own_id(self, earlier, redispatch):+ original = derive_mention_workflow_id(self._inputs(**earlier))+ again = derive_mention_workflow_id(self._inputs(**earlier, **redispatch))+ assert original != again+ assert again.startswith(original)def test_id_is_stable_without_a_slack_event_id(self):inputs = self._inputs(slack_event_id=None)diff --git a/products/slack_app/backend/temporal/types.py b/products/slack_app/backend/temporal/types.pyindex f1a6c6f1c48f..00c849024d96 100644--- a/products/slack_app/backend/temporal/types.py+++ b/products/slack_app/backend/temporal/types.py@@ -127,6 +127,9 @@ class PostHogCodeSlackMentionWorkflowInputs:# True when the author already accepted the private offer to answer, so the run# skips the classifier and the offer on the way back through.untagged_question_confirmed: bool = False+ # True when the thread creator let this person join and the message that asked is sent+ # again. The same Slack event already came through once to raise the join prompt.+ thread_join_approved: bool = False# Slack sets this on the event envelope for Slack Connect channels. It is# threaded through to task run state so customer-facing Slack replies remain# approval-gated even when a user's internal-write tier is full-auto.diff --git a/products/slack_app/backend/tests/services/test_slack_app_home.py b/products/slack_app/backend/tests/services/test_slack_app_home.pyindex fa6784d0de78..97ca35ada545 100644--- a/products/slack_app/backend/tests/services/test_slack_app_home.py+++ b/products/slack_app/backend/tests/services/test_slack_app_home.py@@ -32,6 +32,7 @@ from products.slack_app.backend.models import (SlackSettings,SlackThreadTaskMapping,SlackUserProfileCache,+ ThreadJoinMode,UntaggedFollowupMode,)from products.slack_app.backend.services import slack_app_home@@ -42,6 +43,7 @@ from products.slack_app.backend.services.slack_app_home import (ACTION_SET_AUTO_MODEL_CHOICE,ACTION_SET_CHANNEL_WELCOME_MODE,ACTION_SET_PROJECT_WORKSPACE,+ ACTION_SET_THREAD_JOIN_MODE,ACTION_SET_UNTAGGED_FOLLOWUP_MODE,ACTION_TASKS_FILTER_REPO,ACTION_TASKS_PAGE_NEXT,@@ -476,6 +478,7 @@ class TestRenderHomeView:untagged_question_mode=UntaggedFollowupMode.ASK,channel_welcome_mode=ChannelWelcomeMode.CHANNEL,auto_model_choice=auto_model_choice,+ thread_join_mode=ThreadJoinMode.ASK_PER_THREAD,)def test_every_control_the_tab_renders_is_routable(self):@@ -1258,6 +1261,23 @@ class TestHandleAppHomeOpened:assert mock_capture.call_args.args[1] == "slack app home opened"assert mock_capture.call_args.kwargs["posthog_user"] == opener+ @pytest.mark.parametrize("flag_on_for_viewer", [True, False])+ def test_multiplayer_section_follows_its_flag(+ self, slack_integration, mock_slack_client, flag_on, admin_user, flag_on_for_viewer+ ):+ opener = User.objects.create_and_join(slack_integration.team.organization, "[email protected]", None)+ SlackUserProfileCache.objects.create(integration=slack_integration, slack_user_id="U001", email=opener.email)++ with patch(+ "products.slack_app.backend.services.slack_app_home.is_slack_app_multiplayer_approvals_enabled",+ return_value=flag_on_for_viewer,+ ):+ handle_app_home_opened({"user": "U001"}, SLACK_WORKSPACE_ID, integration=slack_integration)++ view = mock_slack_client.views_publish.call_args.kwargs["view"]+ assert (ACTION_SET_THREAD_JOIN_MODE in _action_ids(view)) is flag_on_for_viewer+ assert ("Multiplayer" in _all_text(view)) is flag_on_for_viewer+def _github_row(self, user: User, login: str) -> UserIntegration:return UserIntegration.objects.create(user=user,diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.pyindex 5525d0353e7c..3ce3c5ab7996 100644--- a/products/slack_app/backend/tests/test_followup_forwarding.py+++ b/products/slack_app/backend/tests/test_followup_forwarding.py@@ -16,7 +16,7 @@ from posthog.models.user import Userfrom posthog.models.user_integration import UserIntegrationfrom products.slack_app.backend.api import SlackUserContext-from products.slack_app.backend.models import SlackThreadTaskMapping+from products.slack_app.backend.models import SlackSettings, SlackThreadJoin, SlackThreadTaskMapping, ThreadJoinModefrom products.slack_app.backend.services.run_preferences import SLACK_DEFAULT_MODELfrom products.slack_app.backend.services.slack_messages import (SlackFileRef,@@ -1173,6 +1173,68 @@ class TestForwardPostHogCodeFollowupActivity(TestCase):assert signal_kwargs["actor_user_id"] == bob.idassert signal_kwargs["message_id"] is not None+ @parameterized.expand(+ [+ ("allow", ThreadJoinMode.ALLOW, None, True, False, True),+ # A creator who never picked a mode is asked once per thread.+ ("unset", None, None, False, True, True),+ ("ask_per_person", ThreadJoinMode.ASK_PER_PERSON, None, False, True, True),+ ("ask_per_person_already_joined", ThreadJoinMode.ASK_PER_PERSON, ["U_BOB"], True, False, True),+ ("ask_per_person_after_someone_else_joined", ThreadJoinMode.ASK_PER_PERSON, ["U_CAROL"], False, True, True),+ ("ask_per_thread", ThreadJoinMode.ASK_PER_THREAD, None, False, True, True),+ ("ask_per_thread_after_someone_else_joined", ThreadJoinMode.ASK_PER_THREAD, ["U_CAROL"], True, False, True),+ ("never", ThreadJoinMode.NEVER, None, False, False, True),+ ("never_after_joining", ThreadJoinMode.NEVER, ["U_BOB"], True, False, True),+ # Turning the rollout flag off brings back today's behavior, whatever was stored.+ ("never_with_the_flag_off", ThreadJoinMode.NEVER, None, True, False, False),+ ]+ )+ @patch("products.slack_app.backend.api.post_thread_join_prompt")+ @patch("products.tasks.backend.facade.api.signal_task_run_user_message", return_value=True)+ @patch("products.slack_app.backend.api.resolve_slack_user")+ @patch("posthog.models.integration.SlackIntegration")+ def test_the_thread_creators_join_mode_decides_who_reaches_the_task(+ self,+ _name,+ mode,+ joined,+ delivered,+ prompted,+ flag_on,+ mock_slack_cls,+ mock_resolve,+ mock_signal,+ mock_prompt,+ ):+ SlackSettings.objects.create(slack_workspace_id="T_SLACK", slack_user_id="U_ALICE", thread_join_mode=mode)+ mapping = self._create_mapping(mentioning_user="U_ALICE")+ for slack_user_id in joined or []:+ SlackThreadJoin.objects.for_team(self.team.id).create(+ team=self.team, thread_mapping=mapping, slack_user_id=slack_user_id+ )+ bob = User.objects.create(email="[email protected]", first_name="Bob")+ mock_slack = MagicMock()+ mock_slack_cls.return_value = mock_slack+ mock_resolve.return_value = SlackUserContext(user=bob, slack_email="[email protected]")++ inputs = _make_inputs(self.integration.id, self.user.id)+ with patch(+ "products.slack_app.backend.logic.thread_join.is_slack_app_multiplayer_approvals_enabled",+ return_value=flag_on,+ ):+ result = forward_posthog_code_followup_activity(+ inputs, "C123", "1234.5678", "U_BOB", "<@BOT> ship it", "1234.5679"+ )++ assert result is True+ assert mock_signal.called is delivered+ assert mock_prompt.called is prompted+ # A held or dropped message must not keep the reaction that says PostHog is working on it.+ removed = [c.kwargs for c in mock_slack.client.reactions_remove.call_args_list]+ assert ({"channel": "C123", "timestamp": "1234.5679", "name": "eyes"} in removed) is not delivered+ if prompted:+ assert mock_prompt.call_args.kwargs["opens_thread"] is (mode in (None, ThreadJoinMode.ASK_PER_THREAD))+@patch("products.slack_app.backend.api.resolve_slack_user", return_value=None)@patch("posthog.models.integration.SlackIntegration")def test_cross_user_followup_unmapped_user_delegates_feedback_to_resolver(self, mock_slack_cls, mock_resolve):diff --git a/products/slack_app/backend/tests/test_untagged_followup_interactivity.py b/products/slack_app/backend/tests/test_untagged_followup_interactivity.pyindex a98c2e5b7cfc..c687e268ee95 100644--- a/products/slack_app/backend/tests/test_untagged_followup_interactivity.py+++ b/products/slack_app/backend/tests/test_untagged_followup_interactivity.py@@ -8,6 +8,7 @@ from django.apps import appsfrom django.core.cache import cachefrom django.test import TestCase, override_settings+from parameterized import parameterizedfrom rest_framework.test import APIClientfrom posthog.models.integration import Integration@@ -16,6 +17,9 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom products.slack_app.backend.api import (+ THREAD_JOIN_ACTION_ALLOW,+ THREAD_JOIN_ACTION_DECLINE,+ THREAD_JOIN_CONTEXT_KIND,UNTAGGED_FOLLOWUP_ACTION_DISMISS,UNTAGGED_FOLLOWUP_ACTION_RUN,UNTAGGED_FOLLOWUP_BLOCK_ID_PREFIX,@@ -25,8 +29,15 @@ from products.slack_app.backend.api import (UNTAGGED_QUESTION_BLOCK_ID_PREFIX,UNTAGGED_QUESTION_CONTEXT_KIND,_picker_context_cache_key,+ post_thread_join_prompt,)-from products.slack_app.backend.models import SlackSettings, SlackThreadTaskMapping, UntaggedFollowupMode+from products.slack_app.backend.models import (+ SlackSettings,+ SlackThreadJoin,+ SlackThreadTaskMapping,+ UntaggedFollowupMode,+)+from products.slack_app.backend.temporal.types import PostHogCodeSlackMentionWorkflowInputsfrom products.slack_app.backend.tests.helpers import sign_slack_request@@ -111,6 +122,24 @@ class TestUntaggedFollowupInteractivity(TestCase):timeout=900,)+ def _stash_thread_join_prompt(self) -> None:+ cache.set(+ _picker_context_cache_key(self.context_token),+ {+ "kind": THREAD_JOIN_CONTEXT_KIND,+ "integration_id": self.integration.id,+ "slack_channel_id": self.slack_channel_id,+ "thread_ts": "1000.0000",+ "owner_slack_user_id": "U_ALICE",+ "joiner_slack_user_id": "U_BOB",+ "event": self.event,+ "untagged_followup": False,+ "untagged_followup_confirmed": False,+ "is_ext_shared_channel": False,+ },+ timeout=900,+ )+def _click(self, action_id: str, slack_user_id: str) -> Any:payload = {"type": "block_actions",@@ -257,6 +286,87 @@ class TestUntaggedFollowupInteractivity(TestCase):assert response.status_code == 200mock_start.assert_not_called()+ def test_a_waiting_join_prompt_is_not_posted_again(self, mock_slack_cls, mock_post):+ # A joiner who keeps typing while the creator has not answered must not flood the creator.+ slack = MagicMock()+ inputs = PostHogCodeSlackMentionWorkflowInputs(+ event=self.event, integration_id=self.integration.id, slack_team_id=self.slack_team_id, user_id=1+ )+ for _ in range(3):+ post_thread_join_prompt(+ slack,+ self.integration,+ inputs,+ channel=self.slack_channel_id,+ thread_ts="1000.0000",+ owner_slack_user_id="U_ALICE",+ joiner_slack_user_id="U_BOB",+ opens_thread=False,+ )++ assert [c.kwargs["user"] for c in slack.client.chat_postEphemeral.call_args_list] == ["U_ALICE", "U_BOB"]++ @parameterized.expand([("thread_creator", "U_ALICE", True), ("someone_else", "U_MALLORY", False)])+ def test_only_the_thread_creator_can_let_someone_join(+ self, mock_slack_cls, mock_post, _name: str, clicker: str, joins: bool+ ):+ mock_slack_cls.slack_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}+ self._stash_thread_join_prompt()++ with (+ self._stub_slack_user_email(self.member_user.email),+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,+ ):+ response = self._click(THREAD_JOIN_ACTION_ALLOW, clicker)++ assert response.status_code == 200+ joined = list(+ SlackThreadJoin.objects.for_team(self.team.id)+ .filter(thread_mapping=self.mapping)+ .values_list("slack_user_id", flat=True)+ )+ assert joined == (["U_BOB"] if joins else [])+ assert mock_start.called is joins+ if joins:+ assert mock_start.call_args.args[0] == self.event+ assert mock_start.call_args.kwargs["posthog_user"].id == self.member_user.id++ def test_an_approval_that_fails_to_send_can_be_clicked_again(self, mock_slack_cls, mock_post):+ # A database or Temporal error must not lose the message that asked to join.+ mock_slack_cls.slack_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}+ self._stash_thread_join_prompt()++ with (+ self._stub_slack_user_email(self.member_user.email),+ patch(+ "products.slack_app.backend.api._start_mention_workflow",+ side_effect=[RuntimeError("temporal down"), "wf"],+ ) as mock_start,+ ):+ with self.assertRaises(RuntimeError):+ self._click(THREAD_JOIN_ACTION_ALLOW, "U_ALICE")+ self._click(THREAD_JOIN_ACTION_ALLOW, "U_ALICE")++ assert mock_start.call_count == 2+ assert mock_start.call_args.args[0] == self.event+ assert mock_start.call_args.kwargs["thread_join_approved"] is True+ assert cache.get(_picker_context_cache_key(self.context_token)) is None++ def test_declining_tells_the_person_who_asked(self, mock_slack_cls, mock_post):+ # Their message was held without the processing reaction, so only this notice says what happened.+ mock_slack_cls.slack_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}+ self._stash_thread_join_prompt()++ with patch("products.slack_app.backend.api._start_mention_workflow") as mock_start:+ response = self._click(THREAD_JOIN_ACTION_DECLINE, "U_ALICE")++ assert response.status_code == 200+ mock_start.assert_not_called()+ notice = mock_slack_cls.return_value.client.chat_postEphemeral.call_args.kwargs+ assert (notice["user"], notice["thread_ts"]) == ("U_BOB", "1000.0000")+ assert "<@U_ALICE> didn't let you join this thread" in notice["text"]+ assert not SlackThreadJoin.objects.for_team(self.team.id).filter(thread_mapping=self.mapping).exists()+@override_settings(DEBUG=True)@patch("products.slack_app.backend.api.requests.post")