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.

feat(slack-app): forward untagged thread replies to running agent (#62628)

Vojta Bartoš36e211f4deaf
diff --git a/posthog/temporal/ai/__init__.py b/posthog/temporal/ai/__init__.py
index fae7880af297..839b6c6dc788 100644
--- a/posthog/temporal/ai/__init__.py
+++ b/posthog/temporal/ai/__init__.py
@@ -33,6 +33,7 @@ from posthog.temporal.ai.posthog_code_slack_mention_command import (
resolve_posthog_code_slack_command_user_activity,
)
from posthog.temporal.ai.research_agent import ResearchAgentWorkflow, process_research_agent_activity
+from posthog.temporal.ai.slack_app import SLACK_APP_ACTIVITIES
from posthog.temporal.ai.slack_conversation import (
SlackConversationRunnerWorkflow,
SlackConversationRunnerWorkflowInputs,
@@ -84,6 +85,7 @@ AI_ACTIVITIES = [
cascade_posthog_code_repository_activity,
discover_posthog_code_repository_via_agent_activity,
classify_posthog_code_task_needs_repo_activity,
+ *SLACK_APP_ACTIVITIES,
post_posthog_code_no_repos_activity,
post_posthog_code_repo_picker_activity,
block_posthog_code_task_if_no_personal_github_activity,
diff --git a/posthog/temporal/ai/posthog_code_slack_mention.py b/posthog/temporal/ai/posthog_code_slack_mention.py
index c0c6dc0c63c9..c6643a422063 100644
--- a/posthog/temporal/ai/posthog_code_slack_mention.py
+++ b/posthog/temporal/ai/posthog_code_slack_mention.py
@@ -14,6 +14,7 @@ from temporalio.common import RetryPolicy
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.repo_routing_rule import RepoRoutingRule
from posthog.storage import object_storage
+from posthog.temporal.ai.slack_app import PostHogCodeSlackMentionWorkflowInputs, classify_untagged_followup_activity
from posthog.temporal.common.base import PostHogWorkflow
from posthog.temporal.common.heartbeat import Heartbeater
from posthog.temporal.common.utils import close_db_connections
@@ -156,20 +157,6 @@ def _build_posthog_code_task_description(
)
-@dataclass
-class PostHogCodeSlackMentionWorkflowInputs:
- event: dict[str, Any]
- integration_id: int
- slack_team_id: str
- # Event that dispatched the workflow
- slack_event_id: str | None = None
- # Resolved at routing time. ``None`` only on in-flight workflow histories
- # started before this field existed; those fall back to the in-workflow
- # resolve activity below. Remove the fallback (and this field's optionality)
- # once the workflow history retention window has elapsed.
- user_id: int | None = None
-
-
def derive_mention_workflow_id(inputs: "PostHogCodeSlackMentionWorkflowInputs") -> str:
"""Construct the dispatch workflow id from webhook inputs."""
event = inputs.event
@@ -272,6 +259,22 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
if blocked:
return
+ # Untagged thread replies face the Haiku classifier before any
+ # forward. The webhook handler punted on this so its 3-second ack
+ # budget stays unencumbered; here we run it under Temporal's retry
+ # policy. Drop on chitchat or any failure (default-deny).
+ if inputs.untagged_followup:
+ should_forward = await _execute_posthog_code_activity(
+ classify_untagged_followup_activity,
+ inputs,
+ channel,
+ thread_ts,
+ slack_user_id,
+ event.get("text", ""),
+ )
+ if not should_forward:
+ return
+
followup_handled = await _execute_posthog_code_activity(
forward_posthog_code_followup_activity,
inputs,
@@ -284,6 +287,13 @@ class PostHogCodeSlackMentionWorkflow(PostHogWorkflow):
if followup_handled:
return
+ # Untagged thread replies must not fall through to the new-task path.
+ # The user never @mentioned us — they only typed in a thread that
+ # used to have an active task. If the mapping is gone by the time we
+ # got here, the right behaviour is to do nothing.
+ if inputs.untagged_followup:
+ return
+
# New starts carry ``user_id`` from routing-time resolution and skip
# the activity. Legacy histories started before the field existed
# deserialize with ``user_id=None`` and replay through the activity so
diff --git a/posthog/temporal/ai/slack_app/__init__.py b/posthog/temporal/ai/slack_app/__init__.py
new file mode 100644
index 000000000000..84a620a45132
--- /dev/null
+++ b/posthog/temporal/ai/slack_app/__init__.py
@@ -0,0 +1,26 @@
+"""Temporal activities for the PostHog Slack App.
+
+Activities living here run on ``settings.MAX_AI_TASK_QUEUE`` and are imported
+by ``posthog/temporal/ai/posthog_code_slack_mention.py`` at module load time.
+The package is the long-term home for activity splits out of that file; this
+PR ships the classifier and follow-ups will land here one PR at a time.
+"""
+
+from posthog.temporal.ai.slack_app.activities import (
+ CLASSIFIER_THREAD_HISTORY_MESSAGES,
+ classify_message_is_agent_directed,
+ classify_untagged_followup_activity,
+)
+from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs
+
+SLACK_APP_ACTIVITIES = [
+ classify_untagged_followup_activity,
+]
+
+__all__ = [
+ "CLASSIFIER_THREAD_HISTORY_MESSAGES",
+ "PostHogCodeSlackMentionWorkflowInputs",
+ "SLACK_APP_ACTIVITIES",
+ "classify_message_is_agent_directed",
+ "classify_untagged_followup_activity",
+]
diff --git a/posthog/temporal/ai/slack_app/activities/__init__.py b/posthog/temporal/ai/slack_app/activities/__init__.py
new file mode 100644
index 000000000000..c974212bab3d
--- /dev/null
+++ b/posthog/temporal/ai/slack_app/activities/__init__.py
@@ -0,0 +1,11 @@
+from posthog.temporal.ai.slack_app.activities.classifiers import (
+ CLASSIFIER_THREAD_HISTORY_MESSAGES,
+ classify_message_is_agent_directed,
+ classify_untagged_followup_activity,
+)
+
+__all__ = [
+ "CLASSIFIER_THREAD_HISTORY_MESSAGES",
+ "classify_message_is_agent_directed",
+ "classify_untagged_followup_activity",
+]
diff --git a/posthog/temporal/ai/slack_app/activities/classifiers.py b/posthog/temporal/ai/slack_app/activities/classifiers.py
new file mode 100644
index 000000000000..51fae895700c
--- /dev/null
+++ b/posthog/temporal/ai/slack_app/activities/classifiers.py
@@ -0,0 +1,155 @@
+import re
+import json
+
+import structlog
+from temporalio import activity
+
+from posthog.llm.gateway_client import get_llm_client
+from posthog.models.integration import SlackIntegration
+from posthog.temporal.ai.slack_app.types import PostHogCodeSlackMentionWorkflowInputs
+from posthog.temporal.common.utils import close_db_connections
+
+from products.slack_app.backend.models import SlackThreadTaskMapping
+
+logger = structlog.get_logger(__name__)
+
+CLASSIFIER_THREAD_HISTORY_MESSAGES = 10
+
+
+def classify_message_is_agent_directed(
+ event_text: str,
+ task_title: str,
+ thread_history: list[dict[str, str]],
+) -> bool:
+ """Classify whether a Slack thread reply is addressing the running PostHog
+ Slack App or pure side chatter between humans.
+
+ The prompt leans toward forwarding when the message could plausibly help
+ the agent or advance the task — a false positive is a single wasted turn
+ the human can correct; a false negative forces the human to re-tag
+ ``@PostHog`` to recover. Cheap pre-LLM heuristics still drop trivial
+ messages (one word, emoji-only, very short) before paying for Haiku, and
+ the function still returns ``False`` on a Haiku call error so a transient
+ LLM outage can't fan out spurious forwards.
+
+ ``thread_history`` is the conversation so far (oldest first), as returned
+ by ``_collect_thread_messages`` — each entry is ``{"user", "text", "ts"}``.
+ """
+ stripped = event_text.strip()
+ # Emoji-only / reaction-only replies are never agent-directed; drop before
+ # paying for Haiku.
+ if re.fullmatch(r"(?:\s*:[a-z0-9_+-]+:\s*)+", stripped):
+ logger.info("classify_message_is_agent_directed_heuristic_emoji_only", event_text=event_text)
+ return False
+
+ # Render the tail of the thread for context. Bound the number of lines and
+ # the per-line length to keep the prompt small and predictable.
+ recent = thread_history[-CLASSIFIER_THREAD_HISTORY_MESSAGES:]
+ history_block = "\n".join(f"{m.get('user', 'Unknown')}: {m.get('text', '')[:500]}" for m in recent) or "(empty)"
+
+ prompt = (
+ "You are routing replies in a Slack thread where the PostHog Slack App is "
+ "currently working on a task. Decide whether the latest message is meant "
+ "for the Slack App to read — instructions, corrections, follow-up asks, "
+ "questions about the task, or context that helps it — versus pure side "
+ "chatter between humans.\n\n"
+ "Lean toward true when the message could plausibly help the Slack App or "
+ "advance the task. Examples of agent_directed=true:\n"
+ " - Direct address ('@PostHog', 'agent, please…', 'bot, …').\n"
+ " - Instructions, corrections, or scope changes ('also handle the empty "
+ " case', 'use the new helper instead', 'actually skip the migration').\n"
+ " - Questions about the task or the Slack App's last update ('why did "
+ " you skip X?', 'what does this PR cover?', 'can you also do Y?').\n"
+ " - Task-relevant context (an error message, a URL, a file path, an "
+ " affected team/customer ID, a stack trace, a reproduction).\n"
+ " - Replies that elaborate on the human's earlier ask in this thread.\n\n"
+ "Return agent_directed=false for clearly off-topic side chatter:\n"
+ " - Pure acknowledgements with no new info ('thanks', 'lgtm', 'nice', "
+ " 'cool', emoji-only, '+1').\n"
+ " - Conversation clearly directed at another human (mentions another "
+ " user, answers their question, refers to people in third person).\n"
+ " - Off-topic chat unrelated to the task ('lunch in 5?', 'gn').\n\n"
+ "When you're genuinely on the fence, prefer true — the human can correct "
+ "the agent if it misreads, but a missed follow-up means the human has to "
+ "re-tag @PostHog.\n\n"
+ f"Task the Slack App is working on: {task_title or '(unknown)'}\n\n"
+ f"Thread so far (oldest first):\n{history_block}\n\n"
+ f"Latest message (from a human in this thread): {event_text}\n\n"
+ 'Respond with ONLY a JSON object: {"agent_directed": true} or {"agent_directed": false}'
+ )
+ try:
+ client = get_llm_client("slack_app_routing")
+ response = client.chat.completions.create(
+ model="claude-haiku-4-5-20251001",
+ messages=[{"role": "user", "content": prompt}],
+ max_tokens=64,
+ temperature=0,
+ )
+ content = (response.choices[0].message.content or "").strip()
+ if content.startswith("```"):
+ content = content.strip("`").removeprefix("json").strip()
+ parsed = json.loads(content)
+ return bool(parsed.get("agent_directed", False))
+ except Exception:
+ logger.exception("classify_message_is_agent_directed_failed")
+ return False
+
+
+@close_db_connections
+def classify_untagged_followup_activity(
+ inputs: PostHogCodeSlackMentionWorkflowInputs,
+ channel: str,
+ thread_ts: str,
+ slack_user_id: str,
+ event_text: str,
+) -> bool:
+ """Decide whether an untagged thread reply should reach the agent.
+
+ Runs the LLM + Slack thread-history fetch inside the workflow rather than
+ the webhook handler so they're retriable under Temporal and don't block
+ the Slack webhook's 3-second ack budget. Returns ``True`` to forward,
+ ``False`` to drop. Conservative defaults: missing mapping → drop, history
+ fetch failure → classify on text alone, classifier failure → drop.
+ """
+ from products.slack_app.backend.api import _collect_thread_messages
+
+ try:
+ mapping = SlackThreadTaskMapping.objects.select_related("task", "integration").get(
+ integration_id=inputs.integration_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ except SlackThreadTaskMapping.DoesNotExist:
+ logger.info(
+ "posthog_code_thread_message_mapping_gone",
+ integration_id=inputs.integration_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ return False
+
+ integration = mapping.integration
+ slack = SlackIntegration(integration)
+
+ try:
+ thread_history = _collect_thread_messages(slack, integration, channel, thread_ts, our_bot_id=None)
+ except Exception:
+ logger.exception(
+ "posthog_code_thread_message_history_fetch_failed",
+ channel=channel,
+ thread_ts=thread_ts,
+ )
+ thread_history = []
+
+ task_title = mapping.task.title if mapping.task and mapping.task.title else ""
+ if classify_message_is_agent_directed(event_text, task_title, thread_history):
+ return True
+
+ logger.info(
+ "posthog_code_thread_message_classified_chitchat",
+ channel=channel,
+ thread_ts=thread_ts,
+ slack_user_id=slack_user_id,
+ )
+ return False
diff --git a/posthog/temporal/ai/slack_app/types.py b/posthog/temporal/ai/slack_app/types.py
new file mode 100644
index 000000000000..19001d3ad776
--- /dev/null
+++ b/posthog/temporal/ai/slack_app/types.py
@@ -0,0 +1,30 @@
+"""Shared dataclasses for PostHog Slack App Temporal workflows.
+
+Living here (and not in the workflow module) so activities split into this
+package can take the inputs dataclass as their typed signature without
+creating an import cycle with the workflow module.
+"""
+
+from dataclasses import dataclass
+from typing import Any
+
+
+@dataclass
+class PostHogCodeSlackMentionWorkflowInputs:
+ event: dict[str, Any]
+ integration_id: int
+ slack_team_id: str
+ # Event that dispatched the workflow
+ slack_event_id: str | None = None
+ # Resolved at routing time. ``None`` only on in-flight workflow histories
+ # started before this field existed; those fall back to the in-workflow
+ # resolve activity below. Remove the fallback (and this field's optionality)
+ # once the workflow history retention window has elapsed.
+ user_id: int | None = None
+ # True when the workflow was started for an untagged thread reply (event type
+ # ``message``) rather than an explicit ``app_mention``. The routing layer
+ # already verified a ``SlackThreadTaskMapping`` exists before dispatch, but
+ # if the mapping is gone by the time the followup activity runs (race with
+ # cleanup), we must NOT fall through to the new-task path — the user never
+ # tagged us, so kicking off a brand-new agent run would be wrong.
+ untagged_followup: bool = False
diff --git a/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py b/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py
new file mode 100644
index 000000000000..68d0554e8121
--- /dev/null
+++ b/posthog/temporal/tests/ai/test_classify_untagged_followup_activity.py
@@ -0,0 +1,165 @@
+from unittest.mock import patch
+
+from django.apps import apps
+from django.test import TestCase
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization
+from posthog.models.team.team import Team
+from posthog.models.user import User
+from posthog.temporal.ai.posthog_code_slack_mention import PostHogCodeSlackMentionWorkflowInputs
+from posthog.temporal.ai.slack_app import classify_message_is_agent_directed, classify_untagged_followup_activity
+
+from products.slack_app.backend.models import SlackThreadTaskMapping
+
+
+class TestClassifyUntaggedFollowupActivity(TestCase):
+ """Activity-level tests for the classifier that now lives inside the
+ mention workflow. The activity owns mapping lookup, thread-history fetch,
+ and the LLM call; the webhook handler is no longer involved."""
+
+ def setUp(self):
+ self.Task = apps.get_model("tasks", "Task")
+ self.TaskRun = apps.get_model("tasks", "TaskRun")
+ self.org = Organization.objects.create(name="TestOrg")
+ self.team = Team.objects.create(organization=self.org, name="TestTeam")
+ self.user = User.objects.create(email="[email protected]")
+ self.integration = Integration.objects.create(team=self.team, kind="slack", integration_id="T_SLACK", config={})
+ self.task = self.Task.objects.create(
+ team=self.team,
+ title="Fix the broken dashboard export",
+ description="desc",
+ origin_product=self.Task.OriginProduct.SLACK,
+ created_by=self.user,
+ repository="org/repo",
+ )
+ self.task_run = self.TaskRun.objects.create(
+ task=self.task, team=self.team, status=self.TaskRun.Status.IN_PROGRESS
+ )
+ self.mapping = SlackThreadTaskMapping.objects.create(
+ team=self.team,
+ integration=self.integration,
+ slack_workspace_id="T_SLACK",
+ channel="C001",
+ thread_ts="1000.0000",
+ task=self.task,
+ task_run=self.task_run,
+ mentioning_slack_user_id="U_ALICE",
+ )
+ self.inputs = PostHogCodeSlackMentionWorkflowInputs(
+ event={},
+ integration_id=self.integration.id,
+ slack_team_id="T_SLACK",
+ untagged_followup=True,
+ )
+
+ def _call(self, event_text: str = "Could you also check the export filter logic, please") -> bool:
+ return classify_untagged_followup_activity(self.inputs, "C001", "1000.0000", "U_BOB", event_text)
+
+ def test_mapping_gone_returns_false(self):
+ """If the mapping vanished between routing-time and the workflow body,
+ drop the followup — the user never @mentioned us in this thread, so
+ kicking off any further work would be wrong."""
+ self.mapping.delete()
+ with patch(
+ "posthog.temporal.ai.slack_app.activities.classifiers.classify_message_is_agent_directed"
+ ) as mock_classify:
+ assert self._call() is False
+ mock_classify.assert_not_called()
+
+ def test_classifier_true_returns_true(self):
+ with (
+ patch("products.slack_app.backend.api._collect_thread_messages", return_value=[]),
+ patch(
+ "posthog.temporal.ai.slack_app.activities.classifiers.classify_message_is_agent_directed",
+ return_value=True,
+ ) as mock_classify,
+ ):
+ assert self._call() is True
+ mock_classify.assert_called_once()
+ # The mapping's task title flows through to the classifier prompt.
+ assert mock_classify.call_args[0][1] == "Fix the broken dashboard export"
+
+ def test_classifier_false_returns_false(self):
+ with (
+ patch("products.slack_app.backend.api._collect_thread_messages", return_value=[]),
+ patch(
+ "posthog.temporal.ai.slack_app.activities.classifiers.classify_message_is_agent_directed",
+ return_value=False,
+ ),
+ ):
+ assert self._call("thanks team!") is False
+
+ def test_history_fetch_failure_classifies_on_empty_history(self):
+ """A Slack hiccup on ``conversations_replies`` falls back to classifying
+ on the message text alone rather than dropping silently."""
+ with (
+ patch(
+ "products.slack_app.backend.api._collect_thread_messages",
+ side_effect=RuntimeError("slack hiccup"),
+ ),
+ patch(
+ "posthog.temporal.ai.slack_app.activities.classifiers.classify_message_is_agent_directed",
+ return_value=True,
+ ) as mock_classify,
+ ):
+ assert self._call() is True
+ mock_classify.assert_called_once()
+ assert mock_classify.call_args[0][2] == []
+
+
+class TestClassifyMessageIsAgentDirected(TestCase):
+ """The Haiku-backed classifier with cheap pre-LLM heuristics. Moved from
+ the API module to the workflow module along with the rest of the LLM
+ work."""
+
+ def test_emoji_only_dropped_without_llm(self):
+ with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as mock_client:
+ assert classify_message_is_agent_directed(":thumbsup: :tada:", "do thing", []) is False
+ mock_client.assert_not_called()
+
+ def test_haiku_directed_true(self):
+ fake_response = type(
+ "Resp",
+ (),
+ {
+ "choices": [
+ type(
+ "Choice",
+ (),
+ {"message": type("Msg", (), {"content": '{"agent_directed": true}'})()},
+ )()
+ ]
+ },
+ )()
+ with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as mock_client:
+ mock_client.return_value.chat.completions.create.return_value = fake_response
+ result = classify_message_is_agent_directed("Please also check the auth flow on safari", "fix the bug", [])
+ assert result is True
+
+ def test_haiku_directed_false(self):
+ fake_response = type(
+ "Resp",
+ (),
+ {
+ "choices": [
+ type(
+ "Choice",
+ (),
+ {"message": type("Msg", (), {"content": '{"agent_directed": false}'})()},
+ )()
+ ]
+ },
+ )()
+ with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as mock_client:
+ mock_client.return_value.chat.completions.create.return_value = fake_response
+ result = classify_message_is_agent_directed("nice work team, going to lunch now", "fix the bug", [])
+ assert result is False
+
+ def test_haiku_failure_defaults_to_drop(self):
+ """Conservative default: a false positive interrupts the agent on
+ every chit-chat reply; a false negative just means the user re-tags."""
+ with patch("posthog.temporal.ai.slack_app.activities.classifiers.get_llm_client") as mock_client:
+ mock_client.return_value.chat.completions.create.side_effect = RuntimeError("boom")
+ result = classify_message_is_agent_directed("Please also check the auth flow on safari", "fix the bug", [])
+ assert result is False
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index a1ea246168b9..82595673ab86 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -65,6 +65,7 @@ class TestAITemporalModuleIntegrity:
"cascade_posthog_code_repository_activity",
"discover_posthog_code_repository_via_agent_activity",
"classify_posthog_code_task_needs_repo_activity",
+ "classify_untagged_followup_activity",
"post_posthog_code_no_repos_activity",
"post_posthog_code_repo_picker_activity",
"block_posthog_code_task_if_no_personal_github_activity",
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 8e29a8378a06..bdcbe2e63ea3 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -53,7 +53,7 @@ from posthog.temporal.ai.posthog_code_slack_mention_command import (
from posthog.temporal.common.client import sync_connect
from posthog.user_permissions import UserPermissions
-from products.slack_app.backend.models import SlackChannel, SlackUserProfileCache
+from products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping, SlackUserProfileCache
from products.slack_app.backend.services.integration_resolver import (
UserResolutionFailure,
format_project_candidate_list,
@@ -65,7 +65,7 @@ from products.slack_app.backend.slack_link_unfurl import handle_posthog_link_unf
logger = structlog.get_logger(__name__)
-HANDLED_EVENT_TYPES = ["app_mention", "link_shared"]
+HANDLED_EVENT_TYPES = ["app_mention", "link_shared", "message"]
# The notifications Slack app (`slack`) install carries every scope the coding-agent flow
# needs, so both surfaces share one kind.
@@ -1365,6 +1365,113 @@ def _app_mention_ignore_reason(event: dict[str, Any]) -> str | None:
return None
+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"
+ if not event.get("text"):
+ return "no_text"
+ if event.get("edited") or event.get("subtype") == "message_changed":
+ 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"
+ # 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.
+ if event.get("subtype"):
+ return f"subtype:{event.get('subtype')}"
+ return None
+
+
+# Feature flag that gates the untagged-thread followup path per org. Off by
+# default until rollout; turning it on for an org makes every message in a
+# tagged thread eligible for classification + forward, instead of requiring a
+# fresh ``@PostHog`` mention. Naming follows the ``posthog-slack-app-*`` prefix
+# the team uses for the Slack App's product flags.
+UNTAGGED_THREAD_FOLLOWUPS_FLAG = "posthog-slack-app-untagged-thread-followups"
+
+
+def _resolve_untagged_followup_mapping(
+ *,
+ candidates: list[Integration],
+ channel: str | None,
+ thread_ts: str | None,
+ slack_team_id: str,
+) -> SlackThreadTaskMapping | None:
+ """Look up a ``SlackThreadTaskMapping`` for an untagged thread reply and
+ confirm the integration's org has opted in via the feature flag.
+
+ Returns the mapping when the message should enter the shared routing
+ pipeline; ``None`` when it should drop. Two distinct ``None`` cases —
+ no mapping (thread we don't own) and FF off — are logged separately so
+ rollout dashboards can tell them apart.
+ """
+ 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 FF check + 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()
+ )
+ if mapping is None:
+ return None
+ if not _untagged_thread_followups_enabled(mapping.integration, slack_team_id):
+ logger.info(
+ "posthog_code_thread_message_feature_flag_off",
+ slack_team_id=slack_team_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ integration_id=mapping.integration_id,
+ )
+ return None
+ return mapping
+
+
+def _untagged_thread_followups_enabled(integration: Integration, slack_team_id: str) -> bool:
+ """Return True if the integration's org has the untagged-thread followup
+ flag enabled. Fail-closed on any error — a transient PostHog API outage
+ must not silently enable the feature for everyone.
+ """
+ try:
+ enabled = posthoganalytics.feature_enabled(
+ UNTAGGED_THREAD_FOLLOWUPS_FLAG,
+ f"slack_workspace:{slack_team_id}",
+ groups={"organization": str(integration.team.organization_id)},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ return bool(enabled)
+ except Exception:
+ logger.exception(
+ "posthog_code_thread_message_feature_flag_check_failed",
+ slack_team_id=slack_team_id,
+ integration_id=integration.id,
+ )
+ return False
+
+
def _notify_missing_slack_scopes(
slack: SlackIntegration,
event: dict,
@@ -1575,28 +1682,43 @@ def route_posthog_code_event_to_relevant_region(
eu_domain=_eu_region_domain(),
)
- if event_type == "app_mention":
- ignore_reason = _app_mention_ignore_reason(event)
- if ignore_reason:
- logger.info(
- "posthog_code_event_app_mention_ignored",
- reason=ignore_reason,
- slack_team_id=slack_team_id,
- channel=event.get("channel"),
- message_ts=event.get("ts"),
- )
- return ROUTE_HANDLED_LOCALLY
+ if event_type in ("app_mention", "message"):
+ if event_type == "app_mention":
+ ignore_reason = _app_mention_ignore_reason(event)
+ if ignore_reason:
+ logger.info(
+ "posthog_code_event_app_mention_ignored",
+ reason=ignore_reason,
+ slack_team_id=slack_team_id,
+ channel=event.get("channel"),
+ message_ts=event.get("ts"),
+ )
+ return ROUTE_HANDLED_LOCALLY
+ else:
+ ignore_reason = _thread_message_ignore_reason(event)
+ if ignore_reason:
+ logger.info(
+ "posthog_code_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; drop before any DB hit.
+ top_level_thread_ts = event.get("thread_ts")
+ if not isinstance(top_level_thread_ts, str) or top_level_thread_ts == event.get("ts"):
+ return ROUTE_HANDLED_LOCALLY
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
- # Workspace lookup first — 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.
+ # 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],
@@ -1610,6 +1732,23 @@ def route_posthog_code_event_to_relevant_region(
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)
+ # Threads we don't own (and orgs that haven't opted in) are dropped here
+ # so the rest of the pipeline only runs for actionable messages.
+ untagged_followup_mapping: SlackThreadTaskMapping | None = None
+ if event_type == "message":
+ untagged_followup_mapping = _resolve_untagged_followup_mapping(
+ candidates=workspace_result.candidates,
+ channel=channel_str,
+ thread_ts=thread_ts_str,
+ slack_team_id=slack_team_id,
+ )
+ if untagged_followup_mapping is None:
+ return ROUTE_HANDLED_LOCALLY
+
+ # 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,
@@ -1618,6 +1757,15 @@ def route_posthog_code_event_to_relevant_region(
)
if resolution.user is None:
+ if untagged_followup_mapping is not None:
+ logger.info(
+ "posthog_code_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,
+ )
+ 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
@@ -1642,26 +1790,68 @@ def route_posthog_code_event_to_relevant_region(
candidates = resolution.candidates
target = resolution.integration
- if _parse_rules_command(event.get("text", "")) is not None:
+ # Rules command is meaningful only when the user actually typed
+ # ``@PostHog`` — an untagged thread reply can never be a rules command.
+ if untagged_followup_mapping is None and _parse_rules_command(event.get("text", "")) is not None:
return _start_command_workflow(event, candidates, slack_team_id, event_id, user_id=posthog_user.id)
+ # 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 mention_target is None:
+ if untagged_followup_mapping is not None:
+ if untagged_followup_mapping.integration_id not in {c.id for c in candidates}:
+ logger.info(
+ "posthog_code_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,
+ )
+ 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)
return ROUTE_HANDLED_LOCALLY
slack = SlackIntegration(mention_target)
missing = slack.missing_scopes(POSTHOG_CODE_REQUIRED_SLACK_SCOPES)
if missing:
+ if untagged_followup_mapping is not None:
+ logger.info(
+ "posthog_code_thread_message_missing_scopes",
+ slack_team_id=slack_team_id,
+ integration_id=mention_target.id,
+ )
+ return ROUTE_HANDLED_LOCALLY
_notify_missing_slack_scopes(slack, event, missing)
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(
+ "posthog_code_thread_message_channel_unapproved",
+ slack_team_id=slack_team_id,
+ channel=channel_id,
+ )
+ return ROUTE_HANDLED_LOCALLY
_post_channel_approval_prompt(slack, mention_target, event)
return ROUTE_HANDLED_LOCALLY
- return _start_mention_workflow(event, mention_target, slack_team_id, event_id, posthog_user=posthog_user)
+ return _start_mention_workflow(
+ event,
+ mention_target,
+ slack_team_id,
+ event_id,
+ posthog_user=posthog_user,
+ untagged_followup=untagged_followup_mapping is not None,
+ )
# link_shared (unfurl) works with either integration kind.
link_result = load_integrations(slack_team_id=slack_team_id, kinds=list(SLACK_INTEGRATION_KINDS))
@@ -1958,17 +2148,36 @@ def _start_mention_workflow(
slack_team_id: str,
event_id: str | None,
*,
- posthog_user: User,
+ posthog_user: User | None,
+ untagged_followup: bool = False,
) -> str:
- _report_slack_mention_received(event, integration, slack_team_id, posthog_user=posthog_user)
- if _resolve_pending_repo_picker_from_followup(event, integration):
- return ROUTE_HANDLED_LOCALLY
+ """Start the mention workflow for either an explicit ``app_mention`` or an
+ untagged thread reply.
+
+ ``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.
+
+ ``posthog_user`` is optional only to keep the door open for the legacy
+ in-workflow resolution path; in practice both event types resolve the
+ user at routing time and pass it in.
+ """
+ if not untagged_followup:
+ assert posthog_user is not None, "app_mention path must always resolve a user before dispatch"
+ _report_slack_mention_received(event, integration, slack_team_id, posthog_user=posthog_user)
+ 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,
+ user_id=posthog_user.id if posthog_user else None,
+ untagged_followup=untagged_followup,
)
# 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
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 92339e015c91..86894a596260 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
@@ -71,7 +71,7 @@ class TestPostHogCodeEventHandler(TestCase):
("app_mention_handled_locally", "app_mention", "handled_locally", 202, True),
("app_mention_proxy_failed", "app_mention", "proxy_failed", 502, True),
("app_mention_no_integration", "app_mention", "no_integration", 202, True),
- ("non_handled_event_type_skips_routing", "message", "handled_locally", 202, False),
+ ("non_handled_event_type_skips_routing", "reaction_added", "handled_locally", 202, False),
]
)
@patch("products.slack_app.backend.api.route_posthog_code_event_to_relevant_region")
diff --git a/products/slack_app/backend/tests/test_thread_message_routing.py b/products/slack_app/backend/tests/test_thread_message_routing.py
new file mode 100644
index 000000000000..5702844531cb
--- /dev/null
+++ b/products/slack_app/backend/tests/test_thread_message_routing.py
@@ -0,0 +1,358 @@
+from unittest.mock import patch
+
+from django.apps import apps
+from django.core.cache import cache
+from django.test import TestCase, override_settings
+from django.test.client import RequestFactory
+from django.utils import timezone
+
+from posthog.models.integration import Integration
+from posthog.models.organization import Organization, OrganizationMembership
+from posthog.models.team.team import Team
+from posthog.models.user import User
+
+from products.slack_app.backend.models import SlackThreadTaskMapping, SlackUserProfileCache
+
+
+class TestRouteThreadMessage(TestCase):
+ """Untagged ``message`` events in already-tagged threads start the mention
+ workflow immediately. Classifier + user resolution have moved inside the
+ workflow so the webhook handler stays fast."""
+
+ def setUp(self):
+ from products.slack_app.backend.api import POSTHOG_CODE_REQUIRED_SLACK_SCOPES
+
+ cache.clear()
+ self.factory = RequestFactory()
+ self.Task = apps.get_model("tasks", "Task")
+ self.TaskRun = apps.get_model("tasks", "TaskRun")
+
+ self.organization = Organization.objects.create(name="Test Org")
+ self.team = Team.objects.create(organization=self.organization, name="Test Team")
+ self.user = User.objects.create(email="[email protected]", distinct_id="user-1")
+ OrganizationMembership.objects.create(organization=self.organization, user=self.user)
+ self.user.current_organization = self.organization
+ self.user.current_team = self.team
+ self.user.save()
+
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T_SLACK",
+ config={"scope": ",".join(sorted(POSTHOG_CODE_REQUIRED_SLACK_SCOPES))},
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+ SlackUserProfileCache.objects.create(
+ integration=self.integration,
+ slack_user_id="U_ALICE",
+ display_name="Alice",
+ real_name="Alice Example",
+ refreshed_at=timezone.now(),
+ )
+ # Bob participates in the thread (default ``_make_event`` user). Seed
+ # him as a real PostHog user with team access so the user-resolution
+ # gate passes for happy-path tests; the silent-drop test deliberately
+ # uses a different unknown user id.
+ self.bob = User.objects.create(email="[email protected]", distinct_id="user-2")
+ OrganizationMembership.objects.create(organization=self.organization, user=self.bob)
+ SlackUserProfileCache.objects.create(
+ integration=self.integration,
+ slack_user_id="U_BOB",
+ display_name="Bob",
+ real_name="Bob Example",
+ refreshed_at=timezone.now(),
+ )
+
+ self.task = self.Task.objects.create(
+ team=self.team,
+ title="Fix the broken dashboard export",
+ description="desc",
+ origin_product=self.Task.OriginProduct.SLACK,
+ created_by=self.user,
+ repository="org/repo",
+ )
+ self.task_run = self.TaskRun.objects.create(
+ task=self.task,
+ team=self.team,
+ status=self.TaskRun.Status.IN_PROGRESS,
+ )
+ self.mapping = SlackThreadTaskMapping.objects.create(
+ team=self.team,
+ integration=self.integration,
+ slack_workspace_id="T_SLACK",
+ channel="C001",
+ thread_ts="1000.0000",
+ task=self.task,
+ task_run=self.task_run,
+ mentioning_slack_user_id="U_ALICE",
+ )
+
+ # All routing tests assume the per-org feature flag is on. The
+ # dedicated ``test_feature_flag_off_dropped`` test stops the patcher
+ # to exercise the off path.
+ self._ff_patcher = patch("products.slack_app.backend.api._untagged_thread_followups_enabled", return_value=True)
+ self._ff_patcher.start()
+ self.addCleanup(self._ff_patcher.stop)
+
+ # --- Helpers -----------------------------------------------------------
+
+ def _make_event(self, **overrides) -> dict:
+ defaults = {
+ "type": "message",
+ "channel": "C001",
+ "user": "U_BOB",
+ "ts": "1001.0000",
+ "thread_ts": "1000.0000",
+ "text": "Could you also check the export filter logic, please",
+ }
+ defaults.update(overrides)
+ return defaults
+
+ def _route(self, event: dict) -> str:
+ from products.slack_app.backend.api import route_posthog_code_event_to_relevant_region
+
+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
+ return route_posthog_code_event_to_relevant_region(request, event, "T_SLACK")
+
+ # --- Cheap pre-DB gates ------------------------------------------------
+
+ def test_top_level_message_dropped_before_db(self):
+ """A message with no ``thread_ts`` (or where ``thread_ts == ts``) is a
+ top-level post in the channel, not a thread reply. Drop before
+ touching the DB — channel chatter dominates wire volume."""
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ event = self._make_event(thread_ts="1001.0000") # same as ts
+ with (
+ patch("products.slack_app.backend.api.SlackThreadTaskMapping.objects.filter") as mock_filter,
+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,
+ ):
+ result = self._route(event)
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_filter.assert_not_called()
+ mock_start.assert_not_called()
+
+ def test_no_user_dropped(self):
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ event = self._make_event(user=None)
+ with patch("products.slack_app.backend.api._start_mention_workflow") as mock_start:
+ result = self._route(event)
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_start.assert_not_called()
+
+ def test_bot_author_dropped(self):
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ event = self._make_event(bot_id="B_OTHER")
+ with patch("products.slack_app.backend.api._start_mention_workflow") as mock_start:
+ result = self._route(event)
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_start.assert_not_called()
+
+ def test_edited_message_dropped(self):
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ event = self._make_event(subtype="message_changed")
+ with patch("products.slack_app.backend.api._start_mention_workflow") as mock_start:
+ result = self._route(event)
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_start.assert_not_called()
+
+ # --- Mapping + FF gate -------------------------------------------------
+
+ def test_thread_without_mapping_dropped(self):
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ self.mapping.delete()
+ with (
+ patch("products.slack_app.backend.api.resolve_user_for_workspace") as mock_resolve,
+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,
+ ):
+ result = self._route(self._make_event())
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_resolve.assert_not_called()
+ mock_start.assert_not_called()
+
+ def test_feature_flag_off_dropped(self):
+ """Off-by-default workspaces pay one DB query and nothing else."""
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ self._ff_patcher.stop()
+ with (
+ patch("products.slack_app.backend.api._untagged_thread_followups_enabled", return_value=False),
+ patch("products.slack_app.backend.api.resolve_user_for_workspace") as mock_resolve,
+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,
+ ):
+ result = self._route(self._make_event())
+ self._ff_patcher.start()
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_resolve.assert_not_called()
+ mock_start.assert_not_called()
+
+ # --- Cross-org access gate -------------------------------------------
+
+ def test_user_without_access_to_mapping_team_dropped_silently(self):
+ """A workspace can be connected to multiple orgs; the message author
+ may belong to a different org than the one that owns the thread's
+ mapping. The handler must drop silently rather than dispatch a
+ workflow against an integration the user has no access to."""
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_org, name="Other Team")
+ carol = User.objects.create(email="[email protected]", distinct_id="user-3")
+ OrganizationMembership.objects.create(organization=other_org, user=carol)
+ # Carol's only org is "Other Org" — she has no access to ``self.team``,
+ # which owns the mapping. The same Slack workspace is wired to both.
+ Integration.objects.create(
+ team=other_team,
+ kind="slack",
+ integration_id="T_SLACK",
+ config={"scope": self.integration.config["scope"]},
+ sensitive_config={"access_token": "xoxb-other"},
+ )
+ SlackUserProfileCache.objects.create(
+ integration=self.integration,
+ slack_user_id="U_CAROL",
+ display_name="Carol",
+ real_name="Carol Example",
+ refreshed_at=timezone.now(),
+ )
+
+ with patch("products.slack_app.backend.api._start_mention_workflow") as mock_start:
+ result = self._route(self._make_event(user="U_CAROL"))
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_start.assert_not_called()
+
+ # --- User-resolution gate ---------------------------------------------
+
+ def test_unknown_user_dropped_silently(self):
+ """An untagged thread message from a Slack user we can't resolve drops
+ silently — unlike the mention path, no failure reply is posted, because
+ per-observer notices would spam the thread on every message."""
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ event = self._make_event(user="U_UNKNOWN")
+ with (
+ patch("products.slack_app.backend.api._post_user_resolution_failure_reply") as mock_failure,
+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,
+ ):
+ result = self._route(event)
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_failure.assert_not_called()
+ mock_start.assert_not_called()
+
+ # --- Scope + approval gates ------------------------------------------
+
+ @override_settings(DEBUG=False)
+ def test_missing_scopes_dropped_silently(self):
+ """Scopes can only be missing if they were revoked after the mapping
+ was created. Drop silently rather than reposting the notice on every
+ message."""
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ with (
+ patch(
+ "products.slack_app.backend.api.SlackIntegration.missing_scopes", return_value=frozenset({"chat:write"})
+ ),
+ patch("products.slack_app.backend.api._notify_missing_slack_scopes") as mock_notify,
+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,
+ ):
+ result = self._route(self._make_event())
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_notify.assert_not_called()
+ mock_start.assert_not_called()
+
+ @override_settings(DEBUG=False)
+ def test_unapproved_ext_shared_channel_dropped_silently(self):
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY, route_posthog_code_event_to_relevant_region
+
+ request = self.factory.post("/slack/event-callback/", HTTP_HOST="us.posthog.com")
+ with (
+ patch("products.slack_app.backend.api._channel_is_approved", return_value=False),
+ patch("products.slack_app.backend.api._post_channel_approval_prompt") as mock_prompt,
+ patch("products.slack_app.backend.api._start_mention_workflow") as mock_start,
+ ):
+ result = route_posthog_code_event_to_relevant_region(
+ request, self._make_event(), "T_SLACK", is_ext_shared_channel=True
+ )
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_prompt.assert_not_called()
+ mock_start.assert_not_called()
+
+ # --- Rules command not invoked for untagged --------------------------
+
+ @override_settings(DEBUG=False)
+ def test_rules_command_text_does_not_trigger_command_workflow(self):
+ """A rules-shaped message in an untagged thread (no @mention) must not
+ kick off the command workflow — the user never tagged us. It should
+ flow through to the regular mention workflow with
+ ``untagged_followup=True`` so the classifier in the workflow can drop
+ it as off-topic."""
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ rules_text = '@PostHog rules add "use the helper" org/repo'
+ with (
+ patch("products.slack_app.backend.api._start_command_workflow") as mock_command,
+ patch(
+ "products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY
+ ) as mock_start,
+ ):
+ result = self._route(self._make_event(text=rules_text))
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_command.assert_not_called()
+ mock_start.assert_called_once()
+ assert mock_start.call_args.kwargs["untagged_followup"] is True
+
+ # --- Workflow handoff (happy path) -----------------------------------
+
+ @override_settings(DEBUG=False)
+ def test_tagged_message_starts_workflow_with_resolved_user_and_untagged_flag(self):
+ """Happy path: the handler runs the same gates as a mention but on
+ success starts the workflow with ``untagged_followup=True`` and the
+ resolved PostHog user. The classifier and thread-history fetch happen
+ inside the workflow."""
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ with patch(
+ "products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY
+ ) as mock_start:
+ result = self._route(self._make_event(user="U_ALICE"))
+ assert result == ROUTE_HANDLED_LOCALLY
+ mock_start.assert_called_once()
+ kwargs = mock_start.call_args.kwargs
+ assert kwargs["posthog_user"].id == self.user.id
+ assert kwargs["untagged_followup"] is True
+
+ # --- Symmetry with the app_mention path -------------------------------
+
+ @override_settings(DEBUG=False)
+ def test_app_mention_and_tagged_message_both_reach_mention_workflow(self):
+ """Both event types end at ``_start_mention_workflow`` with the user
+ resolved; only the ``untagged_followup`` kwarg differs."""
+ from products.slack_app.backend.api import ROUTE_HANDLED_LOCALLY
+
+ mention_event = {
+ "type": "app_mention",
+ "channel": "C001",
+ "user": "U_ALICE",
+ "ts": "1000.0000",
+ "thread_ts": "1000.0000",
+ "text": "<@BOT> please fix the export",
+ }
+ followup_event = self._make_event(user="U_ALICE")
+ with patch(
+ "products.slack_app.backend.api._start_mention_workflow", return_value=ROUTE_HANDLED_LOCALLY
+ ) as mock_start:
+ self._route(mention_event)
+ self._route(followup_event)
+ assert mock_start.call_count == 2
+ first, second = mock_start.call_args_list
+ assert first.kwargs.get("untagged_followup", False) is False
+ assert first.kwargs["posthog_user"].id == self.user.id
+ assert second.kwargs["untagged_followup"] is True
+ assert second.kwargs["posthog_user"].id == self.user.id