Skip to content

: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.

fix(slack_app): make silent mention drops observable and answerable (#74673)

posthog[bot]2c3957eb65de
diff --git a/posthog/temporal/ai/slack_app/slack_app_mention.py b/posthog/temporal/ai/slack_app/slack_app_mention.py
index 1f1d474cf19d..e7ff8e68dcb7 100644
--- a/posthog/temporal/ai/slack_app/slack_app_mention.py
+++ b/posthog/temporal/ai/slack_app/slack_app_mention.py
@@ -10,6 +10,7 @@ from posthog.temporal.ai.slack_app import (
derive_mention_workflow_id,
mark_slack_app_message_processing_activity,
mark_slack_app_message_queued_activity,
+ post_posthog_code_internal_error_activity,
)
from posthog.temporal.ai.slack_app.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflow
from posthog.temporal.ai.slack_app.types import (
@@ -33,6 +34,16 @@ SLACK_APP_MENTION_MAX_PROCESSED_KEYS = 200
# workflows complete after a 30 second idle timeout.
SLACK_APP_MENTION_SEED_IN_INIT_PATCH = "slack-app-mention-seed-in-init"
+# The queue awaits each child serially, so a child that never completes stalls every
+# later message in the conversation and the user sees nothing but an :eyes: reaction
+# that never resolves. The ceiling sits above any healthy run: the child's own waits
+# (15 minutes for the repo picker, 15 more for authorship confirmation) plus its
+# 10-minute activity timeouts stay well inside an hour.
+SLACK_APP_MENTION_CHILD_EXECUTION_TIMEOUT = timedelta(hours=1)
+# Bounding the child and telling the user when it dies both add workflow commands, so
+# executions started before this shipped keep replaying the unbounded, silent path.
+SLACK_APP_MENTION_CHILD_TIMEOUT_PATCH = "slack-app-mention-child-timeout"
+
def derive_slack_app_mention_workflow_id(inputs: PostHogCodeSlackMentionWorkflowInputs) -> str | None:
"""Conversation-scoped workflow ID: one per thread (or DM thread).
@@ -142,6 +153,29 @@ class SlackAppMentionWorkflow(PostHogWorkflow):
# timeout. Cosmetic either way — never stall the queue for it.
workflow.logger.warning("slack_app_reaction_activity_failed")
+ async def _notify_child_failed(self, message: PostHogCodeSlackMentionWorkflowInputs) -> None:
+ """Tell the thread the message won't be answered.
+
+ The child normally posts its own internal-error reply, but it cannot when it
+ is killed from the outside (execution timeout, termination), which is exactly
+ the case where the user has been staring at an unanswered mention. Untagged
+ followups stay silent for the same reason they get no reactions: they were
+ never addressed to the bot.
+ """
+ channel = message.event.get("channel")
+ thread_ts = message.event.get("thread_ts") or message.event.get("ts")
+ if message.untagged_followup or not channel or not thread_ts:
+ return
+ try:
+ await workflow.execute_activity(
+ post_posthog_code_internal_error_activity,
+ args=[message, channel, thread_ts],
+ start_to_close_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ except exceptions.ActivityError:
+ workflow.logger.warning("slack_app_mention_child_failure_notice_failed")
+
async def _process(self, message: PostHogCodeSlackMentionWorkflowInputs) -> None:
"""Run one message to completion as a child workflow.
@@ -151,6 +185,7 @@ class SlackAppMentionWorkflow(PostHogWorkflow):
ALLOW_DUPLICATE mirrors the standalone dispatch's reuse policy for
retries that outlive this instance's dedup keys.
"""
+ bounded = workflow.patched(SLACK_APP_MENTION_CHILD_TIMEOUT_PATCH)
try:
# The default parent close policy (terminate) is deliberate: an
# operator killing this queue means "stop this conversation", so
@@ -162,6 +197,7 @@ class SlackAppMentionWorkflow(PostHogWorkflow):
message,
id=derive_mention_workflow_id(message),
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ execution_timeout=SLACK_APP_MENTION_CHILD_EXECUTION_TIMEOUT if bounded else None,
)
except exceptions.WorkflowAlreadyStartedError:
# A standalone execution for this exact message is already
@@ -173,6 +209,8 @@ class SlackAppMentionWorkflow(PostHogWorkflow):
# expected to fail; this backstop keeps one poisoned message from
# wedging the conversation's queue.
workflow.logger.exception("slack_app_mention_child_failed")
+ if bounded:
+ await self._notify_child_failed(message)
@workflow.run
async def run(self, inputs: SlackAppMentionWorkflowInputs) -> None:
diff --git a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
index 994fbce2fc8f..27473f2080cd 100644
--- a/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
+++ b/posthog/temporal/tests/ai/slack_app/test_slack_app_mention_workflow.py
@@ -1,6 +1,7 @@
import os
import uuid
import asyncio
+from datetime import timedelta
from typing import Any, Literal
import pytest
@@ -10,7 +11,7 @@ from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicy
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
-from posthog.temporal.ai.slack_app import derive_mention_workflow_id
+from posthog.temporal.ai.slack_app import derive_mention_workflow_id, slack_app_mention
from posthog.temporal.ai.slack_app.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflow
from posthog.temporal.ai.slack_app.slack_app_mention import SlackAppMentionWorkflow
from posthog.temporal.ai.slack_app.types import (
@@ -48,6 +49,8 @@ class _Recorder:
self.processing_marked: list[str] = []
# ts per forwarded followup, in execution order.
self.forwarded: list[str] = []
+ # ts per internal-error notice posted back to the thread, in execution order.
+ self.internal_errors: list[str] = []
# ts -> forward result; missing means False (no existing task, fall through to new-task path).
self.forward_results: dict[str, bool] = {}
# ts -> cascade mode; missing means "auto" with a fixed repository.
@@ -188,7 +191,7 @@ def _fake_activities(rec: _Recorder) -> list:
@activity.defn(name="post_posthog_code_internal_error_activity")
async def internal_error(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> None:
- return None
+ rec.internal_errors.append(inputs.event["ts"])
@activity.defn(name="resolve_posthog_code_slack_user_activity")
async def resolve_user(
@@ -407,6 +410,27 @@ async def test_repo_picker_signal_resolves_and_queue_continues():
assert rec.created == [("1.1", "org/picked"), ("1.2", "org/auto-repo")]
+async def test_hung_child_times_out_and_queue_continues(monkeypatch):
+ # A child that never finishes used to stall the conversation forever: the queue
+ # awaits it serially, so every later message in the thread sat behind it with no
+ # reply and no explanation. Shortened here so the time-skipping server reaches the
+ # execution timeout before the child's own 15-minute picker wait.
+ monkeypatch.setattr(slack_app_mention, "SLACK_APP_MENTION_CHILD_EXECUTION_TIMEOUT", timedelta(minutes=5))
+ rec = _Recorder()
+ rec.cascade_modes["1.1"] = "agent_needed"
+
+ async with _Harness(rec) as h:
+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", _message("1.1"))
+ # The first message parks on the repo picker and is never answered.
+ await asyncio.wait_for(rec.picker_posted.wait(), timeout=30)
+ await handle.signal(SlackAppMentionWorkflow.new_message, _message("1.2"))
+ await asyncio.wait_for(handle.result(), timeout=60)
+
+ assert rec.created == [("1.2", "org/auto-repo")]
+ assert rec.internal_errors == ["1.1"]
+
+
@pytest.mark.asyncio
async def test_continue_as_new_carry_over_processes_pending_and_dedups_seen():
rec = _Recorder()
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 5b7dbf119cb8..1b1454024ce2 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -136,6 +136,16 @@ 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"
+
+# Ceiling on a feedback post made from inside the webhook request path, matching
+# _count_session_thread_messages. Slack's retry window is what we're protecting.
+SLACK_FEEDBACK_TIMEOUT_SECONDS = 3
+
PICKER_TOKEN_SALT = "posthog_code_repo_picker"
PICKER_TOKEN_MAX_AGE_SECONDS = 900
@@ -280,11 +290,13 @@ def _post_slack_user_feedback(
text: str,
*,
prefer_thread_message: bool = False,
-) -> None:
+) -> 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."""
if prefer_thread_message:
try:
slack.client.chat_postMessage(channel=channel, thread_ts=thread_ts, text=text)
- return
+ return True
except Exception:
logger.warning("slack_user_feedback_thread_post_failed", channel=channel, slack_user_id=slack_user_id)
@@ -295,6 +307,41 @@ def _post_slack_user_feedback(
slack.client.chat_postMessage(channel=channel, thread_ts=thread_ts, text=text)
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_FEEDBACK_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(
@@ -1079,27 +1126,43 @@ def _resolve_pending_repo_picker_from_followup(event: dict[str, Any], integratio
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
+
+
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": the message was authored by another Slack app/bot. Foreign bots
+ - "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.
"""
if event.get("edited") or event.get("subtype") == "message_changed":
return "edit"
- if (
- event.get("bot_id")
- or event.get("bot_profile")
- or event.get("app_id")
- or event.get("subtype") == "bot_message"
- or event.get("user") == "USLACKBOT"
- ):
- return "bot_author"
- return None
+ return _app_authorship_ignore_reason(event)
def _thread_message_event_has_files(event: dict[str, Any]) -> bool:
@@ -1127,14 +1190,9 @@ def _thread_message_ignore_reason(event: dict[str, Any]) -> str | None:
return "edit"
if event.get("subtype") == "message_deleted":
return "deleted"
- if (
- event.get("bot_id")
- or event.get("bot_profile")
- or event.get("app_id")
- or event.get("subtype") == "bot_message"
- or event.get("user") == "USLACKBOT"
- ):
- return "bot_author"
+ 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
@@ -1191,11 +1249,14 @@ def _notify_missing_slack_scopes(
slack: SlackIntegration,
event: dict,
missing: frozenset[str],
-) -> None:
+) -> 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", "")
@@ -1210,7 +1271,7 @@ def _notify_missing_slack_scopes(
)
if not channel or not thread_ts or not slack_user_id:
- return
+ return False
settings_url = f"{settings.SITE_URL}/integrations/slack"
text = (
@@ -1219,7 +1280,7 @@ def _notify_missing_slack_scopes(
f"A project admin needs to reconnect Slack from project settings: {settings_url}"
)
- _post_slack_user_feedback(slack, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
+ 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: Integration, slack_user_id: str) -> str | None:
@@ -1361,26 +1422,29 @@ def _post_pick_a_project_hint(
probe: SlackIntegration,
candidates: list[Integration],
event: dict[str, Any],
-) -> None:
+) -> bool:
"""Tell the user that this workspace is connected to multiple PostHog
projects, and that they should pick one.
The selection command differs by surface: in a channel the user mentions the app
(`@PostHog project <id>`), but in a DM there is no app to mention, so they just reply
with `project <id>`.
+
+ 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
+ return False
pick_command = "`project <id>`" if event.get("channel_type") == "im" else "`@PostHog project <id>`"
text = (
"This Slack workspace is connected to multiple PostHog projects:\n"
f"{format_project_candidate_list(candidates)}\n\n"
f"Use {pick_command} to pick one — that also saves it as your default."
)
- _post_slack_user_feedback(probe, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
+ return _post_slack_user_feedback(probe, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
def _post_user_resolution_failure_reply(
@@ -1391,7 +1455,9 @@ def _post_user_resolution_failure_reply(
thread_ts: str | None,
failure_reason: UserResolutionFailure | None,
slack_email: str | None,
-) -> 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
@@ -1399,19 +1465,35 @@ def _post_user_resolution_failure_reply(
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
+ return False
text = user_resolution_failure_reply(failure_reason, slack_email=slack_email)
if text is None:
- return
+ 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.
- _post_slack_user_feedback(slack_client, channel, slack_user_id, thread_ts, text, prefer_thread_message=True)
+ 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 is_slack_app_oauth_enabled(probe, probe.integration_id):
invite_url = build_invite_url(
slack_user_id=slack_user_id,
@@ -1428,6 +1510,7 @@ def _post_user_resolution_failure_reply(
slack_email=slack_email,
invite_url=invite_url,
)
+ return posted
def _start_posthog_code_workflow(
@@ -1755,6 +1838,7 @@ def route_posthog_code_event_to_relevant_region(
channel=event.get("channel"),
message_ts=event.get("ts"),
)
+ _report_slack_mention_dropped(event, slack_team_id, reason=f"ignored:{ignore_reason}", replied=False)
return ROUTE_HANDLED_LOCALLY
else:
ignore_reason = _thread_message_ignore_reason(event)
@@ -1776,6 +1860,9 @@ def route_posthog_code_event_to_relevant_region(
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``
@@ -1799,6 +1886,12 @@ def route_posthog_code_event_to_relevant_region(
can_defer=can_defer_to_other_region,
)
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
# Threads we don't own (and orgs that haven't opted in) are dropped here
@@ -1834,25 +1927,48 @@ def route_posthog_code_event_to_relevant_region(
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,
+ )
return ROUTE_HANDLED_LOCALLY
- # Skip the failure reply in an unapproved externally-shared channel —
- # the channel hasn't opted in yet, so a public "Sorry, I couldn't
- # find <email>" post would leak the integration's existence to
- # non-org members. Still capture the mention analytics-side so the
- # unknown-user funnel keeps reporting (it ran on every mention before
- # this PR moved resolution up).
+ # 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]
- _report_slack_mention_received(event, probe, slack_team_id, posthog_user=None)
+ # ``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
- if not (is_ext_shared_channel and channel_id and not _channel_is_approved(slack_team_id, channel_id)):
- _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 = 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,
+ )
return ROUTE_HANDLED_LOCALLY
posthog_user = resolution.user
@@ -1882,10 +1998,30 @@ def route_posthog_code_event_to_relevant_region(
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:
- _post_pick_a_project_hint(SlackIntegration(candidates[0]), candidates, event)
+ replied = _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),
+ )
return ROUTE_HANDLED_LOCALLY
slack = SlackIntegration(mention_target)
@@ -1897,8 +2033,17 @@ def route_posthog_code_event_to_relevant_region(
slack_team_id=slack_team_id,
integration_id=mention_target.id,
)
- return ROUTE_HANDLED_LOCALLY
- _notify_missing_slack_scopes(slack, event, missing)
+ 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
@@ -1909,8 +2054,17 @@ def route_posthog_code_event_to_relevant_region(
slack_team_id=slack_team_id,
channel=channel_id,
)
- return ROUTE_HANDLED_LOCALLY
- _post_channel_approval_prompt(slack, mention_target, event)
+ 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
return _start_mention_workflow(
@@ -2253,7 +2407,7 @@ def _post_channel_approval_prompt(
slack: SlackIntegration,
integration: Integration,
event: dict[str, Any],
-) -> None:
+) -> bool:
"""Post the approval prompt as an ephemeral message to the mentioner.
The prompt itself stays ephemeral — only the mentioner sees the
@@ -2266,11 +2420,14 @@ def _post_channel_approval_prompt(
``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
+ 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
@@ -2349,6 +2506,8 @@ def _post_channel_approval_prompt(
slack_channel_id=channel,
exc_info=True,
)
+ return False
+ return True
def _report_slack_mention_received(
@@ -2357,9 +2516,13 @@ def _report_slack_mention_received(
slack_team_id: str,
*,
posthog_user: User | None = None,
-) -> None:
+) -> 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
@@ -2412,6 +2575,7 @@ def _report_slack_mention_received(
groups=groups(team=integration.team),
send_feature_flags=True,
)
+ return posthog_user
except Exception:
logger.warning(
"slack_app_mention_analytics_failed",
@@ -2419,6 +2583,69 @@ def _report_slack_mention_received(
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: Integration | 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": f"{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_mention_workflow(
diff --git a/products/slack_app/backend/tests/test_posthog_code_event_handler.py b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
index 952e99e462b2..4fea35751292 100644
--- a/products/slack_app/backend/tests/test_posthog_code_event_handler.py
+++ b/products/slack_app/backend/tests/test_posthog_code_event_handler.py
@@ -1,16 +1,16 @@
import json
-from typing import Any
+from typing import Any, cast
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.core.cache import cache
-from django.test import TestCase, override_settings
+from django.test import SimpleTestCase, TestCase, override_settings
from django.test.client import RequestFactory
from parameterized import parameterized
from rest_framework.test import APIClient
-from posthog.models.integration import Integration
+from posthog.models.integration import Integration, SlackIntegration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
@@ -270,15 +270,18 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
@parameterized.expand(
[
- ("edited_field", {"edited": {"user": "U123", "ts": "1234.7777"}}),
- ("message_changed_subtype", {"subtype": "message_changed"}),
- ("bot_id", {"bot_id": "B0ALERT"}),
- ("bot_profile", {"bot_profile": {"name": "Mendral", "id": "B0ALERT"}}),
- ("app_id", {"app_id": "A0ALERT"}),
- ("bot_message_subtype", {"subtype": "bot_message"}),
- ("slackbot_user", {"user": "USLACKBOT"}),
+ ("edited_field", {"edited": {"user": "U123", "ts": "1234.7777"}}, "ignored:edit"),
+ ("message_changed_subtype", {"subtype": "message_changed"}, "ignored:edit"),
+ ("bot_id", {"bot_id": "B0ALERT"}, "ignored:bot_author"),
+ ("bot_profile", {"bot_profile": {"name": "Mendral", "id": "B0ALERT"}}, "ignored:bot_author"),
+ # Still dropped, but under its own reason so the volume of app-posted-as-a-human
+ # mentions is measurable rather than hidden inside the bot bucket.
+ ("app_id", {"app_id": "A0ALERT"}, "ignored:app_authored"),
+ ("bot_message_subtype", {"subtype": "bot_message"}, "ignored:bot_author"),
+ ("slackbot_user", {"user": "USLACKBOT"}, "ignored:bot_author"),
]
)
+ @patch("products.slack_app.backend.api.posthoganalytics.capture")
@patch("products.slack_app.backend.api.asyncio.run")
@patch("products.slack_app.backend.api.sync_connect")
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
@@ -286,13 +289,19 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
self,
_name,
ignore_marker: dict,
+ expected_drop_reason: str,
mock_sync_connect,
mock_asyncio_run,
+ mock_capture,
):
request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
ignored_event = {**self.event, **ignore_marker}
- from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
+ from products.slack_app.backend.api import (
+ ROUTE_HANDLED_LOCALLY,
+ SLACK_MENTION_DROPPED_EVENT,
+ route_posthog_code_event_to_relevant_region,
+ )
result = route_posthog_code_event_to_relevant_region(request, ignored_event, "T12345")
@@ -300,6 +309,13 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
mock_sync_connect.assert_not_called()
mock_asyncio_run.assert_not_called()
+ # Slack gets a 200 either way, so the drop is only visible if we capture it.
+ mock_capture.assert_called_once()
+ capture_kwargs = mock_capture.call_args.kwargs
+ assert capture_kwargs["event"] == SLACK_MENTION_DROPPED_EVENT
+ assert capture_kwargs["properties"]["drop_reason"] == expected_drop_reason
+ assert capture_kwargs["properties"]["replied"] is False
+
@patch("products.slack_app.backend.api.posthoganalytics.capture")
@patch("products.slack_app.backend.api._post_slack_user_feedback")
@patch("products.slack_app.backend.api.asyncio.run")
@@ -315,8 +331,13 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
# No workflow starts.
SlackUserProfileCache.objects.filter(slack_user_id="U123").delete()
self._seed_slack_user_cache("U123", "[email protected]")
+ mock_post_feedback.return_value = True
- from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
+ from products.slack_app.backend.api import (
+ ROUTE_HANDLED_LOCALLY,
+ SLACK_MENTION_DROPPED_EVENT,
+ route_posthog_code_event_to_relevant_region,
+ )
request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345")
@@ -333,29 +354,35 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
assert mock_post_feedback.call_args.kwargs.get("prefer_thread_message") is True
# The mention is still reported to analytics with ``posthog_user_identified=False``
- # so the unknown-user volume stays comparable to the known-user funnel.
- mock_capture.assert_called_once()
- capture_kwargs = mock_capture.call_args.kwargs
- assert capture_kwargs.get("event") == "posthog code slack mention received"
- assert capture_kwargs.get("properties", {}).get("posthog_user_identified") is False
+ # so the unknown-user volume stays comparable to the known-user funnel, and the
+ # drop itself is captured so the unanswered mention is queryable.
+ captured = {call.kwargs["event"]: call.kwargs["properties"] for call in mock_capture.call_args_list}
+ assert captured["posthog code slack mention received"]["posthog_user_identified"] is False
+ assert captured[SLACK_MENTION_DROPPED_EVENT]["drop_reason"] == "user_unresolved:user_not_found"
+ assert captured[SLACK_MENTION_DROPPED_EVENT]["replied"] is True
@patch("products.slack_app.backend.api.posthoganalytics.capture")
+ @patch("products.slack_app.backend.api._post_slack_user_ephemeral")
@patch("products.slack_app.backend.api._post_slack_user_feedback")
@patch("products.slack_app.backend.api.asyncio.run")
@patch("products.slack_app.backend.api.sync_connect")
@override_settings(DEBUG=False, CLOUD_DEPLOYMENT="US")
- def test_unknown_user_in_unapproved_ext_shared_channel_suppresses_failure_reply(
- self, mock_sync_connect, mock_asyncio_run, mock_post_feedback, mock_capture
+ def test_unknown_user_in_unapproved_ext_shared_channel_replies_ephemerally(
+ self, mock_sync_connect, mock_asyncio_run, mock_post_feedback, mock_post_ephemeral, mock_capture
):
# Externally-shared channels that haven't been approved must not receive a
- # public "Sorry, I couldn't find <email>" post — that leaks the integration's
- # existence (and the user's email) to non-org members. The approval prompt
- # itself requires a resolved user, so we stay completely silent in this case.
- # Analytics still records the event for funnel coverage.
+ # channel-visible "Sorry, I couldn't find <email>" post, which would expose the
+ # integration's existence (and the user's email) to non-org members. The
+ # mentioner still gets the reason as an ephemeral instead of silence.
SlackUserProfileCache.objects.filter(slack_user_id="U123").delete()
self._seed_slack_user_cache("U123", "[email protected]")
+ mock_post_ephemeral.return_value = True
- from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
+ from products.slack_app.backend.api import (
+ ROUTE_HANDLED_LOCALLY,
+ SLACK_MENTION_DROPPED_EVENT,
+ route_posthog_code_event_to_relevant_region,
+ )
request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
result = route_posthog_code_event_to_relevant_region(request, self.event, "T12345", is_ext_shared_channel=True)
@@ -363,8 +390,18 @@ class TestRoutePostHogCodeEventToRelevantRegion(TestCase):
assert result == ROUTE_HANDLED_LOCALLY
mock_sync_connect.assert_not_called()
mock_asyncio_run.assert_not_called()
+ # ``_post_slack_user_feedback`` falls back to a channel post, so it must stay out
+ # of this path entirely.
mock_post_feedback.assert_not_called()
- mock_capture.assert_called_once()
+ mock_post_ephemeral.assert_called_once()
+ # ``self.event`` is a top-level mention, so the ephemeral must not be anchored to
+ # a thread: Slack wouldn't render it on the channel view the mentioner is on.
+ assert mock_post_ephemeral.call_args.args[3] is None
+ assert "[email protected]" in mock_post_ephemeral.call_args.args[4]
+
+ captured = {call.kwargs["event"]: call.kwargs["properties"] for call in mock_capture.call_args_list}
+ assert captured[SLACK_MENTION_DROPPED_EVENT]["drop_reason"] == "user_unresolved:user_not_found"
+ assert captured[SLACK_MENTION_DROPPED_EVENT]["replied"] is True
@patch("products.slack_app.backend.api.asyncio.run")
@patch("products.slack_app.backend.api.sync_connect")
@@ -1327,3 +1364,37 @@ class TestQueueWorkflowDispatch(TestCase):
# Dispatch adds no reaction — the queue workflow reacts only on
# messages that actually wait behind another one.
mock_slack.return_value.client.reactions_add.assert_not_called()
+
+
+class TestPostSlackUserEphemeral(SimpleTestCase):
+ def test_request_timeout_applies_to_the_client_that_makes_the_call(self):
+ # ``SlackIntegration.client`` builds a fresh WebClient on every access, so setting
+ # the timeout on one access and calling on another leaves the request on the SDK
+ # default. Nothing about the app's behavior changes when that happens, so only an
+ # assertion on the client instance catches it.
+ from products.slack_app.backend.api import SLACK_FEEDBACK_TIMEOUT_SECONDS, _post_slack_user_ephemeral
+
+ built_clients: list[MagicMock] = []
+
+ class _NewClientPerAccess:
+ @property
+ def client(self) -> MagicMock:
+ built_clients.append(MagicMock())
+ return built_clients[-1]
+
+ posted = _post_slack_user_ephemeral(cast(SlackIntegration, _NewClientPerAccess()), "C001", "U123", None, "nope")
+
+ assert posted is True
+ assert len(built_clients) == 1
+ assert built_clients[0].timeout == SLACK_FEEDBACK_TIMEOUT_SECONDS
+ built_clients[0].chat_postEphemeral.assert_called_once()
+
+ def test_failed_delivery_is_reported_as_not_replied(self):
+ # The drop analytics distinguish "we told them why" from silence, so a Slack
+ # rejection must not be reported as a reply.
+ from products.slack_app.backend.api import _post_slack_user_ephemeral
+
+ slack = MagicMock()
+ slack.client.chat_postEphemeral.side_effect = Exception("ratelimited")
+
+ assert _post_slack_user_ephemeral(slack, "C001", "U123", None, "nope") is False