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(signals): send inbox reviewer pings as a Slack DM (#97190)

posthog[bot]c50690fda7a2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f3a2ca7004f1..5d0fbd5b88b5 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7928,6 +7928,26 @@ snapshots:
hash: v1.k794b7964.748be85b9907181d7eb082c40e4d4f93429073c22a34fd3ad19f010006856b4d.m6AmUOQ3eZ_Le5wuOhR7RCAT_xVrzvZJSHptyYmtTpM
scenes-app-inbox-signalsourcespanel--tools-on-no-recent-data--light:
hash: v1.k794b7964.ace77adbc25963a6ba9f41c77744f726165855b31c0e4486bc5fbbeeec55250f.vWRUFUczQF3fmjvF_LizkGQaBK-ddzgEIjTB8sJEFro
+ scenes-app-inbox-slacknotificationssection--awaiting-target--dark:
+ hash: v1.k794b7964.8ea3584f9e8ba12a10845825520e5297ebf2c60282422cec693b0bd291ceee47.UdwureshdgpAitm-HeIekB6baljLm5XiV93vEw4z3-A
+ scenes-app-inbox-slacknotificationssection--awaiting-target--light:
+ hash: v1.k794b7964.afc4ca112ec8c6aa017b68a925c7973c973490024f141f661bccba7af2135ce4.WA08pPg_tRzIld7tJyEZQxkBBfeXyQdx77Jp7IeICIs
+ scenes-app-inbox-slacknotificationssection--direct-message-to-me--dark:
+ hash: v1.k794b7964.b47818f5f154dfd4d14fe525e714980ec9f06e8c29802231d4e1ebf6df7a0de2.ru2rUWCNxUOD8UACkmW8-dfV0Q4rNvf-D-E7ut9kdXI
+ scenes-app-inbox-slacknotificationssection--direct-message-to-me--light:
+ hash: v1.k794b7964.97016ccf994141237de98a7decd5fa540f8b8fecc6f9b67b6fe070e6fc86c6f6.YSImf6N-fF_YX2F4QDRwBpaQBi2b5C7UgU_s4h3xTDg
+ scenes-app-inbox-slacknotificationssection--not-connected--dark:
+ hash: v1.k794b7964.28ba7f9bff784013ccce1e2a2fc0130d6bb7ce265f501308f221cbdf902614ad.Ou8BqYO_9RvcgnW9eECuR7tiWOtkJbX8mFSUXEkXzWw
+ scenes-app-inbox-slacknotificationssection--not-connected--light:
+ hash: v1.k794b7964.3354167520829af3d1c6014d6eaf5b1f3a4651982251407c37850ae5cc1acecf.28_m7lUzxus-9IPwlhsbHZDN9i-Y0u55w_ciQt6ewAM
+ scenes-app-inbox-slacknotificationssection--nothing-configured--dark:
+ hash: v1.k794b7964.f18df82d8ee19d6c1d77c2a39707de1baa8ba95bb871771e855a08be8d6d72f5.kw_ozyO-TejXxIhuFd8rkW9aW3Y5e10IFOwl93QUhkk
+ scenes-app-inbox-slacknotificationssection--nothing-configured--light:
+ hash: v1.k794b7964.ebf2f4a8d1282b89b4d43396210ca77e3b79a1677f682604d81509864f5bbb92.02C3nsgbjhL-5KrD8GbSPcfBfqfSTZEmm6j5_ptYczg
+ scenes-app-inbox-slacknotificationssection--personal-channel--dark:
+ hash: v1.k794b7964.039af1bc59057ad3e741687368f75e7a1c60d084505a9dda203e2e1e5c147a4c.nY40DHVp_R6hcU7ZMcRXiy-SdXwJXfOvupwdWsEnV9o
+ scenes-app-inbox-slacknotificationssection--personal-channel--light:
+ hash: v1.k794b7964.146421752e601d082301cac6a9e6e876b230f0577ec852d002b46e7f20a96855.Jf8gfYZimmN2-9NcX-_7wLiTa5rgC1JiUyfDNqnGJ-8
scenes-app-inbox-sourcesteeringmodal--legacy-posture--dark:
hash: v1.k794b7964.d8a52379e95bb0cabff2ab1ad8a4620d0f3ac91394cc057577f9a5c69cafb4d2.H8ZYcq__eOG2AMAmV26hDVqVtTuDsPY5dzZN1CkuwQk
scenes-app-inbox-sourcesteeringmodal--legacy-posture--light:
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 80ee18dad72c..d27de4393a88 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -228,6 +228,7 @@ import type {
ColumnConfigurationApi,
PaginatedColumnConfigurationListApi,
} from 'products/product_analytics/frontend/generated/api.schemas'
+import type { SignalUserAutonomyConfigCreateApi } from 'products/signals/frontend/generated/api.schemas'
import {
SignalReport,
SignalReportArtefact,
@@ -5229,7 +5230,7 @@ const api = {
}
},
async update(
- data: Partial<SignalUserAutonomyConfig>,
+ data: SignalUserAutonomyConfigCreateApi,
userId: string | '@me' = '@me'
): Promise<SignalUserAutonomyConfig> {
return await new ApiRequest().signalUserAutonomy(userId).create({ data })
diff --git a/frontend/src/lib/integrations/slackChannel.ts b/frontend/src/lib/integrations/slackChannel.ts
index 736e136de022..4dfafb0bc578 100644
--- a/frontend/src/lib/integrations/slackChannel.ts
+++ b/frontend/src/lib/integrations/slackChannel.ts
@@ -7,6 +7,17 @@ export function slackChannelId(channelValue: string): string {
return channelValue.split('|')[0]
}
+// Member ids start with U, or W for an Enterprise Grid member. Channel ids start with C, G, or D.
+const SLACK_MEMBER_ID_PATTERN = /^[UW][A-Z0-9]{4,}$/
+
+/**
+ * `chat.postMessage` opens the direct message when handed a member id, so a member target and a
+ * channel target share this format. Mirrors the backend `is_slack_member_target`.
+ */
+export function isSlackMemberTarget(value: string): boolean {
+ return SLACK_MEMBER_ID_PATTERN.test(slackChannelId(value))
+}
+
/**
* The friendly name half (`#channel-name`) of a `${channelId}|#${channelName}` picker value, for
* display. Falls back to the raw value when no name is encoded (e.g. a bare channel id). Mirrors
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 05c08f383882..4421440b3541 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -418,8 +418,9 @@ class SignalUserAutonomyConfigSerializer(serializers.ModelSerializer):
extra_kwargs = {
"slack_notification_channel": {
"help_text": (
- "Slack channel target in the same `channel_id|#channel-name` shape PostHog uses elsewhere "
- "(only the channel id is required). Null disables Slack notifications."
+ "Where the reviewer ping goes, in the same `id|name` shape PostHog uses elsewhere (only "
+ "the id is required): a channel (`C0123ABC456|#alerts`), or a workspace member "
+ "(`U0123ABC456|@sam`) who is sent a direct message. Null disables Slack notifications."
)
},
"slack_notification_min_priority": {
@@ -453,7 +454,20 @@ class SignalUserAutonomyConfigCreateSerializer(serializers.Serializer):
allow_null=True,
allow_blank=True,
max_length=255,
- help_text="`channel_id|#channel-name` target — same convention used by Insight Alerts.",
+ help_text=(
+ "`channel_id|#channel-name` target, the same convention used by Insight Alerts, or a "
+ "`member_id|@display-name` target (`U0123ABC456|@sam`) to send the ping as a direct message. "
+ "A member target is checked against the workspace on save."
+ ),
+ )
+ slack_notification_direct_message = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Set true to send the ping as a direct message from the PostHog app. The caller's own member id is "
+ "resolved in the connected workspace and stored in `slack_notification_channel`, so nothing has to be "
+ "picked. Rejected when the workspace has no eligible account for the caller, and cannot be combined "
+ "with `slack_notification_channel`."
+ ),
)
slack_notification_min_priority = serializers.ChoiceField(
choices=AutonomyPriority.choices,
@@ -472,6 +486,13 @@ class SignalUserAutonomyConfigCreateSerializer(serializers.Serializer):
),
)
+ def validate(self, attrs: dict) -> dict:
+ if attrs.get("slack_notification_direct_message") and attrs.get("slack_notification_channel"):
+ raise serializers.ValidationError(
+ "Set either `slack_notification_channel` or `slack_notification_direct_message`, not both."
+ )
+ return attrs
+
class SignalReportRefundSerializer(serializers.ModelSerializer):
billing_synced = serializers.SerializerMethodField(
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 41d71469325f..61f718885eba 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -3,11 +3,13 @@
Mirrors the inbox Reports tab's actionability gate: a report notifies only if it's actionable
(its latest actionability judgment is immediately_actionable or requires_human_input) — READY is
enforced upstream — and has at least one suggested reviewer that resolves to a destination.
-Each reviewer is routed to one channel: their own configured channel if set (filtered by their
-min-priority), otherwise the team-default channel. Reviewers sharing a channel get a single post
-mentioning only the reviewers routed there. When no suggested reviewer resolves, the report is
-still delivered to the team-default channel (if one is configured) with no mentions, so a team is
-notified even when none of its members are linked to a resolvable GitHub identity.
+Each reviewer is routed to one destination: their own configured target if set (filtered by
+their min-priority), otherwise the team-default channel. A personal target is either a channel or
+the reviewer's own Slack account, which Slack delivers as a direct message. Reviewers sharing a
+destination get a single post mentioning only the reviewers routed there. When no suggested
+reviewer resolves, the report is still delivered to the team-default channel (if one is
+configured) with no mentions, so a team is notified even when none of its members are linked to a
+resolvable GitHub identity.
All sends are best-effort.
"""
@@ -19,10 +21,10 @@ from collections.abc import Iterable
from django.conf import settings
-from slack_sdk.errors import SlackApiError
-
+from posthog.event_usage import groups
from posthog.models import User
from posthog.models.integration import Integration, SlackIntegration
+from posthog.ph_client import ph_scoped_capture
from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS
from products.signals.backend.models import (
@@ -46,6 +48,7 @@ from products.signals.backend.slack_formatting import (
slack_markdown_block as _markdown_block,
strip_chart_references as _strip_chart_references,
)
+from products.signals.backend.slack_notification_targets import is_slack_member_target, lookup_slack_user_id_by_email
# Actionability values shown in the inbox Reports tab. Slack notifications mirror that tab, so a
# report notifies iff its latest actionability judgment is one of these (and it's READY).
@@ -219,10 +222,11 @@ def _resolve_suggested_reviewer_user_ids(report: SignalReport) -> set[int]:
return resolved_user_ids
-def _own_channel_configs_by_user(team_id: int, user_ids: set[int]) -> dict[int, SignalUserAutonomyConfig]:
- """Per-user configs that name an own Slack channel on this team's integration.
+def _own_target_configs_by_user(team_id: int, user_ids: set[int]) -> dict[int, SignalUserAutonomyConfig]:
+ """Per-user configs that name an own Slack target on this team's integration.
- A reviewer absent from this map has no own channel and falls back to the team default.
+ The target is a channel or the reviewer's own Slack account. A reviewer absent from this map
+ has no own target and falls back to the team default.
"""
configs = (
SignalUserAutonomyConfig.objects.filter(user_id__in=user_ids)
@@ -265,32 +269,6 @@ def _posthog_user_display_name(user: User) -> str:
return email or "Unknown user"
-def lookup_slack_user_id_by_email(slack: SlackIntegration, email: str) -> str | None:
- normalized_email = email.strip().lower()
- if not normalized_email:
- return None
-
- try:
- response = slack.client.users_lookupByEmail(email=normalized_email)
- except SlackApiError as exc:
- error_code = exc.response.get("error") if exc.response else None
- if error_code != "users_not_found":
- logger.warning(
- "signals_inbox_slack_user_email_lookup_failed",
- extra={"email": normalized_email, "error": error_code},
- )
- return None
-
- data = response.data if hasattr(response, "data") and isinstance(response.data, dict) else response
- if not isinstance(data, dict) or not data.get("ok"):
- return None
-
- slack_user = data.get("user")
- if not isinstance(slack_user, dict) or not slack_user.get("id"):
- return None
- return str(slack_user["id"])
-
-
def _resolve_reviewer_mentions(slack: SlackIntegration, reviewer_users: list[User]) -> list[str]:
# `<@U…>` mention when the reviewer's email resolves in this workspace, else escaped name.
mentions: list[str] = []
@@ -521,12 +499,16 @@ def _post_signal_evidence_thread(
class _ChannelRoute:
- """One Slack channel and the reviewers routed to it (mentioned only there)."""
+ """One Slack destination and the reviewers routed to it (mentioned only there).
+
+ The destination is a channel, or a member whose id Slack turns into a direct message.
+ """
def __init__(self, integration: Integration, channel: str, *, is_team_channel: bool) -> None:
self.integration = integration
self.channel = channel
self.is_team_channel = is_team_channel
+ self.is_direct_message = is_slack_member_target(channel)
self.users: list[User] = []
@@ -537,10 +519,10 @@ def _build_reviewer_routes(
team_integration: Integration | None,
team_channel: str | None,
) -> list[_ChannelRoute]:
- """Route resolvable suggested reviewers to a destination channel, mentioning them there.
+ """Route resolvable suggested reviewers to a destination, mentioning them there.
- Own channel (filtered by the reviewer's min-priority) if set, else the team default. A reviewer
- filtered out of their own channel does not fall back to the team channel — that was their choice.
+ Own target (filtered by the reviewer's min-priority) if set, else the team default. A reviewer
+ filtered out of their own target does not fall back to the team channel — that was their choice.
Reviewers sharing a destination are grouped so each channel is posted to once, mentioning only
its own reviewers. When no suggested reviewer resolves, the report is still delivered to the
team-default channel (if configured) with no mentions, so a team is notified even when none of
@@ -548,7 +530,7 @@ def _build_reviewer_routes(
"""
reviewer_user_ids = _resolve_suggested_reviewer_user_ids(report)
reviewer_users = {user.id: user for user in User.objects.filter(id__in=reviewer_user_ids)}
- own_configs = _own_channel_configs_by_user(report.team_id, reviewer_user_ids)
+ own_configs = _own_target_configs_by_user(report.team_id, reviewer_user_ids)
# Keyed by (integration_id, channel_id) so a reviewer's own channel and the team
# default collapse into one post when they resolve to the same Slack channel.
@@ -560,6 +542,8 @@ def _build_reviewer_routes(
if route is None:
route = _ChannelRoute(integration, channel, is_team_channel=is_team_channel)
routes[key] = route
+ elif is_team_channel:
+ route.is_team_channel = True
return route
for user_id in sorted(reviewer_user_ids):
@@ -602,9 +586,10 @@ def _deliver_route_notification(
priority: str | None,
source_products: list[str],
repository: str | None,
+ trigger: str,
signals: list[dict] | None = None,
) -> bool:
- """Post one report notification to a route's channel (with optional evidence thread).
+ """Post one report notification to a route's destination (with optional evidence thread).
Shared by the report-ready and reviewer-added dispatchers. Returns True if the top-level
message was sent. Best-effort: Slack errors are logged, not raised.
@@ -615,10 +600,18 @@ def _deliver_route_notification(
"team_id": report.team_id,
"channel": _channel_display_name(route.channel),
"destination": "team" if route.is_team_channel else "user",
+ "target_kind": "direct_message" if route.is_direct_message else "channel",
}
+ delivered = False
try:
slack = SlackIntegration(route.integration)
- mentions = _resolve_reviewer_mentions(slack, route.users)
+ if route.is_direct_message and slack.get_user_by_id(channel_id) is None:
+ # A member reachable when the target was saved can since have left or become a guest.
+ logger.warning("Skipping signals inbox-item Slack DM to an ineligible member", extra=log_context)
+ _capture_notification_delivered(report, route, trigger=trigger, delivered=False)
+ return False
+ # The only reviewer a direct message could mention is the person already reading it.
+ mentions = [] if route.is_direct_message else _resolve_reviewer_mentions(slack, route.users)
blocks, text = _build_message_blocks(
report,
priority=priority,
@@ -627,13 +620,46 @@ def _deliver_route_notification(
repository=repository,
)
response = slack.client.chat_postMessage(channel=channel_id, blocks=blocks, text=text)
+ delivered = True
thread_ts = response.get("ts") if hasattr(response, "get") else None
if signals and thread_ts:
_post_signal_evidence_thread(slack, channel_id, str(thread_ts), signals)
- return True
except Exception:
logger.exception("Failed to deliver signals inbox-item Slack notification", extra=log_context)
- return False
+ _capture_notification_delivered(report, route, trigger=trigger, delivered=delivered)
+ return delivered
+
+
+def _capture_notification_delivered(
+ report: SignalReport, route: _ChannelRoute, *, trigger: str, delivered: bool
+) -> None:
+ """Emit `signals_inbox_notification_delivered` for one destination's outcome.
+
+ Nothing else measures this path, so a reviewer ping that is set up but never arrives looks the
+ same as one nobody configured. The target itself names the customer's own channel or teammate,
+ so only its kind travels.
+
+ Best-effort: never raises, so analytics can't stop a notification.
+ """
+ try:
+ team = report.team
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=str(team.uuid),
+ event="signals_inbox_notification_delivered",
+ properties={
+ "team_id": report.team_id,
+ "report_id": str(report.id),
+ "trigger": trigger,
+ "destination": "team" if route.is_team_channel else "user",
+ "target_kind": "direct_message" if route.is_direct_message else "channel",
+ "reviewer_count": len(route.users),
+ "delivered": delivered,
+ },
+ groups=groups(team.organization, team),
+ )
+ except Exception:
+ logger.exception("Failed to capture signals_inbox_notification_delivered for report %s", report.id)
def dispatch_inbox_item_notifications(
@@ -708,6 +734,7 @@ def dispatch_inbox_item_notifications(
priority=priority,
source_products=sources,
repository=repository,
+ trigger="report_ready",
signals=signals,
):
sent += 1
@@ -731,8 +758,8 @@ def dispatch_reviewer_added_notifications(
pipeline, when a report first becomes READY — this fires when someone manually adds
reviewers afterwards, so a reviewer who wasn't on the report at generation time still
hears about it. It targets only the given logins and only their own configured Slack
- channel: a manual add is a personal ping, so there's no team-default fallback (that
- would ping the whole team for a one-person add) and a reviewer with no personal channel
+ target: a manual add is a personal ping, so there's no team-default fallback (that
+ would ping the whole team for a one-person add) and a reviewer with no personal target
set up (or whose min-priority filters the report out) gets nothing.
Gated on the same READY + actionable condition as the initial notification, so it only
@@ -769,8 +796,8 @@ def dispatch_reviewer_added_notifications(
priority = _latest_priority(report)
- # Personal channels only — a manual add never falls back to the team channel.
- own_configs = _own_channel_configs_by_user(team_id, user_ids)
+ # Personal targets only — a manual add never falls back to the team channel.
+ own_configs = _own_target_configs_by_user(team_id, user_ids)
users_by_id = {user.id: user for user in User.objects.filter(id__in=user_ids)}
routes: dict[tuple[int, str], _ChannelRoute] = {}
@@ -810,6 +837,7 @@ def dispatch_reviewer_added_notifications(
priority=priority,
source_products=sources,
repository=repository,
+ trigger="reviewer_added",
):
sent += 1
logger.info(
diff --git a/products/signals/backend/slack_notification_targets.py b/products/signals/backend/slack_notification_targets.py
new file mode 100644
index 000000000000..4fb6eb2d921e
--- /dev/null
+++ b/products/signals/backend/slack_notification_targets.py
@@ -0,0 +1,183 @@
+"""Slack targets for inbox notifications.
+
+A target is the picker's `id|name` composite: a channel (`C…|#name`) or a workspace member
+(`U…|@name`). Slack's `chat.postMessage` accepts either id as its `channel` and opens the direct
+message for a member id, so both kinds ride in the same stored field.
+
+A member target decides which person receives report contents, so it is resolved when it is saved:
+a settings card can then say that the ping will never arrive, instead of the reviewer finding out
+by never being pinged.
+"""
+
+from __future__ import annotations
+
+import re
+import hashlib
+import logging
+
+from django.core.cache import cache
+
+from rest_framework import serializers
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.integration import Integration, SlackIntegration
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
+
+from products.signals.backend.models import SignalUserAutonomyConfig
+from products.signals.backend.slack_formatting import slack_channel_id_from_target
+
+logger = logging.getLogger(__name__)
+
+# Member ids start with U, or W for an Enterprise Grid member. Channel ids start with C, G, or D.
+_MEMBER_ID_RE = re.compile(r"[UW][A-Z0-9]{4,}")
+
+_UNRESOLVED_MEMBER_ERROR = "PostHog cannot direct message that person. Pick someone else."
+_UNRESOLVED_SELF_ERROR = (
+ "PostHog could not find your account in this Slack workspace. Connect your Slack account, or pick a channel."
+)
+_SLACK_UNAVAILABLE_ERROR = "Slack did not answer. Try saving this again in a moment."
+_SLACK_MISSING_SCOPE_ERROR = (
+ "Your Slack connection cannot list workspace members. Reconnect Slack, and then save this setting again."
+)
+_NO_WORKSPACE_ERROR = "Choose the Slack workspace to send these through."
+_MEMBER_LOOKUPS_PER_MINUTE = 30
+
+
+def is_slack_member_target(target: str) -> bool:
+ """Whether a target addresses one workspace member, which Slack delivers as a direct message."""
+ return bool(_MEMBER_ID_RE.fullmatch(slack_channel_id_from_target(target)))
+
+
+def saved_notification_integration(user: User) -> Integration | None:
+ """The Slack workspace this user's notifications already go through, if any."""
+ config = SignalUserAutonomyConfig.objects.filter(user=user).select_related("slack_notification_integration").first()
+ return config.slack_notification_integration if config else None
+
+
+def lookup_slack_user_id_by_email(
+ slack: SlackIntegration, email: str, integration: Integration | None = None
+) -> str | None:
+ integration = integration or slack.integration
+ normalized_email = email.strip().lower()
+ if not normalized_email:
+ return None
+
+ email_hash = hashlib.sha256(normalized_email.encode()).hexdigest()
+ lookup_key = f"signals/slack/{integration.id}/users_by_email/{email_hash}"
+ cached_member_id = cache.get(lookup_key)
+ if cached_member_id is not None:
+ return cached_member_id or None
+
+ _take_member_lookup_budget(integration)
+ try:
+ response = slack.client.users_lookupByEmail(email=normalized_email)
+ except SlackApiError as exc:
+ error_code = exc.response.get("error") if exc.response else None
+ if error_code == "users_not_found":
+ cache.set(lookup_key, "", 60 * 60)
+ return None
+ logger.warning(
+ "signals_inbox_slack_user_email_lookup_failed",
+ extra={"integration_id": integration.id, "error": error_code},
+ )
+ raise
+
+ data = response.data if hasattr(response, "data") and isinstance(response.data, dict) else response
+ slack_user = data.get("user") if isinstance(data, dict) and data.get("ok") else None
+ member_id = str(slack_user["id"]) if isinstance(slack_user, dict) and slack_user.get("id") else None
+ cache.set(lookup_key, member_id or "", 60 * 60)
+ return member_id
+
+
+def _take_member_lookup_budget(integration: Integration) -> None:
+ budget_key = f"signals/slack/{integration.id}/member_lookup_budget"
+ try:
+ lookups = 1 if cache.add(budget_key, 1, 60) else cache.incr(budget_key)
+ except ValueError:
+ lookups = 1
+ if lookups > _MEMBER_LOOKUPS_PER_MINUTE:
+ raise serializers.ValidationError({"slack_notification_direct_message": _SLACK_UNAVAILABLE_ERROR})
+
+
+def _cached_slack_member(slack: SlackIntegration, integration: Integration, member_id: str) -> dict | None:
+ lookup_key = f"slack/{integration.id}/users/{member_id}"
+ cached_lookup = cache.get(lookup_key)
+ if cached_lookup is not None:
+ return cached_lookup[0] if cached_lookup else None
+
+ _take_member_lookup_budget(integration)
+ member = slack.get_user_by_id(member_id)
+ serialized_lookup = (
+ [{"id": member["id"], "name": member.get("name", ""), "display_name": _member_display_name(member)}]
+ if member
+ else []
+ )
+ cache.set(lookup_key, serialized_lookup, 60 * 60)
+ return serialized_lookup[0] if serialized_lookup else None
+
+
+def resolve_own_direct_message_target(user: User, integration: Integration | None) -> str:
+ """Resolve a user's own Slack account in this workspace to a `U…|@name` target.
+
+ The Slack account they linked to PostHog answers first, then their PostHog email against the
+ workspace directory, which is what lets someone turn direct messages on without picking
+ anything. `get_user_by_id` then decides eligibility the same way the member picker does.
+ """
+ if integration is None:
+ raise serializers.ValidationError({"slack_notification_direct_message": _NO_WORKSPACE_ERROR})
+ slack = SlackIntegration(integration)
+ try:
+ member_id = _linked_slack_member_id(user, integration) or (
+ lookup_slack_user_id_by_email(slack, user.email, integration) if user.email else None
+ )
+ member = _cached_slack_member(slack, integration, member_id) if member_id else None
+ except SlackApiError as exc:
+ logger.warning("signals_slack_self_lookup_failed", extra={"integration_id": integration.id})
+ error_code = exc.response.get("error") if exc.response else None
+ message = _SLACK_MISSING_SCOPE_ERROR if error_code == "missing_scope" else _SLACK_UNAVAILABLE_ERROR
+ raise serializers.ValidationError({"slack_notification_direct_message": message})
+ if member is None:
+ raise serializers.ValidationError({"slack_notification_direct_message": _UNRESOLVED_SELF_ERROR})
+ return f"{member['id']}|@{_member_display_name(member)}"
+
+
+def validate_slack_notification_target(user: User, target: str, integration: Integration | None) -> None:
+ """Resolve a member target a caller sent itself, or raise.
+
+ A channel target needs no lookup: the picker already warns when the app is missing from the
+ channel. A member target goes through the same eligibility check as the resolved one, so an
+ API caller cannot store a bot, a deactivated account, a guest, or a Slack Connect member whose
+ home workspace is another one.
+ """
+ if not is_slack_member_target(target):
+ return
+ if integration is None:
+ raise serializers.ValidationError({"slack_notification_channel": _NO_WORKSPACE_ERROR})
+ resolved_target = resolve_own_direct_message_target(user, integration)
+ if slack_channel_id_from_target(resolved_target) != slack_channel_id_from_target(target):
+ raise serializers.ValidationError({"slack_notification_channel": _UNRESOLVED_MEMBER_ERROR})
+
+
+def _linked_slack_member_id(user: User, integration: Integration) -> str | None:
+ link = (
+ UserIntegration.objects.filter(
+ user=user,
+ kind=UserIntegration.IntegrationKind.SLACK,
+ config__slack_team_id=integration.integration_id,
+ )
+ .order_by("-created_at")
+ .first()
+ )
+ return link.integration_id if link else None
+
+
+def _member_display_name(member: dict) -> str:
+ profile = member.get("profile") or {}
+ return (
+ profile.get("display_name")
+ or profile.get("real_name")
+ or member.get("display_name")
+ or member.get("name")
+ or "you"
+ )
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index 5fd05e2a05c7..333e60f0a417 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -305,15 +305,23 @@ def test_dispatch_no_notification_without_team_channel_or_user_config(org_and_te
assert slack_cls.call_count == 0
+ ("target", "expected_conversation", "expects_mention"),
+ [
+ ("C123|#inbox", "C123", True),
+ # A member target is delivered as a direct message, which mentions nobody.
+ ("U0123ABC456|@reviewer", "U0123ABC456", False),
+ ],
+)
@pytest.mark.django_db
-def test_dispatch_sends_to_configured_reviewer(org_and_team):
+def test_dispatch_sends_to_configured_reviewer(org_and_team, target, expected_conversation, expects_mention):
org, team = org_and_team
user = _make_reviewer_user(org, "[email protected]", "another-bot")
integration = _make_slack_integration(team, user)
SignalUserAutonomyConfig.objects.create(
user=user,
slack_notification_integration=integration,
- slack_notification_channel="C123|#inbox",
+ slack_notification_channel=target,
)
report = _make_ready_report(team, priority=AutonomyPriority.P1, suggested_logins=["another-bot"])
@@ -331,16 +339,43 @@ def test_dispatch_sends_to_configured_reviewer(org_and_team):
assert sent == 1
assert fake_client.chat_postMessage.call_count == 1
call_kwargs = fake_client.chat_postMessage.call_args.kwargs
- assert call_kwargs["channel"] == "C123"
+ assert call_kwargs["channel"] == expected_conversation
assert "Report (P1)" in call_kwargs["text"]
blocks = call_kwargs["blocks"]
assert blocks[0]["text"]["text"] == "Test report"
assert blocks[1]["text"].startswith("**❗ P1 · Error tracking**")
- assert "👤 Suggested reviewers: <@U_REVIEWER>" in blocks[2]["elements"][0]["text"]
+ context_text = blocks[2]["elements"][0]["text"]
+ if expects_mention:
+ assert "👤 Suggested reviewers: <@U_REVIEWER>" in context_text
+ else:
+ assert "Suggested reviewers" not in context_text
assert all("<@" not in t for t in _plain_text_block_texts(blocks))
assert blocks[3]["elements"][0]["url"] == f"{settings.SITE_URL}/project/{team.id}/inbox/reports/{report.id}"
+def test_dispatch_skips_a_direct_message_to_an_ineligible_member(org_and_team):
+ # Report contents must not follow a member who left the workspace or became a guest.
+ org, team = org_and_team
+ user = _make_reviewer_user(org, "[email protected]", "dm-bot")
+ integration = _make_slack_integration(team, user)
+ SignalUserAutonomyConfig.objects.create(
+ user=user,
+ slack_notification_integration=integration,
+ slack_notification_channel="U0123ABC456|@reviewer",
+ )
+ report = _make_ready_report(team, priority=AutonomyPriority.P1, suggested_logins=["dm-bot"])
+
+ fake_client = MagicMock()
+ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:
+ slack_cls.return_value.client = fake_client
+ slack_cls.return_value.get_user_by_id.return_value = None
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 0
+ assert fake_client.chat_postMessage.call_count == 0
+
+
@pytest.mark.django_db
def test_dispatch_posts_to_team_channel_without_per_user_config(org_and_team):
org, team = org_and_team
@@ -487,8 +522,11 @@ def test_dispatch_groups_own_and_fallback_reviewers_sharing_a_channel(org_and_te
return {"[email protected]": "U_OWN", "[email protected]": "U_FALLBACK"}.get(email.strip().lower())
fake_client = MagicMock()
+ capture_context = MagicMock()
+ capture = capture_context.__enter__.return_value
with (
patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,
+ patch("products.signals.backend.slack_inbox_notifications.ph_scoped_capture", return_value=capture_context),
patch(
"products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
side_effect=_slack_id,
@@ -501,6 +539,7 @@ def test_dispatch_groups_own_and_fallback_reviewers_sharing_a_channel(org_and_te
assert fake_client.chat_postMessage.call_count == 1
body = fake_client.chat_postMessage.call_args.kwargs["blocks"][2]["elements"][0]["text"]
assert "<@U_OWN>" in body and "<@U_FALLBACK>" in body
+ assert capture.call_args.kwargs["properties"]["destination"] == "team"
@pytest.mark.django_db
diff --git a/products/signals/backend/test/test_slack_notification_targets.py b/products/signals/backend/test/test_slack_notification_targets.py
new file mode 100644
index 000000000000..e50cd841b3ff
--- /dev/null
+++ b/products/signals/backend/test/test_slack_notification_targets.py
@@ -0,0 +1,207 @@
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import serializers, status
+from slack_sdk.errors import SlackApiError
+
+from posthog.models.integration import Integration
+from posthog.models.user_integration import UserIntegration
+
+from products.signals.backend.models import SignalUserAutonomyConfig
+from products.signals.backend.slack_notification_targets import (
+ is_slack_member_target,
+ lookup_slack_user_id_by_email,
+ validate_slack_notification_target,
+)
+
+
+class TestSlackNotificationTargets(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ @parameterized.expand(
+ [
+ ("member id", "U0123ABC456", True),
+ ("member id with display name", "U0123ABC456|@sam", True),
+ ("enterprise grid member", "W0123ABC456|@sam", True),
+ ("public channel", "C0123ABC456|#alerts", False),
+ ("private channel", "G0123ABC456|#alerts", False),
+ # A `D` id is Slack's own DM conversation, delivered as a plain channel target.
+ ("dm conversation", "D0123ABC456", False),
+ ("free text", "not-a-target", False),
+ ]
+ )
+ def test_is_slack_member_target(self, _name: str, target: str, expected: bool) -> None:
+ assert is_slack_member_target(target) is expected
+
+ def test_channel_target_is_not_resolved_against_slack(self) -> None:
+ with patch("products.signals.backend.slack_notification_targets.SlackIntegration") as slack_cls:
+ validate_slack_notification_target(MagicMock(), "C0123ABC456|#alerts", None)
+ assert slack_cls.call_count == 0
+
+ def test_member_target_without_a_workspace_is_rejected(self) -> None:
+ with self.assertRaises(serializers.ValidationError):
+ validate_slack_notification_target(MagicMock(), "U0123ABC456|@sam", None)
+
+ def test_email_lookup_reuses_the_cached_result(self) -> None:
+ integration = MagicMock(id=321)
+ slack = MagicMock(integration=integration)
+ slack.client.users_lookupByEmail.return_value = {"ok": True, "user": {"id": "U0123ABC456"}}
+
+ assert lookup_slack_user_id_by_email(slack, "[email protected]") == "U0123ABC456"
+ assert lookup_slack_user_id_by_email(slack, "[email protected]") == "U0123ABC456"
+ slack.client.users_lookupByEmail.assert_called_once_with(email="[email protected]")
+
+ def test_email_lookup_stops_when_the_workspace_budget_is_spent(self) -> None:
+ integration = MagicMock(id=654)
+ slack = MagicMock(integration=integration)
+ cache.set("signals/slack/654/member_lookup_budget", 30, 60)
+
+ with self.assertRaises(serializers.ValidationError):
+ lookup_slack_user_id_by_email(slack, "[email protected]")
+ slack.client.users_lookupByEmail.assert_not_called()
+
+
+class TestSlackNotificationTargetAPI(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T123",
+ config={"team": {"id": "T123"}},
+ sensitive_config={"access_token": "xoxb-test"},
+ created_by=self.user,
+ )
+
+ def _url(self) -> str:
+ return "/api/users/@me/signal_autonomy/"
+
+ def _post(self, payload: dict, *, member: dict | None, email_member_id: str | None = None):
+ """POST the payload with a Slack workspace that knows `member` and nobody else."""
+ with patch("products.signals.backend.slack_notification_targets.SlackIntegration") as slack_cls:
+ slack = slack_cls.return_value
+ slack.get_user_by_id.side_effect = lambda member_id: (
+ member if member and member_id == member["id"] else None
+ )
+ slack.client.users_lookupByEmail.return_value = {
+ "ok": bool(email_member_id),
+ "user": {"id": email_member_id},
+ }
+ response = self.client.post(
+ self._url(), {"slack_notification_integration_id": self.integration.id, **payload}
+ )
+ return response, slack
+
+ def _saved_target(self) -> str | None:
+ config = SignalUserAutonomyConfig.objects.filter(user=self.user).first()
+ return config.slack_notification_channel if config else None
+
+ def test_direct_message_resolves_the_callers_own_slack_account_by_email(self):
+ response, _ = self._post(
+ {"slack_notification_direct_message": True},
+ member={"id": "U0123ABC456", "profile": {"display_name": "sam"}},
+ email_member_id="U0123ABC456",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert self._saved_target() == "U0123ABC456|@sam"
+
+ def test_direct_message_prefers_the_slack_account_linked_to_posthog(self):
+ # The linked account wins over an email match, which misses when the two emails differ.
+ UserIntegration.objects.create(
+ user=self.user,
+ kind=UserIntegration.IntegrationKind.SLACK,
+ integration_id="U0456DEF789",
+ config={"slack_team_id": "T123"},
+ )
+
+ response, slack = self._post(
+ {"slack_notification_direct_message": True},
+ member={"id": "U0456DEF789", "profile": {"display_name": "kai"}},
+ email_member_id="U0123ABC456",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert self._saved_target() == "U0456DEF789|@kai"
+ slack.client.users_lookupByEmail.assert_not_called()
+
+ def test_direct_message_is_refused_when_the_workspace_has_no_account_for_the_caller(self):
+ # Saving anyway would leave a setting that never delivers, which reads as "notifications on".
+ response, _ = self._post({"slack_notification_direct_message": True}, member=None)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert self._saved_target() is None
+
+ def test_member_target_the_workspace_cannot_dm_is_refused(self):
+ # `get_user_by_id` refuses bots, deactivated accounts, guests, and outside members.
+ response, _ = self._post({"slack_notification_channel": "U0123ABC456|@sam"}, member=None)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert self._saved_target() is None
+
+ def test_member_target_must_match_the_callers_own_slack_account(self):
+ response, _ = self._post(
+ {"slack_notification_channel": "U0999OTHER|@other"},
+ member={"id": "U0123ABC456", "profile": {"display_name": "sam"}},
+ email_member_id="U0123ABC456",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert self._saved_target() is None
+
+ def test_member_target_can_match_the_callers_own_slack_account(self):
+ response, _ = self._post(
+ {"slack_notification_channel": "U0123ABC456|@sam"},
+ member={"id": "U0123ABC456", "profile": {"display_name": "sam"}},
+ email_member_id="U0123ABC456",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert self._saved_target() == "U0123ABC456|@sam"
+
+ def test_workspace_change_resolves_a_saved_direct_message_again(self):
+ SignalUserAutonomyConfig.objects.create(
+ user=self.user,
+ slack_notification_integration=self.integration,
+ slack_notification_channel="U0123OLD456|@sam",
+ )
+ next_integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T456",
+ config={"team": {"id": "T456"}},
+ sensitive_config={"access_token": "xoxb-next"},
+ created_by=self.user,
+ )
+
+ response, _ = self._post(
+ {"slack_notification_integration_id": next_integration.id},
+ member={"id": "U0456NEW789", "profile": {"display_name": "sam"}},
+ email_member_id="U0456NEW789",
+ )
+
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert self._saved_target() == "U0456NEW789|@sam"
+
+ def test_missing_member_scope_returns_reconnect_guidance(self):
+ with patch("products.signals.backend.slack_notification_targets.SlackIntegration") as slack_cls:
+ slack_cls.return_value.client.users_lookupByEmail.side_effect = SlackApiError(
+ "missing scope", {"error": "missing_scope"}
+ )
+ response = self.client.post(
+ self._url(),
+ {
+ "slack_notification_integration_id": self.integration.id,
+ "slack_notification_direct_message": True,
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ body = response.json()
+ assert "Reconnect Slack" in str(body), body
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 1dbff8678b28..6a669dd3d4f5 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -154,6 +154,12 @@ from products.signals.backend.serializers import (
SignalUserAutonomyConfigSerializer,
)
from products.signals.backend.signal_metadata import fetch_source_products_for_reports
+from products.signals.backend.slack_notification_targets import (
+ is_slack_member_target,
+ resolve_own_direct_message_target,
+ saved_notification_integration,
+ validate_slack_notification_target,
+)
from products.signals.backend.task_attribution import (
TASK_ID_HEADER,
resolve_request_attribution,
@@ -4537,7 +4543,9 @@ class SignalUserAutonomyConfigView(APIView):
return Response(status=status.HTTP_404_NOT_FOUND)
return Response(SignalUserAutonomyConfigSerializer(config).data)
- @extend_schema(responses={200: SignalUserAutonomyConfigSerializer})
+ @extend_schema(
+ request=SignalUserAutonomyConfigCreateSerializer, responses={200: SignalUserAutonomyConfigSerializer}
+ )
def post(self, request, user_id, **kwargs):
user = self._resolve_user(request, user_id)
serializer = SignalUserAutonomyConfigCreateSerializer(data=request.data)
@@ -4555,7 +4563,8 @@ class SignalUserAutonomyConfigView(APIView):
defaults["github_assign_on_pull_request"] = validated.get("github_assign_on_pull_request", False)
if "slack_notification_channel" in serializer.initial_data:
defaults["slack_notification_channel"] = validated.get("slack_notification_channel") or None
- if "slack_notification_integration_id" in serializer.initial_data:
+ integration_in_request = "slack_notification_integration_id" in serializer.initial_data
+ if integration_in_request:
integration_id = validated.get("slack_notification_integration_id")
integration = None
if integration_id is not None:
@@ -4575,6 +4584,36 @@ class SignalUserAutonomyConfigView(APIView):
)
integration = candidate
defaults["slack_notification_integration"] = integration
+ wants_direct_message = bool(validated.get("slack_notification_direct_message"))
+ existing_config = SignalUserAutonomyConfig.objects.filter(user=user).first() if integration_in_request else None
+ if (
+ integration_in_request
+ and "slack_notification_channel" not in serializer.initial_data
+ and not wants_direct_message
+ and existing_config is not None
+ and existing_config.slack_notification_integration_id
+ != getattr(defaults["slack_notification_integration"], "id", None)
+ ):
+ existing_target = existing_config.slack_notification_channel or ""
+ if is_slack_member_target(existing_target) and defaults["slack_notification_integration"] is not None:
+ defaults["slack_notification_channel"] = resolve_own_direct_message_target(
+ user, defaults["slack_notification_integration"]
+ )
+ else:
+ defaults["slack_notification_channel"] = None
+
+ target = defaults.get("slack_notification_channel")
+ if wants_direct_message or (target and is_slack_member_target(target)):
+ # Resolve against the workspace that would deliver it: this request's, or the saved one.
+ workspace = (
+ defaults["slack_notification_integration"]
+ if integration_in_request
+ else saved_notification_integration(user)
+ )
+ if wants_direct_message:
+ defaults["slack_notification_channel"] = resolve_own_direct_message_target(user, workspace)
+ elif target:
+ validate_slack_notification_target(user, target, workspace)
config, _created = SignalUserAutonomyConfig.objects.update_or_create(
user=user,
defaults=defaults,
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index a59a15586dee..d4cb57014879 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4384,7 +4384,7 @@ export interface SignalUserAutonomyConfigApi {
*/
readonly slack_notification_integration_id: number | null
/**
- * Slack channel target in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null disables Slack notifications.
+ * Where the reviewer ping goes, in the same `id|name` shape PostHog uses elsewhere (only the id is required): a channel (`C0123ABC456|#alerts`), or a workspace member (`U0123ABC456|@sam`) who is sent a direct message. Null disables Slack notifications.
* @maxLength 255
* @nullable
*/
@@ -4403,6 +4403,33 @@ export interface SignalUserAutonomyConfigApi {
readonly updated_at: string
}
+export interface SignalUserAutonomyConfigCreateApi {
+ autostart_priority?: AutonomyPriorityEnumApi | null
+ /**
+ * Primary key of a Slack `Integration` row in one of the caller's teams. Pair with `slack_notification_channel` to enable notifications; pass null on either to disable them.
+ * @nullable
+ */
+ slack_notification_integration_id?: number | null
+ /**
+ * `channel_id|#channel-name` target, the same convention used by Insight Alerts, or a `member_id|@display-name` target (`U0123ABC456|@sam`) to send the ping as a direct message. A member target is checked against the workspace on save.
+ * @maxLength 255
+ * @nullable
+ */
+ slack_notification_channel?: string | null
+ /** Set true to send the ping as a direct message from the PostHog app. The caller's own member id is resolved in the connected workspace and stored in `slack_notification_channel`, so nothing has to be picked. Rejected when the workspace has no eligible account for the caller, and cannot be combined with `slack_notification_channel`. */
+ slack_notification_direct_message?: boolean
+ /** P0 is highest. Null = notify for every priority. When set, reports without a priority judgment do not notify.
+ *
+ * * `P0` - P0
+ * * `P1` - P1
+ * * `P2` - P2
+ * * `P3` - P3
+ * * `P4` - P4 */
+ slack_notification_min_priority?: AutonomyPriorityEnumApi | null
+ /** Add this user as a GitHub assignee on implementation pull requests for reports that suggest them as reviewer. Off by default. Turning it off stops future assignment and never removes an existing assignee. */
+ github_assign_on_pull_request?: boolean
+}
+
export type SignalsProcessingListParams = {
/**
* Number of results to return per page.
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 29c7ec63526d..b5f6f3e2fa3c 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -78,6 +78,7 @@ import type {
SignalScoutRunSummaryApi,
SignalSourceConfigApi,
SignalUserAutonomyConfigApi,
+ SignalUserAutonomyConfigCreateApi,
SignalsProcessingListParams,
SignalsReportArtefactsListParams,
SignalsReportsListParams,
@@ -1709,14 +1710,14 @@ export const getUsersSignalAutonomyCreateUrl = (userId: string) => {
*/
export const usersSignalAutonomyCreate = async (
userId: string,
- signalUserAutonomyConfigApi?: NonReadonly<SignalUserAutonomyConfigApi>,
+ signalUserAutonomyConfigCreateApi?: SignalUserAutonomyConfigCreateApi,
options?: RequestInit
): Promise<SignalUserAutonomyConfigApi> => {
return apiMutator<SignalUserAutonomyConfigApi>(getUsersSignalAutonomyCreateUrl(userId), {
...options,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(signalUserAutonomyConfigApi),
+ body: JSON.stringify(signalUserAutonomyConfigCreateApi),
})
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 3f1f38a7191b..76fd4aa82017 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1868,33 +1868,43 @@ export const UsersSignalAutonomyCreateBody = /* @__PURE__ */ zod.object({
zod
.enum(['P0', 'P1', 'P2', 'P3', 'P4'])
.describe('\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'),
- zod.enum(['']),
zod.null(),
])
.optional(),
+ slack_notification_integration_id: zod
+ .number()
+ .nullish()
+ .describe(
+ "Primary key of a Slack `Integration` row in one of the caller's teams. Pair with `slack_notification_channel` to enable notifications; pass null on either to disable them."
+ ),
slack_notification_channel: zod
.string()
.max(usersSignalAutonomyCreateBodySlackNotificationChannelMax)
.nullish()
.describe(
- 'Slack channel target in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null disables Slack notifications.'
+ '`channel_id|#channel-name` target, the same convention used by Insight Alerts, or a `member_id|@display-name` target (`U0123ABC456|@sam`) to send the ping as a direct message. A member target is checked against the workspace on save.'
+ ),
+ slack_notification_direct_message: zod
+ .boolean()
+ .optional()
+ .describe(
+ "Set true to send the ping as a direct message from the PostHog app. The caller's own member id is resolved in the connected workspace and stored in `slack_notification_channel`, so nothing has to be picked. Rejected when the workspace has no eligible account for the caller, and cannot be combined with `slack_notification_channel`."
),
slack_notification_min_priority: zod
.union([
zod
.enum(['P0', 'P1', 'P2', 'P3', 'P4'])
.describe('\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'),
- zod.enum(['']),
zod.null(),
])
.optional()
.describe(
- 'Minimum report priority that triggers a Slack notification. P0 is highest. Null means notify on every priority. When set, reports without a priority judgment do not notify.\n\n\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'
+ 'P0 is highest. Null = notify for every priority. When set, reports without a priority judgment do not notify.\n\n\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'
),
github_assign_on_pull_request: zod
.boolean()
.optional()
.describe(
- 'Whether to add this user as a GitHub assignee on implementation pull requests for reports that suggest them as reviewer. Off by default. Assignment is additive, so turning it off never removes an assignee from a pull request that already has one.'
+ 'Add this user as a GitHub assignee on implementation pull requests for reports that suggest them as reviewer. Off by default. Turning it off stops future assignment and never removes an existing assignee.'
),
})
diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx
new file mode 100644
index 000000000000..5adaf08d11f1
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.stories.tsx
@@ -0,0 +1,87 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { useStorybookMocks } from '~/mocks/browser'
+
+import { SlackNotificationsSection } from './SlackNotificationsSection'
+
+const WORKSPACE = { id: 1, kind: 'slack', display_name: 'PostHog', config: {}, created_at: '2026-01-01T00:00:00Z' }
+
+const CHANNELS = [
+ { id: 'C0123ABC456', name: 'self-driving', is_private: false, is_member: true, is_ext_shared: false },
+ { id: 'C0456DEF789', name: 'engineering', is_private: false, is_member: true, is_ext_shared: false },
+]
+
+interface CardsState {
+ connected?: boolean
+ teamChannel?: string | null
+ /** The personal reviewer ping target: the person's own account (`U…|@name`) or a channel. */
+ myTarget?: string | null
+ /** Personal notifications turned on with no target chosen yet. */
+ awaitingTarget?: boolean
+}
+
+function Cards({
+ connected = true,
+ teamChannel = null,
+ myTarget = null,
+ awaitingTarget = false,
+}: CardsState): JSX.Element {
+ useStorybookMocks({
+ get: {
+ '/api/environments/:team_id/integrations/': { results: connected ? [WORKSPACE] : [] },
+ '/api/environments/:team_id/integrations/:id/channels': { channels: CHANNELS, has_more: false },
+ '/api/projects/:team_id/signals/config/': {
+ id: 'cfg-1',
+ default_slack_notification_channel: teamChannel,
+ default_autostart_priority: 'P2',
+ autostart_base_branches: {},
+ },
+ '/api/users/@me/signal_autonomy/': {
+ id: 'auto-1',
+ autostart_priority: null,
+ slack_notification_integration_id: myTarget || awaitingTarget ? WORKSPACE.id : null,
+ slack_notification_channel: myTarget,
+ slack_notification_min_priority: null,
+ },
+ },
+ })
+ // Mimic the agents rail (`w-80` aside + the column's `px-4 py-3`) so the cards lay out as in the scene.
+ return (
+ <div className="w-80 px-4 py-3 bg-surface-secondary">
+ <SlackNotificationsSection />
+ </div>
+ )
+}
+
+const meta: Meta = {
+ title: 'Scenes-App/Inbox/SlackNotificationsSection',
+ component: SlackNotificationsSection,
+ parameters: {
+ layout: 'centered',
+ viewMode: 'story',
+ mockDate: '2024-03-20',
+ },
+}
+export default meta
+
+type Story = StoryObj
+
+export const NotConnected: Story = {
+ render: () => <Cards connected={false} />,
+}
+
+export const NothingConfigured: Story = {
+ render: () => <Cards />,
+}
+
+export const AwaitingTarget: Story = {
+ render: () => <Cards awaitingTarget />,
+}
+
+export const DirectMessageToMe: Story = {
+ render: () => <Cards myTarget="U0123ABC456|@sam" />,
+}
+
+export const PersonalChannel: Story = {
+ render: () => <Cards teamChannel="C0456DEF789|#engineering" myTarget="C0123ABC456|#self-driving" />,
+}
diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx
new file mode 100644
index 000000000000..8fe63f845046
--- /dev/null
+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.test.tsx
@@ -0,0 +1,126 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import type { IntegrationType } from '~/types'
+
+import { SlackNotificationsSection } from './SlackNotificationsSection'
+
+const WORKSPACE = { id: 1, kind: 'slack', display_name: 'PostHog' } as IntegrationType
+const DM_TARGET = 'U0123ABC456|@sam'
+const DM_SAVED = 'PostHog sends these to @sam in Slack.'
+// Anchored: the team card's copy carries the same sentence, after one of its own.
+const CHANNEL_HELP = /^PostHog must be in the channel/
+
+describe('SlackNotificationsSection', () => {
+ let autonomyConfig: Record<string, unknown> | null = null
+ let saves: Record<string, unknown>[] = []
+ let saveGate: Promise<void> | null = null
+
+ beforeEach(() => {
+ initKeaTests()
+ autonomyConfig = null
+ saves = []
+ saveGate = null
+ // msw handlers reset between tests, so register per test rather than once per file.
+ useMocks({
+ get: {
+ '/api/environments/:team_id/integrations/': () => [200, { results: [WORKSPACE] }],
+ '/api/environments/:team_id/integrations/:id/channels': () => [200, { channels: [], has_more: false }],
+ '/api/projects/:team_id/signals/config/': () => [200, { default_slack_notification_channel: null }],
+ '/api/users/@me/signal_autonomy/': () =>
+ autonomyConfig ? [200, autonomyConfig] : [404, { detail: 'Not found' }],
+ },
+ post: {
+ '/api/users/@me/signal_autonomy/': async ({ request }) => {
+ const body = (await request.clone().json()) as Record<string, unknown>
+ saves.push(body)
+ await saveGate
+ // The client never names the direct message target; the API answers with it.
+ const { slack_notification_direct_message: wantsDm, ...fields } = body
+ autonomyConfig = {
+ ...autonomyConfig,
+ ...fields,
+ ...(wantsDm ? { slack_notification_channel: DM_TARGET } : {}),
+ }
+ return [200, autonomyConfig]
+ },
+ },
+ })
+ })
+ afterEach(cleanup)
+
+ it('opens a saved direct message on the direct message tab', async () => {
+ autonomyConfig = { slack_notification_integration_id: 1, slack_notification_channel: DM_TARGET }
+
+ render(<SlackNotificationsSection />)
+
+ expect(await screen.findByText(DM_SAVED)).toBeInTheDocument()
+ expect(screen.queryByText(CHANNEL_HELP)).not.toBeInTheDocument()
+ })
+
+ // The channel picker emits a clear when it mounts empty, which must not wipe a saved target.
+ it('keeps a saved direct message when the channel tab is opened', async () => {
+ autonomyConfig = { slack_notification_integration_id: 1, slack_notification_channel: DM_TARGET }
+
+ render(<SlackNotificationsSection />)
+ expect(await screen.findByText(DM_SAVED)).toBeInTheDocument()
+ await userEvent.click(screen.getByText('Channel'))
+
+ expect(await screen.findByText(CHANNEL_HELP)).toBeInTheDocument()
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ expect(saves).toEqual([])
+ })
+
+ it('turns the card on straight into a direct message', async () => {
+ render(<SlackNotificationsSection />)
+
+ await userEvent.click(await screen.findByLabelText('Enable Slack notifications'))
+
+ expect(await screen.findByText(DM_SAVED)).toBeInTheDocument()
+ expect(saves).toEqual([{ slack_notification_integration_id: 1, slack_notification_direct_message: true }])
+ })
+
+ // Switching from a channel asks the API for the target, since only it knows the member id.
+ it('replaces a saved channel with a direct message', async () => {
+ autonomyConfig = { slack_notification_integration_id: 1, slack_notification_channel: 'C0123ABC456|#alerts' }
+
+ render(<SlackNotificationsSection />)
+ await userEvent.click(await screen.findByText('Direct message'))
+ await userEvent.click(await screen.findByText('Send me a direct message'))
+
+ expect(await screen.findByText(DM_SAVED)).toBeInTheDocument()
+ expect(saves).toEqual([{ slack_notification_integration_id: 1, slack_notification_direct_message: true }])
+ })
+
+ it('disables the switch while the direct message is being saved', async () => {
+ let finishSave: () => void = () => {}
+ saveGate = new Promise((resolve) => {
+ finishSave = resolve
+ })
+
+ render(<SlackNotificationsSection />)
+ const toggle = await screen.findByLabelText('Enable Slack notifications')
+ await userEvent.click(toggle)
+
+ expect(toggle).toBeDisabled()
+ finishSave()
+ expect(await screen.findByText(DM_SAVED)).toBeInTheDocument()
+ })
+
+ it('returns to direct message mode after notifications are disabled', async () => {
+ autonomyConfig = { slack_notification_integration_id: 1, slack_notification_channel: DM_TARGET }
+
+ render(<SlackNotificationsSection />)
+ await userEvent.click(await screen.findByText('Channel'))
+ const toggle = screen.getByLabelText('Enable Slack notifications')
+ await userEvent.click(toggle)
+ await waitFor(() => expect(toggle).not.toBeDisabled())
+ await userEvent.click(toggle)
+
+ expect(await screen.findByText(DM_SAVED)).toBeInTheDocument()
+ })
+})
diff --git a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx
index f986bce3d0fe..54e11f15d157 100644
--- a/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx
+++ b/products/signals/frontend/inbox/components/config/SlackNotificationsSection.tsx
@@ -2,10 +2,11 @@ import { useActions, useMountedLogic, useValues } from 'kea'
import { ReactNode, useState } from 'react'
import { IconChevronRight } from '@posthog/icons'
-import { LemonSelect, LemonSkeleton, LemonSwitch, Link } from '@posthog/lemon-ui'
+import { LemonButton, LemonSegmentedButton, LemonSelect, LemonSkeleton, LemonSwitch, Link } from '@posthog/lemon-ui'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { isSlackMemberTarget, slackChannelDisplayName } from 'lib/integrations/slackChannel'
import { SlackChannelPicker } from 'lib/integrations/SlackIntegrationHelpers'
import { IconSlack } from 'lib/lemon-ui/icons'
import { urls } from 'scenes/urls'
@@ -14,11 +15,13 @@ import { IntegrationType } from '~/types'
import { signalTeamConfigLogic } from '../../logics/signalTeamConfigLogic'
import { userAutonomyLogic } from '../../logics/userAutonomyLogic'
-import { PRIORITY_THRESHOLD_OPTIONS, SignalReportPriority } from '../../types'
+import { PRIORITY_THRESHOLD_OPTIONS, SignalReportPriority, SignalUserAutonomyConfig } from '../../types'
import { ConfigCardHeader } from './ConfigCardHeader'
const NOTIFY_ALL_VALUE = '__all__'
+type SlackTargetMode = 'dm' | 'channel'
+
/** Minimum report priority that triggers a Slack ping. "All priorities" maps to a null min-priority. */
const MIN_PRIORITY_OPTIONS: { value: SignalReportPriority | typeof NOTIFY_ALL_VALUE; label: string }[] = [
{ value: NOTIFY_ALL_VALUE, label: 'All priorities' },
@@ -123,57 +126,151 @@ function TeamChannelCard({ integration }: { integration: IntegrationType }): JSX
)
}
+/** Where a saved config sends this user's reviewer pings, and whether that counts as enabled. */
+function readSlackTarget(
+ config: SignalUserAutonomyConfig | null,
+ integrations: IntegrationType[]
+): {
+ selectedIntegrationId: number | null
+ integration: IntegrationType | null
+ channel: string | null
+ savedMode: SlackTargetMode
+ /** The Slack account a saved direct message goes to, e.g. `@sam`. */
+ recipient: string | null
+ enabled: boolean
+} {
+ const selectedIntegrationId = config?.slack_notification_integration_id ?? null
+ // Workspace is shared with the team default. Default to the only workspace, or the user's saved pick.
+ const integration =
+ integrations.find((i) => i.id === selectedIntegrationId) ?? (integrations.length === 1 ? integrations[0] : null)
+ const channel = config?.slack_notification_channel ?? null
+ const savedMode: SlackTargetMode = channel && !isSlackMemberTarget(channel) ? 'channel' : 'dm'
+ return {
+ selectedIntegrationId,
+ integration,
+ channel,
+ savedMode,
+ recipient: savedMode === 'dm' && channel ? slackChannelDisplayName(channel) : null,
+ enabled: !!integration && !!channel,
+ }
+}
+
+function DirectMessageTarget({
+ recipient,
+ saving,
+ onEnable,
+}: {
+ recipient: string | null
+ saving: boolean
+ onEnable: () => void
+}): JSX.Element {
+ if (recipient) {
+ return <span className="text-xs text-secondary">PostHog sends these to {recipient} in Slack.</span>
+ }
+ return (
+ <>
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={onEnable}
+ loading={saving}
+ disabledReason={saving ? 'Setting this up…' : undefined}
+ >
+ Send me a direct message
+ </LemonButton>
+ <span className="text-xs text-secondary">
+ PostHog finds you in the workspace and messages you there. There is no channel to create.
+ </span>
+ </>
+ )
+}
+
+function ChannelTarget({
+ integration,
+ value,
+ onChange,
+}: {
+ integration: IntegrationType
+ value: string | undefined
+ onChange: (next: string | null) => void
+}): JSX.Element {
+ return (
+ <>
+ <SlackChannelPicker integration={integration} value={value} onChange={onChange} />
+ <span className="text-xs text-secondary">
+ PostHog must be in the channel. Invite it with <code>/invite @PostHog</code>.
+ </span>
+ </>
+ )
+}
+
/**
* Per-user Slack notification controls – a cloud port of desktop's
* `SlackInboxNotificationsSettings` / `SignalSlackNotificationsSettings`.
- * Notifications are enabled when an integration + channel are both set; the
+ * Notifications are enabled when an integration + target are both set; the
* enable toggle clears them to disable. Min-priority gates which reports ping.
* Backed by the `slack_notification_*` fields on `userAutonomyLogic`.
*/
-function PerUserChannelCard({ integrations }: { integrations: IntegrationType[] }): JSX.Element {
+function PerUserNotificationCard({ integrations }: { integrations: IntegrationType[] }): JSX.Element {
const redesign = useFeatureFlag('INBOX_REDESIGN')
- const { autonomyConfig, autonomyConfigLoading, slackPickersExpanded } = useValues(userAutonomyLogic)
+ const { autonomyConfig, autonomyConfigLoading, slackNotificationsSaving, slackPickersExpanded } =
+ useValues(userAutonomyLogic)
const { updateSlackNotifications, setSlackPickersExpanded } = useActions(userAutonomyLogic)
- // Workspace is shared with the team default. Default to the only workspace, or the user's saved pick.
- const selectedIntegrationId = autonomyConfig?.slack_notification_integration_id ?? null
- const effectiveIntegration =
- integrations.find((i) => i.id === selectedIntegrationId) ?? (integrations.length === 1 ? integrations[0] : null)
- const channel = autonomyConfig?.slack_notification_channel ?? null
+ const { selectedIntegrationId, integration, channel, savedMode, recipient, enabled } = readSlackTarget(
+ autonomyConfig,
+ integrations
+ )
const minPriority = autonomyConfig?.slack_notification_min_priority ?? null
- const notificationsEnabled = !!effectiveIntegration && !!channel
+
+ // The toggle is view state only: switching it must never write, or an exploratory click would
+ // clear a saved target. A direct message is the default because it needs no channel set up.
+ const [pendingMode, setPendingMode] = useState<SlackTargetMode | null>(null)
+ const mode = pendingMode ?? savedMode
const onToggleEnabled = (enabled: boolean): void => {
if (enabled) {
- // Turning on just opens the workspace/channel pickers – the actual enable
- // happens once a channel is chosen. Reveal them even when the workspace is
- // ambiguous (multiple connected) so the user can pick one; persist it now
- // only when it's unambiguous.
+ // With one workspace there is nothing to pick, so this also sets the direct message up.
setSlackPickersExpanded(true)
- if (effectiveIntegration && selectedIntegrationId === null) {
- updateSlackNotifications({ integrationId: effectiveIntegration.id })
+ if (integration && selectedIntegrationId === null) {
+ setPendingMode('dm')
+ updateSlackNotifications({ integrationId: integration.id, directMessage: true })
}
} else {
- // Disable by clearing the target and collapsing the pickers.
+ setPendingMode(null)
setSlackPickersExpanded(false)
updateSlackNotifications({ integrationId: null, channel: null })
}
}
const onWorkspaceChange = (integrationId: number): void => {
- // Switching workspaces clears the channel – it won't exist in the new workspace.
+ // The target won't exist in the new workspace. Pin the toggle to the mode the user was in.
+ setPendingMode(mode)
updateSlackNotifications({ integrationId, channel: null })
}
+ const onSendDirectMessages = (): void => {
+ if (!integration) {
+ return
+ }
+ setPendingMode('dm')
+ updateSlackNotifications({ integrationId: integration.id, directMessage: true })
+ }
+
const onChannelChange = (next: string | null): void => {
if (next === null) {
- updateSlackNotifications({ channel: null })
+ // An empty picker still emits clears (e.g. Backspace in its input), so only a picker
+ // whose own target is saved may clear – otherwise viewing it would wipe a saved DM.
+ if (savedMode === 'channel' && channel) {
+ setPendingMode('channel')
+ updateSlackNotifications({ channel: null })
+ }
return
}
- if (!effectiveIntegration) {
+ if (!integration) {
return
}
- updateSlackNotifications({ integrationId: effectiveIntegration.id, channel: next })
+ updateSlackNotifications({ integrationId: integration.id, channel: next })
}
const onMinPriorityChange = (value: string): void => {
@@ -182,8 +279,7 @@ function PerUserChannelCard({ integrations }: { integrations: IntegrationType[]
})
}
- // "On" means the pickers are visible: the user expanded them, or a saved integration/channel
- // already implies an enabled state.
+ // "On" means the controls are visible, which a saved integration or target implies on its own.
const showPickers = slackPickersExpanded || selectedIntegrationId !== null || !!channel
return (
@@ -191,17 +287,12 @@ function PerUserChannelCard({ integrations }: { integrations: IntegrationType[]
<div className="flex items-start justify-between gap-4">
<SlackCardHeader
title="Notify me directly"
- description={
- <>
- When you're a suggested reviewer, get pinged in your own channel. PostHog must be in the
- channel. Invite it with <code>/invite @PostHog</code>.
- </>
- }
+ description="Get pinged when you're a suggested reviewer. PostHog can send you a direct message, or post in a channel you pick."
/>
<LemonSwitch
checked={showPickers}
onChange={onToggleEnabled}
- disabled={autonomyConfigLoading && autonomyConfig === null}
+ disabled={slackNotificationsSaving || (autonomyConfigLoading && autonomyConfig === null)}
aria-label="Enable Slack notifications"
/>
</div>
@@ -213,7 +304,7 @@ function PerUserChannelCard({ integrations }: { integrations: IntegrationType[]
<span className="text-xs text-secondary">Workspace</span>
<LemonSelect
className="max-w-[260px]"
- value={effectiveIntegration?.id ?? null}
+ value={integration?.id ?? null}
options={integrations.map((i) => ({
value: i.id,
label: i.display_name || `Slack workspace ${i.id}`,
@@ -224,14 +315,30 @@ function PerUserChannelCard({ integrations }: { integrations: IntegrationType[]
</div>
)}
- {effectiveIntegration && (
- <div className="flex flex-col gap-1 min-w-0 max-w-md">
- <span className="text-xs text-secondary">Channel</span>
- <SlackChannelPicker
- integration={effectiveIntegration}
- value={channel ?? undefined}
- onChange={onChannelChange}
+ {integration && (
+ <div className="flex flex-col gap-2 min-w-0 max-w-md">
+ <LemonSegmentedButton
+ size="small"
+ value={mode}
+ onChange={(next) => setPendingMode(next as SlackTargetMode)}
+ options={[
+ { value: 'dm', label: 'Direct message' },
+ { value: 'channel', label: 'Channel' },
+ ]}
/>
+ {mode === 'dm' ? (
+ <DirectMessageTarget
+ recipient={recipient}
+ saving={slackNotificationsSaving}
+ onEnable={onSendDirectMessages}
+ />
+ ) : (
+ <ChannelTarget
+ integration={integration}
+ value={savedMode === 'channel' && channel ? channel : undefined}
+ onChange={onChannelChange}
+ />
+ )}
</div>
)}
@@ -241,7 +348,7 @@ function PerUserChannelCard({ integrations }: { integrations: IntegrationType[]
className="max-w-[240px]"
value={minPriority ?? NOTIFY_ALL_VALUE}
options={MIN_PRIORITY_OPTIONS}
- disabledReason={!notificationsEnabled ? 'Pick a channel first' : undefined}
+ disabledReason={!enabled ? 'Choose where to send these first' : undefined}
onChange={onMinPriorityChange}
/>
</div>
@@ -272,7 +379,7 @@ export function SlackNotificationsSection(): JSX.Element {
return (
<div className="flex flex-col gap-3">
<TeamChannelCard integration={integrations[0]} />
- <PerUserChannelCard integrations={integrations} />
+ <PerUserNotificationCard integrations={integrations} />
</div>
)
}
diff --git a/products/signals/frontend/inbox/inboxAnalytics.ts b/products/signals/frontend/inbox/inboxAnalytics.ts
index aca362024301..deaede183be8 100644
--- a/products/signals/frontend/inbox/inboxAnalytics.ts
+++ b/products/signals/frontend/inbox/inboxAnalytics.ts
@@ -644,12 +644,16 @@ export function captureInboxSettingsChanged(params: {
success: boolean
/** Whether the setting governs the whole team or just the person changing it. */
scope: 'team' | 'user'
+ /** Which kind of target a Slack notification setting points at. The target itself names the
+ * customer's own channel or teammate, so only its kind travels. */
+ targetKind?: 'direct_message' | 'channel' | null
}): void {
captureInboxEvent(INBOX_EVENTS.SETTINGS_CHANGED, {
setting: params.setting,
...settingValueProperties('new_value', params.newValue),
success: params.success,
setting_scope: params.scope,
+ ...(params.targetKind === undefined ? {} : { target_kind: params.targetKind }),
})
}
diff --git a/products/signals/frontend/inbox/logics/userAutonomyLogic.ts b/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
index ad2ad054248f..735811d4461b 100644
--- a/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
+++ b/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
@@ -4,16 +4,89 @@ import { loaders } from 'kea-loaders'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { isSlackMemberTarget } from 'lib/integrations/slackChannel'
+
+import type { SignalUserAutonomyConfigCreateApi } from 'products/signals/frontend/generated/api.schemas'
import { captureInboxSettingsChanged } from '../inboxAnalytics'
import type { SignalReportPriority, SignalUserAutonomyConfig } from '../types'
+interface SlackNotificationUpdates {
+ integrationId?: number | null
+ channel?: string | null
+ directMessage?: true
+ minPriority?: SignalReportPriority | null
+}
+
+/** Only the keys the caller passed, so unrelated fields (e.g. autostart_priority) aren't wiped. */
+function slackNotificationBody(updates: SlackNotificationUpdates): SignalUserAutonomyConfigCreateApi {
+ const body: SignalUserAutonomyConfigCreateApi = {}
+ if ('integrationId' in updates) {
+ body.slack_notification_integration_id = updates.integrationId ?? null
+ }
+ if ('channel' in updates) {
+ body.slack_notification_channel = updates.channel ?? null
+ }
+ if ('minPriority' in updates) {
+ body.slack_notification_min_priority = updates.minPriority ?? null
+ }
+ if (updates.directMessage) {
+ body.slack_notification_direct_message = true
+ }
+ return body
+}
+
+function slackTargetKind(setting: string, value: unknown): 'direct_message' | 'channel' | null | undefined {
+ if (setting === 'slack_notification_direct_message') {
+ return 'direct_message'
+ }
+ if (setting !== 'slack_notification_channel') {
+ return undefined
+ }
+ return typeof value === 'string' && value ? (isSlackMemberTarget(value) ? 'direct_message' : 'channel') : null
+}
+
+function captureSlackNotificationSaves(body: SignalUserAutonomyConfigCreateApi, success: boolean): void {
+ for (const [setting, newValue] of Object.entries(body)) {
+ // The target names the customer's own channel or account, so only its kind travels.
+ const targetKind = slackTargetKind(setting, newValue)
+ captureInboxSettingsChanged({
+ setting,
+ newValue: setting === 'slack_notification_channel' ? newValue !== null : newValue,
+ success,
+ scope: 'user',
+ ...(targetKind === undefined ? {} : { targetKind }),
+ })
+ }
+}
+
+function apiErrorMessage(error: any, fallback: string): string {
+ if (typeof error?.detail === 'string' && error.detail) {
+ return error.detail
+ }
+ if (error?.data && typeof error.data === 'object') {
+ for (const value of Object.values(error.data)) {
+ if (Array.isArray(value) && typeof value[0] === 'string') {
+ return value[0]
+ }
+ if (typeof value === 'string') {
+ return value
+ }
+ }
+ }
+ if (typeof error?.message === 'string' && error.message) {
+ return error.message
+ }
+ return fallback
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface userAutonomyLogicValues {
autonomyConfig: SignalUserAutonomyConfig | null
autonomyConfigLoading: boolean
autostartPriorityUpdating: boolean
githubAssignUpdating: boolean
+ slackNotificationsSaving: boolean
slackPickersExpanded: boolean
}
@@ -49,16 +122,11 @@ export interface userAutonomyLogicActions {
setSlackPickersExpanded: (expanded: boolean) => {
expanded: boolean
}
- updateSlackNotifications: (updates: {
- channel?: string | null
- integrationId?: number | null
- minPriority?: SignalReportPriority | null
- }) => {
- updates: {
- channel?: string | null | undefined
- integrationId?: number | null | undefined
- minPriority?: SignalReportPriority | null | undefined
- }
+ slackNotificationsSettled: () => {
+ value: true
+ }
+ updateSlackNotifications: (updates: SlackNotificationUpdates) => {
+ updates: SlackNotificationUpdates
}
}
@@ -80,12 +148,11 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
// Slack preference save also triggers and would otherwise release the save guard early.
autostartPrioritySettled: true,
// Slack notification preferences (suggested-reviewer pings for new inbox items).
- // integration + channel together enable notifications; either null disables them.
- updateSlackNotifications: (updates: {
- integrationId?: number | null
- channel?: string | null
- minPriority?: SignalReportPriority | null
- }) => ({ updates }),
+ // integration + target together enable notifications; either null disables them.
+ // `directMessage` is the one target the client can't name: the backend resolves it.
+ updateSlackNotifications: (updates: SlackNotificationUpdates) => ({ updates }),
+ // Fires when a Slack preference POST settles, releasing the save guard on its trigger.
+ slackNotificationsSettled: true,
// Opt in to being added as a GitHub assignee on PRs for reports suggesting this user.
setGithubAssignOnPullRequest: (enabled: boolean) => ({ enabled }),
// Fires when the GitHub assignment POST settles, releasing the switch's save guard.
@@ -144,6 +211,14 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
githubAssignSettled: () => false,
},
],
+ // Covers the POST itself, which `autonomyConfigLoading` only reflects once it resolves.
+ slackNotificationsSaving: [
+ false,
+ {
+ updateSlackNotifications: () => true,
+ slackNotificationsSettled: () => false,
+ },
+ ],
slackPickersExpanded: [
false,
{
@@ -189,34 +264,17 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
}
},
updateSlackNotifications: async ({ updates }) => {
- // Send only the keys the caller passed so unrelated fields (e.g. autostart_priority) aren't wiped.
- const body: Partial<SignalUserAutonomyConfig> = {}
- if ('integrationId' in updates) {
- body.slack_notification_integration_id = updates.integrationId ?? null
- }
- if ('channel' in updates) {
- body.slack_notification_channel = updates.channel ?? null
- }
- if ('minPriority' in updates) {
- body.slack_notification_min_priority = updates.minPriority ?? null
- }
+ const body = slackNotificationBody(updates)
let success = true
try {
- await api.signalUserAutonomy.update(body)
+ const config = await api.signalUserAutonomy.update(body)
+ actions.loadAutonomyConfigSuccess(config)
} catch (error: any) {
success = false
- lemonToast.error(error?.detail ?? error?.message ?? 'Failed to update Slack notification setting')
+ lemonToast.error(apiErrorMessage(error, 'Failed to update Slack notification setting'))
} finally {
- for (const [setting, newValue] of Object.entries(body)) {
- // The channel name is the customer's own, so only whether one is now set travels.
- const isChannel = setting === 'slack_notification_channel'
- captureInboxSettingsChanged({
- setting,
- newValue: isChannel ? newValue !== null : newValue,
- success,
- scope: 'user',
- })
- }
+ actions.slackNotificationsSettled()
+ captureSlackNotificationSaves(body, success)
actions.loadAutonomyConfig()
}
},
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5fa9e5d7435a..735c1a262ed3 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79987,7 +79987,7 @@ export namespace Schemas {
*/
readonly slack_notification_integration_id: number | null;
/**
- * Slack channel target in the same `channel_id|#channel-name` shape PostHog uses elsewhere (only the channel id is required). Null disables Slack notifications.
+ * Where the reviewer ping goes, in the same `id|name` shape PostHog uses elsewhere (only the id is required): a channel (`C0123ABC456|#alerts`), or a workspace member (`U0123ABC456|@sam`) who is sent a direct message. Null disables Slack notifications.
* @maxLength 255
* @nullable
*/
@@ -80006,6 +80006,33 @@ export namespace Schemas {
readonly updated_at: string;
}
+ export interface SignalUserAutonomyConfigCreate {
+ autostart_priority?: AutonomyPriorityEnum | null;
+ /**
+ * Primary key of a Slack `Integration` row in one of the caller's teams. Pair with `slack_notification_channel` to enable notifications; pass null on either to disable them.
+ * @nullable
+ */
+ slack_notification_integration_id?: number | null;
+ /**
+ * `channel_id|#channel-name` target, the same convention used by Insight Alerts, or a `member_id|@display-name` target (`U0123ABC456|@sam`) to send the ping as a direct message. A member target is checked against the workspace on save.
+ * @maxLength 255
+ * @nullable
+ */
+ slack_notification_channel?: string | null;
+ /** Set true to send the ping as a direct message from the PostHog app. The caller's own member id is resolved in the connected workspace and stored in `slack_notification_channel`, so nothing has to be picked. Rejected when the workspace has no eligible account for the caller, and cannot be combined with `slack_notification_channel`. */
+ slack_notification_direct_message?: boolean;
+ /** P0 is highest. Null = notify for every priority. When set, reports without a priority judgment do not notify.
+ *
+ * * `P0` - P0
+ * * `P1` - P1
+ * * `P2` - P2
+ * * `P3` - P3
+ * * `P4` - P4 */
+ slack_notification_min_priority?: AutonomyPriorityEnum | null;
+ /** Add this user as a GitHub assignee on implementation pull requests for reports that suggest them as reviewer. Off by default. Turning it off stops future assignment and never removes an existing assignee. */
+ github_assign_on_pull_request?: boolean;
+ }
+
export interface SlackChannel {
/** Slack channel ID (e.g. C0123ABC) — pass to cdp-functions inputs.channel. */
id: string;