: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
import re
import json
import time
import uuid
import asyncio
import hashlib
from collections.abc import Sequence
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any, Literal
from urllib.parse import urlparse, urlunparse
from django.conf import settings
from django.core import signing
from django.core.cache import cache
from django.http import HttpRequest, HttpResponse, JsonResponse
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
import requests
import structlog
import posthoganalytics
from slack_sdk.errors import SlackApiError
from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy
from posthog.dataclasses import frozen
from posthog.egress.limiter.policies import Priority
from posthog.event_usage import groups
from posthog.git import extract_explicit_repo, extract_linked_repo, extract_repo_from_scopes
from posthog.integrations import IntegrationManager, IntegrationNotFound
from posthog.models.integration import (
SLACK_INTEGRATION_KINDS,
SlackIntegration,
SlackIntegrationError,
sign_slack_request,
validate_slack_request,
)
from posthog.models.organization import OrganizationMembership
from posthog.models.team import Team
from posthog.models.user import User
from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
from posthog.temporal.common.client import sync_connect
from posthog.user_permissions import UserPermissions
from posthog.utils import get_instance_region
from products.commands.backend.facade import api as commands_api
from products.slack_app.backend import inbox_channel
from products.slack_app.backend.analytics import capture_slack_event, slack_session_id
from products.slack_app.backend.discussion_replies import try_ingest_discussion_reply
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_email
from products.slack_app.backend.logic import interview_recruitment, reply_suggestions
from products.slack_app.backend.logic.feature_tips import interactivity as feature_tip_interactivity
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 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_onboarding
from products.slack_app.backend.logic.untagged_question import is_untagged_question_candidate
from products.slack_app.backend.models import (
ChannelWelcomeMode,
SlackChannel,
SlackSettings,
SlackThreadJoin,
SlackThreadTaskMapping,
UntaggedFollowupMode,
)
from products.slack_app.backend.services import (
bare_mention,
inbox_interactivity,
project_picker,
slack_welcome_messages,
turn_feedback,
)
from products.slack_app.backend.services.commands import SLASH_COMMAND_PREFIX, mention_command_redirect
from products.slack_app.backend.services.integration_resolver import (
ResolutionResult,
UserResolutionFailure,
load_integrations,
pick_a_project_message,
resolve_from_candidates,
resolve_user_for_workspace,
unresolved_user_properties,
user_resolution_failure_reply,
)
from products.slack_app.backend.services.slack_app_home import (
EDIT_MODAL_PERSONAL_CALLBACK_ID,
HOME_ACTION_IDS,
MODAL_ACTION_MODEL,
MODAL_ACTION_RUNTIME_ADAPTER,
handle_ai_preferences_block_action as _handle_ai_preferences_block_action,
handle_app_home_opened as _handle_app_home_opened,
handle_app_home_view_submission as _handle_app_home_view_submission,
)
from products.slack_app.backend.services.slack_conversations import channel_ext_shared_state, channel_is_ext_shared
from products.slack_app.backend.services.slack_fork_context import clear_pending_fork, get_pending_fork
from products.slack_app.backend.services.slack_messages import (
FORK_THREAD_ACTION_ID,
SLACK_WEBHOOK_TIMEOUT_SECONDS,
TURN_FEEDBACK_ACTION_ID,
SlackThreadMessage,
app_home_url,
decode_slack_entities,
parse_slack_file_refs,
post_slack_ephemeral,
post_slack_thread_reply,
unwrap_slack_links,
)
from products.slack_app.backend.services.slack_scopes import REQUIRED_SLACK_SCOPES
from products.slack_app.backend.services.slack_settings import (
resolve_channel_welcome_mode,
resolve_untagged_followup_mode,
resolve_untagged_question_mode,
set_untagged_question_mode,
)
from products.slack_app.backend.services.slack_user_info import (
clear_workspace_profile_cache,
get_cached_bot_user_id,
get_cached_workspace_bot_user_id,
get_slack_user_info,
normalize_slack_response,
persist_slack_user_info,
)
from products.slack_app.backend.services.slack_user_oauth import (
build_invite_url,
find_linked_posthog_user,
linked_posthog_user_ids,
post_link_invite_message,
)
from products.slack_app.backend.services.slack_welcome_messages import (
build_assistant_pane_welcome,
build_channel_welcome,
build_team_join_welcome,
)
from products.slack_app.backend.services.workspace_integrations import (
WorkspaceIntegration,
get_team_workspace_integration,
get_workspace_integration,
workspace_integration_exists,
workspace_integrations,
)
from products.slack_app.backend.slack_link_unfurl import (
ADHOC_INSIGHT_KIND,
handle_posthog_link_unfurl,
link_url_region,
parse_posthog_resource_link,
)
from products.slack_app.backend.slack_workflow_events import emit_slack_message_event, is_triggering_message
from products.slack_app.backend.temporal import (
PostHogCodeSlackMentionCommandWorkflowInputs,
PostHogCodeSlackMentionWorkflowInputs,
SlackAppMentionWorkflowInputs,
derive_mention_workflow_id,
)
from products.slack_app.backend.temporal.posthog_code_slack_mention_command import (
PostHogCodeSlackMentionCommandWorkflow,
)
from products.slack_app.backend.temporal.slack_app_fork import SlackAppForkThreadWorkflow
from products.slack_app.backend.temporal.slack_app_mention import (
SlackAppMentionWorkflow,
derive_slack_app_mention_workflow_id,
)
from products.slack_app.backend.temporal.slack_app_mention_processing import SlackAppMentionProcessingWorkflow
from products.slack_app.backend.temporal.types import SlackAppForkThreadInputs
logger = structlog.get_logger(__name__)
HANDLED_EVENT_TYPES = [
"app_mention",
"link_shared",
"message",
"member_joined_channel",
"team_join",
"assistant_thread_started",
"assistant_thread_context_changed",
"app_home_opened",
"app_uninstalled",
"reaction_added",
]
# The notifications Slack app (`slack`) install carries every scope the coding-agent flow
# needs, so both surfaces share one kind.
SLACK_INTEGRATION_KIND = "slack"
# Slack substitutes this placeholder for the message author in ``link_shared``
# events it cannot attribute to a real user — messages posted by apps and bots,
# or authors whose identity is hidden. Calling ``users.info`` on it always
# fails with ``user_not_found``.
SLACK_PLACEHOLDER_USER_ID = "U00"
# Onboarding-on-join dedupe TTL (channel and workspace joins): just long enough
# to absorb Slack retries and a near-simultaneous cross-region race during
# cutover. A real re-join after this window should re-onboard — most likely the
# person forgot how it works.
ONBOARDING_DEDUPE_TTL_SECONDS = 60 * 10
# Shown when the alerts platform owns an insight alert and refuses a snooze from Slack.
NOT_SNOOZABLE_FROM_SLACK = "This alert couldn't be snoozed from Slack. Snooze it in PostHog instead."
EDITED_MENTION_WINDOW_SECONDS = 60 * 60
# Outlives the window, because an expired marker would let an edit start a second run.
MESSAGE_HANDLED_MARKER_TTL_SECONDS = 2 * EDITED_MENTION_WINDOW_SECONDS
ROUTE_HANDLED_LOCALLY = "handled_locally"
ROUTE_PROXIED = "proxied"
ROUTE_PROXY_FAILED = "proxy_failed"
ROUTE_NO_INTEGRATION = "no_integration"
# Every routing exit that answers a mention with silence (or with a reply we can't
# confirm landed) captures this event. Slack gets a 200 either way, so without it
# "the app didn't respond" is unattributable: the mention-received funnel only
# covers mentions that got far enough to resolve an integration.
SLACK_MENTION_DROPPED_EVENT = "posthog code slack mention dropped"
PICKER_TOKEN_SALT = "posthog_code_repo_picker"
PICKER_TOKEN_MAX_AGE_SECONDS = 900
CHANNEL_APPROVAL_BLOCK_ID_PREFIX = "posthog_code_channel_approval"
CHANNEL_APPROVAL_ACTION_APPROVE = "posthog_code_channel_approve"
CHANNEL_APPROVAL_ACTION_DENY = "posthog_code_channel_deny"
CHANNEL_APPROVAL_CONTEXT_KIND = "channel_approval"
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 * 60
UNTAGGED_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"
UNTAGGED_QUESTION_ACTION_TURN_OFF = "posthog_code_untagged_question_turn_off"
UNTAGGED_QUESTION_CONTEXT_KIND = "untagged_question"
_MAX_GITHUB_REPOS = 500
# The installation webhook marks snapshots stale without saving rows, so it does not clear this key.
# This TTL is the longest time a repo access change can take to reach Slack.
REPO_LIST_CACHE_TTL_SECONDS = 60 * 60
# Mentions do not wait for this refresh, so the interval only sets how often Slack lists GitHub.
REPO_SNAPSHOT_REFRESH_INTERVAL_SECONDS = 6 * 60 * 60
PENDING_REPO_PICKER_TTL_SECONDS = PICKER_TOKEN_MAX_AGE_SECONDS
def _user_repo_list_cache_key(user_id: int) -> str:
return f"posthog_code:user_repo_list:v1:{user_id}"
def _invalidate_user_repo_list_cache(user_id: int) -> None:
cache.delete(_user_repo_list_cache_key(user_id))
def _pending_repo_picker_cache_key(integration_id: int, channel: str, thread_ts: str, slack_user_id: str) -> str:
raw_key = f"{integration_id}:{channel}:{thread_ts}:{slack_user_id}"
return f"posthog_code:pending_repo_picker:v1:{hashlib.sha256(raw_key.encode('utf-8')).hexdigest()}"
def _set_pending_repo_picker(
*,
integration_id: int,
channel: str,
thread_ts: str,
slack_user_id: str,
user_id: int,
workflow_id: str,
context_token: str,
message_ts: str | None,
) -> None:
cache.set(
_pending_repo_picker_cache_key(integration_id, channel, thread_ts, slack_user_id),
{
"workflow_id": workflow_id,
"context_token": context_token,
"message_ts": message_ts,
"mentioning_user_id": user_id,
},
timeout=PENDING_REPO_PICKER_TTL_SECONDS,
)
def _get_pending_repo_picker(
*, integration_id: int, channel: str, thread_ts: str, slack_user_id: str
) -> dict[str, Any] | None:
cached = cache.get(_pending_repo_picker_cache_key(integration_id, channel, thread_ts, slack_user_id))
return cached if isinstance(cached, dict) else None
def _clear_pending_repo_picker(*, integration_id: int, channel: str, thread_ts: str, slack_user_id: str) -> None:
cache.delete(_pending_repo_picker_cache_key(integration_id, channel, thread_ts, slack_user_id))
@dataclass
class SlackUserContext:
user: User
# `None` on the linked-user path: the OAuth link binds slack_user_id to a
# PostHog user without ever consulting Slack's email, so no value is
# available. The email-matching path still always populates this.
slack_email: str | None
@frozen
class RulesCommand:
"""Parsed `/posthog <command>` text.
The same parser reads mention text, where a match means the mention is not a task description.
"""
action: Literal[
"list",
"add",
"remove",
"help",
"deprecated_default_repo",
"project_show",
"project_set",
"project_set_workspace",
"welcome_show",
"welcome_set",
]
rule_text: str | None = None
repository: str | None = None
rule_numbers: list[int] | None = None
project_team_id: int | None = None
welcome_mode: ChannelWelcomeMode | None = None
QUOTA_EXHAUSTED_MESSAGE = (
"Your team has used its monthly PostHog AI credits. "
"Top up at https://us.posthog.com/organization/billing to continue."
)
AI_PROCESSING_NOT_APPROVED_MESSAGE = (
":lock: *PostHog AI is turned off for your organization*\n"
"I can't work on this request until AI analysis is on. "
"Ask an organization admin to turn it on in <{settings_url}|organization settings>."
)
def post_quota_exhausted_denial(
*,
integration: WorkspaceIntegration,
slack: SlackIntegration,
channel: str,
thread_ts: str,
slack_user_id: str,
context: str,
) -> None:
"""Post the AI-credits denial message into a Slack thread.
Called by the workflow's quota gate after it determines the team is over
quota. Lives in this module so the Slack-posting helpers and the message
text stay co-located; the quota check itself lives in the temporal layer
(which is the only side allowed to import ``ee.billing``).
"""
logger.info(
"slack_app_slack_blocked_by_quota",
context=context,
team_id=integration.team_id,
channel=channel,
thread_ts=thread_ts,
)
_post_slack_user_feedback(
slack,
channel,
slack_user_id,
thread_ts,
QUOTA_EXHAUSTED_MESSAGE,
prefer_thread_message=True,
)
def post_ai_processing_not_approved_denial(
*,
integration: WorkspaceIntegration,
slack: SlackIntegration,
channel: str,
thread_ts: str,
slack_user_id: str,
context: str,
) -> None:
"""Post the AI-consent denial message into a Slack thread."""
logger.info(
"slack_app_slack_blocked_by_ai_consent",
context=context,
team_id=integration.team_id,
channel=channel,
thread_ts=thread_ts,
)
_post_slack_user_feedback(
slack,
channel,
slack_user_id,
thread_ts,
AI_PROCESSING_NOT_APPROVED_MESSAGE.format(
settings_url=f"{settings.SITE_URL}/settings/organization-details#organization-ai-consent"
),
prefer_thread_message=True,
)
def _post_slack_user_feedback(
slack: SlackIntegration,
channel: str,
slack_user_id: str,
thread_ts: str,
text: str,
*,
prefer_thread_message: bool = False,
) -> bool:
"""Post feedback to a Slack user. Returns whether anything reached Slack, so callers
that report on whether the user was actually told something aren't guessing.
A thread post whose root has been deleted is skipped rather than posted — see
``post_slack_thread_reply``. That counts as "nothing reached Slack", which is
accurate: the user retracted the message this feedback answers."""
# Every caller runs inside the Slack webhook, so the SDK's 30 second default would
# outlast the acknowledgement window. The client is held in a local because
# ``SlackIntegration.client`` builds a new one on every access.
client = slack.client
client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
if prefer_thread_message:
try:
return post_slack_thread_reply(client, channel=channel, thread_ts=thread_ts, text=text) is not None
except Exception:
logger.warning("slack_user_feedback_thread_post_failed", channel=channel, slack_user_id=slack_user_id)
try:
client.chat_postEphemeral(channel=channel, user=slack_user_id, thread_ts=thread_ts, text=text)
except Exception:
try:
return post_slack_thread_reply(client, channel=channel, thread_ts=thread_ts, text=text) is not None
except Exception:
logger.warning("slack_user_feedback_failed", channel=channel, slack_user_id=slack_user_id)
return False
return True
def _post_slack_user_ephemeral(
slack: SlackIntegration,
channel: str,
slack_user_id: str,
thread_ts: str | None,
text: str,
) -> bool:
"""Reply to one Slack user with no channel-visible fallback. Returns delivery success.
``_post_slack_user_feedback`` falls back to a channel post when the ephemeral
fails, which is the wrong trade in a channel where the content must not be
visible to everyone. Here a failed ephemeral stays unsent.
Pass ``thread_ts=None`` for a message that isn't already in a thread. Slack only
renders an ephemeral on the surface the user is currently viewing, so a threaded
ephemeral is invisible from the channel's main view, which is where someone who
just typed a top-level mention is sitting.
"""
# Runs inside the Slack webhook request path, so bound the call the same way
# ``_count_session_thread_messages`` does: a slow or rate-limited Slack response
# must not eat into the window we have to acknowledge the event. ``SlackIntegration.client``
# builds a fresh WebClient on every access, so the client has to be held in a local
# for the timeout to apply to the instance that makes the request.
client = slack.client
client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
try:
client.chat_postEphemeral(channel=channel, user=slack_user_id, thread_ts=thread_ts, text=text)
except Exception:
logger.warning("slack_user_ephemeral_failed", channel=channel, slack_user_id=slack_user_id)
return False
return True
def resolve_slack_user(
slack: SlackIntegration,
integration: WorkspaceIntegration,
slack_user_id: str,
channel: str,
thread_ts: str,
*,
post_feedback: bool = True,
) -> SlackUserContext | None:
"""Resolve a Slack user to a PostHog user. Posts an ephemeral error message and returns None on failure (unless post_feedback is False)."""
if slack_user_id == SLACK_PLACEHOLDER_USER_ID:
# There is no real user behind the placeholder, so there is nobody to
# resolve or to post feedback to.
return None
try:
slack_team_id = integration.integration_id
# Linked-user path: when the user has bound their Slack identity to a
# PostHog account via the OAuth link flow, we resolve directly without
# paying for users.info / email matching. Falls through to the email
# path on miss so this stays additive — a workspace with no links
# behaves exactly like before.
#
linked_user = find_linked_posthog_user(
slack_user_id=slack_user_id,
slack_team_id=slack_team_id,
candidate_org_ids={integration.team.organization_id},
)
if linked_user is not None and is_slack_app_oauth_enabled(integration):
user_permissions = UserPermissions(user=linked_user, team=integration.team)
if user_permissions.current_team.effective_membership_level is None:
logger.warning(
"slack_app_linked_user_no_team_access",
user_id=linked_user.id,
team_id=integration.team_id,
slack_user_id=slack_user_id,
)
if post_feedback:
_post_slack_user_feedback(
slack,
channel,
slack_user_id,
thread_ts,
(
"Sorry, you don't have access to the PostHog project connected to this Slack workspace. "
"Please ask an admin of your PostHog organization to grant you access."
),
)
return None
return SlackUserContext(user=linked_user, slack_email=None)
slack_email = get_slack_email_for_user(integration, slack_user_id)
if (dev_email := local_dev_slack_email()) is not None:
# Local dev: match the seeded test fixture user regardless of what
# Slack returns. Applied here rather than in the shared helper so
# other callers (e.g. `resolve_posthog_user_from_event` from the
# channel-approval path) can still drive the helper with stubbed
# Slack responses in tests.
slack_email = dev_email
if not slack_email:
logger.warning("slack_app_no_user_email", slack_user_id=slack_user_id)
if post_feedback:
_post_slack_user_feedback(
slack,
channel,
slack_user_id,
thread_ts,
(
"Sorry, I couldn't find your email address in Slack. "
"Please make sure your email is visible in your Slack profile, "
"and contact the PostHog team if the issue persists."
),
prefer_thread_message=True,
)
return None
# Trust model: Slack signature validation proves the payload is authentic.
# The email comes from Slack's `users.info` API via `users:read.email` scope, not from
# user-supplied input. Slack verifies emails at workspace sign-up, and admins control
# membership
membership = (
OrganizationMembership.objects.filter(
organization_id=integration.team.organization_id, user__email__iexact=slack_email
)
.select_related("user")
.first()
)
if not membership or not membership.user:
organization_name = integration.team.organization.name
if post_feedback:
# Two messages by design, with distinct audiences:
#
# * The text reply goes into the thread (`prefer_thread_message=True`)
# so other channel members can see why the bot stayed silent on
# this mention. Without it, the channel reads as if the mention
# was simply ignored.
# * The invite-button message is ephemeral — only the affected
# user sees the recovery affordance. Posting the button into
# the public thread would be noise for everyone else.
_post_slack_user_feedback(
slack,
channel,
slack_user_id,
thread_ts,
(
f"Sorry, I couldn't find {slack_email} in the {organization_name} organization. "
f"Please make sure you're a member of that PostHog organization."
),
prefer_thread_message=True,
)
if is_slack_app_oauth_enabled(integration):
invite_url = build_invite_url(
slack_user_id=slack_user_id,
slack_team_id=slack_team_id,
posthog_team_id=integration.team_id,
channel=channel,
thread_ts=thread_ts,
)
post_link_invite_message(
slack_client=slack.client,
channel=channel,
slack_user_id=slack_user_id,
thread_ts=thread_ts,
slack_email=slack_email,
invite_url=invite_url,
)
return None
posthog_user = membership.user
user_permissions = UserPermissions(user=posthog_user, team=integration.team)
if user_permissions.current_team.effective_membership_level is None:
logger.warning(
"slack_app_no_team_access",
user_id=posthog_user.id,
team_id=integration.team_id,
organization_id=integration.team.organization_id,
)
if post_feedback:
_post_slack_user_feedback(
slack,
channel,
slack_user_id,
thread_ts,
(
"Sorry, you don't have access to the PostHog project connected to this Slack workspace. "
"Please ask an admin of your PostHog organization to grant you access."
),
)
return None
return SlackUserContext(user=posthog_user, slack_email=slack_email)
except Exception as e:
logger.exception("slack_app_user_lookup_failed", error=str(e))
if post_feedback:
_post_slack_user_feedback(
slack,
channel,
slack_user_id,
thread_ts,
"Sorry, I encountered an error looking up your user account. Please try again later.",
)
return None
# Slack delivers a single webhook URL per app, but the workspace's PostHog Integration may live
# in either Cloud region. Whichever region Slack hits, we route the event to the region that
# owns the workspace. US is the primary; when both regions hold a row for the same workspace
# (only possible during cutover or migration), US wins. This means:
#
# - hit US, local match -> handle locally
# - hit US, no local match -> proxy to EU (loop header set)
# - hit EU, US says "I have it" -> proxy to US (loop header set)
# - hit EU, US says "no" -> handle locally if found, else drop
# - hit EU, probe errs / unknown -> assume US claims and proxy (optimistic); US drops if it
# also has nothing, which is the same outcome as before
# - hit either with loop header -> never proxy again; handle locally or drop
#
# This keeps the slack manifest endpoint swappable between us.posthog.com and eu.posthog.com
# without any other coordination.
REGION_PROXY_HEADER = "X-PostHog-Region-Proxied"
# Marks a copy of a channel message forwarded only for the workflow-trigger emit. A workspace can
# be connected in both regions; the receiver runs the emit for its own projects and nothing else,
# so the sender's pipeline (thread follow-ups, mentions) stays the only one handling the event.
EMIT_ONLY_MIRROR_HEADER = "X-PostHog-Slack-Emit-Only"
# Marks a full top-level post the sender already emitted and mirrored. The receiver handles the
# untagged question but skips the emit, which the mirror already covers.
ALREADY_EMITTED_HEADER = "X-PostHog-Slack-Already-Emitted"
REGION_PROXY_TIMEOUT_SECONDS = 3
# Tight budget: the workspace_claims endpoint is just a DB .exists(), and EU calls it inline
# before deciding whether to proxy. Slack's webhook ack deadline is 3s total, so we want this
# call to fail fast (and fall back to optimistic proxy) rather than eat into the proxy budget.
WORKSPACE_CLAIMS_TIMEOUT_SECONDS = (1, 1)
# Cache definitive (True/False) claim answers per workspace so a single probe flake does not
# re-flap routing for every subsequent event. Short TTL keeps us responsive when an integration
# moves between regions; None answers are never cached.
WORKSPACE_CLAIMS_CACHE_TTL_SECONDS = 60
def cross_region_routing_enabled() -> bool:
# Cross-region routing only makes sense between PostHog Cloud US and EU — they share the
# Slack app's signing secret and split workspace ownership between them. The hosted dev
# environment (CLOUD_DEPLOYMENT="DEV"), local dev, E2E, and self-hosted deployments all run
# as a single region; proxying their Slack events to us.posthog.com targets a different
# signing secret and a workspace this region doesn't own, which surfaces as a 403 on every
# webhook hit (see slack_app_region_proxy_non_success).
return get_instance_region() in ("US", "EU")
def _us_region_domain() -> str:
# Resolved at call time so override_settings(DEBUG=...) flips the topology cleanly in tests.
# In dev we run a single instance pretending to be both regions: the incoming SITE_URL host
# plays the part of US, and the other region is mapped to localhost so the proxy round-trips
# through the same process and exercises the at-most-one-hop guarantee end-to-end.
if settings.DEBUG:
return urlparse(settings.SITE_URL).netloc
return "us.posthog.com"
def _eu_region_domain() -> str:
if settings.DEBUG:
return "localhost:8000"
return "eu.posthog.com"
def is_us_host(host: str) -> bool:
return host == _us_region_domain()
def other_region_domain(incoming_host: str) -> str:
return _eu_region_domain() if is_us_host(incoming_host) else _us_region_domain()
def was_proxied(request: HttpRequest) -> bool:
# Match the literal value the sender sets (`"1"`) rather than coercing the header value to
# bool — semgrep flags the latter as nan-injection and we control the sender anyway.
return request.headers.get(REGION_PROXY_HEADER) == "1"
def _is_emit_only_mirror(request: HttpRequest) -> bool:
# Mirror copies also carry REGION_PROXY_HEADER, so `proxied` keeps guarding against re-hops.
return request.headers.get(EMIT_ONLY_MIRROR_HEADER) == "1"
def _proxy_target_url(request: HttpRequest, target_domain: str) -> str:
parsed_url = urlparse(request.build_absolute_uri())
# In dev the EU "region" is plain-HTTP localhost while the incoming URI is HTTPS (ngrok-
# terminated TLS), so always pick the scheme by target domain rather than copying the
# inbound one. Production talks HTTPS region-to-region.
target_scheme = "http" if settings.DEBUG else "https"
return urlunparse(parsed_url._replace(scheme=target_scheme, netloc=target_domain))
def _proxy_request_headers(request: HttpRequest) -> dict[str, str]:
# Drop Host plus the host-identifying forwarded headers so the receiver computes its own
# host from the new TCP connection rather than mirroring the sender's edge. X-Forwarded-For
# is intentionally preserved so the original Slack client IP survives the inter-region hop.
stripped = {"host", "x-forwarded-host", "forwarded"}
headers = {key: value for key, value in request.headers.items() if key.lower() not in stripped}
headers[REGION_PROXY_HEADER] = "1"
return headers
def send_region_proxy_request(
*,
method: str,
target_url: str,
headers: dict[str, str],
params: dict[str, list[str]] | None = None,
body: bytes | None = None,
) -> requests.Response | None:
"""POST a Slack event payload to the other region and translate the outcome into logs."""
try:
response = requests.request(
method=method,
url=target_url,
headers=headers,
params=params,
data=body,
timeout=REGION_PROXY_TIMEOUT_SECONDS,
)
if 200 <= response.status_code < 300:
logger.info("slack_app_region_proxy_ok", target_url=target_url, status_code=response.status_code)
return response
logger.warning(
"slack_app_region_proxy_non_success",
target_url=target_url,
status_code=response.status_code,
)
return None
except requests.RequestException as exc:
logger.exception("slack_app_region_proxy_failed", error=str(exc), target_url=target_url)
return None
def _proxy_event_to_region(
request: HttpRequest, target_domain: str, extra_headers: dict[str, str] | None = None
) -> requests.Response | None:
"""Forward the original Slack event to the other region, tagged so the receiver does not hop again."""
return send_region_proxy_request(
method=request.method or "POST",
target_url=_proxy_target_url(request, target_domain),
headers={**_proxy_request_headers(request), **(extra_headers or {})},
params=dict(request.GET.lists()) if request.GET else None,
body=request.body or None,
)
def _proxy_event_and_return_route(
request: HttpRequest, target_domain: str, extra_headers: dict[str, str] | None = None
) -> str:
"""Forward and translate the upstream result into a routing outcome string."""
upstream = _proxy_event_to_region(request, target_domain, extra_headers)
return ROUTE_PROXIED if upstream is not None else ROUTE_PROXY_FAILED
def _is_top_level_channel_post(event: dict[str, Any]) -> bool:
"""Whether a channel ``message`` starts a thread rather than replying inside one.
Slack sets ``thread_ts`` on replies and to ``ts`` on the post that opened the thread. Top-level
posts are the ones the follow-up pipeline discards before its region gate, so the mirror is what
carries them across; a reply already reaches that gate and crosses through it.
"""
thread_ts = event.get("thread_ts")
return not isinstance(thread_ts, str) or thread_ts == event.get("ts")
def _mirror_message_event_to_other_region(
request: HttpRequest,
event: dict,
*,
slack_team_id: str,
incoming_host: str,
other_domain: str,
) -> None:
"""Queue an emit-only copy of a top-level channel post for the other region.
A workspace connected in both regions gets its events consumed by the region Slack delivers to,
and the plain hand-off only fires when that region holds no connection, so the other region's
workflow triggers would otherwise never see a top-level channel message. The claims probe and
the cross-region POST run in a Celery task: top-level posts dominate wire volume and the webhook
owes Slack an ack within three seconds, so this path spends no cross-region I/O inline.
Only top-level posts are mirrored. A thread reply already reaches the follow-up pipeline's
region gate and crosses through it, so mirroring one would make the other region emit it twice.
"""
if not _is_top_level_channel_post(event):
return
if not is_triggering_message(event):
return
headers = _proxy_request_headers(request)
headers[EMIT_ONLY_MIRROR_HEADER] = "1"
# noqa reason: the task module imports this module's probe and transport, so a module-level
# import here would be circular.
from products.slack_app.backend.tasks import mirror_slack_message_event # noqa: PLC0415
try:
mirror_slack_message_event.delay(
slack_team_id=slack_team_id,
incoming_host=incoming_host,
target_url=_proxy_target_url(request, other_domain),
headers=headers,
body=(request.body or b"").decode("utf-8"),
)
except Exception:
# A broker failure must not 500 the shared webhook: Slack would redeliver, and the mention
# pipeline would handle the copy again. A lost mirror costs the other region one message.
logger.exception("slack_app_mirror_dispatch_failed", slack_team_id=slack_team_id)
def _workspace_claims_cache_key(slack_team_id: str, kinds: list[str]) -> str:
kinds_token = ",".join(sorted(kinds))
return f"slack_app:ws_claims:{slack_team_id}:{kinds_token}"
def does_other_region_claim_workspace(
*,
slack_team_id: str,
kinds: list[str],
incoming_host: str,
channel: str | None = None,
thread_ts: str | None = None,
) -> bool | None:
"""Ask the other region whether it claims the given workspace for any of the kinds.
Project IDs differ between regions, so probes use Slack workspace and thread IDs.
Thread probes bypass the workspace cache because a notification can create a new mapping.
Returns None when the peer cannot confirm ownership. Workspace-only probes cache definitive
answers for ``WORKSPACE_CLAIMS_CACHE_TTL_SECONDS``.
"""
cache_key = _workspace_claims_cache_key(slack_team_id, kinds)
thread_probe = bool(channel and thread_ts)
cached = None if thread_probe else cache.get(cache_key)
if isinstance(cached, bool):
logger.info(
"slack_app_workspace_claims_cache_hit",
slack_team_id=slack_team_id,
claimed=cached,
)
return cached
target_domain = other_region_domain(incoming_host)
scheme = "http" if settings.DEBUG else "https"
target_url = f"{scheme}://{target_domain}/slack/workspace/claims/"
payload: dict[str, Any] = {"slack_team_id": slack_team_id, "kinds": kinds}
if thread_probe:
payload.update(channel=channel, thread_ts=thread_ts)
body = json.dumps(payload).encode("utf-8")
signing_secret = SlackIntegration.slack_config()["SLACK_APP_SIGNING_SECRET"]
signed = sign_slack_request(body, signing_secret)
try:
response = requests.post(
target_url,
data=body,
headers={
"Content-Type": "application/json",
"X-Slack-Signature": signed.signature,
"X-Slack-Request-Timestamp": signed.timestamp,
REGION_PROXY_HEADER: "1",
},
timeout=WORKSPACE_CLAIMS_TIMEOUT_SECONDS,
)
except requests.RequestException as exc:
logger.warning("slack_app_workspace_claims_failed", target_url=target_url, error=str(exc))
return None
if response.status_code != 200:
logger.warning(
"slack_app_workspace_claims_non_200",
target_url=target_url,
status_code=response.status_code,
)
return None
try:
data = response.json()
except ValueError:
logger.warning("slack_app_workspace_claims_bad_json", target_url=target_url)
return None
claimed = data.get("thread_claimed" if thread_probe else "claimed")
if not isinstance(claimed, bool):
logger.warning("slack_app_workspace_claims_bad_payload", target_url=target_url)
return None
if not thread_probe:
cache.set(cache_key, claimed, timeout=WORKSPACE_CLAIMS_CACHE_TTL_SECONDS)
return claimed
_VALID_WORKSPACE_CLAIM_KINDS = frozenset(SLACK_INTEGRATION_KINDS)
@csrf_exempt
def slack_workspace_claims_view(request: HttpRequest) -> HttpResponse:
"""Cross-region probe: does this region hold an Integration row for the given Slack workspace?
Both Cloud regions provision the PostHog Desktop Slack signing secret, so a region can HMAC-sign
a small JSON body and the receiver can verify it with the same routine that validates real
Slack webhooks. The signed body covers every filter, so a captured signature cannot be replayed
against a different workspace.
"""
if request.method != "POST":
return HttpResponse(status=405)
try:
slack_config = SlackIntegration.slack_config()
validate_slack_request(request, slack_config["SLACK_APP_SIGNING_SECRET"])
except SlackIntegrationError as e:
logger.warning("slack_app_workspace_claims_invalid_request", error=str(e))
return HttpResponse("Invalid request", status=403)
try:
data = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponse("Invalid JSON", status=400)
slack_team_id = data.get("slack_team_id")
kinds = data.get("kinds")
if not isinstance(slack_team_id, str) or not slack_team_id:
return HttpResponse("Missing slack_team_id", status=400)
if not isinstance(kinds, list) or not kinds:
return HttpResponse("Missing kinds", status=400)
filtered = [k for k in kinds if isinstance(k, str) and k in _VALID_WORKSPACE_CLAIM_KINDS]
if not filtered:
return HttpResponse("No valid kinds", status=400)
claimed = IntegrationManager.slack.oauth.exists_by_external_id(slack_team_id)
channel, thread_ts = data.get("channel"), data.get("thread_ts")
if channel is not None or thread_ts is not None:
if not isinstance(channel, str) or not channel or not isinstance(thread_ts, str) or not thread_ts:
return HttpResponse("Invalid thread", status=400)
candidates = workspace_integrations(slack_team_id)
result = resolve_from_candidates(candidates, slack_team_id=slack_team_id, channel=channel, thread_ts=thread_ts)
return JsonResponse({"claimed": claimed, "thread_claimed": result.source == "thread"})
return JsonResponse({"claimed": claimed})
def _strip_bot_mentions(text: str) -> str:
"""Remove all <@BOT_ID> mentions from text."""
return re.sub(r"<@[A-Z0-9]+>", "", text).strip()
# The words people type in `/posthog welcome <value>`, mapped to the stored mode.
WELCOME_COMMAND_VALUES: dict[str, ChannelWelcomeMode] = {
"channel": ChannelWelcomeMode.CHANNEL,
"private": ChannelWelcomeMode.INVITER,
"off": ChannelWelcomeMode.OFF,
}
def parse_rules_command(text: str) -> RulesCommand | None:
cleaned = _strip_bot_mentions(text).strip()
if not cleaned:
return None
list_match = re.fullmatch(r"rules\s+list", cleaned, flags=re.IGNORECASE)
if list_match:
return RulesCommand(action="list")
add_with_repo_match = re.fullmatch(
r'rules\s+add\s+"([^"]+)"\s+([\w.-]+/[\w.-]+)',
cleaned,
flags=re.IGNORECASE,
)
if add_with_repo_match:
return RulesCommand(
action="add", rule_text=add_with_repo_match.group(1), repository=add_with_repo_match.group(2)
)
add_no_repo_match = re.fullmatch(
r'rules\s+add\s+"([^"]+)"',
cleaned,
flags=re.IGNORECASE,
)
if add_no_repo_match:
return RulesCommand(action="add", rule_text=add_no_repo_match.group(1))
remove_match = re.fullmatch(r"rules\s+remove\s+([\d,\s]+)", cleaned, flags=re.IGNORECASE)
if remove_match:
numbers = [int(n.strip()) for n in remove_match.group(1).split(",") if n.strip().isdigit()]
if numbers:
return RulesCommand(action="remove", rule_numbers=numbers)
# `project workspace <id>` sets the workspace-wide default and must be tested
# before the generic `project` branch. Trailing text after the id is ignored.
# `[`*_]*` lets the id keep the Slack code or emphasis formatting the picker
# message wraps it in, so a pasted `452770` still parses.
project_workspace_match = re.fullmatch(
r"project\s+workspace\s+[`*_]*(\d+)[`*_]*(?:\s+.*)?", cleaned, flags=re.IGNORECASE | re.DOTALL
)
if project_workspace_match is not None:
return RulesCommand(action="project_set_workspace", project_team_id=int(project_workspace_match.group(1)))
# Trailing text after the id is tolerated but ignored — we only act on the id.
project_match = re.fullmatch(
r"project(?:\s+[`*_]*(\d+)[`*_]*(?:\s+.*)?)?", cleaned, flags=re.IGNORECASE | re.DOTALL
)
if project_match is not None:
team_id_str = project_match.group(1)
if team_id_str is None:
return RulesCommand(action="project_show")
return RulesCommand(action="project_set", project_team_id=int(team_id_str))
# Only the known values match, so a mention like "welcome the new hire" stays a task.
welcome_match = re.fullmatch(r"welcome(?:\s+(channel|private|off))?", cleaned, flags=re.IGNORECASE)
if welcome_match is not None:
value = welcome_match.group(1)
if value is None:
return RulesCommand(action="welcome_show")
return RulesCommand(action="welcome_set", welcome_mode=WELCOME_COMMAND_VALUES[value.lower()])
if re.fullmatch(r"help", cleaned, flags=re.IGNORECASE):
return RulesCommand(action="help")
# Intercept legacy `default repo` verbs so `default repo set org/repo` doesn't
# fall through into the explicit-repo cascade and spawn a junk task.
if re.fullmatch(r"default\s+repo\s+(set|show|clear)(\s+.*)?", cleaned, flags=re.IGNORECASE):
return RulesCommand(action="deprecated_default_repo")
return None
def _post_repo_picker_message(
*,
slack: SlackIntegration,
integration: WorkspaceIntegration,
channel: str,
thread_ts: str,
slack_user_id: str,
user_id: int,
event_text: str,
user_message_ts: str | None,
guidance: str,
action_id: str,
workflow_id: str | None = None,
allow_no_repo: bool = False,
) -> None:
context_data = {
"integration_id": integration.id,
"channel": channel,
"thread_ts": thread_ts,
"user_message_ts": user_message_ts,
"mentioning_slack_user_id": slack_user_id,
"mentioning_user_id": user_id,
"event_text": event_text,
"created_at": int(time.time()),
"workflow_id": workflow_id,
}
context_token = uuid.uuid4().hex
cache.set(_picker_context_cache_key(context_token), context_data, timeout=PICKER_TOKEN_MAX_AGE_SECONDS)
blocks: list[dict[str, Any]] = [
{
"type": "section",
"block_id": f"posthog_code_repo_picker_v2:{integration.id}:{slack_user_id}:{context_token}",
"text": {"type": "mrkdwn", "text": guidance},
"accessory": {
"type": "external_select",
"action_id": action_id,
"placeholder": {"type": "plain_text", "text": "Search GitHub repositories..."},
"min_query_length": 0,
},
}
]
if allow_no_repo:
blocks.append(
{
"type": "actions",
"block_id": f"posthog_code_repo_picker_v2:{integration.id}:{slack_user_id}:{context_token}:actions",
"elements": [
{
"type": "button",
"action_id": "posthog_code_repo_none",
"text": {"type": "plain_text", "text": "No repo needed"},
"style": "primary",
"value": "no_repo_needed",
}
],
}
)
response = post_slack_thread_reply(
slack.client,
channel=channel,
thread_ts=thread_ts,
text=guidance,
blocks=blocks,
metadata={
"event_type": "posthog_code_repo_picker",
"event_payload": {"context_token": context_token, "workflow_id": workflow_id},
},
)
if response is None:
# No prompt left to route, so there is nothing to ask about and nothing to await.
return
if workflow_id:
response_data = normalize_slack_response(response)
message_ts = response_data.get("ts") if isinstance(response_data.get("ts"), str) else None
_set_pending_repo_picker(
integration_id=integration.id,
channel=channel,
thread_ts=thread_ts,
slack_user_id=slack_user_id,
user_id=user_id,
workflow_id=workflow_id,
context_token=context_token,
message_ts=message_ts,
)
# Pre-warm the repo list cache so the external_select options request
# is served from cache rather than hitting the GitHub API inline.
# Non-fatal: the dropdown will still work, it will just fetch on demand.
try:
_get_full_repo_names(integration, user_id=user_id)
except Exception:
logger.warning("slack_app_repo_list_prewarm_failed", user_id=user_id, exc_info=True)
def _extract_explicit_repo(text: str, all_repos: list[str]) -> str | None:
"""Repo named by Slack message text, as a typed org/repo token or as a GitHub link."""
cleaned = _strip_bot_mentions(text)
return extract_explicit_repo(cleaned, all_repos) or extract_linked_repo(cleaned, all_repos)
def _extract_explicit_repo_from_thread(thread_messages: list[SlackThreadMessage], all_repos: list[str]) -> str | None:
"""Repo named by the thread around a mention, newest message first.
People paste the link into the thread and mention the bot in a later reply that carries no
link of its own. Reading only the mention hands those asks to the discovery agent, which
answers them from this same thread text. Newest first because the link under discussion is
the one most recently posted.
"""
return extract_repo_from_scopes(
[_strip_bot_mentions(message.text) for message in reversed(thread_messages)], all_repos
)
def _schedule_user_repo_cache_refresh(user_integration_id: str) -> None:
# The task module imports this module, so a module-level import here would be circular.
from products.slack_app.backend.tasks import refresh_user_github_repository_cache # noqa: PLC0415
try:
refresh_user_github_repository_cache.delay(user_integration_id=user_integration_id)
except Exception:
# The stale snapshot still answers this mention, and the next mention schedules the refresh again.
logger.warning("slack_app_github_repo_cache_refresh_dispatch_failed", user_integration_id=user_integration_id)
def _repo_snapshot_needs_refresh(record: UserIntegration) -> bool:
updated_at = record.repository_cache_updated_at
if updated_at is None:
return True
return (timezone.now() - updated_at).total_seconds() >= REPO_SNAPSHOT_REFRESH_INTERVAL_SECONDS
def _get_full_repo_names(integration: WorkspaceIntegration, *, user_id: int | None) -> list[str]:
"""Repo names available to the mentioner, from their personal GitHub install. Cached per user."""
if user_id is None:
return []
cache_key = _user_repo_list_cache_key(user_id)
cached = cache.get(cache_key)
if cached is not None:
return cached
user_records = UserIntegration.objects.filter(
user_id=user_id,
kind=UserIntegration.IntegrationKind.GITHUB,
)
if not user_records.exists():
cache.set(cache_key, [], timeout=REPO_LIST_CACHE_TTL_SECONDS)
return []
all_repos: set[str] = set()
for record in user_records:
github = UserGitHubIntegration(record, source="slack_app_repo_selection", priority=Priority.NORMAL)
# A live listing of a large install takes seconds while the person waits in Slack, so a
# snapshot with repos is served as it is and refreshed in the background.
has_cached_repos = bool(record.repository_cache)
if has_cached_repos and _repo_snapshot_needs_refresh(record):
_schedule_user_repo_cache_refresh(str(record.id))
repo_entries = github.list_all_cached_repositories(
max_repos=_MAX_GITHUB_REPOS, allow_refresh=not has_cached_repos
)
for repo in repo_entries:
all_repos.add(repo["full_name"])
if len(all_repos) >= _MAX_GITHUB_REPOS:
logger.warning(
"slack_app_github_repo_list_capped",
user_id=user_id,
team_id=integration.team_id,
cap=_MAX_GITHUB_REPOS,
)
result = sorted(all_repos)
cache.set(cache_key, result, timeout=REPO_LIST_CACHE_TTL_SECONDS)
return result
result = sorted(all_repos)
if result:
cache.set(cache_key, result, timeout=REPO_LIST_CACHE_TTL_SECONDS)
return result
def _replace_repo_picker_message_with_selection(
*,
integration_id: int,
slack_team_id: str,
channel: str,
message_ts: str,
selected_repo: str,
) -> None:
try:
integration = get_workspace_integration(integration_id, slack_team_id)
if integration is None:
raise IntegrationNotFound
slack = SlackIntegration(integration)
text = f"Repository selected: `{selected_repo}`"
slack.client.chat_update(
channel=channel,
ts=message_ts,
text=text,
blocks=[
{
"type": "section",
"text": {"type": "mrkdwn", "text": f"*Repository selected:* `{selected_repo}`"},
}
],
)
except Exception:
logger.warning(
"slack_app_repo_submit_picker_update_failed",
integration_id=integration_id,
channel=channel,
message_ts=message_ts,
)
def _replace_repo_picker_message_with_no_repo(
*,
integration_id: int,
slack_team_id: str,
channel: str,
message_ts: str,
) -> None:
try:
integration = get_workspace_integration(integration_id, slack_team_id)
if integration is None:
raise IntegrationNotFound
slack = SlackIntegration(integration)
text = "Continuing without a repository."
slack.client.chat_update(
channel=channel,
ts=message_ts,
text=text,
blocks=[
{
"type": "section",
"text": {"type": "mrkdwn", "text": "*Continuing without a repository.*"},
}
],
)
except Exception:
logger.warning(
"slack_app_repo_none_picker_update_failed",
integration_id=integration_id,
channel=channel,
message_ts=message_ts,
)
def _resolve_pending_repo_picker_from_followup(event: dict[str, Any], integration: WorkspaceIntegration) -> bool:
channel = event.get("channel")
thread_ts = event.get("thread_ts") or event.get("ts")
slack_user_id = event.get("user")
if not channel or not thread_ts or not slack_user_id:
return False
pending_picker = _get_pending_repo_picker(
integration_id=integration.id,
channel=channel,
thread_ts=thread_ts,
slack_user_id=slack_user_id,
)
if not pending_picker:
return False
workflow_id = pending_picker.get("workflow_id")
if not isinstance(workflow_id, str) or not workflow_id:
_clear_pending_repo_picker(
integration_id=integration.id,
channel=channel,
thread_ts=thread_ts,
slack_user_id=slack_user_id,
)
return False
mentioning_user_id = pending_picker.get("mentioning_user_id")
if not isinstance(mentioning_user_id, int):
# Without a known PostHog user we can't scope the picker to a personal install;
# let the message fall through to the standard flow, which will re-resolve and re-post.
return False
try:
all_repos = _get_full_repo_names(integration, user_id=mentioning_user_id)
except Exception:
logger.exception("slack_app_pending_picker_repo_fetch_failed", integration_id=integration.id)
return False
selected_repo = _extract_explicit_repo(event.get("text", ""), all_repos)
if not selected_repo:
return False
try:
client = sync_connect()
handle = client.get_workflow_handle(workflow_id)
asyncio.run(handle.signal(SlackAppMentionProcessingWorkflow.repo_selected, selected_repo))
except Exception as e:
logger.warning(
"slack_app_pending_picker_signal_failed",
workflow_id=workflow_id,
integration_id=integration.id,
channel=channel,
thread_ts=thread_ts,
error=str(e),
)
_clear_pending_repo_picker(
integration_id=integration.id,
channel=channel,
thread_ts=thread_ts,
slack_user_id=slack_user_id,
)
return False
_clear_pending_repo_picker(
integration_id=integration.id,
channel=channel,
thread_ts=thread_ts,
slack_user_id=slack_user_id,
)
message_ts = pending_picker.get("message_ts")
if isinstance(message_ts, str) and message_ts:
_replace_repo_picker_message_with_selection(
integration_id=integration.id,
slack_team_id=integration.integration_id,
channel=channel,
message_ts=message_ts,
selected_repo=selected_repo,
)
logger.info(
"slack_app_pending_picker_resolved_from_followup",
workflow_id=workflow_id,
integration_id=integration.id,
channel=channel,
thread_ts=thread_ts,
repository=selected_repo,
)
return True
def _app_authorship_ignore_reason(event: dict[str, Any]) -> str | None:
"""Return why a Slack app, rather than a person typing, is behind this message.
- "bot_author": posted with a bot token or an incoming webhook, which is what
`bot_id`, `bot_profile` and the `bot_message` subtype mark.
- "app_authored": carries `app_id` with no bot marker, which is how Slack stamps a
message an app posted on a person's behalf with a user token. Reported under its
own reason rather than folded into `bot_author` because the two have very
different volumes and the drop funnel needs to tell them apart.
Both drop. An app posting as a user is indistinguishable from that user typing, so
admitting them would let relay and mirror apps that repost human text verbatim spawn
duplicate tasks, and would run privileged actions (rules commands, agent runs that
open pull requests) under a person who never asked for them.
"""
if event.get("bot_id") or event.get("bot_profile") or event.get("subtype") == "bot_message":
return "bot_author"
if event.get("user") == "USLACKBOT":
return "bot_author"
if event.get("app_id"):
return "app_authored"
return None
_MENTION_WITH_TRAILING_SLASH_RE = re.compile(r"<@[A-Z0-9]+>(/?)")
def _every_mention_is_a_path_segment(event: dict[str, Any]) -> bool:
"""Whether every user mention in the text is glued to a following ``/``.
Slack linkifies a typed ``@PostHog`` even inside an org-scoped package or repo path, so
``@PostHog/react-native-plugin`` reaches us as ``<@BOT>/react-native-plugin`` and fires a
real ``app_mention``. Nobody addressed the app in that message, they named a package, and
answering it starts an agent run against a prompt that is only the path's tail.
Requiring *every* mention to be glued keeps this from firing on a message that also tags
the app properly, because the app's own mention can't be told apart from a teammate's
without a ``users.info`` round-trip that this gate runs too early to afford.
"""
text = event.get("text")
if not isinstance(text, str):
return False
trailing_slashes = _MENTION_WITH_TRAILING_SLASH_RE.findall(text)
return bool(trailing_slashes) and all(trailing_slashes)
def _path_mention_drop_properties(event: dict[str, Any]) -> dict[str, Any]:
"""Analytics context specific to a ``path_mention`` drop.
The drop count on its own can't separate a harmless package paste from a real request
the gate ate, so it can't tell us whether the gate is tuned right. Word count splits
them: a message that is only ``@PostHog/posthog-js`` counts one word, and anything
higher means prose surrounded the path, which is the shape worth reviewing.
"""
text = event.get("text")
if not isinstance(text, str):
text = ""
return {
"slack_mention_count": len(_MENTION_WITH_TRAILING_SLASH_RE.findall(text)),
"slack_message_word_count": len(text.split()),
}
def _app_mention_ignore_reason(event: dict[str, Any]) -> str | None:
"""Return a short reason if this app_mention shouldn't trigger the coding agent, else None.
- "edit": Slack re-fires app_mention with a new event_id when a previously-posted
mention is edited. The new event_id bypasses Temporal workflow dedup, so without
this guard the edit spawns a duplicate task alongside the original.
- "bot_author" / "app_authored": see ``_app_authorship_ignore_reason``. Foreign bots
that quote `<@PostHog>` in their text (incident bots, alert relays, our own
notifications integration) would trigger reply loops on every re-post.
- "path_mention": see ``_every_mention_is_a_path_segment``.
"""
if event.get("edited") or event.get("subtype") == "message_changed":
return "edit"
return _mention_content_ignore_reason(event)
def _mention_content_ignore_reason(event: dict[str, Any]) -> str | None:
authorship = _app_authorship_ignore_reason(event)
if authorship:
return authorship
if _every_mention_is_a_path_segment(event):
return "path_mention"
return None
def _message_handled_cache_key(slack_team_id: str, event: dict[str, Any]) -> str | None:
channel = event.get("channel")
message_ts = event.get("ts")
if not isinstance(channel, str) or not channel or not isinstance(message_ts, str) or not message_ts:
return None
return f"slack_app:message_handled:v1:{slack_team_id}:{channel}:{message_ts}"
def claim_message_handled(slack_team_id: str, event: dict[str, Any], handled_as: str) -> bool:
"""Record that the pipeline acted on this message, unless another path already did.
Atomic, so an answer to an untagged question and an edit of the same message that adds a tag
can't both start a run. Returns the marker's current value on a lost claim, so a caller can
recognise its own earlier claim.
"""
cache_key = _message_handled_cache_key(slack_team_id, event)
if cache_key is None:
return True
return bool(cache.add(cache_key, handled_as, timeout=MESSAGE_HANDLED_MARKER_TTL_SECONDS))
def message_handled_by(slack_team_id: str, event: dict[str, Any]) -> str | None:
cache_key = _message_handled_cache_key(slack_team_id, event)
return cache.get(cache_key) if cache_key else None
def _mark_message_handled(slack_team_id: str, event: dict[str, Any], handled_as: str) -> None:
"""Record that the pipeline acted on this message, so that a later edit of it starts nothing."""
cache_key = _message_handled_cache_key(slack_team_id, event)
if cache_key is not None:
cache.set(cache_key, handled_as, timeout=MESSAGE_HANDLED_MARKER_TTL_SECONDS)
def _edited_mention_ignore_cause(event: dict[str, Any], slack_team_id: str) -> str | None:
"""Why an edited ``app_mention`` must start nothing, or None when it must start a run.
The marker claim is atomic and comes last, so a second edit of the same message stops here.
"""
# The envelope nests the message, so its top-level ``ts`` is the ts of the change.
if event.get("subtype") == "message_changed":
return "message_changed_envelope"
content_reason = _mention_content_ignore_reason(event)
if content_reason:
return content_reason
cache_key = _message_handled_cache_key(slack_team_id, event)
if cache_key is None:
return "no_message_ts"
try:
posted_at = float(event["ts"])
except ValueError:
return "no_message_ts"
if time.time() - posted_at > EDITED_MENTION_WINDOW_SECONDS:
return "too_old"
if not claim_message_handled(slack_team_id, event, "edited_mention"):
return f"handled_as_{cache.get(cache_key) or 'unknown'}"
return None
def _awaits_request_from_author(event: dict[str, Any], slack_team_id: str, probe: WorkspaceIntegration) -> bool:
"""Whether this threaded message is the request a bare mention in its thread asked for."""
channel = event.get("channel")
thread_ts = event.get("thread_ts")
awaited_from = bare_mention.awaited_request_from(
slack_team_id,
channel if isinstance(channel, str) else None,
thread_ts if isinstance(thread_ts, str) else None,
now=time.time(),
)
if awaited_from is None:
return False
if awaited_from != event.get("user"):
if event.get("type") == "message":
_report_slack_mention_dropped(
event, slack_team_id, reason="awaited_reply_other_user", replied=False, integration=probe
)
return False
return True
def _answer_bare_mention(
event: dict[str, Any], integration: WorkspaceIntegration, slack_team_id: str, *, posthog_user: User
) -> str:
channel = event.get("channel")
message_ts = event.get("ts")
slack_user_id = event.get("user")
replied = False
if isinstance(channel, str) and isinstance(message_ts, str) and isinstance(slack_user_id, str):
if bare_mention.await_request(slack_team_id, channel, message_ts, slack_user_id=slack_user_id):
replied = _post_slack_user_feedback(
SlackIntegration(integration),
channel,
slack_user_id,
message_ts,
bare_mention.BARE_MENTION_REPLY,
prefer_thread_message=True,
)
# No run started, so an edit that adds the request must be free to start one.
handled_key = _message_handled_cache_key(slack_team_id, event)
if handled_key is not None:
cache.delete(handled_key)
_report_slack_mention_dropped(
event,
slack_team_id,
reason="bare_mention",
replied=replied,
integration=integration,
posthog_user=posthog_user,
)
return ROUTE_HANDLED_LOCALLY
def _thread_message_event_has_files(event: dict[str, Any]) -> bool:
files = event.get("files")
return isinstance(files, list) and len(files) > 0
def _slack_attachment_props(event: dict[str, Any]) -> dict[str, Any]:
"""Analytics context for whatever a message carried alongside its text.
The agent reads images now, so how often people send one is the question the mention
event has to answer, and it can only do that by counting the uploads as they arrive.
Distinct mimetypes ride along so a screenshot is separable from a log or a CSV without
a second event.
"""
files = parse_slack_file_refs(event.get("files"))
image_count = sum(1 for file in files if file.mimetype.startswith("image/"))
return {
"slack_attachment_count": len(files),
"slack_image_count": image_count,
"slack_has_image": image_count > 0,
"slack_attachment_mimetypes": sorted({file.mimetype for file in files if file.mimetype}),
}
def _thread_message_ignore_reason(event: dict[str, Any]) -> str | None:
"""Return a short reason if this ``message`` event shouldn't be considered as an
untagged thread follow-up, else None.
Distinct from ``_app_mention_ignore_reason`` because ``message`` events have
more subtypes worth dropping early — joins, leaves, deletions — and arrive
in vastly higher volume (every message in every channel the bot is in), so
the cheap gates here run before any DB or LLM work.
"""
if not event.get("user"):
return "no_user"
# A file-only reply has empty text and the ``file_share`` subtype — both
# must be admitted here or the attachment silently never reaches the agent.
has_files = _thread_message_event_has_files(event)
if not event.get("text") and not has_files:
return "no_text"
if event.get("edited") or event.get("subtype") == "message_changed":
return "edit"
if event.get("subtype") == "message_deleted":
return "deleted"
app_authorship = _app_authorship_ignore_reason(event)
if app_authorship:
return app_authorship
# Any other ``subtype`` (channel_join, channel_leave, thread_broadcast,
# etc.) is system noise from this gate's perspective. ``thread_broadcast``
# is the only one a human types, but it's typically an announcement to the
# parent channel, not agent-directed work.
subtype = event.get("subtype")
if subtype and not (subtype == "file_share" and has_files):
return f"subtype:{subtype}"
return None
def _resolve_untagged_followup_mapping(
*,
candidates: Sequence[WorkspaceIntegration],
channel: str | None,
thread_ts: str | None,
) -> SlackThreadTaskMapping | None:
"""Look up the ``SlackThreadTaskMapping`` for an untagged thread reply.
Returns the mapping when the message should enter the shared routing
pipeline; ``None`` when the thread isn't ours and it should drop.
"""
candidate_ids = [c.id for c in candidates]
# ``task`` is fetched separately inside the classifier activity — the
# handler hot path only needs the integration (for the ``mention_target``
# override downstream).
mapping = (
SlackThreadTaskMapping.objects.filter(
integration_id__in=candidate_ids,
channel=channel,
thread_ts=thread_ts,
)
.select_related("integration", "integration__team")
.first()
)
return mapping
def _message_tags_bot(event: dict[str, Any], integration: WorkspaceIntegration) -> bool:
"""Whether the message text mentions the app's own bot user.
Slack delivers a thread reply that tags the bot twice — as ``app_mention``
and as a plain ``message`` — under two different event ids, so the queue
workflow's event-id dedup never collapses them. The mention pipeline owns
the tagged copy; this gate keeps the ``message`` copy out of the
untagged-followup path. When the bot user id can't be resolved the gate
stays open: a duplicate prompt beats silently dropping a genuine follow-up.
"""
text = event.get("text") or ""
if "<@" not in text:
return False
# Mirror the ``app_mention`` gate: when every mention is glued to a ``/`` the
# message names package paths rather than tagging the app, and the
# ``app_mention`` copy was dropped as ``path_mention`` — this copy is the
# only one left, so it must stay in the untagged pipeline.
if _every_mention_is_a_path_segment(event):
return False
bot_user_id = get_cached_bot_user_id(SlackIntegration(integration), integration)
if not bot_user_id:
return False
return re.search(rf"<@{re.escape(bot_user_id)}(\|[^>]*)?>", text) is not None
def _untagged_followups_switched_off(
event: dict[str, Any],
integration: WorkspaceIntegration,
slack_team_id: str,
*,
mapping: SlackThreadTaskMapping,
posthog_user: User,
) -> bool:
"""Whether the thread creator has untagged follow-ups turned off.
Only ``never`` is decided here. ``ask`` waits until the classifier has judged
the reply worth forwarding, inside the workflow — prompting from the webhook
would raise one for every "thanks" in the thread. ``never`` costs nobody an
LLM call, so it drops before dispatch.
"""
if resolve_untagged_followup_mode(integration, mapping.mentioning_slack_user_id) != UntaggedFollowupMode.NEVER:
return False
logger.info(
"slack_app_thread_message_mode_never",
slack_team_id=slack_team_id,
channel=event.get("channel"),
thread_ts=mapping.thread_ts,
integration_id=integration.id,
)
_report_slack_mention_dropped(
event,
slack_team_id,
reason="untagged_followup_mode_never",
replied=False,
integration=integration,
posthog_user=posthog_user,
)
return True
def _notify_missing_slack_scopes(
slack: SlackIntegration,
event: dict,
missing: frozenset[str],
) -> bool:
"""Tell the user the install is missing scopes and how to fix it.
`chat:write` has been part of the base Slack scope set since the integration existed,
so the feedback post itself is safe to attempt even when other scopes are absent.
Returns whether the notice was posted, so callers can record whether the user was
left with an explanation or with silence.
"""
channel = event.get("channel", "")
thread_ts = event.get("thread_ts") or event.get("ts", "")
slack_user_id = event.get("user", "")
integration = slack.integration
logger.warning(
"slack_app_slack_missing_scopes",
integration_id=integration.id,
team_id=integration.team_id,
missing=sorted(missing),
)
if not channel or not thread_ts or not slack_user_id:
return False
settings_url = f"{settings.SITE_URL}/integrations/slack"
text = (
":warning: PostHog can't reply because the Slack integration is missing required "
f"permissions: `{', '.join(sorted(missing))}`.\n"
f"A project admin needs to reconnect Slack from project settings: {settings_url}"
)
return _post_slack_user_feedback(slack, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
def get_slack_email_for_user(probe_integration: WorkspaceIntegration, slack_user_id: str) -> str | None:
"""Best-effort lookup of the Slack user's email via ``users.info``, cache-first then
a fresh hit on miss. Returns ``None`` when Slack doesn't expose an email for the
user (profile email hidden) or the lookup fails.
Every termination path emits a distinct structured log so a silent ``None`` can
still be diagnosed from logs alone — historically the failure modes collapsed
onto a downstream ``user_not_found`` warning that hid the actual cause.
Auth-class ``SlackApiError`` outcomes flip the shared ``slack_auth`` cache to
``ok=false`` so the resolver demotes this install on subsequent mentions
rather than pinning every one to a dead token. The success path deliberately
does NOT write ``ok=true``: the cache lives in the resolver's ``auth.test``
layer, and a DB-cache hit (``SlackUserProfileCache``) proves nothing about
the live token. Letting the resolver own the positive verdict keeps the
cache truthful.
"""
from products.slack_app.backend.services.slack_auth import SLACK_AUTH_FAILURE_CODES, write_auth_state_broken
slack_client = SlackIntegration(probe_integration)
try:
user_info = get_slack_user_info(slack_client, probe_integration, slack_user_id)
slack_email = user_info.get("user", {}).get("profile", {}).get("email")
if slack_email:
return slack_email
fresh = normalize_slack_response(slack_client.client.users_info(user=slack_user_id))
if not fresh:
logger.warning(
"slack_app_resolve_user_email_empty_response",
integration_id=probe_integration.id,
slack_user_id=slack_user_id,
)
return None
persist_slack_user_info(probe_integration, slack_user_id, fresh)
slack_email = fresh.get("user", {}).get("profile", {}).get("email")
if not slack_email:
logger.warning(
"slack_app_resolve_user_email_missing_in_profile",
integration_id=probe_integration.id,
slack_user_id=slack_user_id,
ok=fresh.get("ok"),
)
return None
return slack_email
except SlackApiError as exc:
error_code = exc.response.get("error") if exc.response else None
token_broken = isinstance(error_code, str) and error_code in SLACK_AUTH_FAILURE_CODES
if token_broken and isinstance(error_code, str):
write_auth_state_broken(probe_integration.id, error_code)
logger.warning(
"slack_app_resolve_user_email_failed",
integration_id=probe_integration.id,
slack_user_id=slack_user_id,
error_code=error_code,
token_broken=token_broken,
exc_info=True,
)
return None
except Exception:
logger.warning(
"slack_app_resolve_user_email_failed",
integration_id=probe_integration.id,
slack_user_id=slack_user_id,
error_code=None,
token_broken=False,
exc_info=True,
)
return None
def resolve_posthog_user_from_event(
*,
slack_user_id: str,
probe_integration: WorkspaceIntegration,
candidate_integrations: Sequence[WorkspaceIntegration],
slack_email: str | None = None,
) -> User | None:
"""Resolve the acting Slack user to a PostHog ``User`` who is a member of
at least one organization connected to this Slack workspace.
The probe is used to call Slack's ``users.info``; the candidate list scopes
the organization-membership check. A user with no membership in any
connected org returns ``None`` so the caller can refuse the event. A
deactivated user is treated the same as "no membership" — every caller of
this helper (dismiss, channel approval, alert snooze, ...) authorizes off
the returned ``User``, so a deactivated account must not resolve to one.
``slack_email`` may be passed by callers that already have it (e.g.
``resolve_user_and_integrations``) so we don't repeat the cache lookup.
"""
org_ids = {c.team.organization_id for c in candidate_integrations}
if not org_ids:
return None
# Linked-user path: short-circuit the email match when the user has bound
# their Slack identity to a PostHog account.
slack_team_id = probe_integration.integration_id
linked_user = find_linked_posthog_user(
slack_user_id=slack_user_id,
slack_team_id=slack_team_id,
candidate_org_ids=org_ids,
)
if linked_user is not None and is_slack_app_oauth_enabled(probe_integration):
return linked_user
if slack_email is None:
slack_email = get_slack_email_for_user(probe_integration, slack_user_id)
if not slack_email:
return None
try:
membership = (
OrganizationMembership.objects.filter(
organization_id__in=org_ids, user__email__iexact=slack_email, user__is_active=True
)
.select_related("user")
.first()
)
except Exception:
# Don't propagate transient DB errors to the Slack webhook — Slack
# retries 5xx and would replay the event. The caller gets ``None`` and
# treats it the same as "no membership found".
logger.warning(
"slack_app_resolve_user_membership_failed",
integration_id=probe_integration.id,
slack_user_id=slack_user_id,
exc_info=True,
)
return None
return membership.user if membership else None
def _post_pick_a_project_hint(
probe: SlackIntegration,
candidates: Sequence[WorkspaceIntegration],
event: dict[str, Any],
) -> bool:
"""Tell the user that this workspace is connected to multiple PostHog
projects, list the ones they can reach, and point at the two ways to pick one.
The slash command reads the same on both surfaces this runs on: a channel mention, and a DM,
where there is no app to mention in the first place.
Returns whether the hint was posted, so callers can record whether the user was
left with an explanation or with silence.
"""
slack_user_id = event.get("user")
channel = event.get("channel")
thread_ts = event.get("thread_ts") or event.get("ts")
if not isinstance(slack_user_id, str) or not isinstance(channel, str) or not isinstance(thread_ts, str):
return False
text = pick_a_project_message(
"This Slack workspace is connected to multiple PostHog projects. You can work in any of these:",
candidates,
set_command=SLASH_COMMAND_PREFIX,
home_tab_url=app_home_url(probe.integration),
)
return _post_slack_user_feedback(probe, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
def _post_project_picker(
candidates: Sequence[WorkspaceIntegration],
event: dict[str, Any],
event_id: str | None,
*,
is_ext_shared_channel: bool,
mention_is_threaded: bool,
) -> bool:
"""Offer the projects as choices. Returns whether the picker reached Slack."""
probe = candidates[0]
slack_user_id = event.get("user")
channel = event.get("channel")
message_ts = event.get("ts")
if not isinstance(slack_user_id, str) or not isinstance(channel, str) or not isinstance(message_ts, str):
return False
context_token = uuid.uuid4().hex
cache.set(
_picker_context_cache_key(context_token),
project_picker.build_project_picker_context(
event=event,
event_id=event_id,
probe=probe,
candidates=candidates,
slack_user_id=slack_user_id,
is_ext_shared_channel=is_ext_shared_channel,
),
timeout=PICKER_TOKEN_MAX_AGE_SECONDS,
)
client = SlackIntegration(probe).client
client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
thread_ts = event.get("thread_ts")
try:
post_slack_ephemeral(
client,
channel=channel,
user=slack_user_id,
# Slack renders an ephemeral only on the surface the person is viewing.
thread_ts=thread_ts if mention_is_threaded and isinstance(thread_ts, str) else None,
text="Which PostHog project should I use?",
blocks=project_picker.build_project_picker_blocks(
candidates,
context_token=context_token,
slack_user_id=slack_user_id,
home_tab_url=app_home_url(probe),
),
)
except Exception:
logger.warning(
"slack_app_project_picker_post_failed",
integration_id=probe.id,
slack_workspace_id=probe.integration_id,
slack_channel_id=channel,
exc_info=True,
)
cache.delete(_picker_context_cache_key(context_token))
return False
return True
def _handle_project_picker_pick(payload: dict) -> HttpResponse:
"""Run the mention the picker was raised for against the project the person picked."""
response_url = payload.get("response_url", "")
context_token = _extract_context_token(payload)
context = _decode_picker_context(context_token) if context_token else None
if not context or context.get("kind") != project_picker.PROJECT_PICKER_CONTEXT_KIND:
inbox_interactivity.post_response_url(
response_url, {"replace_original": True, "text": project_picker.PICKER_EXPIRED_MESSAGE}
)
return HttpResponse(status=200)
slack_team_id = payload.get("team", {}).get("id", "")
clicker_slack_user_id = payload.get("user", {}).get("id", "")
event = context.get("event")
integration_id = project_picker.picked_integration_id(payload)
rejection: str | None = project_picker.pick_rejection(
context, clicker_slack_user_id=clicker_slack_user_id, integration_id=integration_id
)
integration = None
if rejection is None and integration_id is not None and slack_team_id:
integration = get_workspace_integration(integration_id, slack_team_id)
# Access can change between the post and the click.
posthog_user = _is_org_member(integration, clicker_slack_user_id) if integration is not None else None
if (
not isinstance(event, dict)
or integration is None
or posthog_user is None
or not _can_access_team(posthog_user, integration)
):
rejection = rejection or "no_access"
logger.info(
"slack_app_project_picker_pick_rejected",
reason=rejection,
slack_workspace_id=slack_team_id,
slack_user_id=clicker_slack_user_id,
)
if integration is not None:
capture_slack_event(
integration,
"slack app project picker rejected",
slack_user_id=clicker_slack_user_id,
posthog_user=posthog_user,
reason=rejection,
)
inbox_interactivity.post_response_url(
response_url, {"replace_original": True, "text": project_picker.PICK_REJECTED_MESSAGE}
)
return HttpResponse(status=200)
# The context is single use, so a second click finds none and starts nothing.
cache.delete(_picker_context_cache_key(context_token))
SlackSettings.objects.update_or_create(
slack_workspace_id=slack_team_id,
slack_user_id=clicker_slack_user_id,
defaults={"default_integration_id": integration.id},
)
# The mention never reached the workflow, so its event id is still unused.
_dispatch_mention_to_target(
event,
integration,
slack_team_id,
context.get("event_id"),
posthog_user=posthog_user,
untagged_followup_mapping=None,
is_ext_shared_channel=bool(context.get("is_ext_shared_channel")),
)
inbox_interactivity.post_response_url(
response_url,
{
"replace_original": True,
"text": project_picker.project_picked_message(integration, home_tab_url=app_home_url(integration)),
},
)
capture_slack_event(
integration,
"slack app project picker picked",
slack_user_id=clicker_slack_user_id,
posthog_user=posthog_user,
candidate_count=len(context.get("candidate_integration_ids") or []),
seconds_to_pick=int(time.time()) - int(context.get("created_at") or time.time()),
)
return HttpResponse(status=200)
def _post_user_resolution_failure_reply(
*,
probe: WorkspaceIntegration,
channel: str | None,
slack_user_id: str | None,
thread_ts: str | None,
failure_reason: UserResolutionFailure | None,
slack_email: str | None,
ephemeral_only: bool = False,
mention_is_threaded: bool = True,
) -> bool:
"""Tell a Slack user when we can't route their mention to a PostHog project.
Posts in-thread (with the established ephemeral fallback in
``_post_slack_user_feedback``) so the message lands in the place the
mention happened. ``failure_reason`` is mapped to the user-facing text by
``user_resolution_failure_reply``; ``slack_email`` is woven in when known
so the user sees which address PostHog tried to match.
``ephemeral_only`` restricts the reply to a message only the mentioner sees and
drops the invite button, for channels where a channel-visible post would expose
the integration (and the user's email) to people outside the org. The mentioner
already knows the app is there, having just typed its handle.
``mention_is_threaded`` says whether the mention was itself a thread reply, which
decides the surface the ephemeral is anchored to.
Returns whether feedback actually reached Slack, so callers can record whether the
user was left with an explanation or with silence.
"""
if not channel or not thread_ts or not slack_user_id:
return False
linking_available = is_slack_app_oauth_enabled(probe)
text = user_resolution_failure_reply(
failure_reason,
slack_email=slack_email,
linking_available=linking_available,
home_tab_url=app_home_url(probe) if linking_available else None,
)
if text is None:
return False
slack_client = SlackIntegration(probe)
if ephemeral_only:
return _post_slack_user_ephemeral(
slack_client, channel, slack_user_id, thread_ts if mention_is_threaded else None, text
)
# The text reply lands in the thread so the rest of the channel knows why
# the bot stayed silent. The invite button is a separate ephemeral, visible
# only to the affected user — both messages have distinct audiences and
# neither is redundant. Only `user_not_found` is link-recoverable;
# `no_team_access` means the user *is* known but lacks project access.
posted = _post_slack_user_feedback(
slack_client, channel, slack_user_id, thread_ts, text, prefer_thread_message=True
)
if failure_reason == "user_not_found" and linking_available:
invite_url = build_invite_url(
slack_user_id=slack_user_id,
slack_team_id=probe.integration_id,
posthog_team_id=probe.team_id,
channel=channel,
thread_ts=thread_ts,
)
post_link_invite_message(
slack_client=slack_client.client,
channel=channel,
slack_user_id=slack_user_id,
thread_ts=thread_ts,
slack_email=slack_email,
invite_url=invite_url,
)
return posted
def _start_posthog_code_workflow(
workflow_cls: Any,
workflow_inputs: Any,
*,
id_prefix: str,
slack_team_id: str,
event: dict,
event_id: str | None,
workflow_id: str | None = None,
start_signal: str | None = None,
start_signal_args: list[Any] | None = None,
) -> None:
"""Start a Slack-app workflow, optionally as a signal-with-start.
With ``start_signal`` set the operation is atomic on the server: a running
execution gets the signal, a finished (or never-started) one is started
with the signal as its first event — how the queue workflow guarantees a
message lands exactly once in its conversation's queue.
"""
if workflow_id is None:
fallback = event_id if event_id else f"{event.get('channel', '')}:{event.get('ts', '')}"
workflow_id = f"{id_prefix}-{slack_team_id}:{fallback}"
client = sync_connect()
asyncio.run(
client.start_workflow(
workflow_cls.run,
workflow_inputs,
id=workflow_id,
task_queue=settings.TASKS_TASK_QUEUE,
id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
# None / [] match the SDK defaults, so a plain start stays a plain start.
start_signal=start_signal,
start_signal_args=start_signal_args or [],
)
)
_ASSISTANT_CONTEXT_TTL_SECONDS = 60 * 60
_ASSISTANT_SUGGESTED_PROMPTS = [
{"title": "Fix a bug", "message": "Open a PR to fix a bug in my connected repo"},
{"title": "Investigate an issue", "message": "Investigate why one of my insights is slow"},
{"title": "Work an inbox item", "message": "Pick up a signals inbox item that needs a code fix"},
]
_ASSISTANT_UNAVAILABLE = (
"I can only help PostHog org members whose project has a connected repo. Make sure your Slack "
"email matches your PostHog account and that a repo is connected, then try again."
)
@frozen
class AssistantEventFields:
slack_user_id: str
dm_channel_id: str | None
thread_ts: str | None
viewed_channel_id: str | None
def _assistant_event_fields(event: dict) -> AssistantEventFields:
"""Extract the assistant-surface fields for assistant events.
For `message` events the fields live at the top level; for `assistant_thread_*` events
they live under `assistant_thread` (with the viewed channel under `context`).
"""
if event.get("type") == "message":
ts = event.get("thread_ts") or event.get("ts")
return AssistantEventFields(
slack_user_id=str(event.get("user") or ""),
dm_channel_id=event.get("channel") if isinstance(event.get("channel"), str) else None,
thread_ts=ts if isinstance(ts, str) else None,
viewed_channel_id=None,
)
thread = event.get("assistant_thread") or {}
ctx = thread.get("context") or {}
return AssistantEventFields(
slack_user_id=str(thread.get("user_id") or ""),
dm_channel_id=thread.get("channel_id") if isinstance(thread.get("channel_id"), str) else None,
thread_ts=thread.get("thread_ts") if isinstance(thread.get("thread_ts"), str) else None,
viewed_channel_id=ctx.get("channel_id") if isinstance(ctx.get("channel_id"), str) else None,
)
def _assistant_context_cache_key(integration_id: int, channel_id: str, thread_ts: str) -> str:
return f"slack_assistant_ctx:{integration_id}:{channel_id}:{thread_ts}"
def _store_assistant_channel_context(
integration_id: int, channel_id: str, thread_ts: str, viewed_channel_id: str | None
) -> None:
if viewed_channel_id:
cache.set(
_assistant_context_cache_key(integration_id, channel_id, thread_ts),
viewed_channel_id,
timeout=_ASSISTANT_CONTEXT_TTL_SECONDS,
)
def _get_assistant_channel_context(integration_id: int, channel_id: str, thread_ts: str) -> str | None:
value = cache.get(_assistant_context_cache_key(integration_id, channel_id, thread_ts))
return value if isinstance(value, str) else None
def _handle_assistant_thread_started(slack: SlackIntegration, channel_id: str, thread_ts: str) -> str:
"""Greet the user and offer suggested prompts when they open the agent container."""
try:
slack.client.assistant_threads_setSuggestedPrompts(
channel_id=channel_id,
thread_ts=thread_ts,
title="What can I help you ship?",
prompts=_ASSISTANT_SUGGESTED_PROMPTS,
)
# Slack's own assistant container thread, not a reply to a user message that can be deleted.
slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, text=build_assistant_pane_welcome())
except Exception:
logger.warning("assistant_thread_started_failed", exc_info=True)
return ROUTE_HANDLED_LOCALLY
def _post_assistant_unavailable(slack: SlackIntegration, channel_id: str, thread_ts: str) -> None:
try:
# Slack's own assistant container thread, not a reply to a user message that can be deleted.
slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, text=_ASSISTANT_UNAVAILABLE)
except Exception:
logger.warning("assistant_unavailable_post_failed", exc_info=True)
def _handle_assistant_dm_message(
event: dict,
integration: WorkspaceIntegration,
slack_team_id: str,
event_id: str | None,
channel_id: str,
thread_ts: str,
*,
posthog_user: User,
) -> str:
slack = SlackIntegration(integration)
missing = slack.missing_scopes(ASSISTANT_REQUIRED_SCOPES)
if missing:
_notify_missing_slack_scopes(slack, event, missing)
return ROUTE_HANDLED_LOCALLY
# Carry the channel the user was viewing (from assistant_thread_context_changed) so the agent
# can ground a "look into this" DM in that channel's context.
viewed = _get_assistant_channel_context(integration.id, channel_id, thread_ts)
agent_event = {**event, "assistant_viewed_channel_id": viewed} if viewed else event
# A fork parks the thread it came from and then asks what the user wants to know.
# This is that answer: it reads as an ordinary DM, so the pointer is the only thing
# that says otherwise. Consumed once — the run it starts writes a thread mapping,
# and every later message is a follow-up against that.
pending = get_pending_fork(integration.id, channel_id, thread_ts)
fork_kwargs: dict[str, Any] = {}
if pending:
clear_pending_fork(integration.id, channel_id, thread_ts)
fork_kwargs = {
"is_ext_shared_channel": pending.is_ext_shared,
"fork_source_channel": pending.source_channel,
"fork_source_thread_ts": pending.source_thread_ts,
"fork_source_message_ts": pending.source_message_ts,
"fork_source_task_id": pending.task_id,
}
return _start_mention_workflow(
agent_event, integration, slack_team_id, event_id, posthog_user=posthog_user, **fork_kwargs
)
def _route_assistant_event(
request: HttpRequest,
event: dict,
slack_team_id: str,
event_id: str | None,
*,
proxied: bool,
incoming_host: str,
other_domain: str,
can_defer: bool,
) -> str:
"""Route DM / agent-container events through the same region + project resolution as mentions."""
event_type = event.get("type")
fields = _assistant_event_fields(event)
# Only first-party human DMs proceed — ignore channel messages, bot echoes, and edits.
if event_type == "message" and (
event.get("channel_type") != "im"
or event.get("bot_id")
or event.get("subtype")
or not str(event.get("text") or "").strip()
):
return ROUTE_HANDLED_LOCALLY
if not (fields.slack_user_id and fields.dm_channel_id and fields.thread_ts):
return ROUTE_HANDLED_LOCALLY
result = load_integrations(
slack_team_id=slack_team_id,
kinds=[SLACK_INTEGRATION_KIND],
slack_user_id=fields.slack_user_id,
user=None,
channel=fields.dm_channel_id,
thread_ts=fields.thread_ts,
)
region_route = resolve_region_or_terminal_route(
request,
slack_team_id,
candidates_present=bool(result.candidates),
kinds=[SLACK_INTEGRATION_KIND],
proxied=proxied,
other_domain=other_domain,
incoming_host=incoming_host,
can_defer=can_defer,
channel=fields.dm_channel_id,
thread_ts=fields.thread_ts if event.get("thread_ts") else None,
local_thread=result.source == "thread",
)
if region_route is not None:
return region_route
probe = (
result.integration
if result.integration is not None and result.integration in result.candidates
else result.candidates[0]
)
# Share the mention path's user resolution + access filter, so the DM only ever sees and runs
# against projects the resolved PostHog user can actually access (no cross-org metadata leak).
resolution = resolve_user_for_workspace(
workspace_result=result,
slack_team_id=slack_team_id,
slack_user_id=fields.slack_user_id,
event_id=event_id,
)
if resolution.user is None:
# The Slack user isn't a resolvable org member — tell them why (DMs only).
if event_type == "message":
_post_assistant_unavailable(SlackIntegration(probe), fields.dm_channel_id, fields.thread_ts)
return ROUTE_HANDLED_LOCALLY
posthog_user = resolution.user
if event_type == "assistant_thread_started":
capture_slack_event(
probe, "slack app assistant thread started", slack_user_id=fields.slack_user_id, posthog_user=posthog_user
)
return _handle_assistant_thread_started(SlackIntegration(probe), fields.dm_channel_id, fields.thread_ts)
if event_type == "assistant_thread_context_changed":
_store_assistant_channel_context(probe.id, fields.dm_channel_id, fields.thread_ts, fields.viewed_channel_id)
return ROUTE_HANDLED_LOCALLY
# message.im — run the agent against the user's accessible default project, else ask them to pick.
accessible = resolution.candidates
mention_target = resolution.integration or (accessible[0] if len(accessible) == 1 else None)
if mention_target is None:
_post_pick_a_project_hint(SlackIntegration(accessible[0]), accessible, event)
return ROUTE_HANDLED_LOCALLY
return _handle_assistant_dm_message(
event,
mention_target,
slack_team_id,
event_id,
fields.dm_channel_id,
fields.thread_ts,
posthog_user=posthog_user,
)
def _route_app_home_opened(
request: HttpRequest,
event: dict,
slack_team_id: str,
event_id: str | None,
*,
proxied: bool,
incoming_host: str,
other_domain: str,
can_defer: bool,
) -> str:
"""Publish the Home tab from the region that owns the workspace's integration.
Slack delivers every event to a single Request URL, so the receiving region is
not necessarily the one holding the row the view renders against. Without this
gate the publish is silently skipped for every workspace owned by the other
region.
"""
slack_user_id = str(event.get("user") or "")
if not slack_user_id:
return ROUTE_HANDLED_LOCALLY
result = load_integrations(
slack_team_id=slack_team_id,
kinds=[SLACK_INTEGRATION_KIND],
slack_user_id=slack_user_id,
)
region_route = resolve_region_or_terminal_route(
request,
slack_team_id,
candidates_present=bool(result.candidates),
kinds=[SLACK_INTEGRATION_KIND],
proxied=proxied,
other_domain=other_domain,
incoming_host=incoming_host,
can_defer=can_defer,
)
if region_route is not None:
return region_route
integration = result.resolved_or_first()
if integration is None:
return ROUTE_NO_INTEGRATION
try:
_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
def _route_reaction_added(
request: HttpRequest,
event: dict,
slack_team_id: str,
*,
proxied: bool,
other_domain: str,
) -> str:
"""Turn a thumbs reaction on an agent reply into turn feedback, in the owning region.
The event names only a channel and a message ts, so which region owns the run is not
known until the handler reads the message back and finds the reply's own integration
id. The gate here is therefore two-step: no local integration for the workspace defers
the whole event, and a fetched integration id belonging to the other region defers it
after the fetch. The US-precedence rule for dual-owned workspaces does not apply,
because the embedded integration id is definitive.
"""
# Everything up to the workspace lookup is free, and most reactions fail it: only a
# thumb on a message is a rating candidate.
item = event.get("item") or {}
channel = item.get("channel")
message_ts = item.get("ts")
if turn_feedback.reaction_sentiment(event.get("reaction")) is None or item.get("type") != "message":
return ROUTE_HANDLED_LOCALLY
# The reacted message's author rides on the event, and the bot's user id is the same
# for every install of the workspace, so a warm workspace cache rejects a thumb on a
# human message here, before the first database query. A miss falls through: the
# handler re-checks against the integration-scoped lookup, which also warms this cache.
workspace_bot_user_id = get_cached_workspace_bot_user_id(slack_team_id)
if workspace_bot_user_id is not None and event.get("item_user") != workspace_bot_user_id:
return ROUTE_HANDLED_LOCALLY
# Same candidate loading as the mention pipeline: broken-token installs are filtered
# out (with none left the event defers to the other region, whose healthy install can
# still serve a rating this region cannot), and the resolver ladder picks the install
# the same way a mention would. A reaction carries no thread_ts, so the message ts
# stands in; it only matches a thread mapping when the reacted message opened the
# thread, and the resolver falls through to the defaults otherwise.
workspace_result = load_integrations(
slack_team_id=slack_team_id,
kinds=[SLACK_INTEGRATION_KIND],
slack_user_id=str(event.get("user") or ""),
channel=channel if isinstance(channel, str) else None,
thread_ts=message_ts if isinstance(message_ts, str) else None,
)
workspace_integration = workspace_result.resolved_or_first()
if workspace_integration is None:
return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
outcome = turn_feedback.handle_reaction_added(event, slack_team_id, workspace_integration)
if outcome == turn_feedback.REACTION_NOT_LOCAL:
if not proxied and cross_region_routing_enabled():
return _proxy_event_and_return_route(request, other_domain)
logger.warning(
"slack_app_reaction_feedback_not_local",
slack_team_id=slack_team_id,
incoming_host=request.get_host(),
)
return ROUTE_HANDLED_LOCALLY
def _handle_app_uninstalled(request: HttpRequest, slack_team_id: str) -> str:
"""Drop the workspace's cached Slack profiles so a reinstall resolves users from
fresh ``users.info`` data instead of emails cached under the previous install.
Fanned out once to the other region (loop-guarded) since a dual-owned workspace
caches profiles on both sides.
"""
deleted = clear_workspace_profile_cache(slack_team_id)
logger.info("slack_app_uninstalled_profile_cache_cleared", slack_team_id=slack_team_id, rows_deleted=deleted)
# A workspace linked to several projects matches several rows, but the uninstall is
# one act: capture once per region so plain event counts stay honest, with
# `linked_project_count` carrying how many links it severed.
linked_integrations = workspace_integrations(slack_team_id)
if linked_integrations:
capture_slack_event(
linked_integrations[0],
"slack app uninstalled",
was_proxied=was_proxied(request),
linked_project_count=len(linked_integrations),
)
if not was_proxied(request) and cross_region_routing_enabled():
_proxy_event_to_region(request, other_region_domain(request.get_host()))
return ROUTE_HANDLED_LOCALLY
def _route_untagged_question(
request: HttpRequest,
event: dict[str, Any],
slack_team_id: str,
event_id: str | None,
*,
proxied: bool,
incoming_host: str,
other_domain: str,
can_defer: bool,
is_ext_shared_channel: bool,
) -> str:
"""Start the classifier workflow for a top-level channel post nobody tagged the app in.
Every drop here is silent: nobody asked PostHog anything, so nobody waits for an answer.
An author without a PostHog account is a normal drop, not a failure.
Externally shared channels are out, because people outside the organization would see the reply.
"""
if is_ext_shared_channel or not is_untagged_question_candidate(event):
return ROUTE_HANDLED_LOCALLY
slack_user_id = str(event.get("user") or "")
channel = event.get("channel") if isinstance(event.get("channel"), str) else None
workspace_result = load_integrations(
slack_team_id=slack_team_id,
kinds=[SLACK_INTEGRATION_KIND],
slack_user_id=slack_user_id,
channel=channel,
)
# Without a local connection no mirror went out, so the full event can cross, but only to a
# region that confirms it holds the workspace. The probe answer is cached per workspace.
if not workspace_result.candidates:
if proxied or not cross_region_routing_enabled():
return ROUTE_HANDLED_LOCALLY
claimed = does_other_region_claim_workspace(
slack_team_id=slack_team_id, kinds=[SLACK_INTEGRATION_KIND], incoming_host=incoming_host
)
if claimed is not True:
return ROUTE_HANDLED_LOCALLY
return _proxy_event_and_return_route(request, other_domain)
# The same US precedence as mentions, so an author whose account is only in US still gets an
# answer when EU receives the post. This region already emitted the post and queued a mirror,
# so the forwarded copy tells the receiver to skip its emit.
if _us_should_handle_instead(slack_team_id, [SLACK_INTEGRATION_KIND], can_defer, incoming_host):
return _proxy_event_and_return_route(request, other_domain, {ALREADY_EMITTED_HEADER: "1"})
# One indexed read, ahead of user resolution, which can call Slack's users.info for every author.
if resolve_untagged_question_mode(slack_team_id, slack_user_id) == UntaggedFollowupMode.NEVER:
return ROUTE_HANDLED_LOCALLY
resolution = resolve_user_for_workspace(
workspace_result=workspace_result,
slack_team_id=slack_team_id,
slack_user_id=slack_user_id,
event_id=event_id,
)
posthog_user = resolution.user
if posthog_user is None:
return ROUTE_HANDLED_LOCALLY
candidates = resolution.candidates
# No picker: asking which project a question nobody addressed to us belongs to is noise.
target = resolution.integration or (candidates[0] if len(candidates) == 1 else None)
if target is None or SlackIntegration(target).missing_scopes(REQUIRED_SLACK_SCOPES):
return ROUTE_HANDLED_LOCALLY
# A post that tags the app also arrives as an ``app_mention``, and the mention pipeline answers that copy.
if _message_tags_bot(event, target):
return ROUTE_HANDLED_LOCALLY
logger.info(
"slack_app_untagged_question_dispatched",
slack_team_id=slack_team_id,
integration_id=target.id,
channel=channel,
message_ts=event.get("ts"),
)
return _start_mention_workflow(
event,
target,
slack_team_id,
event_id,
posthog_user=posthog_user,
untagged_question=True,
)
def _dispatch_mention_to_target(
event: dict,
mention_target: WorkspaceIntegration,
slack_team_id: str,
event_id: str | None,
*,
posthog_user: User,
untagged_followup_mapping: SlackThreadTaskMapping | None,
is_ext_shared_channel: bool,
awaited_request_reply: bool = False,
) -> str:
"""Run the gates that need a resolved project, then start the mention workflow."""
slack = SlackIntegration(mention_target)
missing = slack.missing_scopes(REQUIRED_SLACK_SCOPES)
if missing:
if untagged_followup_mapping is not None:
logger.info(
"slack_app_thread_message_missing_scopes",
slack_team_id=slack_team_id,
integration_id=mention_target.id,
)
replied = False
else:
replied = _notify_missing_slack_scopes(slack, event, missing)
_report_slack_mention_dropped(
event,
slack_team_id,
reason="missing_scopes",
replied=replied,
integration=mention_target,
posthog_user=posthog_user,
)
return ROUTE_HANDLED_LOCALLY
channel_id = event.get("channel") if isinstance(event.get("channel"), str) else None
if channel_id and is_ext_shared_channel and not _channel_is_approved(mention_target.integration_id, channel_id):
if untagged_followup_mapping is not None:
logger.info(
"slack_app_thread_message_channel_unapproved",
slack_team_id=slack_team_id,
channel=channel_id,
)
replied = False
else:
replied = _post_channel_approval_prompt(slack, mention_target, event)
_report_slack_mention_dropped(
event,
slack_team_id,
reason="channel_not_approved",
replied=replied,
integration=mention_target,
posthog_user=posthog_user,
)
return ROUTE_HANDLED_LOCALLY
# Last gate on the untagged path: a thread whose creator has follow-ups off
# never reaches the workflow. ``ask`` is decided there instead, once the
# classifier has judged the reply worth forwarding.
if untagged_followup_mapping is not None and _untagged_followups_switched_off(
event,
mention_target,
slack_team_id,
mapping=untagged_followup_mapping,
posthog_user=posthog_user,
):
return ROUTE_HANDLED_LOCALLY
if untagged_followup_mapping is not None:
_mark_message_handled(slack_team_id, event, "untagged_followup")
channel = event.get("channel")
thread_ts = event.get("thread_ts") or event.get("ts")
if awaited_request_reply and isinstance(channel, str) and isinstance(thread_ts, str):
bare_mention.clear_awaited_request(slack_team_id, channel, thread_ts)
_mark_message_handled(slack_team_id, event, "mention")
elif event.get("type") == "app_mention":
if bare_mention.is_bare_mention(event):
return _answer_bare_mention(event, mention_target, slack_team_id, posthog_user=posthog_user)
# An edit that adds the request to a bare mention starts the run here, so the
# thread must stop waiting for a reply that would otherwise start a second one.
if event.get("edited") and isinstance(channel, str) and isinstance(thread_ts, str):
bare_mention.clear_awaited_request(slack_team_id, channel, thread_ts)
return _start_mention_workflow(
event,
mention_target,
slack_team_id,
event_id,
posthog_user=posthog_user,
untagged_followup=untagged_followup_mapping is not None,
is_ext_shared_channel=is_ext_shared_channel,
awaited_request_reply=awaited_request_reply,
)
def route_posthog_code_event_to_relevant_region(
request: HttpRequest,
event: dict,
slack_team_id: str,
event_id: str | None = None,
*,
is_ext_shared_channel: bool = False,
) -> str:
event_type = event.get("type")
incoming_host = request.get_host()
proxied = was_proxied(request)
other_domain = other_region_domain(incoming_host)
# In local dev we run a single instance, so cross-region routing is meaningless: the only
# consumer is this process. Disable both the probe and the proxy hop and always handle
# locally.
can_defer_to_other_region = cross_region_routing_enabled() and not is_us_host(incoming_host) and not proxied
logger.info(
"slack_app_route_enter",
incoming_host=incoming_host,
is_us=is_us_host(incoming_host),
proxied=proxied,
other_domain=other_domain,
can_defer=can_defer_to_other_region,
event_type=event_type,
slack_team_id=slack_team_id,
event_id=event_id,
debug=settings.DEBUG,
us_domain=_us_region_domain(),
eu_domain=_eu_region_domain(),
)
if event_type == "app_uninstalled":
return _handle_app_uninstalled(request, slack_team_id)
if event_type == "reaction_added":
return _route_reaction_added(
request,
event,
slack_team_id,
proxied=proxied,
other_domain=other_domain,
)
# App Home tab: published per-user when they open the Home tab. The view is
# rendered against the workspace's integration row, which only the owning
# region holds, so this takes the same region gate as every other surface.
if event_type == "app_home_opened":
return _route_app_home_opened(
request,
event,
slack_team_id,
event_id,
proxied=proxied,
incoming_host=incoming_host,
other_domain=other_domain,
can_defer=can_defer_to_other_region,
)
# Assistant surface: DMs to the app and agent-container events resolve the DMing user and run
# against their project. A ``message`` is a DM iff ``channel_type == "im"`` — channel ``message``
# events (untagged thread follow-ups) and ``app_mention`` share the pipeline below instead.
if event_type in ("assistant_thread_started", "assistant_thread_context_changed") or (
event_type == "message" and event.get("channel_type") == "im"
):
return _route_assistant_event(
request,
event,
slack_team_id,
event_id,
proxied=proxied,
incoming_host=incoming_host,
other_domain=other_domain,
can_defer=can_defer_to_other_region,
)
if event_type in ("app_mention", "message"):
# Above every drop below, because a workflow trigger watches a whole channel: the top-level
# posts the follow-up pipeline discards are the ones it exists for. Emitting here rather
# than inside that pipeline keeps the two independent.
if event_type == "message":
# A mirror copy exists only to feed the receiving region's emit — the sender's pipeline
# already handles the event itself, so running the drops below would double-handle it.
if _is_emit_only_mirror(request):
emit_slack_message_event(
event,
slack_team_id,
event_id=event_id,
is_ext_shared_channel=is_ext_shared_channel,
)
return ROUTE_HANDLED_LOCALLY
should_try_other_region = request.headers.get(ALREADY_EMITTED_HEADER) != "1" and emit_slack_message_event(
event,
slack_team_id,
event_id=event_id,
is_ext_shared_channel=is_ext_shared_channel,
)
# The emit sees only this region's connections, and the drops below end a top-level post
# before the pipeline's region gate could forward it. For a channel trigger, every
# region holding a connection should run its workflows: with no local connection the
# whole event defers to the other region, and with one the event is handled here and a
# workspace connected over there as well gets an emit-only mirror.
if not proxied and cross_region_routing_enabled():
if should_try_other_region:
return _proxy_event_and_return_route(request, other_domain)
_mirror_message_event_to_other_region(
request,
event,
slack_team_id=slack_team_id,
incoming_host=incoming_host,
other_domain=other_domain,
)
if event_type == "app_mention":
ignore_reason = _app_mention_ignore_reason(event)
drop_context: dict[str, Any] = {}
if ignore_reason == "edit":
edit_ignore_cause = _edited_mention_ignore_cause(event, slack_team_id)
if edit_ignore_cause is None:
ignore_reason = None
logger.info(
"slack_app_edited_mention_accepted",
slack_team_id=slack_team_id,
channel=event.get("channel"),
message_ts=event.get("ts"),
)
else:
drop_context = {"edit_ignore_cause": edit_ignore_cause}
elif ignore_reason == "path_mention":
drop_context = _path_mention_drop_properties(event)
elif ignore_reason is None:
# Marked before the later gates, so that an edit of a refused mention does not
# repeat the explanation.
_mark_message_handled(slack_team_id, event, "mention")
if ignore_reason:
logger.info(
"slack_app_event_app_mention_ignored",
reason=ignore_reason,
slack_team_id=slack_team_id,
channel=event.get("channel"),
message_ts=event.get("ts"),
**drop_context,
)
_report_slack_mention_dropped(
event, slack_team_id, reason=f"ignored:{ignore_reason}", replied=False, **drop_context
)
return ROUTE_HANDLED_LOCALLY
else:
ignore_reason = _thread_message_ignore_reason(event)
if ignore_reason:
logger.info(
"slack_app_thread_message_ignored",
reason=ignore_reason,
slack_team_id=slack_team_id,
channel=event.get("channel"),
message_ts=event.get("ts"),
)
return ROUTE_HANDLED_LOCALLY
# Top-level channel posts dominate the wire volume, so they leave the shared pipeline
# here and face cheap gates before any DB hit.
if _is_top_level_channel_post(event):
return _route_untagged_question(
request,
event,
slack_team_id,
event_id,
proxied=proxied,
incoming_host=incoming_host,
other_domain=other_domain,
can_defer=can_defer_to_other_region,
is_ext_shared_channel=is_ext_shared_channel,
)
slack_user_id_str = str(event.get("user") or "")
channel_str = event.get("channel") if isinstance(event.get("channel"), str) else None
thread_ts_value = event.get("thread_ts") or event.get("ts")
thread_ts_str = thread_ts_value if isinstance(thread_ts_value, str) else None
# Whether the message is a reply inside a thread rather than a top-level channel
# post. Decides which surface an ephemeral has to be anchored to to be visible.
mention_is_threaded = isinstance(event.get("thread_ts"), str) and event.get("thread_ts") != event.get("ts")
# Region routing only needs candidate presence, not user resolution. We
# defer the Slack ``users.info`` hit and the ``OrganizationMembership``
# query until we know this region is handling the event so cross-region
# proxied events don't pay for work the receiving region will redo.
workspace_result = load_integrations(
slack_team_id=slack_team_id,
kinds=[SLACK_INTEGRATION_KIND],
slack_user_id=slack_user_id_str,
channel=channel_str,
thread_ts=thread_ts_str,
)
region_route = resolve_region_or_terminal_route(
request,
slack_team_id,
candidates_present=bool(workspace_result.candidates),
kinds=[SLACK_INTEGRATION_KIND],
proxied=proxied,
other_domain=other_domain,
incoming_host=incoming_host,
can_defer=can_defer_to_other_region,
channel=channel_str,
thread_ts=thread_ts_str if mention_is_threaded else None,
local_thread=workspace_result.source == "thread",
)
if region_route is not None:
# A mention that no region claims is the most confusing failure of all: the
# workspace still has the app installed in Slack but we hold no integration
# row, so nothing ever answers. Only `app_mention` is captured because
# `message` volume here is unbounded.
if region_route == ROUTE_NO_INTEGRATION and event_type == "app_mention":
_report_slack_mention_dropped(event, slack_team_id, reason="no_integration", replied=False)
return region_route
# A reply on a thread that mirrors a PostHog discussion becomes a comment, not agent work.
if event_type == "message":
try:
ingested = try_ingest_discussion_reply(
event, workspace_result.candidates, channel_str, thread_ts_str, slack_team_id
)
except Exception:
# Never let discussion ingest break the shared event handler — a 500 here would
# also lose the agent-followup routing, and Slack retries are dropped upstream.
logger.exception(
"slack_discussion_reply_ingest_failed", slack_team_id=slack_team_id, channel=channel_str
)
ingested = False
if ingested:
return ROUTE_HANDLED_LOCALLY
# Threads we don't own are dropped here so the rest of the pipeline
# only runs for actionable messages.
untagged_followup_mapping: SlackThreadTaskMapping | None = None
awaited_request_reply = False
if event_type == "message":
untagged_followup_mapping = _resolve_untagged_followup_mapping(
candidates=workspace_result.candidates,
channel=channel_str,
thread_ts=thread_ts_str,
)
if untagged_followup_mapping is None:
if not _awaits_request_from_author(event, slack_team_id, workspace_result.candidates[0]):
return ROUTE_HANDLED_LOCALLY
awaited_request_reply = True
# A tagged reply also arrives as its own ``app_mention`` event, which owns
# it. Letting this copy through would run the untagged-followup classifier
# (and the ``ask`` prompt) on a message that explicitly addressed the app.
if _message_tags_bot(
event,
untagged_followup_mapping.integration
if untagged_followup_mapping is not None
else workspace_result.candidates[0],
):
logger.info(
"slack_app_thread_message_ignored",
reason="tagged_reply",
slack_team_id=slack_team_id,
channel=channel_str,
message_ts=event.get("ts"),
)
return ROUTE_HANDLED_LOCALLY
elif mention_is_threaded:
awaited_request_reply = _awaits_request_from_author(event, slack_team_id, workspace_result.candidates[0])
# Both event types share the rest of the pipeline. Mention-only side
# effects (failure reply, scope notice, approval prompt, rules command,
# picker hint) are silent drops for untagged followups — the originating
# ``app_mention`` already cleared those gates.
resolution = resolve_user_for_workspace(
workspace_result=workspace_result,
slack_team_id=slack_team_id,
slack_user_id=slack_user_id_str,
event_id=event_id,
)
if resolution.user is None:
if untagged_followup_mapping is not None:
logger.info(
"slack_app_thread_message_unknown_user",
slack_team_id=slack_team_id,
channel=channel_str,
thread_ts=thread_ts_str,
slack_user_id=slack_user_id_str,
)
_report_slack_mention_dropped(
event,
slack_team_id,
reason=f"user_unresolved:{resolution.failure_reason or 'unknown'}",
replied=False,
integration=untagged_followup_mapping.integration,
**unresolved_user_properties(resolution, untagged_followup_mapping.integration),
)
return ROUTE_HANDLED_LOCALLY
# Keep the failure reply out of the channel in an unapproved
# externally-shared channel: the channel hasn't opted in yet, so a
# channel-visible "Sorry, I couldn't find <email>" post would expose the
# integration's existence to non-org members. The mentioner still gets
# the reason, as an ephemeral only they can see. Still capture the
# mention analytics-side so the unknown-user funnel keeps reporting (it
# ran on every mention before this PR moved resolution up).
probe = workspace_result.candidates[0]
# ``no_team_access`` means the Slack user *did* map to a PostHog user, just
# one without access here. Reusing whoever mention-received attributed to
# keeps the two halves of the funnel joinable on the same actor.
attributed_user = _report_slack_mention_received(event, probe, slack_team_id, posthog_user=None)
channel_id = event.get("channel") if isinstance(event.get("channel"), str) else None
ephemeral_only = bool(
is_ext_shared_channel and channel_id and not _channel_is_approved(slack_team_id, channel_id)
)
replied = _post_user_resolution_failure_reply(
probe=probe,
channel=channel_str,
slack_user_id=slack_user_id_str,
thread_ts=thread_ts_str,
failure_reason=resolution.failure_reason,
slack_email=resolution.slack_email,
ephemeral_only=ephemeral_only,
mention_is_threaded=mention_is_threaded,
)
_report_slack_mention_dropped(
event,
slack_team_id,
reason=f"user_unresolved:{resolution.failure_reason or 'unknown'}",
replied=replied,
integration=probe,
posthog_user=attributed_user,
**unresolved_user_properties(resolution, probe),
)
_start_onboarding_on_mention(event, slack_team_id, workspace_result)
return ROUTE_HANDLED_LOCALLY
posthog_user = resolution.user
candidates = resolution.candidates
target = resolution.integration
# Recognised but not run: unrecognised, ``@PostHog project 452770`` becomes a task about
# its own syntax. Only a message addressed to the app can be a command.
if untagged_followup_mapping is None:
command_probe = resolution.resolved_or_first()
if command_probe is not None and _hand_off_command(
event,
workspace_result.candidates,
slack_team_id,
probe=command_probe,
posthog_user=posthog_user,
is_ext_shared_channel=is_ext_shared_channel,
):
return ROUTE_HANDLED_LOCALLY
mention_command = parse_rules_command(event.get("text", ""))
if mention_command is not None:
# The redirect reply is static, but its analytics event attributes to whichever
# install it is sent through, so use the resolution's stable tie-break rather than
# the head of ``candidates`` — that order reshuffles as auth verdicts expire.
redirect_probe = resolution.resolved_or_first()
if redirect_probe is not None:
return _redirect_mention_command(
mention_command, event, redirect_probe, slack_team_id, posthog_user=posthog_user
)
# A tagged-thread ``message`` is bound to its mapping's integration —
# the mapping was the user's last explicit choice in this thread, so no
# picker hint applies. The user must still have access to the bound
# integration's team though: ``resolution.candidates`` is already
# filtered by access, so requiring the mapping integration to be in it
# closes the gap where the message author belongs to a different org
# connected to the same workspace than the thread owner did.
mention_target = target or (candidates[0] if len(candidates) == 1 else None)
if untagged_followup_mapping is not None:
if untagged_followup_mapping.integration_id not in {c.id for c in candidates}:
logger.info(
"slack_app_thread_message_user_no_access_to_mapping_team",
slack_team_id=slack_team_id,
channel=channel_str,
thread_ts=thread_ts_str,
user_id=posthog_user.id,
mapping_integration_id=untagged_followup_mapping.integration_id,
)
_report_slack_mention_dropped(
event,
slack_team_id,
reason="no_access_to_thread_team",
replied=False,
integration=untagged_followup_mapping.integration,
posthog_user=posthog_user,
)
return ROUTE_HANDLED_LOCALLY
mention_target = untagged_followup_mapping.integration
elif mention_target is None:
picker_shown = _post_project_picker(
candidates,
event,
event_id,
is_ext_shared_channel=is_ext_shared_channel,
mention_is_threaded=mention_is_threaded,
)
replied = picker_shown or _post_pick_a_project_hint(SlackIntegration(candidates[0]), candidates, event)
# No integration is passed on purpose: this drop exists precisely because no
# project was picked, and candidate order has nothing to do with what the
# user meant. Attributing it to candidates[0] would pin workspace-level
# ambiguity onto one arbitrary project (possibly in a different org).
_report_slack_mention_dropped(
event,
slack_team_id,
reason="multiple_projects",
replied=replied,
posthog_user=posthog_user,
candidate_count=len(candidates),
picker_shown=picker_shown,
)
_start_onboarding_on_mention(event, slack_team_id, workspace_result)
return ROUTE_HANDLED_LOCALLY
route = _dispatch_mention_to_target(
event,
mention_target,
slack_team_id,
event_id,
posthog_user=posthog_user,
untagged_followup_mapping=untagged_followup_mapping,
is_ext_shared_channel=is_ext_shared_channel,
awaited_request_reply=awaited_request_reply,
)
_start_onboarding_on_mention(event, slack_team_id, workspace_result)
return route
if event_type == "member_joined_channel":
return _route_member_joined_channel(
request,
event,
slack_team_id,
proxied=proxied,
other_domain=other_domain,
can_defer_to_other_region=can_defer_to_other_region,
incoming_host=incoming_host,
is_ext_shared_channel=is_ext_shared_channel,
)
if event_type == "team_join":
return _route_team_join(
request,
event,
slack_team_id,
proxied=proxied,
other_domain=other_domain,
can_defer_to_other_region=can_defer_to_other_region,
incoming_host=incoming_host,
)
# Never unfurl into a Slack Connect channel, even an approved one. A card or its chart shows project
# data to people outside the organization, and a pasted link is not a request for it. Every region
# drops the event the same way, so this runs before any lookup or cross-region forward.
if event_type == "link_shared" and is_ext_shared_channel:
logger.info("slack_link_unfurl_external_channel", slack_team_id=slack_team_id, channel=event.get("channel"))
return ROUTE_HANDLED_LOCALLY
# The link's own host decides the region, from URL parsing alone — ahead of ``load_integrations``,
# whose query and Slack auth check would be thrown away on the forward. A workspace connected in
# both regions otherwise resolves a `us.` link's `/project/:id` against this region's project of
# the same number, which holds someone else's data or nothing at all.
link_region = _link_shared_url_region(event) if event_type == "link_shared" else None
if (
link_region is not None
and link_region != get_instance_region()
and not proxied
and cross_region_routing_enabled()
):
logger.info(
"slack_app_link_unfurl_region_forward",
slack_team_id=slack_team_id,
event_id=event_id,
link_region=link_region,
incoming_host=incoming_host,
)
return _proxy_event_and_return_route(request, other_domain)
# link_shared (unfurl) works with either integration kind.
link_result = load_integrations(slack_team_id=slack_team_id, kinds=list(SLACK_INTEGRATION_KINDS))
if event_type == "link_shared":
link_target = _link_shared_target(event, link_result.candidates, slack_team_id=slack_team_id)
logger.info(
"slack_app_link_unfurl_target_selected",
slack_team_id=slack_team_id,
event_id=event_id,
source=link_target.source,
link_region=link_region,
candidate_count=len(link_result.candidates),
integration_id=link_target.integration.id if link_target.integration else None,
team_id=link_target.integration.team_id if link_target.integration else None,
)
else:
# Every other event type reaching this fallthrough (``app_uninstalled``) is workspace-wide,
# so any install for the workspace serves it.
link_target = LinkSharedTarget(link_result.resolved_or_first(), "workspace")
local_match = link_target.integration
if local_match:
# A link whose host names this region belongs here, whatever the other region claims about
# the workspace. Links with no region in the host say nothing about ownership, so those fall
# back to the workspace-level precedence every other surface uses.
if link_region != get_instance_region() and _us_should_handle_instead(
slack_team_id,
list(SLACK_INTEGRATION_KINDS),
can_defer_to_other_region,
incoming_host,
):
return _proxy_event_and_return_route(request, other_domain)
if event_type == "link_shared":
handle_posthog_link_unfurl(event, local_match)
return ROUTE_HANDLED_LOCALLY
return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
def _us_should_handle_instead(slack_team_id: str, kinds: list[str], can_defer: bool, incoming_host: str) -> bool:
"""US-precedence guard. EU yields to US when both claim a workspace.
Skipped when we're already US (we win) or when we were proxied to (the other region already
deferred). When the probe transport itself fails (None), bias toward proxying to US: during
a region cutover both regions hold a row for the same workspace and US is the rightful owner,
so a single probe flake should not pin the event to EU. If US in fact has no row, it sees the
proxied event with the loop header set and drops it — the same outcome the caller would have
reached by handling locally.
"""
if not can_defer:
return False
claimed = does_other_region_claim_workspace(slack_team_id=slack_team_id, kinds=kinds, incoming_host=incoming_host)
decision = True if claimed is None else claimed
logger.info(
"slack_app_route_us_probe_result",
slack_team_id=slack_team_id,
claimed=claimed,
decision=decision,
optimistic_proxy=claimed is None,
)
return decision
def _route_to_other_region_or_drop(
request: HttpRequest, slack_team_id: str, *, proxied: bool, other_domain: str
) -> str:
"""No local match: either forward to the other region or drop if we are the second hop.
Single-region deployments (local dev, hosted dev, E2E, self-hosted) have no other region
to forward to, so we just record the miss and stop.
"""
if proxied or not cross_region_routing_enabled():
logger.warning(
"slack_app_no_integration_found",
slack_team_id=slack_team_id,
incoming_host=request.get_host(),
)
return ROUTE_NO_INTEGRATION
return _proxy_event_and_return_route(request, other_domain)
def resolve_region_or_terminal_route(
request: HttpRequest,
slack_team_id: str,
*,
candidates_present: bool,
kinds: list[str],
proxied: bool,
other_domain: str,
incoming_host: str,
can_defer: bool,
channel: str | None = None,
thread_ts: str | None = None,
local_thread: bool = False,
) -> str | None:
"""Shared region gate for every coding-agent surface (mentions, channel followups, DMs).
Returns a terminal route when the event leaves this region — forwarded/dropped because no
local integration claims the workspace, or proxied to US under the US-precedence rule — else
``None`` to signal the caller should keep handling the event locally.
"""
if local_thread:
return None
if channel and thread_ts and not proxied and cross_region_routing_enabled():
thread_claimed = does_other_region_claim_workspace(
slack_team_id=slack_team_id,
kinds=kinds,
incoming_host=incoming_host,
channel=channel,
thread_ts=thread_ts,
)
if thread_claimed is True:
return _proxy_event_and_return_route(request, other_domain)
if thread_claimed is None:
# Unknown ownership must not send report context to an unrelated project.
return ROUTE_PROXY_FAILED
if not candidates_present:
return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
if _us_should_handle_instead(slack_team_id, kinds, can_defer, incoming_host):
return _proxy_event_and_return_route(request, other_domain)
return None
def _redirect_mention_command(
command: RulesCommand,
event: dict[str, Any],
probe: WorkspaceIntegration,
slack_team_id: str,
*,
posthog_user: User,
) -> str:
"""Point a mention that reads as a command at the slash command, without running it.
``probe`` needs no project resolved first, because the reply is static text. It is still the
resolution's stable pick, so the analytics event lands on the same project every time.
The reply goes out ephemerally with no fallback: a channel-visible one would announce the
integration in an externally-shared channel that has not approved it yet.
"""
channel = event.get("channel")
slack_user_id = event.get("user")
if not isinstance(channel, str) or not isinstance(slack_user_id, str):
return ROUTE_HANDLED_LOCALLY
logger.info(
"slack_app_mention_command_redirected",
slack_team_id=slack_team_id,
channel=channel,
action=command.action,
)
capture_slack_event(
probe,
"slack app command used",
slack_user_id=slack_user_id,
posthog_user=posthog_user,
action=command.action,
source="mention",
)
# Slack sets ``thread_ts`` to ``ts`` on a thread-opening post as well, and an ephemeral
# anchored there is invisible from the channel view the mentioner is looking at.
thread_ts = event.get("thread_ts")
_post_slack_user_ephemeral(
SlackIntegration(probe),
channel,
slack_user_id,
thread_ts if isinstance(thread_ts, str) and not _is_top_level_channel_post(event) else None,
mention_command_redirect(command),
)
return ROUTE_HANDLED_LOCALLY
def _connected_organization_ids(candidates: Sequence[WorkspaceIntegration]) -> tuple[str, ...]:
team_ids = {candidate.team_id for candidate in candidates}
organization_ids = Team.objects.filter(id__in=team_ids).values_list("organization_id", flat=True).distinct()
return tuple(str(organization_id) for organization_id in organization_ids)
def _hand_off_command(
event: dict[str, Any],
candidates: Sequence[WorkspaceIntegration],
slack_team_id: str,
*,
probe: WorkspaceIntegration,
posthog_user: User,
is_ext_shared_channel: bool,
) -> bool:
"""Hand a mention such as ``@PostHog review --deep <PR URL>`` to the commands product.
Commands decides whether it is a command, runs it without the agent and answers in the thread.
False leaves the mention to the agent: free text, a mistyped command, or an organization outside
the commands rollout.
"""
text = event.get("text")
channel = event.get("channel")
slack_user_id = event.get("user")
message_ts = event.get("ts")
if event.get("type") != "app_mention" or not (
isinstance(text, str)
and isinstance(channel, str)
and isinstance(slack_user_id, str)
and isinstance(message_ts, str)
):
return False
# Nearly every mention is free text for the agent, and this keeps their path free of queries.
if not commands_api.may_hold_command(text):
return False
# The answer is visible in the thread, which would announce PostHog in a shared channel that has
# not approved it yet. The agent path has the approval gate for that.
if is_ext_shared_channel and not _channel_is_approved(slack_team_id, channel):
return False
# A command is addressed to the app: a message that opens with someone else's mention is not.
bot_user_id = get_cached_bot_user_id(SlackIntegration(probe), probe)
bot_mention = f"<@{bot_user_id}>"
text = text.strip()
if bot_user_id is None or not text.startswith(bot_mention):
return False
thread_ts_value = event.get("thread_ts")
thread_ts = thread_ts_value if isinstance(thread_ts_value, str) else message_ts
# A broken command lookup must not cost the person their agent run. That includes the linked
# accounts, whose lookup the user resolver also survives by falling back to the email match.
try:
# The account the resolver picked comes first. Every other linked account joins, so the
# project the command runs in picks the account rather than the order of linking.
user_ids = (
posthog_user.id,
*linked_posthog_user_ids(slack_user_id=slack_user_id, slack_team_id=slack_team_id),
)
mention = commands_api.SlackMention(
text=decode_slack_entities(unwrap_slack_links(text.removeprefix(bot_mention).strip())),
slack_team_id=slack_team_id,
slack_user_id=slack_user_id,
channel=channel,
thread_ts=thread_ts,
message_ts=message_ts,
integration_id=probe.id,
integration_team_id=probe.team_id,
user_ids=tuple(dict.fromkeys(user_ids)),
organization_ids=_connected_organization_ids(candidates),
)
verb = commands_api.accept_slack_mention(mention)
except Exception:
logger.warning("slack_app_command_failed", slack_team_id=slack_team_id, exc_info=True)
return False
if verb is None:
return False
# The command is the request a bare mention in this thread waited for, so a later "thanks"
# must not start an agent run.
bare_mention.clear_awaited_request(slack_team_id, channel, thread_ts)
capture_slack_event(
probe,
"slack app command used",
slack_user_id=slack_user_id,
posthog_user=posthog_user,
action=f"command_{verb}",
source="mention",
)
return True
def _start_command_workflow(
event: dict,
integrations: Sequence[WorkspaceIntegration],
slack_team_id: str,
event_id: str | None,
*,
user_id: int | None,
command_prefix: str,
) -> str:
# ``user_id=None`` defers user resolution into the workflow — the slash entry
# point uses it to keep its ack under Slack's 3s budget.
_start_posthog_code_workflow(
PostHogCodeSlackMentionCommandWorkflow,
PostHogCodeSlackMentionCommandWorkflowInputs(
event=event,
integration_ids=[i.id for i in integrations],
slack_team_id=slack_team_id,
user_id=user_id,
command_prefix=command_prefix,
),
id_prefix="posthog-code-mention-command",
slack_team_id=slack_team_id,
event=event,
event_id=event_id,
)
return ROUTE_HANDLED_LOCALLY
def _count_session_thread_messages(
integration: WorkspaceIntegration, channel: str | None, thread_ts: str | None
) -> int | None:
"""Best-effort count of messages in a Slack thread (the session). None if unavailable.
Runs in the Slack webhook request path, so the client timeout is bounded: a slow or
rate-limited Slack response must not eat into Slack's retry window before we return.
"""
if not channel or not thread_ts:
return None
try:
client = SlackIntegration(integration).client
client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
response = client.conversations_replies(channel=channel, ts=thread_ts, limit=200)
return len(response.get("messages", []))
except Exception:
logger.warning(
"slack_app_mention_count_failed",
integration_id=integration.id,
channel=channel,
thread_ts=thread_ts,
exc_info=True,
)
return None
def _route_member_joined_channel(
request: HttpRequest,
event: dict[str, Any],
slack_team_id: str,
*,
proxied: bool,
other_domain: str,
can_defer_to_other_region: bool,
incoming_host: str,
is_ext_shared_channel: bool,
) -> str:
"""Welcome the @PostHog bot to a new channel exactly once.
Slack fires ``member_joined_channel`` for every user (including bot users)
added to a channel. We only act when the joining user is our own bot, and
we cache the first post per (workspace, channel) so retries and re-adds
don't double-post. Externally-shared channels are dropped before any DB
work — anyone outside the home workspace would see the welcome, and the
first @PostHog mention there will run the existing approval flow.
"""
joined_user = event.get("user") if isinstance(event.get("user"), str) else None
channel_id = event.get("channel") if isinstance(event.get("channel"), str) else None
if not joined_user or not channel_id:
return ROUTE_HANDLED_LOCALLY
# Drop ext-shared channels before touching the DB. Anyone outside the home
# workspace would see the welcome message, and the ``is_ext_shared_channel``
# flag lives on the event envelope so this costs nothing.
if is_ext_shared_channel:
return ROUTE_HANDLED_LOCALLY
workspace_result = load_integrations(slack_team_id=slack_team_id, kinds=[SLACK_INTEGRATION_KIND])
if not workspace_result.candidates:
return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
if _us_should_handle_instead(slack_team_id, [SLACK_INTEGRATION_KIND], can_defer_to_other_region, incoming_host):
return _proxy_event_and_return_route(request, other_domain)
integration = workspace_result.candidates[0]
slack = SlackIntegration(integration)
bot_user_id = get_cached_bot_user_id(slack, integration)
if bot_user_id is None or joined_user != bot_user_id:
# We only care about our own bot joining a channel. Every other join
# (humans, third-party bots) is ignored silently — Slack fires this
# event for every channel-membership change, so the volume is high.
return ROUTE_HANDLED_LOCALLY
# The onboarding flow has its own messaging for the inbox channel — skip the generic welcome here.
if inbox_channel.is_inbox_channel(integration, channel_id):
return ROUTE_HANDLED_LOCALLY
welcome_mode = resolve_channel_welcome_mode(slack_team_id)
inviter = event.get("inviter") if isinstance(event.get("inviter"), str) else None
# With no inviter on the event, there is nobody to show a private welcome to.
# Skip it rather than fall back to a post the whole channel sees.
if welcome_mode == ChannelWelcomeMode.OFF or (welcome_mode == ChannelWelcomeMode.INVITER and not inviter):
logger.info(
"slack_app_channel_onboarding_skipped_by_setting",
slack_team_id=slack_team_id,
channel_id=channel_id,
welcome_mode=welcome_mode.value,
)
return ROUTE_HANDLED_LOCALLY
if not _claim_channel_onboarding(slack_team_id, channel_id):
logger.info(
"slack_app_channel_onboarding_skipped_duplicate",
slack_team_id=slack_team_id,
channel_id=channel_id,
)
return ROUTE_HANDLED_LOCALLY
posted = _post_channel_onboarding_message(
slack,
integration,
channel_id,
only_to_user=inviter if welcome_mode == ChannelWelcomeMode.INVITER else None,
)
if not posted:
# Release the dedupe slot so the next delivery (retry or future re-add)
# gets another shot rather than being silently swallowed.
_release_channel_onboarding_claim(slack_team_id, channel_id)
return ROUTE_HANDLED_LOCALLY
def _channel_onboarding_cache_key(slack_team_id: str, channel_id: str) -> str:
return f"slack_app:channel_onboarded:v1:{slack_team_id}:{channel_id}"
def _claim_once(cache_key: str) -> bool:
"""Atomically claim a one-shot slot, e.g. the right to send an onboarding message.
``cache.add`` is the Django-blessed idempotency primitive: it returns True
only if the key didn't already exist, so concurrent webhook deliveries
(Slack retries, two-region race during cutover) can't double-post. Callers
release the slot with ``cache.delete`` when the claimed action fails, so
the next delivery gets another shot.
"""
return bool(cache.add(cache_key, True, timeout=ONBOARDING_DEDUPE_TTL_SECONDS))
def _claim_channel_onboarding(slack_team_id: str, channel_id: str) -> bool:
return _claim_once(_channel_onboarding_cache_key(slack_team_id, channel_id))
def _release_channel_onboarding_claim(slack_team_id: str, channel_id: str) -> None:
cache.delete(_channel_onboarding_cache_key(slack_team_id, channel_id))
def skip_channel_welcome(slack_team_id: str, channel_id: str) -> bool:
"""Hold the welcome slot before the bot joins a channel, so it joins without a welcome message.
Returns False when another flow already holds the slot."""
return _claim_channel_onboarding(slack_team_id, channel_id)
def release_channel_welcome_skip(slack_team_id: str, channel_id: str) -> None:
_release_channel_onboarding_claim(slack_team_id, channel_id)
def _post_channel_onboarding_message(
slack: SlackIntegration,
integration: WorkspaceIntegration,
channel_id: str,
*,
only_to_user: str | None = None,
) -> bool:
"""Post the welcome message. Returns True on success.
With ``only_to_user``, the welcome is ephemeral: only that user sees it, in the channel.
"""
text, blocks = build_channel_welcome(integration)
try:
if only_to_user:
slack.client.chat_postEphemeral(channel=channel_id, user=only_to_user, text=text, blocks=blocks)
else:
slack.client.chat_postMessage(
channel=channel_id,
text=text,
blocks=blocks,
unfurl_links=False,
unfurl_media=False,
)
logger.info(
"slack_app_channel_onboarding_posted",
integration_id=integration.id,
slack_workspace_id=integration.integration_id,
channel_id=channel_id,
ephemeral=bool(only_to_user),
)
return True
except Exception:
logger.warning(
"slack_app_channel_onboarding_post_failed",
integration_id=integration.id,
slack_workspace_id=integration.integration_id,
channel_id=channel_id,
exc_info=True,
)
return False
def _route_team_join(
request: HttpRequest,
event: dict[str, Any],
slack_team_id: str,
*,
proxied: bool,
other_domain: str,
can_defer_to_other_region: bool,
incoming_host: str,
) -> str:
"""DM a personal welcome to a new workspace member, at most once.
Slack fires ``team_join`` for every account added to the workspace —
including bots and single/multi-channel guests, which we skip. Every full
member gets the DM: it grants no access on its own — the assistant
resolves and authorizes the user on every interaction, offering the
account-linking flow when their email doesn't match — so eligibility
sorts itself out on first use. The DM stays dark for installs that lack
the assistant scopes.
"""
joiner = event.get("user") if isinstance(event.get("user"), dict) else None
slack_user_id = joiner.get("id") if joiner else None
if not joiner or not isinstance(slack_user_id, str):
return ROUTE_HANDLED_LOCALLY
if joiner.get("is_bot") or joiner.get("is_restricted") or joiner.get("is_ultra_restricted"):
return ROUTE_HANDLED_LOCALLY
workspace_result = load_integrations(slack_team_id=slack_team_id, kinds=[SLACK_INTEGRATION_KIND])
if not workspace_result.candidates:
return _route_to_other_region_or_drop(request, slack_team_id, proxied=proxied, other_domain=other_domain)
if _us_should_handle_instead(slack_team_id, [SLACK_INTEGRATION_KIND], can_defer_to_other_region, incoming_host):
return _proxy_event_and_return_route(request, other_domain)
integration = next((c for c in workspace_result.candidates if is_slack_app_assistant_enabled(c)), None)
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",
slack_team_id=slack_team_id,
slack_user_id=slack_user_id,
)
return ROUTE_HANDLED_LOCALLY
if not _post_team_join_welcome(integration, slack_user_id):
# Release the dedupe slot so the next delivery gets another shot
# rather than being silently swallowed.
cache.delete(_team_join_onboarding_cache_key(slack_team_id, slack_user_id))
return ROUTE_HANDLED_LOCALLY
def _team_join_onboarding_cache_key(slack_team_id: str, slack_user_id: str) -> str:
return f"slack_app:team_join_welcomed:v1:{slack_team_id}:{slack_user_id}"
def _post_team_join_welcome(integration: WorkspaceIntegration, slack_user_id: str) -> bool:
text, blocks = build_team_join_welcome(integration)
try:
SlackIntegration(integration).client.chat_postMessage(
channel=slack_user_id, text=text, blocks=blocks, unfurl_links=False, unfurl_media=False
)
logger.info(
"slack_app_team_join_welcome_posted",
integration_id=integration.id,
slack_workspace_id=integration.integration_id,
slack_user_id=slack_user_id,
)
return True
except Exception:
logger.warning(
"slack_app_team_join_welcome_post_failed",
integration_id=integration.id,
slack_workspace_id=integration.integration_id,
slack_user_id=slack_user_id,
exc_info=True,
)
return False
def _channel_is_approved(slack_workspace_id: str, channel_id: str) -> bool:
"""True iff a user in this channel has already granted PostHog approval.
The ``is_ext_shared_channel`` flag that gates whether approval is required
at all lives on the Slack event envelope — see ``posthog_code_event_handler``
— so this only needs to answer the persistence question.
"""
return SlackChannel.approval_granted(slack_workspace_id, channel_id)
def _post_channel_approval_prompt(
slack: SlackIntegration,
integration: WorkspaceIntegration,
event: dict[str, Any],
) -> bool:
"""Post the approval prompt as an ephemeral message to the mentioner.
The prompt itself stays ephemeral — only the mentioner sees the
buttons — but every click *outcome* (approve, deny, non-member
rejection) is posted as a public threaded reply under the original
mention so the whole channel has a permanent record.
The ephemeral is **not** threaded: Slack only renders ephemerals on
the surface the user is currently viewing, so an ephemeral with
``thread_ts`` is invisible from the channel main view — i.e. the
place where the mentioner usually is right after typing the mention.
Dropping ``thread_ts`` here is what makes the prompt actually visible.
Returns whether the prompt reached Slack, so callers can record whether the user
was left with an explanation or with silence.
"""
channel = event.get("channel") if isinstance(event.get("channel"), str) else None
slack_user_id = event.get("user") if isinstance(event.get("user"), str) else None
if not channel or not slack_user_id:
return False
raw_thread_ts = event.get("thread_ts") if isinstance(event.get("thread_ts"), str) else None
message_ts = event.get("ts") if isinstance(event.get("ts"), str) else None
thread_ts = raw_thread_ts or message_ts
context_data = {
"kind": CHANNEL_APPROVAL_CONTEXT_KIND,
"integration_id": integration.id,
"slack_workspace_id": integration.integration_id,
"slack_channel_id": channel,
"thread_ts": thread_ts,
"created_at": int(time.time()),
}
context_token = uuid.uuid4().hex
cache.set(
_picker_context_cache_key(context_token),
context_data,
timeout=PICKER_TOKEN_MAX_AGE_SECONDS,
)
org_label = _org_label(integration)
text = (
f":wave: This is an externally-shared Slack channel. My answers can pull from {org_label}'s "
"PostHog project — including data about users, customers, and other internal metrics that aren't "
"otherwise visible in this channel — and anything I post will be seen by every member here, "
f"including people outside {org_label}'s workspace. A member of {org_label} can enable me below."
)
blocks: list[dict[str, Any]] = [
{
"type": "section",
"block_id": f"{CHANNEL_APPROVAL_BLOCK_ID_PREFIX}:{context_token}",
"text": {"type": "mrkdwn", "text": text},
},
{
"type": "actions",
"block_id": f"{CHANNEL_APPROVAL_BLOCK_ID_PREFIX}_actions:{context_token}",
"elements": [
{
"type": "button",
"action_id": CHANNEL_APPROVAL_ACTION_APPROVE,
"style": "primary",
"text": {"type": "plain_text", "text": "✅ Allow PostHog in this channel"},
"value": context_token,
},
{
"type": "button",
"action_id": CHANNEL_APPROVAL_ACTION_DENY,
"text": {"type": "plain_text", "text": "✋ Not here"},
"value": context_token,
},
],
},
]
logger.info(
"slack_app_channel_approval_prompt_requested",
integration_id=integration.id,
slack_workspace_id=integration.integration_id,
slack_channel_id=channel,
slack_user_id=slack_user_id,
)
try:
slack.client.chat_postEphemeral(
channel=channel,
user=slack_user_id,
text="The PostHog Slack app needs approval before answering in this externally-shared channel.",
blocks=blocks,
)
except Exception:
logger.warning(
"slack_app_channel_approval_prompt_failed",
integration_id=integration.id,
slack_workspace_id=integration.integration_id,
slack_channel_id=channel,
exc_info=True,
)
return False
return True
def _post_untagged_followup_prompt(
slack: SlackIntegration,
integration: WorkspaceIntegration,
event: dict[str, Any],
*,
is_ext_shared_channel: bool,
) -> bool:
"""Ask the replier whether their message should go to PostHog.
Posted when the thread creator's mode is ``ask``. The whole event is stashed
behind a one-off token so a click can dispatch the original message rather
than a reconstruction of it. Unlike the channel-approval prompt this one is
threaded: the person just typed inside the thread, so that is the surface
they are looking at.
"""
channel = event.get("channel") if isinstance(event.get("channel"), str) else None
slack_user_id = event.get("user") if isinstance(event.get("user"), str) else None
thread_ts = event.get("thread_ts") if isinstance(event.get("thread_ts"), str) else None
if not channel or not slack_user_id or not thread_ts:
logger.warning(
"slack_app_untagged_followup_prompt_skipped",
reason="incomplete_event",
integration_id=integration.id,
has_channel=bool(channel),
has_user=bool(slack_user_id),
has_thread_ts=bool(thread_ts),
)
return False
context_token = uuid.uuid4().hex
cache.set(
_picker_context_cache_key(context_token),
{
"kind": UNTAGGED_FOLLOWUP_CONTEXT_KIND,
"integration_id": integration.id,
"slack_workspace_id": integration.integration_id,
"slack_channel_id": channel,
"thread_ts": thread_ts,
"slack_user_id": slack_user_id,
"event": event,
"is_ext_shared_channel": is_ext_shared_channel,
"created_at": int(time.time()),
},
timeout=PICKER_TOKEN_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"{UNTAGGED_FOLLOWUP_BLOCK_ID_PREFIX}:{context_token}",
"text": {
"type": "mrkdwn",
"text": (
"I'm working in this thread. Want me to pick up your message? "
"Only you can see this, and I won't reply or start work unless you say so."
),
},
},
{
"type": "actions",
"block_id": f"{UNTAGGED_FOLLOWUP_BLOCK_ID_PREFIX}_actions:{context_token}",
"elements": [
{
"type": "button",
"action_id": UNTAGGED_FOLLOWUP_ACTION_RUN,
"style": "primary",
"text": {"type": "plain_text", "text": "Yes, take a look"},
"value": context_token,
},
{
"type": "button",
"action_id": UNTAGGED_FOLLOWUP_ACTION_DISMISS,
"text": {"type": "plain_text", "text": "No thanks"},
"value": context_token,
},
],
},
{
"type": "context",
"elements": [
{"type": "mrkdwn", "text": f"In the {home_tab_label} you can set what happens in threads you start."}
],
},
]
try:
slack.client.chat_postEphemeral(
channel=channel,
user=slack_user_id,
thread_ts=thread_ts,
text="Want PostHog to pick up your message in this thread?",
blocks=blocks,
)
except Exception:
logger.warning(
"slack_app_untagged_followup_prompt_failed",
integration_id=integration.id,
slack_workspace_id=integration.integration_id,
slack_channel_id=channel,
exc_info=True,
)
return False
logger.info(
"slack_app_untagged_followup_prompt_posted",
integration_id=integration.id,
slack_workspace_id=integration.integration_id,
slack_channel_id=channel,
slack_user_id=slack_user_id,
)
return True
def _post_untagged_question_prompt(
slack: SlackIntegration, integration: WorkspaceIntegration, event: dict[str, Any]
) -> bool:
"""Offer the author, privately, to answer the question they posted without tagging the app.
Posted when the author's mode is ``ask``. The whole event is stashed behind a one-off
token so a click dispatches the original message. Not threaded: the post has no thread
yet, so an ephemeral anchored to one would never be seen.
"""
channel = event.get("channel") if isinstance(event.get("channel"), str) else None
slack_user_id = event.get("user") if isinstance(event.get("user"), str) else None
if not channel or not slack_user_id:
logger.warning("slack_app_untagged_question_prompt_skipped", integration_id=integration.id)
return False
context_token = uuid.uuid4().hex
cache.set(
_picker_context_cache_key(context_token),
{
"kind": UNTAGGED_QUESTION_CONTEXT_KIND,
"integration_id": integration.id,
"slack_user_id": slack_user_id,
"event": event,
},
timeout=PICKER_TOKEN_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"{UNTAGGED_QUESTION_BLOCK_ID_PREFIX}:{context_token}",
"text": {
"type": "mrkdwn",
"text": (
"I think I can answer your question from your PostHog data. Want me to reply in a thread? "
"Only you can see this."
),
},
},
{
"type": "actions",
"block_id": f"{UNTAGGED_QUESTION_BLOCK_ID_PREFIX}_actions:{context_token}",
"elements": [
{
"type": "button",
"action_id": UNTAGGED_QUESTION_ACTION_RUN,
"style": "primary",
"text": {"type": "plain_text", "text": "Yes, answer it"},
"value": context_token,
},
{
"type": "button",
"action_id": UNTAGGED_QUESTION_ACTION_DISMISS,
"text": {"type": "plain_text", "text": "No thanks"},
"value": context_token,
},
{
"type": "button",
"action_id": UNTAGGED_QUESTION_ACTION_TURN_OFF,
"text": {"type": "plain_text", "text": "Only when I tag you"},
"value": context_token,
},
],
},
{
"type": "context",
"elements": [{"type": "mrkdwn", "text": f"You can change this in the {home_tab_label}."}],
},
]
try:
slack.client.chat_postEphemeral(
channel=channel,
user=slack_user_id,
text="PostHog can answer your question. Want a reply?",
blocks=blocks,
)
except Exception:
logger.warning(
"slack_app_untagged_question_prompt_failed",
integration_id=integration.id,
slack_channel_id=channel,
exc_info=True,
)
return False
capture_slack_event(integration, "slack app unprompted answer offered", slack_user_id=slack_user_id)
return True
@frozen
class _UntaggedQuestionClick:
context_token: str
context: dict[str, Any]
integration: WorkspaceIntegration
def _untagged_question_click(payload: dict) -> _UntaggedQuestionClick | None:
"""The live prompt context and its integration, or None when the prompt is stale or not the clicker's."""
context_token = _extract_context_token(payload)
context = _decode_picker_context(context_token) if context_token else None
if not context or context.get("kind") != UNTAGGED_QUESTION_CONTEXT_KIND:
return None
slack_team_id = payload.get("team", {}).get("id", "")
integration_id = context.get("integration_id")
# The prompt is ephemeral, so only its recipient can click it, but the dispatch runs as the clicker.
if not integration_id or not slack_team_id or payload.get("user", {}).get("id") != context.get("slack_user_id"):
return None
integration = get_workspace_integration(integration_id, slack_team_id)
if integration is None:
return None
return _UntaggedQuestionClick(context_token=context_token, context=context, integration=integration)
def _handle_untagged_question_run(payload: dict) -> HttpResponse:
response_url = payload.get("response_url", "")
click = _untagged_question_click(payload)
if click is None:
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
context_token, context, integration = click.context_token, click.context, click.integration
slack_user_id = context["slack_user_id"]
event = context.get("event")
# The confirmed run skips the gates the webhook and the workflow already applied, so the
# ones that can change while the prompt waits are checked again here. The two checks that
# call Slack run last.
slack = SlackIntegration(integration)
if (
not isinstance(event, dict)
or slack.missing_scopes(REQUIRED_SLACK_SCOPES)
or resolve_untagged_question_mode(integration.integration_id, slack_user_id) == UntaggedFollowupMode.NEVER
or (posthog_user := _is_org_member(integration, slack_user_id)) is None
or not _can_access_team(posthog_user, integration)
):
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
# A channel shared outside the organization since the offer would show the answer to people
# the webhook's gate kept it from. When Slack cannot say, the offer stays for a later click.
ext_shared = channel_ext_shared_state(slack, event.get("channel", ""))
if ext_shared is None:
return HttpResponse(status=200)
if ext_shared:
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
_start_mention_workflow(
event,
integration,
integration.integration_id,
None,
posthog_user=posthog_user,
untagged_question=True,
untagged_question_confirmed=True,
)
# Cleared only once the run is dispatched, so a Temporal outage leaves the offer clickable.
cache.delete(_picker_context_cache_key(context_token))
capture_slack_event(
integration, "slack app unprompted answer confirmed", slack_user_id=slack_user_id, posthog_user=posthog_user
)
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
def _handle_untagged_question_dismiss(payload: dict) -> HttpResponse:
"""Drop the offer. The choice covers this one message, so nothing is stored."""
click = _untagged_question_click(payload)
_delete_ephemeral_via_response_url(payload.get("response_url", ""))
if click is not None:
context_token, context, integration = click.context_token, click.context, click.integration
cache.delete(_picker_context_cache_key(context_token))
capture_slack_event(
integration, "slack app unprompted answer dismissed", slack_user_id=context["slack_user_id"]
)
return HttpResponse(status=200)
def _handle_untagged_question_turn_off(payload: dict) -> HttpResponse:
"""Stop answering the clicker's untagged channel questions, and say where to turn it back on."""
response_url = payload.get("response_url", "")
click = _untagged_question_click(payload)
if click is None:
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
context_token, context, integration = click.context_token, click.context, click.integration
slack_user_id = context["slack_user_id"]
cache.delete(_picker_context_cache_key(context_token))
set_untagged_question_mode(integration.integration_id, slack_user_id, UntaggedFollowupMode.NEVER)
capture_slack_event(integration, "slack app unprompted answers turned off", slack_user_id=slack_user_id)
inbox_interactivity.post_response_url(
response_url,
{
"replace_original": True,
"text": (
"Got it. I'll only answer your questions in channels when you tag me. "
"You can change this in the PostHog app Home tab."
),
},
)
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: WorkspaceIntegration,
inputs: PostHogCodeSlackMentionWorkflowInputs,
*,
channel: str,
thread_ts: str,
owner_slack_user_id: str,
joiner_slack_user_id: str,
opens_thread: bool,
plan_name: str | None = None,
) -> 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.
``plan_name`` names the creator's plan when the thread's task runs on it, so the creator
knows that people who join spend it.
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.
"""
plan_note = (
f"This task runs on your {plan_name}, so messages from people who join use it too. " if plan_name else ""
)
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"
thread_url = _thread_permalink(slack, channel, thread_ts)
thread_label = f"<{thread_url}|your thread>" if thread_url else "your thread"
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 {thread_label}. "
+ ("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"{plan_note}In the {home_tab_label} you can choose who joins your threads.",
}
],
},
]
try:
# A DM notifies the creator. An ephemeral message in the thread does not, so they often miss it.
slack.client.chat_postMessage(
channel=owner_slack_user_id,
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_permalink(slack: SlackIntegration, channel: str, thread_ts: str) -> str | None:
try:
permalink = slack.client.chat_getPermalink(channel=channel, message_ts=thread_ts).get("permalink")
except Exception:
logger.warning("slack_app_thread_join_permalink_failed", slack_channel_id=channel, exc_info=True)
return None
return permalink if isinstance(permalink, str) else None
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 goes to the creator's DM, but the answer acts for them, so the clicker is checked.
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 = get_workspace_integration(integration_id, slack_team_id)
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 = get_workspace_integration(integration_id, payload.get("team", {}).get("id", ""))
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: WorkspaceIntegration) -> bool:
"""Whether the user can reach the integration's project.
Org membership alone is what ``_is_org_member`` answers, and it is not enough
here: the routing path drops a reply whose author can't reach the mapped
project, so a click must clear the same bar or it becomes a way around it.
"""
try:
return UserPermissions(user=posthog_user).team(integration.team).effective_membership_level is not None
except Exception:
logger.exception(
"slack_app_untagged_followup_access_check_failed",
integration_id=integration.id,
user_id=posthog_user.id,
)
return False
def _untagged_followups_revoked_since_prompt(integration: WorkspaceIntegration, context: dict[str, Any]) -> bool:
"""Whether the thread creator switched follow-ups off while the prompt sat unanswered.
The confirmed run skips the mode activity — its answer is what re-dispatched
the message — so this is the only place left that can honour a mode changed
inside the prompt's lifetime.
"""
mapping = (
SlackThreadTaskMapping.objects.filter(
integration_id=integration.id,
channel=context.get("slack_channel_id"),
thread_ts=context.get("thread_ts"),
)
.only("mentioning_slack_user_id")
.first()
)
if mapping is None:
return True
if resolve_untagged_followup_mode(integration, mapping.mentioning_slack_user_id) != UntaggedFollowupMode.NEVER:
return False
logger.info(
"slack_app_untagged_followup_confirm_after_revoke",
integration_id=integration.id,
slack_channel_id=context.get("slack_channel_id"),
thread_ts=context.get("thread_ts"),
)
return True
def _handle_untagged_followup_run(payload: dict) -> HttpResponse:
"""Dispatch the message the replier just confirmed, then clear the prompt."""
response_url = payload.get("response_url", "")
context_token = _extract_context_token(payload)
context = _decode_picker_context(context_token) if context_token else None
if not context or context.get("kind") != UNTAGGED_FOLLOWUP_CONTEXT_KIND:
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
slack_team_id = payload.get("team", {}).get("id", "")
clicker_slack_user_id = payload.get("user", {}).get("id", "")
event = context.get("event")
integration_id = context.get("integration_id")
if not isinstance(event, dict) or not integration_id or not slack_team_id:
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
# The prompt is ephemeral, so only its recipient can click it — but the
# dispatch below runs as that recipient, so tie the two together explicitly.
if clicker_slack_user_id != context.get("slack_user_id"):
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
integration = get_workspace_integration(integration_id, slack_team_id)
if integration is None:
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
# A confirmed run re-enters the pipeline past the gates the webhook applied to the
# original reply, so the two it can't inherit are re-checked here: the clicker's
# access to the mapped project, and the creator's mode as it stands now.
posthog_user = _is_org_member(integration, clicker_slack_user_id)
if posthog_user is None or not _can_access_team(posthog_user, integration):
logger.info(
"slack_app_untagged_followup_confirm_no_access",
integration_id=integration.id,
slack_workspace_id=slack_team_id,
slack_user_id=clicker_slack_user_id,
)
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
if _untagged_followups_revoked_since_prompt(integration, context):
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
cache.delete(_picker_context_cache_key(context_token))
_start_mention_workflow(
event,
integration,
slack_team_id,
None,
posthog_user=posthog_user,
untagged_followup=True,
untagged_followup_confirmed=True,
is_ext_shared_channel=bool(context.get("is_ext_shared_channel")),
)
logger.info(
"slack_app_untagged_followup_confirmed",
integration_id=integration.id,
slack_workspace_id=slack_team_id,
slack_channel_id=context.get("slack_channel_id"),
slack_user_id=clicker_slack_user_id,
)
record_feature_used(slack_team_id, clicker_slack_user_id, SlackFeature.THREAD_FOLLOWUP)
capture_slack_event(
integration,
"slack app untagged followup confirmed",
slack_user_id=clicker_slack_user_id,
posthog_user=posthog_user,
)
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
def _handle_untagged_followup_dismiss(payload: dict) -> HttpResponse:
"""Drop the message the replier declined. Nothing is persisted — the choice
covers this one message, not the thread."""
context_token = _extract_context_token(payload)
context = _decode_picker_context(context_token) if context_token else None
if context_token:
cache.delete(_picker_context_cache_key(context_token))
_delete_ephemeral_via_response_url(payload.get("response_url", ""))
# Only a live untagged-followup context names the integration that raised the prompt,
# so resolving it there matches the confirm path's attribution instead of an
# arbitrary row of a multi-project workspace.
if not context or context.get("kind") != UNTAGGED_FOLLOWUP_CONTEXT_KIND:
return HttpResponse(status=200)
slack_team_id = payload.get("team", {}).get("id", "")
integration_id = context.get("integration_id")
dismissing_integration = (
get_workspace_integration(integration_id, slack_team_id) if integration_id and slack_team_id else None
)
dismisser_slack_user_id = payload.get("user", {}).get("id")
if dismissing_integration is not None:
capture_slack_event(
dismissing_integration,
"slack app untagged followup dismissed",
slack_user_id=dismisser_slack_user_id,
posthog_user=resolve_posthog_user_from_event(
slack_user_id=dismisser_slack_user_id,
probe_integration=dismissing_integration,
candidate_integrations=[dismissing_integration],
)
if dismisser_slack_user_id
else None,
)
return HttpResponse(status=200)
def _handle_reply_suggestion_click(payload: dict, clicked: reply_suggestions.ClickedSuggestion) -> HttpResponse:
"""Post the clicked reply in the thread and send it to the agent as the clicker's reply.
The click already says the message is for the agent, so it takes the confirmed untagged
follow-up path: no classifier, no creator prompt, and no new task in a thread without one.
The follow-up removes the buttons once the reply reaches the agent, which keeps that
Slack call out of the three seconds Slack gives this request.
"""
slack_team_id = payload.get("team", {}).get("id", "")
clicker_slack_user_id = payload.get("user", {}).get("id", "")
container = payload.get("container") or {}
message = payload.get("message") or {}
channel = container.get("channel_id") or (payload.get("channel") or {}).get("id")
message_ts = container.get("message_ts") or message.get("ts")
thread_ts = container.get("thread_ts") or message.get("thread_ts")
if not (
slack_team_id
and clicker_slack_user_id
and isinstance(channel, str)
and isinstance(message_ts, str)
and isinstance(thread_ts, str)
):
return HttpResponse(status=200)
claim_key = f"slack_app_reply_suggestion_claim:{clicked.integration_id}:{channel}:{message_ts}"
if cache.get(claim_key):
return HttpResponse(status=200)
integration = get_workspace_integration(clicked.integration_id, slack_team_id)
if integration is None:
return HttpResponse(status=200)
slack = SlackIntegration(integration)
# Anyone in the channel sees the buttons, so the click must clear the bar a typed reply clears.
posthog_user = _is_org_member(integration, clicker_slack_user_id)
if posthog_user is None or not _can_access_team(posthog_user, integration):
logger.info(
"slack_app_reply_suggestion_no_access",
integration_id=integration.id,
slack_workspace_id=slack_team_id,
slack_user_id=clicker_slack_user_id,
)
_post_slack_user_ephemeral(
slack,
channel,
clicker_slack_user_id,
thread_ts,
"Only members of this PostHog project can reply to the agent. Ask a project member to reply instead.",
)
return HttpResponse(status=200)
# A typed reply in an unapproved Slack Connect channel is dropped before dispatch, and a
# channel can become shared after the buttons were posted.
if not _channel_is_approved(slack_team_id, channel) and channel_is_ext_shared(slack, channel):
logger.info("slack_app_reply_suggestion_channel_unapproved", integration_id=integration.id)
_post_slack_user_ephemeral(
slack,
channel,
clicker_slack_user_id,
thread_ts,
"This channel is shared with another organization, so PostHog needs approval here first. "
"Mention @PostHog in the channel to approve it.",
)
return HttpResponse(status=200)
# Two people can click before the buttons disappear, and only the first click may reach the agent.
# The claim lasts as long as the buttons are tracked, in case removing them fails.
if not cache.add(claim_key, clicker_slack_user_id, timeout=reply_suggestions.OPEN_SUGGESTIONS_TTL_SECONDS):
return HttpResponse(status=200)
client = slack.client
client.timeout = SLACK_WEBHOOK_TIMEOUT_SECONDS
# A message of its own keeps the thread in order: the question, the reply, the next answer.
# Its ts carries the progress reactions and keys the follow-up's idempotent message id.
reply_ts = message_ts
posted_reply_ts: str | None = None
try:
posted = post_slack_thread_reply(
client,
channel=channel,
thread_ts=thread_ts,
text=f"<@{clicker_slack_user_id}> picked a suggested reply: *{clicked.text}*",
)
if posted is not None and isinstance(posted.get("ts"), str):
reply_ts = posted_reply_ts = posted["ts"]
except Exception:
logger.warning("slack_app_reply_suggestion_post_failed", integration_id=integration.id, exc_info=True)
event = {
"type": "message",
"user": clicker_slack_user_id,
"channel": channel,
"ts": reply_ts,
"thread_ts": thread_ts,
"text": clicked.text,
}
try:
_start_mention_workflow(
event,
integration,
slack_team_id,
None,
posthog_user=posthog_user,
untagged_followup=True,
untagged_followup_confirmed=True,
)
except Exception:
# Nothing reached the agent, so the buttons stay usable and the reply does not stand in the thread.
cache.delete(claim_key)
if posted_reply_ts:
try:
client.chat_delete(channel=channel, ts=posted_reply_ts)
except Exception:
logger.warning("slack_app_reply_suggestion_delete_failed", integration_id=integration.id)
raise
record_feature_used(slack_team_id, clicker_slack_user_id, SlackFeature.REPLY_SUGGESTIONS)
capture_slack_event(
integration,
"slack app reply suggestion clicked",
slack_user_id=clicker_slack_user_id,
posthog_user=posthog_user,
suggestion_index=clicked.index,
slack_session_id=slack_session_id(slack_team_id, channel, thread_ts),
ai_trace_id=clicked.trace_id,
)
return HttpResponse(status=200)
def _report_slack_mention_received(
event: dict,
integration: WorkspaceIntegration,
slack_team_id: str,
*,
posthog_user: User | None = None,
awaited_request_reply: bool = False,
) -> User | None:
"""Capture a product-analytics event each time the @PostHog bot is mentioned.
Returns the PostHog user the event was attributed to (``None`` when the Slack user
maps to nobody), so a caller that goes on to report a drop for the same mention
attributes both events to the same person instead of re-resolving.
A Slack thread is treated as the session: ``thread_ts`` identifies it, and a mention whose
``thread_ts`` is absent or equal to its own ``ts`` is the session's first message. The acting
Slack user is resolved to a PostHog ``User`` so the event is attributed to a real person where
one exists; otherwise it falls back to a stable Slack-derived distinct id.
When the caller has already resolved the PostHog user at routing time it passes ``posthog_user``
so we skip the redundant Slack ``users.info`` + ``OrganizationMembership`` roundtrip.
"""
try:
channel = event.get("channel") if isinstance(event.get("channel"), str) else None
message_ts = event.get("ts") if isinstance(event.get("ts"), str) else None
raw_thread_ts = event.get("thread_ts") if isinstance(event.get("thread_ts"), str) else None
thread_ts = raw_thread_ts or message_ts
is_first_message_in_session = raw_thread_ts is None or raw_thread_ts == message_ts
slack_user_id = event.get("user") if isinstance(event.get("user"), str) and event.get("user") else None
if posthog_user is None and slack_user_id:
posthog_user = resolve_posthog_user_from_event(
slack_user_id=slack_user_id,
probe_integration=integration,
candidate_integrations=[integration],
)
# Prefer the resolved PostHog user's distinct id so the event attributes to a real person;
# fall back to a stable Slack-derived id so anonymous-but-valid mentions are still captured.
identified_distinct_id = posthog_user.distinct_id if posthog_user else None
distinct_id = identified_distinct_id or f"slack:{slack_team_id}:{slack_user_id or 'unknown'}"
if is_first_message_in_session:
session_message_count: int | None = 1
else:
session_message_count = _count_session_thread_messages(integration, channel, thread_ts)
properties: dict[str, Any] = {
"is_first_message_in_session": is_first_message_in_session,
"session_message_count": session_message_count,
"slack_session_id": slack_session_id(slack_team_id, channel, thread_ts) if channel and thread_ts else None,
"slack_team_id": slack_team_id,
"slack_channel": channel,
"slack_thread_ts": thread_ts,
# Identifies the individual message, so an accepted mention can be ordered against
# the drops in its thread and joined to the agent turn that answered it.
"slack_message_ts": message_ts,
"slack_user_id": slack_user_id,
# Whether the message tagged the bot. ``app_mention`` is a tagged message;
# ``message`` is an untagged thread reply that the follow-up mode let through,
# because the ``message`` copy of a tagged reply drops earlier as ``tagged_reply``.
# ``posthog code slack mention dropped`` reports the same field, so the two sides
# add up to a funnel.
"slack_event_type": event.get("type"),
"slack_message_edited": bool(event.get("edited")),
"awaited_request_reply": awaited_request_reply,
# "im" marks an assistant DM; channel mentions carry "channel"/"group" or no type at all.
"slack_channel_type": event.get("channel_type"),
"posthog_user_identified": identified_distinct_id is not None,
**_slack_attachment_props(event),
}
if posthog_user is not None and identified_distinct_id is not None:
properties["$set"] = posthog_user.get_analytics_metadata()
if event.get("files"):
record_feature_used(slack_team_id, slack_user_id, SlackFeature.FILE_ATTACHMENTS)
posthoganalytics.capture(
distinct_id=distinct_id,
event="posthog code slack mention received",
properties=properties,
groups=groups(team=integration.team),
send_feature_flags=True,
)
return posthog_user
except Exception:
logger.warning(
"slack_app_mention_analytics_failed",
slack_team_id=slack_team_id,
integration_id=integration.id,
exc_info=True,
)
return None
def _report_slack_mention_dropped(
event: dict,
slack_team_id: str,
*,
reason: str,
replied: bool,
integration: WorkspaceIntegration | None = None,
posthog_user: User | None = None,
**extra: object,
) -> None:
"""Capture a product-analytics event for a mention that never reaches the agent.
Slack is answered with a 200 on every one of these paths, so the drop is otherwise
invisible: support can only guess why a workspace says the app stopped responding.
`replied` records whether the user got any feedback in Slack, which separates
"we told them why" from true silence.
`integration` is absent on the paths that drop before a workspace is resolved, and
on the ones where picking any single project would be a lie; the event then falls
back to a Slack-derived distinct id and carries no groups. `extra` goes onto the
event as-is for reason-specific context.
"""
try:
channel = event.get("channel") if isinstance(event.get("channel"), str) else None
message_ts = event.get("ts") if isinstance(event.get("ts"), str) else None
raw_thread_ts = event.get("thread_ts") if isinstance(event.get("thread_ts"), str) else None
thread_ts = raw_thread_ts or message_ts
slack_user_id = event.get("user") if isinstance(event.get("user"), str) and event.get("user") else None
properties: dict[str, Any] = {
"drop_reason": reason,
"replied": replied,
"slack_event_type": event.get("type"),
"slack_session_id": slack_session_id(slack_team_id, channel, thread_ts) if channel and thread_ts else None,
"slack_team_id": slack_team_id,
"slack_channel": channel,
"slack_thread_ts": thread_ts,
"slack_message_ts": message_ts,
"slack_user_id": slack_user_id,
"posthog_user_identified": posthog_user is not None,
**extra,
}
if integration is not None:
properties["integration_id"] = integration.id
properties["team_id"] = integration.team_id
posthoganalytics.capture(
distinct_id=(posthog_user.distinct_id if posthog_user else None)
or f"slack:{slack_team_id}:{slack_user_id or 'unknown'}",
event=SLACK_MENTION_DROPPED_EVENT,
properties=properties,
groups=groups(team=integration.team) if integration is not None else {},
)
except Exception:
logger.warning(
"slack_app_mention_drop_analytics_failed",
slack_team_id=slack_team_id,
reason=reason,
exc_info=True,
)
def _start_onboarding_on_mention(event: dict, slack_team_id: str, workspace_result: ResolutionResult) -> None:
"""Someone who only tags PostHog in channels may never open its DM, so their mention starts the onboarding.
It runs after the mention is handled, so a slow onboarding start never delays the answer. A guest from
another workspace in a shared channel gets no onboarding, because it would come from this workspace's app."""
slack_user_id = event.get("user")
if event.get("type") != "app_mention" or event.get("user_team", slack_team_id) != slack_team_id:
return
integration = workspace_result.resolved_or_first()
if integration is not None and isinstance(slack_user_id, str) and slack_user_id:
request_onboarding(integration, slack_user_id, may_start=True, start_only=True)
def _start_mention_workflow(
event: dict,
integration: WorkspaceIntegration,
slack_team_id: str,
event_id: str | None,
*,
posthog_user: User,
untagged_followup: bool = False,
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,
fork_source_thread_ts: str | None = None,
fork_source_message_ts: str | None = None,
fork_source_task_id: str | None = None,
) -> str:
"""Start the mention workflow for an explicit ``app_mention``, an untagged
thread reply, or a forked thread.
``untagged_followup`` toggles two mention-only side effects: the
``slack_mention_received`` analytics fire (which would otherwise pollute
the mention funnel with non-mentions) and the pending-picker resolution
(which is meaningful only when the user actually typed ``@PostHog``). It
is also threaded into the workflow inputs so the workflow runs the
classifier activity at the top of its body and short-circuits if the
mapping is gone by the time the followup activity runs.
The ``fork_source_*`` fields mark a forked run, where the thread being answered
(a DM) and the thread supplying the context (the forked channel thread) differ.
They suppress the same two side effects: nobody mentioned us, and a reply in a
forked DM can't be resolving a picker. ``untagged_question`` suppresses them
for the same reason, and makes the workflow ask its classifier first.
"""
is_fork = bool(fork_source_channel and fork_source_thread_ts)
if not untagged_followup and not untagged_question and not is_fork:
_report_slack_mention_received(
event,
integration,
slack_team_id,
posthog_user=posthog_user,
awaited_request_reply=awaited_request_reply,
)
if _resolve_pending_repo_picker_from_followup(event, integration):
return ROUTE_HANDLED_LOCALLY
workflow_inputs = PostHogCodeSlackMentionWorkflowInputs(
event=event,
integration_id=integration.id,
slack_team_id=slack_team_id,
slack_event_id=event_id,
user_id=posthog_user.id,
untagged_followup=untagged_followup,
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,
fork_source_message_ts=fork_source_message_ts,
fork_source_task_id=fork_source_task_id,
)
# Events without channel/ts fall back to the per-message workflow.
queue_workflow_id = derive_slack_app_mention_workflow_id(workflow_inputs)
if queue_workflow_id is not None:
_start_posthog_code_workflow(
SlackAppMentionWorkflow,
SlackAppMentionWorkflowInputs(),
id_prefix="slack-app-mention",
slack_team_id=slack_team_id,
event=event,
event_id=event_id,
workflow_id=queue_workflow_id,
start_signal="new_message",
start_signal_args=[workflow_inputs],
)
return ROUTE_HANDLED_LOCALLY
# Use derive_mention_workflow_id as the single source of truth: the workflow persists the same
# value as slack_mention_workflow_id, so dispatch and the debug-tool Temporal link stay consistent
_start_posthog_code_workflow(
SlackAppMentionProcessingWorkflow,
workflow_inputs,
id_prefix="slack-app-mention-processing",
slack_team_id=slack_team_id,
event=event,
event_id=event_id,
workflow_id=derive_mention_workflow_id(workflow_inputs),
)
return ROUTE_HANDLED_LOCALLY
def _picker_context_cache_key(context_token: str) -> str:
token_hash = hashlib.sha256(context_token.encode("utf-8")).hexdigest()
return f"posthog_code_repo_picker_ctx:{token_hash}"
def _decode_picker_context(context_token: str) -> dict[str, Any] | None:
if not context_token:
return None
cached = cache.get(_picker_context_cache_key(context_token))
if isinstance(cached, dict):
return cached
# Backward-compat for older tests/keys using raw token in cache key.
if len(context_token) < 120:
cached = cache.get(f"posthog_code_repo_picker_ctx:{context_token}")
if isinstance(cached, dict):
return cached
try:
decoded = signing.loads(context_token, salt=PICKER_TOKEN_SALT, max_age=PICKER_TOKEN_MAX_AGE_SECONDS)
if isinstance(decoded, dict):
return decoded
except signing.SignatureExpired:
return None
except signing.BadSignature:
pass
return None
@csrf_exempt
def posthog_code_event_handler(request: HttpRequest) -> HttpResponse:
if request.method != "POST":
return HttpResponse(status=405)
try:
slack_config = SlackIntegration.slack_config()
validate_slack_request(request, slack_config["SLACK_APP_SIGNING_SECRET"])
except SlackIntegrationError as e:
logger.warning("slack_app_event_invalid_request", error=str(e))
return HttpResponse("Invalid request", status=403)
retry_num = request.headers.get("X-Slack-Retry-Num")
if retry_num:
logger.info("slack_app_event_retry", retry_num=retry_num)
return HttpResponse(status=200)
try:
data = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponse("Invalid JSON", status=400)
event_type = data.get("type")
if event_type == "url_verification":
challenge = data.get("challenge", "")
return JsonResponse({"challenge": challenge})
if event_type == "event_callback":
event = data.get("event", {})
slack_team_id = data.get("team_id", "")
event_id = data.get("event_id")
if event.get("type") in HANDLED_EVENT_TYPES:
# ``is_ext_shared_channel`` lives on the event envelope (Slack adds it for
# any event delivered from a Slack Connect channel). Reading it here avoids
# a per-mention ``conversations.info`` round-trip.
raw_is_ext_shared_channel = data.get("is_ext_shared_channel", False)
if event.get("type") == "link_shared":
logger.info(
"slack_link_unfurl_received",
slack_team_id=slack_team_id,
event_id=event_id,
channel=event.get("channel"),
message_ts=event.get("message_ts"),
is_ext_shared_channel=raw_is_ext_shared_channel,
is_ext_shared_channel_type=type(raw_is_ext_shared_channel).__name__,
resources=_link_shared_resource_refs(event),
)
is_ext_shared = bool(raw_is_ext_shared_channel)
result = route_posthog_code_event_to_relevant_region(
request,
event,
slack_team_id,
event_id=event_id,
is_ext_shared_channel=is_ext_shared,
)
logger.info(
"slack_app_event_dispatch_result",
result=result,
slack_team_id=slack_team_id,
event_id=event_id,
)
if result == ROUTE_PROXY_FAILED:
return HttpResponse(status=502)
return HttpResponse(status=202)
# posthog_code_event_handler: unrecognized event type
return HttpResponse(status=200)
def _is_posthog_app_url(url: str) -> bool:
hostname = urlparse(url).hostname
return hostname == urlparse(settings.SITE_URL).hostname or hostname in {
"app.posthog.com",
"eu.posthog.com",
"posthog.com",
"us.posthog.com",
}
def _link_shared_resource_refs(event: dict[str, Any]) -> list[dict[str, str]]:
links = event.get("links")
if not isinstance(links, list):
return []
resources: list[dict[str, str]] = []
for link in links:
if not isinstance(link, dict):
continue
url = link.get("url")
if not isinstance(url, str) or not _is_posthog_app_url(url):
continue
parsed = parse_posthog_resource_link(url)
if parsed:
resources.append({"type": parsed.kind, "ref": parsed.id})
return resources
@dataclass(frozen=True)
class LinkSharedTarget:
"""The install that serves a ``link_shared`` event, and how it was chosen."""
integration: WorkspaceIntegration | None
source: str
def _link_shared_resource_urls(event: dict[str, Any]) -> list[str]:
"""The event's links that parse as a resource we can unfurl.
A shared replay or settings link carries a project id but can never produce an unfurl, so
letting it speak for the event would route a resource link in the same message to a project
that doesn't hold it.
"""
links = event.get("links")
if not isinstance(links, list):
return []
refs: list[tuple[str, str]] = []
for link in links:
if not isinstance(link, dict):
continue
url = link.get("url")
if isinstance(url, str) and (ref := parse_posthog_resource_link(url)) is not None:
refs.append((url, ref.kind))
# An ad hoc insight link unfurls only as the message's single link, so beside other links it
# must not route the event to its own project or region.
if len(refs) > 1:
refs = [(url, kind) for url, kind in refs if kind != ADHOC_INSIGHT_KIND]
return [url for url, _ in refs]
def _link_shared_url_region(event: dict[str, Any]) -> str | None:
"""The Cloud region the event's links name, when they agree on one.
Project ids are issued per region, so `/project/2` on a `us.` link and `/project/2` on an `eu.`
link are unrelated projects. Reading the region off the host is what keeps a link from being
resolved against the same number in the wrong region.
"""
regions = {region for url in _link_shared_resource_urls(event) if (region := link_url_region(url)) is not None}
return regions.pop() if len(regions) == 1 else None
def _link_shared_url_team_ids(event: dict[str, Any]) -> set[int]:
"""Team ids named by ``/project/:id`` or ``/api/projects/:id`` in the event's unfurlable links."""
team_ids: set[int] = set()
for url in _link_shared_resource_urls(event):
parts = [part for part in urlparse(url).path.split("/") if part]
if parts[:2] == ["api", "projects"]:
parts = parts[1:]
if len(parts) >= 2 and parts[0] in ("project", "projects"):
try:
team_ids.add(int(parts[1]))
except ValueError:
continue
return team_ids
def _link_shared_target(
event: dict[str, Any], candidates: Sequence[WorkspaceIntegration], *, slack_team_id: str
) -> LinkSharedTarget:
"""Pick the install to unfurl with, preferring the project the link itself names."""
team_ids = _link_shared_url_team_ids(event)
if len(team_ids) == 1:
team_id = next(iter(team_ids))
match = next((candidate for candidate in candidates if candidate.team_id == team_id), None)
if match is not None:
return LinkSharedTarget(match, "url_project")
# The link names a project no install in this region covers. Refusing lets the caller fall
# through to the other region rather than unfurling out of an unrelated project.
return LinkSharedTarget(None, "url_project_not_local")
if team_ids:
# Links naming different projects cannot be served by one install, and picking either one
# would leak the wrong project's data, so serve none of them.
return LinkSharedTarget(None, "url_projects_conflict")
# Links with no project id (short ``/i/:short_id`` links, ticket links) go through the same
# precedence ladder mentions use, so a workspace with several connected projects lands on the
# project the user actually works in rather than on whichever install happens to be oldest.
# Resolving without a ``user`` only picks which project to look in — ``handle_posthog_link_unfurl``
# still resolves the sharer against that project and access-checks every resource it unfurls.
slack_user_id = str(event.get("user") or "")
thread_ts = event.get("thread_ts") or event.get("message_ts")
resolution = resolve_from_candidates(
candidates,
slack_team_id=slack_team_id,
slack_user_id="" if slack_user_id == SLACK_PLACEHOLDER_USER_ID else slack_user_id,
channel=event.get("channel") if isinstance(event.get("channel"), str) else None,
thread_ts=thread_ts if isinstance(thread_ts, str) else None,
)
# No thread mapping and no default in a multi-project workspace: there is no picker to fall
# back on for a pasted link, so ``resolved_or_first`` still answers with an install — the same
# id-ordered tie-break the other must-pick-something surfaces use.
return LinkSharedTarget(resolution.resolved_or_first(), resolution.source)
def _extract_context_token(payload: dict) -> str:
"""Extract the context token from a block_id (block_suggestion) or message metadata (block_actions)."""
def token_from_block_id(raw_block_id: str) -> str:
if not raw_block_id:
return ""
if raw_block_id.startswith("posthog_code_repo_picker_v2:"):
parts = raw_block_id.split(":")
return parts[3] if len(parts) >= 4 else ""
if ":" in raw_block_id:
return raw_block_id.split(":", 1)[1]
return ""
# block_suggestion: block_id is at top level
block_id = payload.get("block_id", "")
token = token_from_block_id(block_id)
if token:
return token
# block_actions: block_id is inside each action
for action in payload.get("actions", []):
action_block_id = action.get("block_id", "")
token = token_from_block_id(action_block_id)
if token:
return token
# fallback: message metadata
return payload.get("message", {}).get("metadata", {}).get("event_payload", {}).get("context_token", "")
# Every Home tab control, plus the two modal selects that re-render the edit modal.
# Sourced from `HOME_ACTION_IDS` rather than re-listed, so a control added to the tab
# is routable here the moment it exists.
_AI_PREFERENCES_ACTION_IDS = HOME_ACTION_IDS | {MODAL_ACTION_RUNTIME_ADAPTER, MODAL_ACTION_MODEL}
_AI_PREFERENCES_CALLBACK_IDS = frozenset({EDIT_MODAL_PERSONAL_CALLBACK_ID})
def _is_ai_preferences_interactivity(payload: dict, payload_type: str) -> bool:
"""Return True if this payload is a Slack App Home AI-settings interaction.
AI-settings buttons (Edit/Reset on the Home tab, runtime/model dispatch
re-renders inside the modal) and modal submissions carry no per-row hint —
the picker is workspace-scoped, not tied to a specific task or repo. The
cross-region router uses this to claim locality based on the workspace
integration alone rather than dropping the click.
"""
if payload_type == "view_submission":
return payload.get("view", {}).get("callback_id", "") in _AI_PREFERENCES_CALLBACK_IDS
if payload_type == "block_actions":
for action in payload.get("actions", []) or ():
if action.get("action_id", "") in _AI_PREFERENCES_ACTION_IDS:
return True
return False
def _extract_picker_hints(payload: dict) -> tuple[int | None, str | None]:
"""Extract integration_id and mentioning user id from block_id for fallback handling."""
block_id = payload.get("block_id", "")
if not block_id:
actions = payload.get("actions", [])
if actions:
block_id = actions[0].get("block_id", "")
if not block_id.startswith("posthog_code_repo_picker_v2:"):
return None, None
parts = block_id.split(":")
if len(parts) < 4:
return None, None
try:
integration_id = int(parts[1])
except ValueError:
return None, None
mentioning_slack_user_id = parts[2]
return integration_id, mentioning_slack_user_id
def _extract_action_value_hints(payload: dict, action_id: str) -> tuple[int | None, str | None]:
"""Pull (integration_id, mentioning_slack_user_id) from a block action's JSON value, or (None, None).
A button carries its payload in ``value``; an overflow menu carries the chosen
entry's under ``selected_option.value`` instead. Reading both lets one extractor
serve either element.
"""
actions = payload.get("actions", [])
action = next((a for a in actions if a.get("action_id") == action_id), None)
if not action:
return None, None
value_raw = action.get("value") or (action.get("selected_option") or {}).get("value", "")
if not value_raw:
return None, None
try:
value = json.loads(value_raw)
except json.JSONDecodeError:
return None, None
integration_id = value.get("integration_id")
mentioning_user_id = value.get("mentioning_slack_user_id")
if not isinstance(integration_id, int):
return None, None
if mentioning_user_id is not None and not isinstance(mentioning_user_id, str):
mentioning_user_id = None
return integration_id, mentioning_user_id
def _handle_repo_picker_options(payload: dict) -> JsonResponse:
"""Return filtered repo options for the external_select picker."""
action = payload.get("action_id") or (payload.get("actions", [{}])[0].get("action_id", ""))
if action != "posthog_code_repo_select":
return JsonResponse({"options": []})
context_token = _extract_context_token(payload)
slack_team_id = payload.get("team", {}).get("id")
if not slack_team_id:
logger.info("slack_app_repo_picker_options_missing_slack_team")
return JsonResponse({"options": []})
if not context_token:
logger.info("slack_app_repo_picker_options_missing_token")
return JsonResponse({"options": []})
ctx = _decode_picker_context(context_token)
hinted_integration_id, hinted_user_id = _extract_picker_hints(payload)
if not ctx and not hinted_integration_id:
team_id = payload.get("team", {}).get("id")
if team_id:
fallback_integration = next(iter(workspace_integrations(team_id)), None)
if fallback_integration:
hinted_integration_id = fallback_integration.id
logger.info(
"slack_app_repo_picker_options_fallback_team",
context_token=context_token,
team_id=team_id,
integration_id=hinted_integration_id,
)
if not ctx and not hinted_integration_id:
logger.info("slack_app_repo_picker_options_no_context", context_token=context_token)
return JsonResponse({"options": []})
requesting_user = payload.get("user", {}).get("id", "")
expected_user = ctx["mentioning_slack_user_id"] if ctx else hinted_user_id
if expected_user and requesting_user != expected_user:
logger.info(
"slack_app_repo_picker_options_user_mismatch",
context_token=context_token,
requesting_user=requesting_user,
expected_user=expected_user,
)
return JsonResponse({"options": []})
if not expected_user:
logger.info("slack_app_repo_picker_options_missing_expected_user", context_token=context_token)
integration_id: int | None = ctx["integration_id"] if ctx else hinted_integration_id
integration = get_workspace_integration(integration_id, slack_team_id) if integration_id else None
if integration is None:
logger.info("slack_app_repo_picker_options_no_integration", context_token=context_token)
return JsonResponse({"options": []})
mentioning_user_id = ctx.get("mentioning_user_id") if ctx else None
if not isinstance(mentioning_user_id, int):
# Without a known PostHog user we can't scope the options to a personal install;
# return empty rather than falling back to the team install — the user can re-mention.
logger.info("slack_app_repo_picker_options_missing_user_id", context_token=context_token)
return JsonResponse({"options": []})
try:
all_repos = _get_full_repo_names(integration, user_id=mentioning_user_id)
except Exception:
logger.exception("twig_repo_picker_options_repo_fetch_error", integration_id=integration.id)
return JsonResponse({"options": []})
if not all_repos:
logger.info(
"slack_app_repo_picker_options_no_repos", context_token=context_token, integration_id=integration.id
)
return JsonResponse({"options": []})
query = (payload.get("value") or "").lower()
filtered = [r for r in all_repos if query in r.lower()] if query else all_repos
options = [{"text": {"type": "plain_text", "text": r}, "value": r} for r in filtered[:25]]
return JsonResponse({"options": options})
def _handle_repo_picker_submit(payload: dict) -> HttpResponse:
"""Signal Temporal mention workflow for repo submit."""
actions = payload.get("actions", [])
action = next((a for a in actions if a.get("action_id") == "posthog_code_repo_select"), None)
selected_repo = action.get("selected_option", {}).get("value") if action else None
context_token = _extract_context_token(payload)
context = _decode_picker_context(context_token) if context_token else None
pending_picker_user_id = context.get("mentioning_slack_user_id") if context else None
workflow_id = None
if context and isinstance(context.get("workflow_id"), str):
workflow_id = context.get("workflow_id")
if not workflow_id:
workflow_id = payload.get("message", {}).get("metadata", {}).get("event_payload", {}).get("workflow_id")
def post_selection_expired() -> None:
slack_team_id = payload.get("team", {}).get("id")
integration_id = context.get("integration_id") if context else None
channel = context.get("channel") if context else payload.get("channel", {}).get("id")
thread_ts = context.get("thread_ts") if context else payload.get("message", {}).get("ts")
if not slack_team_id or not integration_id or not channel or not thread_ts:
logger.warning(
"slack_app_repo_submit_expired_feedback_missing_context",
slack_team_id=slack_team_id,
integration_id=integration_id,
channel=channel,
thread_ts=thread_ts,
)
return
if isinstance(pending_picker_user_id, str) and pending_picker_user_id:
_clear_pending_repo_picker(
integration_id=integration_id,
channel=channel,
thread_ts=thread_ts,
slack_user_id=pending_picker_user_id,
)
# If another workflow already created a task for this thread (e.g. the
# user sent a follow-up message instead of using the picker), skip the
# expired message.
from products.slack_app.backend.models import SlackThreadTaskMapping
if SlackThreadTaskMapping.objects.filter(
integration_id=integration_id,
channel=channel,
thread_ts=thread_ts,
).exists():
return
try:
integration = get_workspace_integration(integration_id, slack_team_id)
if integration is None:
raise IntegrationNotFound
post_slack_thread_reply(
SlackIntegration(integration).client,
channel=channel,
thread_ts=thread_ts,
text="Repository selection expired. Please mention PostHog again to retry.",
)
except Exception:
logger.warning(
"slack_app_repo_submit_expired_feedback_failed",
integration_id=integration_id,
channel=channel,
thread_ts=thread_ts,
)
if not selected_repo:
return HttpResponse(status=200)
if not workflow_id:
logger.info("slack_app_repo_submit_missing_workflow_id")
post_selection_expired()
return HttpResponse(status=200)
try:
client = sync_connect()
handle = client.get_workflow_handle(workflow_id)
asyncio.run(handle.signal(SlackAppMentionProcessingWorkflow.repo_selected, selected_repo))
if context and pending_picker_user_id:
_clear_pending_repo_picker(
integration_id=context["integration_id"],
channel=context["channel"],
thread_ts=context["thread_ts"],
slack_user_id=pending_picker_user_id,
)
_replace_repo_picker_with_selection(payload, context, selected_repo)
return HttpResponse(status=200)
except Exception as e:
logger.warning("slack_app_repo_submit_signal_failed", workflow_id=workflow_id, error=str(e))
post_selection_expired()
return HttpResponse(status=200)
def _replace_repo_picker_with_selection(payload: dict, context: dict | None, selected_repo: str) -> None:
integration_id = context.get("integration_id") if context else None
slack_team_id = payload.get("team", {}).get("id")
channel = context.get("channel") if context else payload.get("channel", {}).get("id")
message_ts = payload.get("message", {}).get("ts")
if not integration_id or not slack_team_id or not channel or not message_ts:
logger.info(
"slack_app_repo_submit_missing_picker_update_context",
integration_id=integration_id,
slack_team_id=slack_team_id,
channel=channel,
message_ts=message_ts,
)
return
_replace_repo_picker_message_with_selection(
integration_id=integration_id,
slack_team_id=slack_team_id,
channel=channel,
message_ts=message_ts,
selected_repo=selected_repo,
)
def _handle_no_repo_needed_submit(payload: dict) -> HttpResponse:
context_token = _extract_context_token(payload)
context = _decode_picker_context(context_token) if context_token else None
pending_picker_user_id = context.get("mentioning_slack_user_id") if context else None
workflow_id = None
if context and isinstance(context.get("workflow_id"), str):
workflow_id = context.get("workflow_id")
if not workflow_id:
workflow_id = payload.get("message", {}).get("metadata", {}).get("event_payload", {}).get("workflow_id")
if not workflow_id or not context:
logger.info("slack_app_repo_none_missing_workflow_id")
return HttpResponse(status=200)
try:
client = sync_connect()
handle = client.get_workflow_handle(workflow_id)
asyncio.run(handle.signal(SlackAppMentionProcessingWorkflow.no_repo_needed))
if pending_picker_user_id:
_clear_pending_repo_picker(
integration_id=context["integration_id"],
channel=context["channel"],
thread_ts=context["thread_ts"],
slack_user_id=pending_picker_user_id,
)
message_ts = payload.get("message", {}).get("ts")
slack_team_id = payload.get("team", {}).get("id")
if message_ts and slack_team_id:
_replace_repo_picker_message_with_no_repo(
integration_id=context["integration_id"],
slack_team_id=slack_team_id,
channel=context["channel"],
message_ts=message_ts,
)
return HttpResponse(status=200)
except Exception as e:
logger.warning("slack_app_repo_none_signal_failed", workflow_id=workflow_id, error=str(e))
return HttpResponse(status=200)
def _delete_ephemeral_via_response_url(response_url: str) -> None:
"""Remove the original ephemeral prompt via the interactivity ``response_url`` once its public
threaded outcome has been posted."""
inbox_interactivity.post_response_url(response_url, {"delete_original": True})
def _post_channel_approval_outcome(
integration: WorkspaceIntegration,
channel_id: str,
thread_ts: str | None,
text: str,
) -> None:
"""Post a public threaded reply documenting a click outcome.
The prompt itself is ephemeral, so this is the only channel-visible
record of what happened. ``thread_ts`` ties the message to the
original mention so the audit trail sits next to the trigger.
"""
if not thread_ts:
return
try:
post_slack_thread_reply(
SlackIntegration(integration).client,
channel=channel_id,
thread_ts=thread_ts,
text=text,
)
except Exception:
logger.warning(
"slack_app_channel_approval_outcome_post_failed",
integration_id=integration.id,
channel=channel_id,
exc_info=True,
)
# nosemgrep: tuple-return-prefer-dataclass -- existing shape, only the record type changed
def _resolve_channel_approval_context(payload: dict) -> tuple[WorkspaceIntegration, dict, str, str] | None:
"""Decode the click context and load the prompt's integration in one place.
Returns ``(integration, context, channel_id, clicker_slack_user_id)`` on
success, or ``None`` after silently cleaning up the ephemeral. Used by
both approve and deny so they share the same context + integration
resolution path.
"""
response_url = payload.get("response_url", "")
context_token = _extract_context_token(payload)
context = _decode_picker_context(context_token) if context_token else None
if not context or context.get("kind") != CHANNEL_APPROVAL_CONTEXT_KIND:
_delete_ephemeral_via_response_url(response_url)
return None
integration_id = context.get("integration_id")
channel_id = context.get("slack_channel_id")
slack_team_id = payload.get("team", {}).get("id", "")
clicker_slack_user_id = payload.get("user", {}).get("id", "")
if not integration_id or not channel_id or not clicker_slack_user_id or not slack_team_id:
_delete_ephemeral_via_response_url(response_url)
return None
integration = get_workspace_integration(integration_id, slack_team_id)
if integration is None:
_delete_ephemeral_via_response_url(response_url)
return None
return integration, context, channel_id, clicker_slack_user_id
def _is_org_member(integration: WorkspaceIntegration, clicker_slack_user_id: str) -> User | None:
"""Resolve the clicker to a PostHog ``User`` belonging to the integration's
organization, or ``None`` if no such membership exists.
"""
return resolve_posthog_user_from_event(
slack_user_id=clicker_slack_user_id,
probe_integration=integration,
candidate_integrations=[integration],
)
def _org_label(integration: WorkspaceIntegration) -> str:
try:
org_name = integration.team.organization.name
except Exception:
org_name = ""
return f"*{org_name}*" if org_name else "this PostHog organization"
def _reject_non_member_click(
integration: WorkspaceIntegration,
channel_id: str,
thread_ts: str | None,
response_url: str,
) -> None:
"""Post the public "only members can manage" rejection and clear the ephemeral.
Shared between approve and deny so the rejection wording, the public
placement, and the ephemeral cleanup all stay in one place.
"""
_post_channel_approval_outcome(
integration,
channel_id,
thread_ts,
f":warning: Only members of {_org_label(integration)} can manage the PostHog Slack app in this channel.",
)
_delete_ephemeral_via_response_url(response_url)
def _handle_channel_approval_submit(payload: dict) -> HttpResponse:
"""Approve the bot for this Slack channel after verifying the clicker is a
member of the integration's PostHog organization.
The prompt is ephemeral to the mentioner; every outcome (approve, deny,
non-member rejection) is posted as a public threaded reply so the whole
channel sees the result.
"""
resolved = _resolve_channel_approval_context(payload)
if resolved is None:
return HttpResponse(status=200)
integration, context, channel_id, clicker_slack_user_id = resolved
response_url = payload.get("response_url", "")
thread_ts = context.get("thread_ts") if isinstance(context.get("thread_ts"), str) else None
posthog_user = _is_org_member(integration, clicker_slack_user_id)
if posthog_user is None:
_reject_non_member_click(integration, channel_id, thread_ts, response_url)
return HttpResponse(status=200)
workspace_id = context.get("slack_workspace_id") or integration.integration_id
SlackChannel.objects.update_or_create(
slack_workspace_id=workspace_id,
slack_channel_id=channel_id,
defaults={
"approved_at": timezone.now(),
"approved_by": posthog_user,
},
)
context_token = _extract_context_token(payload)
if context_token:
cache.delete(_picker_context_cache_key(context_token))
_post_channel_approval_outcome(
integration,
channel_id,
thread_ts,
f"✅ <@{clicker_slack_user_id}> enabled the PostHog Slack app in this channel.",
)
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
def _handle_channel_approval_deny(payload: dict) -> HttpResponse:
"""Dismiss the approval prompt without recording any state.
Same membership gate as approve, since only the mentioner sees the
ephemeral and a non-member mentioner's dismissal would otherwise just
silently consume the prompt.
"""
resolved = _resolve_channel_approval_context(payload)
if resolved is None:
return HttpResponse(status=200)
integration, context, channel_id, clicker_slack_user_id = resolved
response_url = payload.get("response_url", "")
thread_ts = context.get("thread_ts") if isinstance(context.get("thread_ts"), str) else None
posthog_user = _is_org_member(integration, clicker_slack_user_id)
if posthog_user is None:
_reject_non_member_click(integration, channel_id, thread_ts, response_url)
return HttpResponse(status=200)
context_token = _extract_context_token(payload)
if context_token:
cache.delete(_picker_context_cache_key(context_token))
_post_channel_approval_outcome(
integration,
channel_id,
thread_ts,
f"✋ <@{clicker_slack_user_id}> dismissed the PostHog Slack app for this channel. Mention me again to retry.",
)
_delete_ephemeral_via_response_url(response_url)
return HttpResponse(status=200)
# Handles the Dismiss button on inbox notifications delivered before that button was removed.
SIGNALS_DISMISS_REPORT_ACTION_ID = "signals_dismiss_report"
def _dismiss_action_value(payload: dict) -> dict | None:
action = next(
(a for a in payload.get("actions", []) if a.get("action_id") == SIGNALS_DISMISS_REPORT_ACTION_ID), None
)
if not action:
return None
try:
value = json.loads(action.get("value", ""))
except (json.JSONDecodeError, TypeError):
return None
return value if isinstance(value, dict) else None
def _extract_dismiss_hints(payload: dict) -> int | None:
"""Integration id carried by a signals 'Dismiss' button, used for region-ownership routing."""
value = _dismiss_action_value(payload)
if not value:
return None
integration_id = value.get("integration_id")
return integration_id if isinstance(integration_id, int) else None
def _handle_signals_dismiss_report(payload: dict) -> HttpResponse:
"""Suppress a signals inbox report when a reviewer clicks 'Dismiss' in Slack."""
from products.signals.backend.facade.api import ( # noqa: PLC0415 — cross-product action kept off the slack import path
dismiss_report_from_slack,
)
value = _dismiss_action_value(payload)
slack_team_id = payload.get("team", {}).get("id")
if not value or not slack_team_id:
return HttpResponse(status=200)
integration_id = value.get("integration_id")
report_id = value.get("report_id")
report_team_id = value.get("team_id")
if not (isinstance(integration_id, int) and report_id and isinstance(report_team_id, int)):
return HttpResponse(status=200)
# Slack webhook: no team context; scoped by PK + kind + workspace ID. The team match below
# ensures the report belongs to the workspace's integration before we touch it.
integration = get_workspace_integration(integration_id, slack_team_id)
if integration is None:
logger.info("signals_dismiss_report_no_integration", integration_id=integration_id)
return HttpResponse(status=200)
if integration.team_id != report_team_id:
logger.warning(
"signals_dismiss_report_team_mismatch",
integration_team_id=integration.team_id,
report_team_id=report_team_id,
)
return HttpResponse(status=200)
slack_user_id = payload.get("user", {}).get("id", "")
# Only PostHog org members may dismiss — a non-member in a shared channel must not suppress reports.
org_member = _is_org_member(integration, slack_user_id)
if org_member is None:
logger.warning(
"signals_dismiss_report_not_org_member",
integration_id=integration.id,
slack_user_id=slack_user_id,
)
return HttpResponse(status=200)
suppressed = dismiss_report_from_slack(
report_team_id, str(report_id), slack_user_id=slack_user_id, user_id=org_member.id
)
_post_signals_dismiss_feedback(payload, dismissed=suppressed, slack_user_id=slack_user_id)
return HttpResponse(status=200)
def _replace_message_stripping_actions(
payload: dict, text: str, *, keep_link_buttons: bool = True, process_attachments: bool = False
) -> None:
"""Best-effort: replace the original message's interactive buttons with a context line.
When keep_link_buttons is True, link buttons (elements with a "url" key, e.g. "View in
PostHog") are preserved instead of being dropped along with the interactive ones.
"""
response_url = payload.get("response_url")
if not response_url:
return
original_message = payload.get("message", {})
def without_actions(blocks: list[dict]) -> list[dict]:
kept_blocks = []
for block in blocks:
if block.get("type") != "actions":
kept_blocks.append(block)
continue
if keep_link_buttons:
kept_elements = [el for el in block.get("elements", []) if "url" in el]
if kept_elements:
kept_blocks.append({**block, "elements": kept_elements})
return kept_blocks
kept_blocks = without_actions(original_message.get("blocks", []))
kept_blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": text}]})
response: dict = {"replace_original": True, "text": text, "blocks": kept_blocks}
if process_attachments and original_message.get("attachments"):
response["attachments"] = [
{**attachment, "blocks": without_actions(attachment.get("blocks", []))}
for attachment in original_message["attachments"]
]
inbox_interactivity.post_response_url(response_url, response)
def _post_signals_dismiss_feedback(payload: dict, *, dismissed: bool, slack_user_id: str) -> None:
"""Best-effort: replace the original message so it reads as dismissed."""
if dismissed:
actor = f"<@{slack_user_id}>" if slack_user_id else "a reviewer"
text = f"✅ Dismissed by {actor}"
else:
text = "This report could not be dismissed — it may already be resolved or removed."
# keep_link_buttons=False: historical dismiss-capable messages carried "Review PR"/"Open in
# PostHog" link buttons in the same actions block as Dismiss (see the pre-removal
# slack_inbox_notifications.py block construction), so dropping the whole block here matches
# existing behavior rather than the default.
_replace_message_stripping_actions(payload, text, keep_link_buttons=False)
# Snoozes an insight alert from the button on its firing Slack message.
INSIGHT_ALERT_SNOOZE_ACTION_ID = "insight_alert_snooze"
INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID = "insight_alert_snooze_until"
# Slack's datetimepicker element can't carry a custom value, so the alert id rides on the
# actions block's block_id instead (set by the alert-firing sub-template).
INSIGHT_ALERT_SNOOZE_BLOCK_ID_PREFIX = "insight_alert_snooze:"
INSIGHT_ALERT_SNOOZE_DURATION_LABELS: dict[str, str] = {
"1h": "1 hour",
"6h": "6 hours",
"1d": "1 day",
"1w": "1 week",
}
# Dropdown option that opens a modal date/time picker instead of snoozing immediately.
INSIGHT_ALERT_SNOOZE_CUSTOM_TOKEN = "custom"
INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID = "insight_alert_snooze_modal"
INSIGHT_ALERT_SNOOZE_MODAL_DATE_BLOCK = "snooze_date"
INSIGHT_ALERT_SNOOZE_MODAL_TIME_BLOCK = "snooze_time"
def _insight_alert_snooze_action(payload: dict) -> dict | None:
return next(
(
a
for a in payload.get("actions", [])
if a.get("action_id") in (INSIGHT_ALERT_SNOOZE_ACTION_ID, INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID)
),
None,
)
def _parse_insight_alert_snooze_value(value: str) -> tuple[uuid.UUID, str] | None:
parts = value.split("|")
if len(parts) != 2:
return None
alert_uuid_str, duration = parts
if duration not in INSIGHT_ALERT_SNOOZE_DURATION_LABELS and duration != INSIGHT_ALERT_SNOOZE_CUSTOM_TOKEN:
return None
try:
alert_uuid = uuid.UUID(alert_uuid_str)
except (ValueError, AttributeError, TypeError):
return None
return alert_uuid, duration
def _parse_insight_alert_snooze_action(action: dict) -> tuple[uuid.UUID, str | None, datetime | None] | None:
"""Normalize the three snooze action shapes to (alert_uuid, duration_token, until).
Shapes: the preset static_select (value on selected_option), the legacy single button from
already-posted messages (value on the action itself), and the datetimepicker (unix timestamp
on selected_date_time, alert id on the block_id).
"""
if action.get("action_id") == INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID:
block_id = action.get("block_id", "")
if not isinstance(block_id, str) or not block_id.startswith(INSIGHT_ALERT_SNOOZE_BLOCK_ID_PREFIX):
return None
try:
alert_uuid = uuid.UUID(block_id[len(INSIGHT_ALERT_SNOOZE_BLOCK_ID_PREFIX) :])
except (ValueError, AttributeError, TypeError):
return None
selected = action.get("selected_date_time")
if not isinstance(selected, int):
return None
try:
until = datetime.fromtimestamp(selected, tz=UTC)
except (OverflowError, OSError, ValueError):
return None
return alert_uuid, None, until
selected_option = action.get("selected_option")
value = selected_option.get("value") if isinstance(selected_option, dict) else action.get("value", "")
if not isinstance(value, str):
return None
parsed = _parse_insight_alert_snooze_value(value)
if parsed is None:
return None
return parsed[0], parsed[1], None
def _snooze_modal_alert_uuid(view: dict) -> uuid.UUID | None:
"""Alert UUID stashed in the snooze modal's private_metadata."""
try:
meta = json.loads(view.get("private_metadata", "") or "{}")
return uuid.UUID(meta.get("alert_id"))
except (json.JSONDecodeError, TypeError, ValueError, AttributeError):
return None
def _extract_alert_snooze_hints(payload: dict) -> uuid.UUID | None:
"""Alert UUID carried by a snooze interaction, used for region-ownership routing.
Covers both the dropdown/button block_actions and the date/time modal's view_submission
(which carries the alert id in private_metadata, not in an action).
"""
view = payload.get("view")
if isinstance(view, dict) and view.get("callback_id") == INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID:
return _snooze_modal_alert_uuid(view)
action = _insight_alert_snooze_action(payload)
if not action:
return None
parsed = _parse_insight_alert_snooze_action(action)
return parsed[0] if parsed else None
def _handle_insight_alert_snooze(payload: dict) -> HttpResponse:
"""Snooze an insight alert when a user clicks 'Snooze' on its firing Slack message.
Only Slack-side concerns live here (parsing, workspace-integration match, org membership) —
alert-side authorization and the mutation itself belong to products.alerts and are reached
through its facade, never a direct cross-product model import (see tach.toml).
"""
action = _insight_alert_snooze_action(payload)
slack_team_id = payload.get("team", {}).get("id")
if not action or not slack_team_id:
return HttpResponse(status=200)
parsed = _parse_insight_alert_snooze_action(action)
if parsed is None:
logger.info("insight_alert_snooze_malformed_value")
return HttpResponse(status=200)
alert_uuid, duration, until = parsed
from products.alerts.backend.facade.api import ( # noqa: PLC0415 — cross-product calls kept off the slack import path
SLACK_SNOOZE_MAX_DAYS,
get_alert_team_id,
snooze_alert_from_slack,
)
alert_team_id = get_alert_team_id(alert_uuid)
if alert_team_id is None:
logger.info("insight_alert_snooze_no_alert", alert_id=str(alert_uuid))
return HttpResponse(status=200)
# Proves the Slack workspace the click came from is connected to the alert's team.
integration = get_team_workspace_integration(alert_team_id, slack_team_id)
if integration is None:
logger.info("insight_alert_snooze_no_integration", alert_id=str(alert_uuid), slack_team_id=slack_team_id)
return HttpResponse(status=200)
slack_user_id = payload.get("user", {}).get("id", "")
org_member = _is_org_member(integration, slack_user_id)
if org_member is None:
logger.warning("insight_alert_snooze_not_org_member", alert_id=str(alert_uuid), slack_user_id=slack_user_id)
return HttpResponse(status=200)
# "Pick a date & time…" opens a modal instead of snoozing now. The real snooze happens on
# modal submit (_handle_insight_alert_snooze_modal_submit), which re-runs this same auth.
if duration == INSIGHT_ALERT_SNOOZE_CUSTOM_TOKEN:
_open_insight_alert_snooze_modal(integration, payload, alert_uuid)
return HttpResponse(status=200)
# Everything below this point is untrusted alert_id/duration re-derived from the alert row
# itself, not the Slack button value — see snooze_alert_from_slack's docstring.
outcome = snooze_alert_from_slack(alert_uuid, duration=duration, until=until, user=org_member)
if outcome == "not_found":
# Existed at get_alert_team_id but is gone now (race, e.g. concurrent delete) — same
# silent drop as the earlier not-found check.
logger.info("insight_alert_snooze_no_alert", alert_id=str(alert_uuid))
return HttpResponse(status=200)
if outcome == "no_access":
logger.warning("insight_alert_snooze_no_access", alert_id=str(alert_uuid), slack_user_id=slack_user_id)
return HttpResponse(status=200)
if outcome == "disabled":
logger.info("insight_alert_snooze_alert_disabled", alert_id=str(alert_uuid))
_replace_message_stripping_actions(
payload, "This alert is disabled, so there is nothing to snooze.", process_attachments=True
)
return HttpResponse(status=200)
if outcome == "not_snoozable":
logger.warning("insight_alert_snooze_refused_by_platform", alert_id=str(alert_uuid))
response_url = payload.get("response_url")
if response_url:
inbox_interactivity.post_response_url(
response_url,
{"response_type": "ephemeral", "replace_original": False, "text": NOT_SNOOZABLE_FROM_SLACK},
)
return HttpResponse(status=200)
if outcome == "invalid_until":
logger.info("insight_alert_snooze_invalid_until", alert_id=str(alert_uuid))
response_url = payload.get("response_url")
if response_url:
# Ephemeral so a bad pick doesn't clobber the alert message — the pickers stay usable.
inbox_interactivity.post_response_url(
response_url,
{
"response_type": "ephemeral",
"replace_original": False,
"text": f"Pick a time in the next {SLACK_SNOOZE_MAX_DAYS} days.",
},
)
return HttpResponse(status=200)
if duration is not None:
snoozed_wording = f"for {INSIGHT_ALERT_SNOOZE_DURATION_LABELS[duration]}"
else:
assert until is not None
snoozed_wording = f"until {until.strftime('%Y-%m-%d %H:%M')} UTC"
actor = f"<@{slack_user_id}>" if slack_user_id else "a teammate"
_replace_message_stripping_actions(payload, f"😴 Snoozed {snoozed_wording} by {actor}", process_attachments=True)
return HttpResponse(status=200)
def _render_insight_alert_snooze_modal(private_metadata: str) -> dict:
tomorrow = (timezone.now() + timedelta(days=1)).date().isoformat()
return {
"type": "modal",
"callback_id": INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID,
"private_metadata": private_metadata,
"title": {"type": "plain_text", "text": "Snooze alert"},
"submit": {"type": "plain_text", "text": "Snooze"},
"close": {"type": "plain_text", "text": "Cancel"},
"blocks": [
{
"type": "input",
"block_id": INSIGHT_ALERT_SNOOZE_MODAL_DATE_BLOCK,
"label": {"type": "plain_text", "text": "Snooze until date"},
"element": {"type": "datepicker", "action_id": "date", "initial_date": tomorrow},
},
{
"type": "input",
"block_id": INSIGHT_ALERT_SNOOZE_MODAL_TIME_BLOCK,
"label": {"type": "plain_text", "text": "Time (UTC)"},
"element": {"type": "timepicker", "action_id": "time", "initial_time": "09:00"},
},
],
}
def _open_insight_alert_snooze_modal(integration: WorkspaceIntegration, payload: dict, alert_uuid: uuid.UUID) -> None:
trigger_id = payload.get("trigger_id")
if not trigger_id:
return
container = payload.get("container", {}) or {}
private_metadata = json.dumps(
{
"alert_id": str(alert_uuid),
"channel": (payload.get("channel") or {}).get("id") or container.get("channel_id"),
"message_ts": (payload.get("message") or {}).get("ts") or container.get("message_ts"),
}
)
try:
SlackIntegration(integration).client.views_open(
trigger_id=trigger_id, view=_render_insight_alert_snooze_modal(private_metadata)
)
except Exception:
logger.exception("insight_alert_snooze_modal_open_failed", alert_id=str(alert_uuid))
def _snooze_modal_error(message: str) -> JsonResponse:
# A view_submission error keeps the modal open and shows the message under the date field.
return JsonResponse({"response_action": "errors", "errors": {INSIGHT_ALERT_SNOOZE_MODAL_DATE_BLOCK: message}})
def _handle_insight_alert_snooze_modal_submit(payload: dict) -> HttpResponse:
"""Snooze an alert to the date/time picked in the modal opened from the 'Pick a date & time…'
dropdown option. Re-runs the same workspace/org authorization the block-action path does —
a modal can be submitted by anyone who has it open, so the submit is the authoritative gate.
"""
view = payload.get("view", {})
try:
meta = json.loads(view.get("private_metadata", "") or "{}")
alert_uuid = uuid.UUID(meta.get("alert_id"))
except (json.JSONDecodeError, TypeError, ValueError, AttributeError):
return HttpResponse(status=200)
values = view.get("state", {}).get("values", {})
selected_date = values.get(INSIGHT_ALERT_SNOOZE_MODAL_DATE_BLOCK, {}).get("date", {}).get("selected_date")
selected_time = values.get(INSIGHT_ALERT_SNOOZE_MODAL_TIME_BLOCK, {}).get("time", {}).get("selected_time")
if not selected_date or not selected_time:
return _snooze_modal_error("Pick a date and time.")
try:
until = datetime.strptime(f"{selected_date} {selected_time}", "%Y-%m-%d %H:%M").replace(tzinfo=UTC)
except ValueError:
return _snooze_modal_error("Pick a date and time.")
slack_team_id = payload.get("team", {}).get("id")
slack_user_id = payload.get("user", {}).get("id", "")
from products.alerts.backend.facade.api import ( # noqa: PLC0415 — cross-product calls kept off the slack import path
SLACK_SNOOZE_MAX_DAYS,
get_alert_team_id,
snooze_alert_from_slack,
)
alert_team_id = get_alert_team_id(alert_uuid)
if alert_team_id is None or not slack_team_id:
return HttpResponse(status=200)
integration = get_team_workspace_integration(alert_team_id, slack_team_id)
if integration is None:
return HttpResponse(status=200)
org_member = _is_org_member(integration, slack_user_id)
if org_member is None:
return _snooze_modal_error("You don't have access to this alert.")
outcome = snooze_alert_from_slack(alert_uuid, until=until, user=org_member)
if outcome == "invalid_until":
return _snooze_modal_error(f"Pick a time in the next {SLACK_SNOOZE_MAX_DAYS} days.")
if outcome == "not_snoozable":
return _snooze_modal_error(NOT_SNOOZABLE_FROM_SLACK)
if outcome in ("no_access", "not_found", "disabled"):
logger.info("insight_alert_snooze_modal_submit_rejected", alert_id=str(alert_uuid), outcome=outcome)
return HttpResponse(status=200)
_post_insight_alert_snooze_modal_confirmation(integration, meta, until, slack_user_id)
return HttpResponse(status=200)
def _post_insight_alert_snooze_modal_confirmation(
integration: WorkspaceIntegration, meta: dict, until: datetime, slack_user_id: str
) -> None:
channel = meta.get("channel")
if not channel:
return
actor = f"<@{slack_user_id}>" if slack_user_id else "a teammate"
text = f"😴 Snoozed until {until.strftime('%Y-%m-%d %H:%M')} UTC by {actor}"
try:
# Insight-alert surface: anchored on the alert the bot posted, not on an @PostHog prompt.
SlackIntegration(integration).client.chat_postMessage(
channel=channel, thread_ts=meta.get("message_ts"), text=text
)
except Exception:
logger.warning("insight_alert_snooze_modal_confirm_failed")
def _handle_fork_thread_submit(payload: dict) -> HttpResponse:
"""Hand the fork to Temporal and ack immediately.
Everything the fork does — resolving the user, reading the thread, opening the DM —
is too slow for Slack's three-second interactivity budget, so this only dispatches.
The id is keyed on the thread being forked, not the reply the menu hangs off, so
forking twice from the same discussion reuses the running fork instead of opening a
second DM about it.
"""
message = payload.get("message", {}) or {}
team_id = payload.get("team", {}).get("id", "")
user_id = payload.get("user", {}).get("id", "")
source_ts = message.get("thread_ts") or message.get("ts", "")
workflow_id = f"slack-app-fork-thread:{team_id}:{user_id}:{source_ts}"
try:
client = sync_connect()
asyncio.run(
client.start_workflow(
SlackAppForkThreadWorkflow.run,
SlackAppForkThreadInputs(payload=payload),
id=workflow_id,
task_queue=settings.TASKS_TASK_QUEUE,
id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
)
)
except Exception as e:
logger.warning("slack_app_fork_submit_start_failed", workflow_id=workflow_id, error=str(e))
return HttpResponse(status=200)
@csrf_exempt
def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
if request.method != "POST":
return HttpResponse(status=405)
try:
slack_config = SlackIntegration.slack_config()
validate_slack_request(request, slack_config["SLACK_APP_SIGNING_SECRET"])
except SlackIntegrationError as e:
logger.warning("slack_app_interactivity_invalid_request", error=str(e))
return HttpResponse("Invalid request", status=403)
try:
payload = json.loads(request.POST.get("payload", "{}"))
except json.JSONDecodeError:
return HttpResponse("Invalid JSON", status=400)
payload_type = payload.get("type")
context_token = _extract_context_token(payload)
logger.info(
"slack_app_interactivity_received",
payload_type=payload_type,
context_token=context_token,
host=request.get_host(),
)
# Check if we own this context locally
context = _decode_picker_context(context_token) if context_token else None
hinted_integration_id, hinted_user_id = _extract_picker_hints(payload)
dismiss_integration_id = _extract_dismiss_hints(payload)
alert_snooze_uuid = _extract_alert_snooze_hints(payload)
inbox_integration_id = inbox_interactivity.extract_inbox_hints(payload)
project_picker_integration_id = project_picker.picked_integration_id(payload)
# Both controls a reply carries, the modal a thumbs-down opens, and the reply suggestions claim
# the same workspace, so one hint serves all of them. The modal and the suggestions need their
# own extractors: a view submission carries no action, and each suggestion has its own action id.
clicked_reply_suggestion = reply_suggestions.clicked_suggestion(payload)
reply_control_integration_id = (
_extract_action_value_hints(payload, FORK_THREAD_ACTION_ID)[0]
or _extract_action_value_hints(payload, TURN_FEEDBACK_ACTION_ID)[0]
or turn_feedback.extract_modal_hint(payload)
or (clicked_reply_suggestion.integration_id if clicked_reply_suggestion else None)
or feature_tip_interactivity.feature_tip_integration_hint(payload)
or interview_recruitment.interview_integration_hint(payload)
or onboarding_interactivity.onboarding_integration_hint(payload)
)
requesting_user = payload.get("user", {}).get("id", "")
slack_team_id = payload.get("team", {}).get("id")
local = False
ctx_integration_id = context.get("integration_id") if context else None
# Slack webhook endpoint: no team context available; queries are scoped by PK + kind + workspace ID
if slack_team_id and ctx_integration_id:
local = workspace_integration_exists(ctx_integration_id, slack_team_id)
elif slack_team_id and hinted_integration_id and hinted_user_id and requesting_user == hinted_user_id:
local = workspace_integration_exists(hinted_integration_id, slack_team_id)
elif slack_team_id and dismiss_integration_id:
# Routing/region-ownership only — this just claims the workspace's integration locally.
# Authorization (report-team match + org-member gate) is enforced in _handle_signals_dismiss_report.
# Intended trust boundary for dismiss is org membership (any org member can dismiss the org's reports).
local = workspace_integration_exists(dismiss_integration_id, slack_team_id)
elif slack_team_id and alert_snooze_uuid:
# Alert UUIDs are globally unique per region (each region has its own DB), so a local
# existence check alone settles region ownership — no need to consult Integration here.
# Authorization (workspace-integration match + org-member gate) is enforced in
# _handle_insight_alert_snooze. Routed through the alerts facade rather than the model
# directly — see tach.toml, products.slack_app doesn't depend on products.alerts's internals.
from products.alerts.backend.facade.api import ( # noqa: PLC0415 — cross-product lookup kept off the slack import path
get_alert_team_id,
)
local = get_alert_team_id(alert_snooze_uuid) is not None
elif slack_team_id and inbox_integration_id:
# Inbox onboarding buttons (create/join) are DMed to a user; any clicker may act, so this
# is gated only on owning the integration locally.
local = workspace_integration_exists(inbox_integration_id, slack_team_id)
elif slack_team_id and project_picker_integration_id:
# Reached once the context expired, so that the handler can tell the person.
local = workspace_integration_exists(project_picker_integration_id, slack_team_id)
elif slack_team_id and _is_ai_preferences_interactivity(payload, payload_type):
# App Home AI-settings actions (Edit/Reset/Save) and the modal
# re-render dispatched_actions carry no per-row hint — the button is
# tied to the workspace, not a specific picker context. Claim locality
# based on the workspace integration alone; if we own *any* Integration
# for this Slack team, the click is ours to handle.
local = bool(workspace_integrations(slack_team_id))
elif slack_team_id and reply_control_integration_id:
# The fork menu and the thumbs ride on a bot reply anyone in the thread can see, so
# any reader may use them, and the same goes for the modal a thumbs-down opens.
# Routing only claims the workspace; who the fork runs as, and whether they may, is
# settled in the fork activity, and a rating is matched to its run in the feedback
# handler.
local = workspace_integration_exists(reply_control_integration_id, slack_team_id)
proxied = was_proxied(request)
incoming_host = request.get_host()
logger.info(
"slack_app_interactivity_resolution",
context_token_present=bool(context_token),
has_context=bool(context),
hinted_integration_id=hinted_integration_id,
requesting_user=requesting_user,
hinted_user=hinted_user_id,
local=local,
host=incoming_host,
proxied=proxied,
)
if not local and not proxied and cross_region_routing_enabled():
# The payload's integration_id pinpoints exactly one row, so a lookup would tell us
# nothing new — just forward to the other region. The loop header keeps us at one hop.
# Skipped in single-region deployments (local dev, hosted dev, E2E, self-hosted) where
# there is no other region to talk to.
target = other_region_domain(incoming_host)
upstream = _proxy_event_to_region(request, target)
if upstream is not None:
logger.info(
"slack_app_interactivity_route",
outcome="proxied",
from_host=incoming_host,
to_domain=target,
payload_type=payload_type,
)
return HttpResponse(
upstream.content,
status=upstream.status_code,
content_type=upstream.headers.get("Content-Type", "application/json"),
)
# Proxy failed — return safe defaults
logger.warning(
"slack_app_interactivity_route",
outcome="proxy_failed",
from_host=incoming_host,
to_domain=target,
payload_type=payload_type,
)
if payload_type == "block_suggestion":
return JsonResponse({"options": []})
return HttpResponse(status=502)
if not local:
logger.warning(
"slack_app_interactivity_route",
outcome="dropped",
from_host=incoming_host,
payload_type=payload_type,
context_token=context_token,
)
if payload_type == "block_suggestion":
return JsonResponse({"options": []})
return HttpResponse(status=200)
logger.info(
"slack_app_interactivity_route",
outcome="handled",
from_host=incoming_host,
payload_type=payload_type,
)
# Handled locally
if payload_type == "block_suggestion":
return _handle_repo_picker_options(payload)
if payload_type == "view_submission":
callback_id = payload.get("view", {}).get("callback_id")
if callback_id == INSIGHT_ALERT_SNOOZE_MODAL_CALLBACK_ID:
return _handle_insight_alert_snooze_modal_submit(payload)
if callback_id == turn_feedback.TURN_FEEDBACK_MODAL_CALLBACK_ID:
return turn_feedback.handle_turn_feedback_modal_submit(payload)
return _handle_app_home_view_submission(payload)
if payload_type == "block_actions":
actions = payload.get("actions", [])
for action in actions:
action_id = action.get("action_id")
if action_id == "posthog_code_repo_select":
return _handle_repo_picker_submit(payload)
if action_id == "posthog_code_repo_none":
return _handle_no_repo_needed_submit(payload)
if action_id == FORK_THREAD_ACTION_ID:
return _handle_fork_thread_submit(payload)
if action_id == TURN_FEEDBACK_ACTION_ID:
return turn_feedback.handle_turn_feedback_click(payload)
if feature_tip_interactivity.is_feature_tip_action(action_id):
return feature_tip_interactivity.handle_feature_tip_action(payload)
if interview_recruitment.is_interview_action(action_id):
return interview_recruitment.handle_interview_action(payload)
if 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:
return _handle_channel_approval_submit(payload)
if action_id == CHANNEL_APPROVAL_ACTION_DENY:
return _handle_channel_approval_deny(payload)
if action_id == UNTAGGED_FOLLOWUP_ACTION_RUN:
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:
return _handle_untagged_question_dismiss(payload)
if action_id == UNTAGGED_QUESTION_ACTION_TURN_OFF:
return _handle_untagged_question_turn_off(payload)
if project_picker.is_project_picker_action(action_id):
return _handle_project_picker_pick(payload)
if action_id == SIGNALS_DISMISS_REPORT_ACTION_ID:
return _handle_signals_dismiss_report(payload)
if action_id in (INSIGHT_ALERT_SNOOZE_ACTION_ID, INSIGHT_ALERT_SNOOZE_UNTIL_ACTION_ID):
return _handle_insight_alert_snooze(payload)
if action_id == slack_welcome_messages.INBOX_CREATE_ACTION_ID:
return inbox_interactivity.handle_inbox_create(payload)
if action_id == slack_welcome_messages.INBOX_JOIN_ACTION_ID:
return inbox_interactivity.handle_inbox_join(payload)
if action_id == slack_welcome_messages.INBOX_SOURCES_CHECKBOXES_ACTION:
return inbox_interactivity.handle_inbox_sources(payload)
if action_id == slack_welcome_messages.INBOX_AI_APPROVAL_ACTION_ID:
return inbox_interactivity.handle_inbox_ai_approval(payload)
if action_id in _AI_PREFERENCES_ACTION_IDS:
return _handle_ai_preferences_block_action(payload, action)
return HttpResponse(status=200)