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): route inbox notifications to a team channel (#60731)

Joshua Snyder2cb3b273599e
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 5ff7a397a2db..12e5351330e1 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -122,3 +122,12 @@ ERROR_TRACKING_TASK_QUEUE = _set_temporal_task_queue("error-tracking-task-queue"
EVENT_SCREENSHOTS_TASK_QUEUE = _set_temporal_task_queue("event-screenshots-task-queue")
LOGS_ALERTING_TASK_QUEUE = _set_temporal_task_queue("logs-alerting-task-queue")
RASTERIZATION_TASK_QUEUE = "rasterization-task-queue" # Not collapsed in dev — separate Node.js worker process
+
+# Signals inbox notification: how long to wait for an auto-started implementation PR before
+# notifying anyway, and how often to poll for it.
+SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS: int = get_from_env(
+ "SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS", 1800, type_cast=int
+)
+SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS: int = get_from_env(
+ "SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS", 30, type_cast=int
+)
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 004caeebcb5b..29c0520896aa 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -247,6 +247,7 @@ class TestSignalsProductModuleIntegrity:
"RunSignalsScoutWorkflow",
"SignalsScoutCoordinatorWorkflow",
"CustomSignalAgentWorkflow",
+ "SignalReportInboxNotificationWorkflow",
]
actual_workflow_names = [w.__name__ for w in SIGNALS_PRODUCT_WORKFLOWS]
assert len(actual_workflow_names) == len(expected_workflows), (
@@ -262,6 +263,8 @@ class TestSignalsProductModuleIntegrity:
"""Ensure all expected signals product activities are present."""
expected_activities = [
"dispatch_inbox_slack_notifications_activity",
+ "get_inbox_notification_state_activity",
+ "send_report_inbox_notifications_activity",
"emit_backfill_signal_activity",
"fetch_error_tracking_issues_activity",
"assign_and_emit_signal_activity",
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index 935b6a6311fe..aff9f358b4cb 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -24,6 +24,15 @@ logger = structlog.get_logger(__name__)
MAX_SIGNAL_DESCRIPTION_TOKENS = 8000
+def dismiss_report_from_slack(team_id: int, report_id: str, *, slack_user_id: str | None = None) -> bool:
+ """Facade entrypoint for the Slack 'Dismiss' button. See report_actions.suppress_report_from_slack."""
+ from products.signals.backend.report_actions import (
+ suppress_report_from_slack, # noqa: PLC0415 — avoids importing model layer at facade import time
+ )
+
+ return suppress_report_from_slack(team_id, report_id, slack_user_id=slack_user_id)
+
+
def _get_field_values(field: pydantic.fields.FieldInfo) -> tuple[str, ...]:
"""Extract all possible values for a Pydantic field (Literal, StrEnum, or default)."""
args = get_args(field.annotation)
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.md
index 0825b3674212..34c28d6fd43a 100644
--- a/products/signals/backend/management/AGENTS.md
+++ b/products/signals/backend/management/AGENTS.md
@@ -38,7 +38,11 @@ python manage.py list_signal_reports --team-id 1 --signals --json
- `pending_input` — needs human judgment before acting
- `failed` — failed safety review (possible prompt injection)
- `potential` (reset, weight zeroed) — deemed not actionable
-7. `ready` reports accumulate new signals silently. After enough new signals (`signal_count >= signals_at_run`),
+7. On reaching `ready`, the summary workflow starts `signal-report-inbox-notification` to post the Slack
+ inbox notification. If the report auto-started an implementation task, that workflow waits for the PR to
+ open (bounded by `SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS`) so the card can show a "Review PR"
+ button; reports with no auto-start task notify immediately.
+8. `ready` reports accumulate new signals silently. After enough new signals (`signal_count >= signals_at_run`),
the report is re-promoted and the summary workflow runs again — reusing the previous repo selection and
lightly validating previous findings instead of re-researching from scratch.
diff --git a/products/signals/backend/report_actions.py b/products/signals/backend/report_actions.py
new file mode 100644
index 000000000000..8797590a7244
--- /dev/null
+++ b/products/signals/backend/report_actions.py
@@ -0,0 +1,48 @@
+"""Report state actions shared across entrypoints (API, Slack interactivity)."""
+
+from __future__ import annotations
+
+import json
+import logging
+
+from django.db import transaction
+
+from products.signals.backend.models import InvalidStatusTransition, SignalReport, SignalReportArtefact
+
+logger = logging.getLogger(__name__)
+
+
+def suppress_report_from_slack(team_id: int, report_id: str, *, slack_user_id: str | None = None) -> bool:
+ """Suppress (dismiss) a report from a Slack 'Dismiss' click. Idempotent — an
+ already-suppressed report is treated as success; returns False if the report
+ doesn't exist or the transition isn't allowed.
+ """
+ # Row-lock the report so concurrent Dismiss clicks can't both transition + write artefacts.
+ with transaction.atomic():
+ report = SignalReport.objects.filter(id=report_id, team_id=team_id).select_for_update().first()
+ if report is None:
+ logger.warning(
+ "suppress_report_from_slack: report not found", extra={"report_id": report_id, "team_id": team_id}
+ )
+ return False
+
+ if report.status == SignalReport.Status.SUPPRESSED:
+ return True
+
+ try:
+ updated_fields = report.transition_to(SignalReport.Status.SUPPRESSED)
+ except InvalidStatusTransition:
+ logger.warning(
+ "suppress_report_from_slack: invalid transition",
+ extra={"report_id": report_id, "team_id": team_id, "status": report.status},
+ )
+ return False
+
+ report.save(update_fields=updated_fields)
+ SignalReportArtefact.objects.create(
+ team_id=team_id,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.DISMISSAL,
+ content=json.dumps({"reason": "slack_dismiss", "note": None, "slack_user_id": slack_user_id}),
+ )
+ return True
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 35b4e4cdcddb..52dac75bd1e5 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -1,30 +1,19 @@
"""Slack notifications for signals inbox items.
-When a report transitions to READY (a new inbox item lands), we look up the
-suggested reviewers from its `suggested_reviewers` artefact, resolve them to
-PostHog users, and dispatch a Slack message for each user that has configured a
-Slack channel and integration in their `SignalUserAutonomyConfig`.
-
-Reviewers are grouped by their resolved Slack channel so each channel receives a
-single message — when several reviewers point at the same channel, that one
-message tags all of them rather than posting once per reviewer.
-
-Each user's `slack_notification_min_priority` filters out reports below the
-configured threshold (P0 is highest). Reports with pending actionability or
-priority judgments are not dispatchable until those judgments are persisted.
-
-Messages are framed for public channels: each post names the suggested reviewers
-(Slack @mention when email matches the workspace, otherwise their PostHog name).
+Each suggested reviewer on a ready report is routed to exactly one Slack channel:
+their own configured channel if they set one (filtered by their min-priority),
+otherwise the team-default channel, otherwise nowhere. Reviewers sharing a channel —
+notably everyone falling back to the team default — get a single post that mentions
+only the reviewers routed there. A report with no resolvable reviewers posts nothing.
+All sends are best-effort.
"""
from __future__ import annotations
import json
import logging
-from dataclasses import dataclass
from django.conf import settings
-from django.db.models import Q
from slack_sdk.errors import SlackApiError
@@ -37,9 +26,9 @@ from products.signals.backend.models import (
SignalReport,
SignalReportArtefact,
SignalSourceConfig,
+ SignalTeamConfig,
SignalUserAutonomyConfig,
)
-from products.signals.backend.report_generation.research import ActionabilityChoice
from products.signals.backend.report_generation.resolve_reviewers import (
enrich_reviewer_dicts_with_org_members,
normalized_github_logins_from_suggested_reviewer_artefacts,
@@ -50,10 +39,15 @@ logger = logging.getLogger(__name__)
_SUMMARY_EXCERPT_MAX_LEN = 600
_SLACK_HEADER_MAX_LEN = 150
+# Bound message size / avoid pinging a crowd.
+_MAX_REVIEWER_MENTIONS = 5
# Deep link opened by the PostHog Code desktop app. Override via env for dev (`posthog-code-dev`).
POSTHOG_CODE_INBOX_DEEP_LINK_SCHEME = getattr(settings, "POSTHOG_CODE_INBOX_DEEP_LINK_SCHEME", "posthog-code")
+# Wire contract with products/slack_app/backend/api.py — keep this action_id in sync.
+SIGNALS_DISMISS_REPORT_ACTION_ID = "signals_dismiss_report"
+
# Priority ranking — lower index is higher priority. Index used for threshold comparison.
_PRIORITY_ORDER: tuple[str, ...] = (
AutonomyPriority.P0,
@@ -108,12 +102,9 @@ def _meets_min_priority(report_priority: str | None, min_priority: str | None) -
return report_rank <= min_rank
-def _get_latest_priority(report: SignalReport) -> str | None:
- art = (
- report.artefacts.filter(type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT)
- .order_by("-created_at")
- .first()
- )
+def _report_repository(report: SignalReport) -> str | None:
+ """The repository the report's research selected, from the latest repo_selection artefact."""
+ art = report.artefacts.filter(type=SignalReportArtefact.ArtefactType.REPO_SELECTION).order_by("-created_at").first()
if art is None:
return None
try:
@@ -122,13 +113,13 @@ def _get_latest_priority(report: SignalReport) -> str | None:
return None
if not isinstance(data, dict):
return None
- value = data.get("priority")
- return value if isinstance(value, str) else None
+ repo = data.get("repository")
+ return repo.strip() if isinstance(repo, str) and repo.strip() else None
-def _get_latest_actionability(report: SignalReport) -> str | None:
+def _latest_priority(report: SignalReport) -> str | None:
art = (
- report.artefacts.filter(type=SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT)
+ report.artefacts.filter(type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT)
.order_by("-created_at")
.first()
)
@@ -140,18 +131,10 @@ def _get_latest_actionability(report: SignalReport) -> str | None:
return None
if not isinstance(data, dict):
return None
- value = data.get("actionability")
+ value = data.get("priority")
return value if isinstance(value, str) else None
-@dataclass(frozen=True)
-class _RecipientPresentation:
- # `<@U…>` mention if we resolved the user's Slack ID — only renders inside mrkdwn
- # blocks (header blocks are plain_text and would show the raw `<@U…>` string).
- slack_mention: str | None
- plain_name: str
-
-
def _resolve_suggested_reviewer_user_ids(report: SignalReport) -> set[int]:
"""Resolve the suggested-reviewer GitHub logins on the report to PostHog user IDs.
@@ -190,18 +173,32 @@ def _resolve_suggested_reviewer_user_ids(report: SignalReport) -> set[int]:
return resolved_user_ids
-def _notification_targets_for_report(report: SignalReport) -> list[SignalUserAutonomyConfig]:
- user_ids = _resolve_suggested_reviewer_user_ids(report)
- if not user_ids:
- return []
+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.
- return list(
+ A reviewer absent from this map has no own channel and falls back to the team default.
+ """
+ configs = (
SignalUserAutonomyConfig.objects.filter(user_id__in=user_ids)
- .filter(slack_notification_integration__team_id=report.team_id)
- .exclude(Q(slack_notification_integration__isnull=True) | Q(slack_notification_channel__isnull=True))
+ .filter(slack_notification_integration__team_id=team_id)
+ .exclude(slack_notification_channel__isnull=True)
.exclude(slack_notification_channel="")
.select_related("slack_notification_integration")
)
+ return {config.user_id: config for config in configs}
+
+
+def _get_team_slack_integration(team_id: int) -> Integration | None:
+ # Standard `slack` kind (not `slack-posthog-code`), matching the per-user path.
+ return Integration.objects.filter(team_id=team_id, kind="slack").first()
+
+
+def _team_notification_channel(team_id: int) -> str | None:
+ config = SignalTeamConfig.objects.filter(team_id=team_id).only("default_slack_notification_channel").first()
+ if config is None:
+ return None
+ channel = (config.default_slack_notification_channel or "").strip()
+ return channel or None
def _channel_id_from_target(value: str) -> str:
@@ -253,22 +250,17 @@ def lookup_slack_user_id_by_email(slack: SlackIntegration, email: str) -> str |
return str(slack_user["id"])
-def _recipient_presentation(
- user: User,
- slack: SlackIntegration,
- integration: Integration,
-) -> _RecipientPresentation:
- plain_name = _posthog_user_display_name(user)
- slack_user_id = lookup_slack_user_id_by_email(slack, user.email) if user.email else None
- slack_mention = f"<@{slack_user_id}>" if slack_user_id else None
- return _RecipientPresentation(slack_mention=slack_mention, plain_name=plain_name)
+def _escape_mrkdwn(text: str) -> str:
+ return text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
-def _recipient_label(recipient: _RecipientPresentation) -> str:
- # Mention pings the user inside mrkdwn; otherwise escape the plain name so it renders literally.
- return recipient.slack_mention or recipient.plain_name.replace("&", "&amp;").replace("<", "&lt;").replace(
- ">", "&gt;"
- )
+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] = []
+ for user in reviewer_users[:_MAX_REVIEWER_MENTIONS]:
+ slack_user_id = lookup_slack_user_id_by_email(slack, user.email) if user.email else None
+ mentions.append(f"<@{slack_user_id}>" if slack_user_id else _escape_mrkdwn(_posthog_user_display_name(user)))
+ return mentions
def _format_source_product_labels(source_products: list[str]) -> str:
@@ -296,67 +288,162 @@ def _build_message_blocks(
*,
priority: str | None,
source_products: list[str],
- recipients: list[_RecipientPresentation],
+ reviewer_mentions: list[str],
+ repository: str | None = None,
implementation_pr_url: str | None = None,
+ dismiss_button_value: str | None = None,
) -> tuple[list[dict], str]:
title_line = report.title or "New signals inbox item"
header_text = f"📬 {title_line}"
if len(header_text) > _SLACK_HEADER_MAX_LEN:
header_text = header_text[: _SLACK_HEADER_MAX_LEN - 3] + "..."
- recipient_label = ", ".join(_recipient_label(recipient) for recipient in recipients)
- metadata_parts = [f"Matched to {recipient_label} per code"]
+ meta_parts: list[str] = []
if priority:
- metadata_parts.insert(0, _slack_priority_label(priority))
-
- body_parts: list[str] = [f"*{' • '.join(metadata_parts)}*"]
+ meta_parts.append(_slack_priority_label(priority))
+ sources_line = _format_source_product_labels(source_products)
+ if sources_line:
+ meta_parts.append(sources_line)
+ if repository:
+ # Escape LLM/user-derived strings before they enter mrkdwn so a crafted value can't
+ # inject `<!here>` / `<@U…>` mentions. Reviewer mentions are added pre-escaped elsewhere.
+ meta_parts.append(_escape_mrkdwn(repository))
+
+ body_parts: list[str] = []
+ if meta_parts:
+ body_parts.append(f"*{' · '.join(meta_parts)}*")
summary_text = _summary_excerpt(report.summary or "")
if summary_text:
- body_parts.append(summary_text)
+ body_parts.append(_escape_mrkdwn(summary_text))
+ if not body_parts:
+ body_parts.append(f"*{_escape_mrkdwn(title_line)}*")
blocks: list[dict] = [
{"type": "header", "text": {"type": "plain_text", "text": header_text}},
{"type": "section", "text": {"type": "mrkdwn", "text": "\n\n".join(body_parts)}},
]
+ # Reviewer mentions sit in the context line — they still carry the `<@U…>` token so Slack pings them.
context_parts: list[str] = []
if report.signal_count:
signal_label = "signal" if report.signal_count == 1 else "signals"
context_parts.append(f"{report.signal_count} {signal_label}")
- sources_line = _format_source_product_labels(source_products)
- if sources_line:
- context_parts.append(sources_line)
- context_parts.append("Inbox")
- blocks.append(
- {
- "type": "context",
- "elements": [{"type": "mrkdwn", "text": " · ".join(context_parts)}],
- }
- )
+ if reviewer_mentions:
+ context_parts.append(f"👤 Suggested reviewers: {' '.join(reviewer_mentions)}")
+ if context_parts:
+ blocks.append(
+ {
+ "type": "context",
+ "elements": [{"type": "mrkdwn", "text": " · ".join(context_parts)}],
+ }
+ )
- action_elements: list[dict] = [
+ action_elements: list[dict] = []
+ if implementation_pr_url:
+ action_elements.append(
+ {
+ "type": "button",
+ "text": {"type": "plain_text", "text": "Review PR", "emoji": True},
+ "url": implementation_pr_url,
+ }
+ )
+ action_elements.append(
{
"type": "button",
"text": {"type": "plain_text", "text": "Open in PostHog Code", "emoji": True},
"url": f"{POSTHOG_CODE_INBOX_DEEP_LINK_SCHEME}://inbox/{report.id}",
}
- ]
- if implementation_pr_url:
+ )
+ if dismiss_button_value:
action_elements.append(
{
"type": "button",
- "text": {"type": "plain_text", "text": "Review PR in GitHub", "emoji": True},
- "url": implementation_pr_url,
+ "action_id": SIGNALS_DISMISS_REPORT_ACTION_ID,
+ "text": {"type": "plain_text", "text": "Dismiss", "emoji": True},
+ "value": dismiss_button_value,
+ "confirm": {
+ "title": {"type": "plain_text", "text": "Dismiss this report?"},
+ "text": {
+ "type": "mrkdwn",
+ "text": "This will dismiss the report for everyone. You can still find it in PostHog.",
+ },
+ "confirm": {"type": "plain_text", "text": "Dismiss"},
+ "deny": {"type": "plain_text", "text": "Cancel"},
+ },
}
)
blocks.append({"type": "actions", "elements": action_elements})
priority_suffix = f" ({priority})" if priority else ""
- recipient_names = ", ".join(recipient.plain_name for recipient in recipients)
- fallback_text = f"Inbox for {recipient_names}{priority_suffix}: {title_line}"
+ fallback_text = f"Inbox item{priority_suffix}: {title_line}"
return blocks, fallback_text
+class _ChannelRoute:
+ """One Slack channel and the reviewers routed to it (mentioned only there)."""
+
+ 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.users: list[User] = []
+
+
+def _build_reviewer_routes(
+ report: SignalReport,
+ *,
+ priority: str | None,
+ team_integration: Integration | None,
+ team_channel: str | None,
+) -> list[_ChannelRoute]:
+ """Route each resolvable suggested reviewer to a single destination channel.
+
+ Own channel (filtered by the reviewer's min-priority) if set, else the team
+ default, else nowhere. A reviewer filtered out of their own channel 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.
+ """
+ reviewer_user_ids = _resolve_suggested_reviewer_user_ids(report)
+ if not reviewer_user_ids:
+ return []
+
+ 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)
+
+ # 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.
+ routes: dict[tuple[int, str], _ChannelRoute] = {}
+ for user_id in sorted(reviewer_user_ids):
+ user = reviewer_users.get(user_id)
+ if user is None:
+ continue
+
+ config = own_configs.get(user_id)
+ if config is not None:
+ if not _meets_min_priority(priority, config.slack_notification_min_priority):
+ continue
+ integration = config.slack_notification_integration
+ channel = config.slack_notification_channel
+ is_team_channel = False
+ elif team_integration is not None and team_channel:
+ integration = team_integration
+ channel = team_channel
+ is_team_channel = True
+ else:
+ continue
+
+ if integration is None or not channel:
+ continue
+ key = (integration.id, _channel_id_from_target(channel))
+ route = routes.get(key)
+ if route is None:
+ route = _ChannelRoute(integration, channel, is_team_channel=is_team_channel)
+ routes[key] = route
+ route.users.append(user)
+
+ return list(routes.values())
+
+
def dispatch_inbox_item_notifications(
report_id: str,
team_id: int,
@@ -364,7 +451,7 @@ def dispatch_inbox_item_notifications(
) -> int:
"""Send Slack notifications for a newly-ready report. Returns count of messages sent.
- Best-effort: per-target Slack errors are logged but do not raise.
+ Best-effort: per-destination Slack errors are logged, not raised.
"""
try:
report = SignalReport.objects.get(id=report_id, team_id=team_id)
@@ -375,76 +462,57 @@ def dispatch_inbox_item_notifications(
)
return 0
- if report.status != SignalReport.Status.READY:
- return 0
- if _get_latest_actionability(report) != ActionabilityChoice.IMMEDIATELY_ACTIONABLE:
- return 0
-
- priority = _get_latest_priority(report)
+ priority = _latest_priority(report)
+ # Don't notify until a priority is persisted — an unprioritised report isn't ready for the inbox.
if _priority_rank(priority) is None:
return 0
- targets = _notification_targets_for_report(report)
- if not targets:
+ team_integration = _get_team_slack_integration(team_id)
+ team_channel = _team_notification_channel(team_id) if team_integration is not None else None
+
+ routes = _build_reviewer_routes(
+ report,
+ priority=priority,
+ team_integration=team_integration,
+ team_channel=team_channel,
+ )
+ if not routes:
return 0
sources = source_products or []
+ repository = _report_repository(report)
implementation_pr_url = fetch_implementation_pr_urls_for_reports([str(report.id)]).get(str(report.id))
- users_by_id = {user.id: user for user in User.objects.filter(id__in=[config.user_id for config in targets])}
-
- # Several reviewers can resolve to the same channel — group them so each channel gets a
- # single message that still tags every matched reviewer. Keyed by integration + channel id,
- # since the same channel id under a different integration is a distinct destination.
- channels: dict[tuple[int, str], list[SignalUserAutonomyConfig]] = {}
- for config in targets:
- if not _meets_min_priority(priority, config.slack_notification_min_priority):
- continue
- if config.user_id not in users_by_id:
- logger.warning(
- "signals_inbox_slack_notification_missing_user",
- extra={"report_id": report_id, "team_id": team_id, "user_id": config.user_id},
- )
- continue
- integration = config.slack_notification_integration
- channel = config.slack_notification_channel
- if integration is None or not channel:
- continue
- channels.setdefault((integration.id, _channel_id_from_target(channel)), []).append(config)
sent = 0
- for configs in channels.values():
- # All configs in a group share the same integration and resolved channel id.
- integration = configs[0].slack_notification_integration
- channel = configs[0].slack_notification_channel
- if integration is None or not channel:
- continue # Needed to satisfy mypy
-
+ for route in routes:
+ channel_id = _channel_id_from_target(route.channel)
+ log_context = {
+ "report_id": report_id,
+ "team_id": team_id,
+ "channel": _channel_display_name(route.channel),
+ "destination": "team" if route.is_team_channel else "user",
+ }
try:
- slack = SlackIntegration(integration)
- recipients = [
- _recipient_presentation(users_by_id[config.user_id], slack, integration) for config in configs
- ]
+ slack = SlackIntegration(route.integration)
+ mentions = _resolve_reviewer_mentions(slack, route.users)
+ dismiss_button_value = json.dumps(
+ {
+ "integration_id": route.integration.id,
+ "report_id": str(report.id),
+ "team_id": team_id,
+ }
+ )
blocks, text = _build_message_blocks(
report,
priority=priority,
source_products=sources,
- recipients=recipients,
+ reviewer_mentions=mentions,
+ repository=repository,
implementation_pr_url=implementation_pr_url,
+ dismiss_button_value=dismiss_button_value,
)
- slack.client.chat_postMessage(
- channel=_channel_id_from_target(channel),
- blocks=blocks,
- text=text,
- )
+ slack.client.chat_postMessage(channel=channel_id, blocks=blocks, text=text)
sent += 1
except Exception:
- logger.exception(
- "Failed to deliver signals inbox-item Slack notification",
- extra={
- "report_id": report_id,
- "team_id": team_id,
- "user_ids": [config.user_id for config in configs],
- "channel": _channel_display_name(channel),
- },
- )
+ logger.exception("Failed to deliver signals inbox-item Slack notification", extra=log_context)
return sent
diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.py
index 72fc490bcd2c..ffa8861a6daa 100644
--- a/products/signals/backend/temporal/__init__.py
+++ b/products/signals/backend/temporal/__init__.py
@@ -34,6 +34,11 @@ from products.signals.backend.temporal.grouping import (
verify_match_specificity_activity,
)
from products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflow, read_signals_from_s3_activity
+from products.signals.backend.temporal.inbox_notification import (
+ SignalReportInboxNotificationWorkflow,
+ get_inbox_notification_state_activity,
+ send_report_inbox_notifications_activity,
+)
from products.signals.backend.temporal.reingestion import (
SignalReportReingestionWorkflow,
TeamSignalReingestionWorkflow,
@@ -79,10 +84,13 @@ WORKFLOWS = [
CustomSignalAgentWorkflow,
RunSignalsScoutWorkflow,
SignalsScoutCoordinatorWorkflow,
+ SignalReportInboxNotificationWorkflow,
]
ACTIVITIES = [
dispatch_inbox_slack_notifications_activity,
+ get_inbox_notification_state_activity,
+ send_report_inbox_notifications_activity,
emit_backfill_signal_activity,
fetch_error_tracking_issues_activity,
fetch_enabled_signals_scout_runs_activity,
diff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.py
new file mode 100644
index 000000000000..e06c360e6053
--- /dev/null
+++ b/products/signals/backend/temporal/inbox_notification.py
@@ -0,0 +1,144 @@
+"""Decides when to send a report's inbox Slack notification.
+
+A report that auto-starts an implementation task waits for the PR to open (so the card can
+carry a "Review PR" button), bounded by a timeout. A report with no auto-start task notifies
+immediately. Posting itself stays in `dispatch_inbox_item_notifications`; this governs timing.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import timedelta
+
+from django.conf import settings
+
+import structlog
+import temporalio
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+
+from posthog.models import Team
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.scoped import scoped_temporal
+
+from products.signals.backend.implementation_pr import fetch_implementation_pr_urls_for_reports
+from products.signals.backend.models import SignalReport, SignalReportTask
+from products.signals.backend.temporal.signal_queries import fetch_signals_for_report_sync
+from products.tasks.backend.models import TaskRun
+
+logger = structlog.get_logger(__name__)
+
+
+@dataclass
+class InboxNotificationInput:
+ team_id: int
+ report_id: str
+
+
+@dataclass
+class InboxNotificationState:
+ has_implementation_task: bool
+ pr_available: bool
+ task_terminal: bool
+
+
+def _compute_inbox_notification_state(team_id: int, report_id: str) -> InboxNotificationState:
+ has_task = SignalReportTask.objects.filter(
+ team_id=team_id,
+ report_id=report_id,
+ relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ ).exists()
+ if not has_task:
+ return InboxNotificationState(has_implementation_task=False, pr_available=False, task_terminal=False)
+
+ pr_available = bool(fetch_implementation_pr_urls_for_reports([report_id]))
+ latest_run = (
+ TaskRun.objects.filter(
+ task__signal_report_tasks__team_id=team_id,
+ task__signal_report_tasks__report_id=report_id,
+ task__signal_report_tasks__relationship=SignalReportTask.Relationship.IMPLEMENTATION,
+ )
+ .order_by("-created_at", "-id")
+ .first()
+ )
+ task_terminal = bool(latest_run and latest_run.is_terminal) and not pr_available
+ return InboxNotificationState(has_implementation_task=True, pr_available=pr_available, task_terminal=task_terminal)
+
+
+@scoped_temporal()
+async def get_inbox_notification_state_activity(input: InboxNotificationInput) -> InboxNotificationState:
+ return await database_sync_to_async(_compute_inbox_notification_state, thread_sensitive=False)(
+ input.team_id, input.report_id
+ )
+
+
+def _send_report_inbox_notifications(team_id: int, report_id: str) -> int:
+ # Guard on status: a deferred wait can outlast the READY state (suppressed/deleted/re-promoted).
+ report = SignalReport.objects.filter(id=report_id, team_id=team_id).only("status").first()
+ if report is None or report.status != SignalReport.Status.READY:
+ logger.info(
+ "inbox notification skipped: report not READY",
+ report_id=report_id,
+ team_id=team_id,
+ status=report.status if report else None,
+ )
+ return 0
+
+ from products.signals.backend.slack_inbox_notifications import dispatch_inbox_item_notifications
+
+ # Team may have been deleted during a long deferred wait — degrade to no-op rather than failing.
+ team = Team.objects.filter(id=team_id).first()
+ if team is None:
+ logger.info("inbox notification skipped: team gone", report_id=report_id, team_id=team_id)
+ return 0
+
+ # Re-derive source products at send time so a deferred notification reflects the current signals.
+ signals = fetch_signals_for_report_sync(team, report_id)
+ source_products = sorted({s["source_product"] for s in signals if s.get("source_product")})
+ return dispatch_inbox_item_notifications(report_id=report_id, team_id=team_id, source_products=source_products)
+
+
+@scoped_temporal()
+async def send_report_inbox_notifications_activity(input: InboxNotificationInput) -> int:
+ return await database_sync_to_async(_send_report_inbox_notifications, thread_sensitive=False)(
+ input.team_id, input.report_id
+ )
+
+
[email protected](name="signal-report-inbox-notification")
+class SignalReportInboxNotificationWorkflow:
+ @staticmethod
+ def workflow_id_for(team_id: int, report_id: str) -> str:
+ return f"signals-inbox-notify:{team_id}:{report_id}"
+
+ @temporalio.workflow.run
+ async def run(self, inputs: InboxNotificationInput) -> int:
+ timeout_seconds = settings.SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS
+ poll_seconds = max(1, settings.SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS)
+
+ state = await self._fetch_state(inputs)
+ if state.has_implementation_task and not state.pr_available and not state.task_terminal:
+ elapsed = 0
+ while elapsed < timeout_seconds:
+ await workflow.sleep(timedelta(seconds=poll_seconds))
+ elapsed += poll_seconds
+ state = await self._fetch_state(inputs)
+ if state.pr_available or state.task_terminal:
+ break
+
+ return await workflow.execute_activity(
+ send_report_inbox_notifications_activity,
+ inputs,
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+
+ async def _fetch_state(self, inputs: InboxNotificationInput) -> InboxNotificationState:
+ return await workflow.execute_activity(
+ get_inbox_notification_state_activity,
+ inputs,
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.py
index dee908cfa731..49c9a9cd5869 100644
--- a/products/signals/backend/temporal/summary.py
+++ b/products/signals/backend/temporal/summary.py
@@ -3,6 +3,7 @@ import asyncio
from dataclasses import dataclass, field
from datetime import timedelta
+from django.conf import settings
from django.db import transaction
import structlog
@@ -10,7 +11,8 @@ import temporalio
import posthoganalytics
from structlog.types import FilteringBoundLogger
from temporalio import workflow
-from temporalio.common import RetryPolicy
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
+from temporalio.workflow import ParentClosePolicy
from posthog.event_usage import groups
from posthog.kafka_client.routing import get_producer
@@ -31,6 +33,10 @@ from products.signals.backend.temporal.agentic.select_repository import (
SelectRepositoryInput,
select_repository_activity,
)
+from products.signals.backend.temporal.inbox_notification import (
+ InboxNotificationInput,
+ SignalReportInboxNotificationWorkflow,
+)
from products.signals.backend.temporal.report_safety_judge import SafetyJudgeInput, report_safety_judge_activity
from products.signals.backend.temporal.signal_queries import (
FetchSignalsForReportInput,
@@ -329,23 +335,37 @@ class SignalReportSummaryWorkflow:
workflow.logger.exception(
f"Failed to publish report_completed notification for {inputs.report_id}",
)
- # Slack notifications to suggested reviewers — separate from the Kafka
- # publish above so a Slack outage doesn't suppress the inbox event,
- # and a Kafka outage doesn't suppress Slack delivery.
+ # Slack notification is detached (ABANDON) so it can wait out the implementation PR.
+ # patched(): summary workflows already in flight at deploy replay the prior inline path.
try:
- await workflow.execute_activity(
- dispatch_inbox_slack_notifications_activity,
- DispatchInboxSlackNotificationsInput(
- team_id=inputs.team_id,
- report_id=inputs.report_id,
- source_products=source_products,
- ),
- start_to_close_timeout=timedelta(minutes=2),
- retry_policy=RetryPolicy(maximum_attempts=2),
- )
+ if workflow.patched("signals-deferred-inbox-notification"):
+ await workflow.start_child_workflow(
+ SignalReportInboxNotificationWorkflow.run,
+ InboxNotificationInput(team_id=inputs.team_id, report_id=inputs.report_id),
+ id=SignalReportInboxNotificationWorkflow.workflow_id_for(inputs.team_id, inputs.report_id),
+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
+ parent_close_policy=ParentClosePolicy.ABANDON,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ execution_timeout=timedelta(
+ seconds=settings.SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS + 600
+ ),
+ )
+ else:
+ await workflow.execute_activity(
+ dispatch_inbox_slack_notifications_activity,
+ DispatchInboxSlackNotificationsInput(
+ team_id=inputs.team_id,
+ report_id=inputs.report_id,
+ source_products=source_products,
+ ),
+ start_to_close_timeout=timedelta(minutes=2),
+ retry_policy=RetryPolicy(maximum_attempts=2),
+ )
+ except temporalio.exceptions.WorkflowAlreadyStartedError:
+ pass
except Exception:
workflow.logger.exception(
- f"Failed to dispatch inbox Slack notifications for {inputs.report_id}",
+ f"Failed to dispatch inbox notification for {inputs.report_id}",
)
return has_new_signals
except Exception as e:
@@ -679,17 +699,11 @@ class DispatchInboxSlackNotificationsInput:
source_products: list[str] = field(default_factory=list)
+# Deprecated: replaced by SignalReportInboxNotificationWorkflow (see the "signals-deferred-inbox-notification"
+# patch above). Retained one release so summary workflows in flight at deploy can replay the old path.
@temporalio.activity.defn
@scoped_temporal()
-async def dispatch_inbox_slack_notifications_activity(
- input: DispatchInboxSlackNotificationsInput,
-) -> int:
- """Send Slack notifications for a newly-READY report to suggested reviewers
- who have configured Slack notifications in their signal autonomy config.
-
- Returns the number of messages dispatched (informational; failures are
- swallowed inside the dispatcher and logged).
- """
+async def dispatch_inbox_slack_notifications_activity(input: DispatchInboxSlackNotificationsInput) -> int:
from products.signals.backend.slack_inbox_notifications import dispatch_inbox_item_notifications
return await database_sync_to_async(dispatch_inbox_item_notifications, thread_sensitive=False)(
diff --git a/products/signals/backend/test/test_inbox_notification_workflow.py b/products/signals/backend/test/test_inbox_notification_workflow.py
new file mode 100644
index 000000000000..550215b3fe9d
--- /dev/null
+++ b/products/signals/backend/test/test_inbox_notification_workflow.py
@@ -0,0 +1,174 @@
+import uuid
+
+import pytest
+from unittest.mock import patch
+
+from django.test import override_settings
+
+from temporalio import activity
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from posthog.models import Organization, Team
+
+from products.signals.backend.models import SignalReport, SignalReportTask
+from products.signals.backend.temporal.inbox_notification import (
+ InboxNotificationInput,
+ InboxNotificationState,
+ SignalReportInboxNotificationWorkflow,
+ _compute_inbox_notification_state,
+ _send_report_inbox_notifications,
+)
+from products.tasks.backend.models import Task, TaskRun
+
+TASK_QUEUE = "test-inbox-notification-queue"
+
+
+def _make_report(team: Team, status: str = SignalReport.Status.READY) -> SignalReport:
+ return SignalReport.objects.create(
+ team=team, status=status, title="t", summary="s", signal_count=1, total_weight=1.0
+ )
+
+
+def _link_implementation_task(team: Team, report: SignalReport, *, pr_url: str | None, run_status: str) -> None:
+ task = Task.objects.create(
+ team=team, title="impl", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT
+ )
+ SignalReportTask.objects.create(
+ team=team, report=report, task=task, relationship=SignalReportTask.Relationship.IMPLEMENTATION
+ )
+ TaskRun.objects.create(team=team, task=task, status=run_status, output={"pr_url": pr_url})
+
+
+def team(db):
+ org = Organization.objects.create(name="inbox-notif-org")
+ team = Team.objects.create(organization=org, name="inbox-notif-team")
+ yield team
+ team.delete()
+ org.delete()
+
+
+def test_state_no_implementation_task(team):
+ report = _make_report(team)
+ state = _compute_inbox_notification_state(team.id, str(report.id))
+ assert state == InboxNotificationState(has_implementation_task=False, pr_available=False, task_terminal=False)
+
+
+def test_state_task_with_pr(team):
+ report = _make_report(team)
+ _link_implementation_task(team, report, pr_url="https://github.com/o/r/pull/1", run_status=TaskRun.Status.COMPLETED)
+ state = _compute_inbox_notification_state(team.id, str(report.id))
+ assert state == InboxNotificationState(has_implementation_task=True, pr_available=True, task_terminal=False)
+
+
+def test_state_task_running_no_pr(team):
+ report = _make_report(team)
+ _link_implementation_task(team, report, pr_url=None, run_status=TaskRun.Status.IN_PROGRESS)
+ state = _compute_inbox_notification_state(team.id, str(report.id))
+ assert state == InboxNotificationState(has_implementation_task=True, pr_available=False, task_terminal=False)
+
+
+def test_state_task_failed_no_pr_is_terminal(team):
+ report = _make_report(team)
+ _link_implementation_task(team, report, pr_url=None, run_status=TaskRun.Status.FAILED)
+ state = _compute_inbox_notification_state(team.id, str(report.id))
+ assert state == InboxNotificationState(has_implementation_task=True, pr_available=False, task_terminal=True)
+
+
+def test_send_skips_when_report_not_ready(team):
+ report = _make_report(team, status=SignalReport.Status.SUPPRESSED)
+ with patch("products.signals.backend.slack_inbox_notifications.dispatch_inbox_item_notifications") as mock_dispatch:
+ sent = _send_report_inbox_notifications(team.id, str(report.id))
+ assert sent == 0
+ mock_dispatch.assert_not_called()
+
+
+class _Recorder:
+ def __init__(self, states: list[InboxNotificationState]) -> None:
+ self._states = states
+ self.state_calls = 0
+ self.dispatch_calls = 0
+
+ def next_state(self) -> InboxNotificationState:
+ state = self._states[min(self.state_calls, len(self._states) - 1)]
+ self.state_calls += 1
+ return state
+
+
+async def _run_workflow(recorder: _Recorder) -> int:
+ @activity.defn(name="get_inbox_notification_state_activity")
+ async def fake_state(_input: InboxNotificationInput) -> InboxNotificationState:
+ return recorder.next_state()
+
+ @activity.defn(name="send_report_inbox_notifications_activity")
+ async def fake_dispatch(_input: InboxNotificationInput) -> int:
+ recorder.dispatch_calls += 1
+ return 1
+
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=TASK_QUEUE,
+ workflows=[SignalReportInboxNotificationWorkflow],
+ activities=[fake_state, fake_dispatch],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ return await env.client.execute_workflow(
+ SignalReportInboxNotificationWorkflow.run,
+ InboxNotificationInput(team_id=1, report_id=str(uuid.uuid4())),
+ id=f"wf-{uuid.uuid4()}",
+ task_queue=TASK_QUEUE,
+ )
+
+
+WAIT = InboxNotificationState(has_implementation_task=True, pr_available=False, task_terminal=False)
+NO_TASK = InboxNotificationState(has_implementation_task=False, pr_available=False, task_terminal=False)
+PR_READY = InboxNotificationState(has_implementation_task=True, pr_available=True, task_terminal=False)
+TERMINAL = InboxNotificationState(has_implementation_task=True, pr_available=False, task_terminal=True)
+
+
+@override_settings(SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS=10, SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS=1)
+async def test_workflow_notifies_immediately_without_task():
+ recorder = _Recorder([NO_TASK])
+ sent = await _run_workflow(recorder)
+ assert sent == 1
+ assert recorder.state_calls == 1 # no polling
+ assert recorder.dispatch_calls == 1
+
+
+@override_settings(SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS=10, SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS=1)
+async def test_workflow_waits_then_notifies_when_pr_opens():
+ recorder = _Recorder([WAIT, WAIT, PR_READY])
+ sent = await _run_workflow(recorder)
+ assert sent == 1
+ assert recorder.state_calls == 3
+ assert recorder.dispatch_calls == 1
+
+
+@override_settings(SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS=10, SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS=1)
+async def test_workflow_stops_waiting_when_task_terminal():
+ recorder = _Recorder([WAIT, TERMINAL])
+ sent = await _run_workflow(recorder)
+ assert sent == 1
+ assert recorder.state_calls == 2
+ assert recorder.dispatch_calls == 1
+
+
+@override_settings(SIGNALS_INBOX_PR_NOTIFICATION_TIMEOUT_SECONDS=3, SIGNALS_INBOX_PR_NOTIFICATION_POLL_SECONDS=1)
+async def test_workflow_notifies_after_timeout_when_pr_never_opens():
+ recorder = _Recorder([WAIT]) # always WAIT
+ sent = await _run_workflow(recorder)
+ assert sent == 1
+ # initial fetch + one fetch per poll until elapsed reaches the timeout
+ assert recorder.state_calls >= 2
+ assert recorder.dispatch_calls == 1
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index e1abb8f7436d..6e6a0561aa6a 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -14,14 +14,14 @@ from products.signals.backend.models import (
SignalReport,
SignalReportArtefact,
SignalReportTask,
+ SignalTeamConfig,
SignalUserAutonomyConfig,
)
from products.signals.backend.report_generation.research import ActionabilityChoice
from products.signals.backend.slack_inbox_notifications import (
_build_message_blocks,
_meets_min_priority,
- _recipient_presentation,
- _RecipientPresentation,
+ _resolve_reviewer_mentions,
_summary_excerpt,
dispatch_inbox_item_notifications,
)
@@ -63,6 +63,20 @@ def test_summary_excerpt_truncates_first_line_at_600_chars() -> None:
assert _summary_excerpt(long_line).endswith("...")
+def _plain_text_block_texts(blocks: list[dict]) -> list[str]:
+ """Every plain_text string in the message — mentions here would render as raw `<@…>`."""
+ texts: list[str] = []
+ for block in blocks:
+ text = block.get("text")
+ if isinstance(text, dict) and text.get("type") == "plain_text":
+ texts.append(text["text"])
+ for element in block.get("elements", []):
+ el_text = element.get("text") if isinstance(element, dict) else None
+ if isinstance(el_text, dict) and el_text.get("type") == "plain_text":
+ texts.append(el_text["text"])
+ return texts
+
+
def test_build_message_blocks_includes_recipient_and_posthog_code_button() -> None:
report = SignalReport(
id="report-uuid",
@@ -70,42 +84,78 @@ def test_build_message_blocks_includes_recipient_and_posthog_code_button() -> No
summary="Error rate rose after deploy.\nIgnored second line.",
signal_count=12,
)
- recipient = _RecipientPresentation(slack_mention="<@U123>", plain_name="Marcus Twix")
blocks, text = _build_message_blocks(
report,
priority="P1",
source_products=["error_tracking"],
- recipients=[recipient],
+ reviewer_mentions=["<@U123>"],
)
assert blocks[0]["text"]["text"] == "📬 Checkout errors spiked"
section_text = blocks[1]["text"]["text"]
- assert "Suggested for" not in section_text
- # Mention belongs in the mrkdwn section so Slack actually pings the user.
- assert section_text.startswith("*‼️ P1 • Matched to <@U123> per code*")
- assert "*Checkout errors spiked*" not in section_text
+ assert section_text.startswith("*‼️ P1 · Error tracking*")
assert "Error rate rose after deploy." in section_text
assert "Ignored second line." not in section_text
+ # A mention in plain_text would render as the raw token, never pinging anyone.
+ assert all("<@" not in t for t in _plain_text_block_texts(blocks))
context_text = blocks[2]["elements"][0]["text"]
assert "12 signals" in context_text
- assert "Error tracking" in context_text
- assert "Inbox" in context_text
+ assert "👤 Suggested reviewers: <@U123>" in context_text
+ assert "Inbox" not in context_text
button = blocks[3]["elements"][0]
assert button["text"]["text"] == "Open in PostHog Code"
assert button["url"] == "posthog-code://inbox/report-uuid"
- assert text == "Inbox for Marcus Twix (P1): Checkout errors spiked"
+ assert text == "Inbox item (P1): Checkout errors spiked"
+
+
+def test_build_message_blocks_mentions_every_routed_reviewer() -> None:
+ report = SignalReport(id="report-uuid", title="Shared channel")
+ blocks, _ = _build_message_blocks(
+ report,
+ priority="P2",
+ source_products=[],
+ reviewer_mentions=["<@U1>", "<@U2>"],
+ )
+
+ assert blocks[1]["text"]["text"] == "*❗ P2*"
+ assert blocks[2]["elements"][0]["text"] == "👤 Suggested reviewers: <@U1> <@U2>"
-def test_build_message_blocks_tags_all_recipients() -> None:
- report = SignalReport(id="report-uuid", title="Shared channel report")
- recipients = [
- _RecipientPresentation(slack_mention="<@U123>", plain_name="Marcus Twix"),
- _RecipientPresentation(slack_mention=None, plain_name="Dana Snickers"),
- ]
- blocks, text = _build_message_blocks(report, priority="P2", source_products=[], recipients=recipients)
+def test_build_message_blocks_includes_repository_in_metadata_line() -> None:
+ report = SignalReport(id="report-uuid", title="Repo test")
+ blocks, _ = _build_message_blocks(
+ report,
+ priority="P2",
+ source_products=["error_tracking"],
+ reviewer_mentions=[],
+ repository="PostHog/posthog",
+ )
+
+ assert blocks[1]["text"]["text"] == "*❗ P2 · Error tracking · PostHog/posthog*"
+
+
+def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields() -> None:
+ # A crafted summary/repository must not inject Slack mentions (<!here>, <@U…>) into mrkdwn.
+ report = SignalReport(
+ id="report-uuid",
+ title="Injection test",
+ summary="<!here> everyone & <@U999> look",
+ signal_count=1,
+ )
+ blocks, _ = _build_message_blocks(
+ report,
+ priority="P2",
+ source_products=[],
+ reviewer_mentions=[],
+ repository="<!channel>/repo",
+ )
- assert blocks[1]["text"]["text"].startswith("*❗ P2 • Matched to <@U123>, Dana Snickers per code*")
- assert text == "Inbox for Marcus Twix, Dana Snickers (P2): Shared channel report"
+ section_text = blocks[1]["text"]["text"]
+ assert "<!here>" not in section_text
+ assert "<@U999>" not in section_text
+ assert "<!channel>" not in section_text
+ assert "&lt;!here&gt;" in section_text
+ assert "&amp;" in section_text
def test_build_message_blocks_includes_github_pr_button_when_pr_url_provided() -> None:
@@ -115,38 +165,59 @@ def test_build_message_blocks_includes_github_pr_button_when_pr_url_provided() -
summary="Error rate rose after deploy.",
signal_count=12,
)
- recipient = _RecipientPresentation(slack_mention="<@U123>", plain_name="Marcus Twix")
pr_url = "https://github.com/org/repo/pull/42"
blocks, _ = _build_message_blocks(
report,
priority="P1",
source_products=["error_tracking"],
- recipients=[recipient],
+ reviewer_mentions=["<@U123>"],
implementation_pr_url=pr_url,
)
buttons = blocks[3]["elements"]
assert len(buttons) == 2
- assert buttons[0]["text"]["text"] == "Open in PostHog Code"
- assert buttons[1]["text"]["text"] == "Review PR in GitHub"
- assert buttons[1]["url"] == pr_url
+ assert buttons[0]["text"]["text"] == "Review PR"
+ assert buttons[0]["url"] == pr_url
+ assert buttons[1]["text"]["text"] == "Open in PostHog Code"
def test_build_message_blocks_omits_github_pr_button_without_pr_url() -> None:
report = SignalReport(id="report-uuid", title="No PR yet")
- recipient = _RecipientPresentation(slack_mention=None, plain_name="Marcus Twix")
blocks, _ = _build_message_blocks(
report,
priority=None,
source_products=[],
- recipients=[recipient],
+ reviewer_mentions=["Marcus Twix"],
implementation_pr_url=None,
)
- assert blocks[1]["text"]["text"] == "*Matched to Marcus Twix per code*"
+ assert blocks[1]["text"]["text"] == "*No PR yet*"
+ assert blocks[2]["elements"][0]["text"] == "👤 Suggested reviewers: Marcus Twix"
assert len(blocks[3]["elements"]) == 1
+def test_build_message_blocks_appends_dismiss_button_last_with_action_id() -> None:
+ report = SignalReport(id="report-uuid", title="Dismissable")
+ dismiss_value = '{"integration_id": 2, "report_id": "report-uuid", "team_id": 1}'
+ blocks, _ = _build_message_blocks(
+ report,
+ priority="P2",
+ source_products=[],
+ reviewer_mentions=["<@U123>"],
+ implementation_pr_url="https://github.com/org/repo/pull/42",
+ dismiss_button_value=dismiss_value,
+ )
+
+ buttons = blocks[3]["elements"]
+ assert [b["text"]["text"] for b in buttons] == ["Review PR", "Open in PostHog Code", "Dismiss"]
+ dismiss = buttons[-1]
+ assert dismiss["action_id"] == "signals_dismiss_report"
+ assert dismiss["value"] == dismiss_value
+ assert "url" not in dismiss
+ assert dismiss["confirm"]["confirm"]["text"] == "Dismiss"
+ assert dismiss["confirm"]["deny"]["text"] == "Cancel"
+
+
@pytest.mark.parametrize(
("priority", "expected_priority_label"),
[
@@ -159,45 +230,45 @@ def test_build_message_blocks_omits_github_pr_button_without_pr_url() -> None:
)
def test_build_message_blocks_prefixes_priority_with_emoji(priority: str, expected_priority_label: str) -> None:
report = SignalReport(id="report-uuid", title="Priority test")
- recipient = _RecipientPresentation(slack_mention="<@U123>", plain_name="Marcus Twix")
blocks, _ = _build_message_blocks(
report,
priority=priority,
source_products=[],
- recipients=[recipient],
+ reviewer_mentions=["<@U123>"],
)
- assert blocks[1]["text"]["text"] == f"*{expected_priority_label} • Matched to <@U123> per code*"
+ assert blocks[1]["text"]["text"] == f"*{expected_priority_label}*"
+ assert blocks[2]["elements"][0]["text"] == "👤 Suggested reviewers: <@U123>"
-def test_recipient_presentation_uses_slack_mention_when_lookup_succeeds() -> None:
+def test_resolve_reviewer_mentions_uses_slack_mention_when_lookup_succeeds() -> None:
user = User(first_name="Marcus", last_name="Twix", email="[email protected]")
slack = MagicMock()
- integration = MagicMock()
-
with patch(
"products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
return_value="U_SLACK",
):
- presentation = _recipient_presentation(user, slack, integration)
-
- assert presentation.slack_mention == "<@U_SLACK>"
- assert presentation.plain_name == "Marcus Twix"
+ assert _resolve_reviewer_mentions(slack, [user]) == ["<@U_SLACK>"]
-def test_recipient_presentation_falls_back_to_name_when_slack_user_not_found() -> None:
+def test_resolve_reviewer_mentions_falls_back_to_name_when_slack_user_not_found() -> None:
user = User(first_name="Marcus", last_name="Twix", email="[email protected]")
slack = MagicMock()
- integration = MagicMock()
-
with patch(
"products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
return_value=None,
):
- presentation = _recipient_presentation(user, slack, integration)
+ assert _resolve_reviewer_mentions(slack, [user]) == ["Marcus Twix"]
- assert presentation.slack_mention is None
- assert presentation.plain_name == "Marcus Twix"
+
+def test_resolve_reviewer_mentions_caps_at_five() -> None:
+ users = [User(first_name=f"U{i}", email=f"u{i}@example.com") for i in range(8)]
+ slack = MagicMock()
+ with patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ return_value=None,
+ ):
+ assert len(_resolve_reviewer_mentions(slack, users)) == 5
@pytest.fixture
@@ -209,6 +280,11 @@ def org_and_team():
org.delete()
+def _set_team_channel(team: Team, channel: str) -> None:
+ # SignalTeamConfig is auto-created per team via register_team_extension_signal.
+ SignalTeamConfig.objects.filter(team=team).update(default_slack_notification_channel=channel)
+
+
def _make_reviewer_user(org: Organization, email: str, login: str) -> User:
user = User.objects.create(email=email, first_name="Reviewer", last_name="Bot")
OrganizationMembership.objects.create(user=user, organization=org)
@@ -290,7 +366,7 @@ def _create_implementation_task_with_run(
@pytest.mark.django_db
-def test_dispatch_no_notification_when_user_has_no_slack_config(org_and_team):
+def test_dispatch_no_notification_without_team_channel_or_user_config(org_and_team):
org, team = org_and_team
user = _make_reviewer_user(org, "[email protected]", "review-bot")
SignalUserAutonomyConfig.objects.create(user=user) # no slack config
@@ -330,46 +406,163 @@ def test_dispatch_sends_to_configured_reviewer(org_and_team):
assert fake_client.chat_postMessage.call_count == 1
call_kwargs = fake_client.chat_postMessage.call_args.kwargs
assert call_kwargs["channel"] == "C123"
- assert "Inbox for Reviewer Bot (P1)" in call_kwargs["text"]
+ assert "Inbox item (P1)" in call_kwargs["text"]
blocks = call_kwargs["blocks"]
assert blocks[0]["text"]["text"] == "📬 Test report"
- assert blocks[1]["text"]["text"].startswith("*‼️ P1 • Matched to <@U_REVIEWER> per code*")
+ assert blocks[1]["text"]["text"].startswith("*‼️ P1 · Error tracking*")
+ assert "👤 Suggested reviewers: <@U_REVIEWER>" in blocks[2]["elements"][0]["text"]
+ assert all("<@" not in t for t in _plain_text_block_texts(blocks))
assert blocks[3]["elements"][0]["url"] == f"posthog-code://inbox/{report.id}"
@pytest.mark.django_db
- ("priority", "actionability"),
- [
- (None, ActionabilityChoice.IMMEDIATELY_ACTIONABLE),
- (AutonomyPriority.P1, None),
- ("XX", ActionabilityChoice.IMMEDIATELY_ACTIONABLE),
- (AutonomyPriority.P1, ActionabilityChoice.NOT_ACTIONABLE),
- ],
-)
-def test_dispatch_skips_until_immediately_actionable_with_valid_priority(
- org_and_team: tuple[Organization, Team], priority: str | None, actionability: str | None
-) -> None:
+def test_dispatch_posts_to_team_channel_without_per_user_config(org_and_team):
+ org, team = org_and_team
+ reviewer = _make_reviewer_user(org, "[email protected]", "team-bot")
+ _make_slack_integration(team, reviewer)
+ _set_team_channel(team, "CTEAM|#posthog-signals")
+ report = _make_ready_report(team, priority=AutonomyPriority.P2, suggested_logins=["team-bot"])
+
+ fake_client = MagicMock()
+ with (
+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,
+ patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ return_value="U_TEAM",
+ ),
+ ):
+ slack_cls.return_value.client = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 1
+ call_kwargs = fake_client.chat_postMessage.call_args.kwargs
+ assert call_kwargs["channel"] == "CTEAM"
+ assert "<@U_TEAM>" in call_kwargs["blocks"][2]["elements"][0]["text"]
+
+
+def test_dispatch_posts_nothing_without_suggested_reviewers(org_and_team):
+ org, team = org_and_team
+ creator = _make_reviewer_user(org, "[email protected]", "creator-bot")
+ _make_slack_integration(team, creator)
+ _set_team_channel(team, "CTEAM|#posthog-signals")
+ report = _make_ready_report(team, priority=AutonomyPriority.P2) # no suggested reviewers
+
+ fake_client = MagicMock()
+ with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:
+ slack_cls.return_value.client = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ # No reviewers to route → the team channel is not posted to.
+ assert sent == 0
+ assert fake_client.chat_postMessage.call_count == 0
+
+
+def test_dispatch_groups_own_and_fallback_reviewers_sharing_a_channel(org_and_team):
+ # One reviewer's own channel resolves to the same channel as the team default that
+ # a second (unconfigured) reviewer falls back to → a single post mentioning both.
org, team = org_and_team
- user = _make_reviewer_user(org, "[email protected]", "missing-judgment-bot")
+ own = _make_reviewer_user(org, "[email protected]", "own-bot")
+ _make_reviewer_user(org, "[email protected]", "fallback-bot")
+ integration = _make_slack_integration(team, own)
+ SignalUserAutonomyConfig.objects.create(
+ user=own,
+ slack_notification_integration=integration,
+ slack_notification_channel="CSHARED|#signals",
+ )
+ _set_team_channel(team, "CSHARED|#signals")
+ report = _make_ready_report(team, priority=AutonomyPriority.P2, suggested_logins=["own-bot", "fallback-bot"])
+
+ def _slack_id(_slack, email):
+ return {"[email protected]": "U_OWN", "[email protected]": "U_FALLBACK"}.get(email.strip().lower())
+
+ fake_client = MagicMock()
+ with (
+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,
+ patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ side_effect=_slack_id,
+ ),
+ ):
+ slack_cls.return_value.client = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 1
+ 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
+
+
+def test_dispatch_skips_team_channel_when_reviewer_has_own_channel(org_and_team):
+ # The only reviewer has their own channel → they are routed there and nobody falls
+ # back to the team default, so the team channel is not posted to at all.
+ org, team = org_and_team
+ user = _make_reviewer_user(org, "[email protected]", "own-only-bot")
integration = _make_slack_integration(team, user)
SignalUserAutonomyConfig.objects.create(
user=user,
slack_notification_integration=integration,
- slack_notification_channel="C123|#inbox",
+ slack_notification_channel="CUSER|#me",
)
- report = _make_ready_report(
- team,
- priority=priority,
- actionability=actionability,
- suggested_logins=["missing-judgment-bot"],
+ _set_team_channel(team, "CTEAM|#posthog-signals")
+ report = _make_ready_report(team, priority=AutonomyPriority.P2, suggested_logins=["own-only-bot"])
+
+ fake_client = MagicMock()
+ with (
+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,
+ patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ return_value=None,
+ ),
+ ):
+ slack_cls.return_value.client = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 1
+ channels = {c.kwargs["channel"] for c in fake_client.chat_postMessage.call_args_list}
+ assert channels == {"CUSER"}
+
+
+def test_dispatch_team_channel_tags_only_fallback_reviewers(org_and_team):
+ # One reviewer has an own channel, one falls back to the team default. The team
+ # post must mention only the fallback reviewer, not the one routed elsewhere.
+ org, team = org_and_team
+ own = _make_reviewer_user(org, "[email protected]", "own-bot")
+ _make_reviewer_user(org, "[email protected]", "fallback-bot")
+ integration = _make_slack_integration(team, own)
+ SignalUserAutonomyConfig.objects.create(
+ user=own,
+ slack_notification_integration=integration,
+ slack_notification_channel="CUSER|#me",
)
+ _set_team_channel(team, "CTEAM|#posthog-signals")
+ report = _make_ready_report(team, priority=AutonomyPriority.P2, suggested_logins=["own-bot", "fallback-bot"])
- with patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls:
+ def _slack_id(_slack, email):
+ return {"[email protected]": "U_OWN", "[email protected]": "U_FALLBACK"}.get(email.strip().lower())
+
+ fake_client = MagicMock()
+ with (
+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,
+ patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ side_effect=_slack_id,
+ ),
+ ):
+ slack_cls.return_value.client = fake_client
sent = dispatch_inbox_item_notifications(str(report.id), team.id)
- assert sent == 0
- assert slack_cls.call_count == 0
+ assert sent == 2
+ by_channel = {
+ c.kwargs["channel"]: c.kwargs["blocks"][2]["elements"][0]["text"]
+ for c in fake_client.chat_postMessage.call_args_list
+ }
+ assert set(by_channel) == {"CUSER", "CTEAM"}
+ assert "<@U_OWN>" in by_channel["CUSER"] and "<@U_FALLBACK>" not in by_channel["CUSER"]
+ assert "<@U_FALLBACK>" in by_channel["CTEAM"] and "<@U_OWN>" not in by_channel["CTEAM"]
@pytest.mark.django_db
@@ -398,13 +591,53 @@ def test_dispatch_includes_github_pr_button_when_implementation_task_has_pr(org_
assert sent == 1
buttons = fake_client.chat_postMessage.call_args.kwargs["blocks"][3]["elements"]
- assert len(buttons) == 2
- assert buttons[1]["text"]["text"] == "Review PR in GitHub"
- assert buttons[1]["url"] == "https://github.com/org/repo/pull/99"
+ assert [b["text"]["text"] for b in buttons] == ["Review PR", "Open in PostHog Code", "Dismiss"]
+ assert buttons[0]["url"] == "https://github.com/org/repo/pull/99"
+ assert buttons[-1]["action_id"] == "signals_dismiss_report"
@pytest.mark.django_db
-def test_dispatch_respects_min_priority_filter(org_and_team):
+def test_dispatch_dismiss_button_carries_routing_ids_and_repository(org_and_team):
+ org, team = org_and_team
+ user = _make_reviewer_user(org, "[email protected]", "dismiss-bot")
+ integration = _make_slack_integration(team, user)
+ SignalUserAutonomyConfig.objects.create(
+ user=user,
+ slack_notification_integration=integration,
+ slack_notification_channel="C123|#inbox",
+ )
+ report = _make_ready_report(team, priority=AutonomyPriority.P2, suggested_logins=["dismiss-bot"])
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.REPO_SELECTION,
+ content=json.dumps({"repository": "PostHog/posthog", "reason": "owns the code"}),
+ )
+
+ fake_client = MagicMock()
+ with (
+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,
+ patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ return_value=None,
+ ),
+ ):
+ slack_cls.return_value.client = fake_client
+ sent = dispatch_inbox_item_notifications(str(report.id), team.id)
+
+ assert sent == 1
+ blocks = fake_client.chat_postMessage.call_args.kwargs["blocks"]
+ assert "PostHog/posthog" in blocks[1]["text"]["text"]
+ dismiss = blocks[3]["elements"][-1]
+ assert json.loads(dismiss["value"]) == {
+ "integration_id": integration.id,
+ "report_id": str(report.id),
+ "team_id": team.id,
+ }
+
+
+def test_dispatch_respects_per_user_min_priority_filter(org_and_team):
org, team = org_and_team
user = _make_reviewer_user(org, "[email protected]", "skip-bot")
integration = _make_slack_integration(team, user)
@@ -414,7 +647,7 @@ def test_dispatch_respects_min_priority_filter(org_and_team):
slack_notification_channel="C123|#inbox",
slack_notification_min_priority=AutonomyPriority.P1,
)
- # P3 < P1 threshold so this should be filtered out
+ # P3 < P1 threshold so the per-user post is filtered out (and no team channel is set).
report = _make_ready_report(team, priority=AutonomyPriority.P3, suggested_logins=["skip-bot"])
fake_client = MagicMock()
@@ -426,6 +659,38 @@ def test_dispatch_respects_min_priority_filter(org_and_team):
assert fake_client.chat_postMessage.call_count == 0
+def test_dispatch_filtered_own_channel_reviewer_does_not_fall_back_to_team(org_and_team):
+ # A reviewer whose own channel is filtered out by their min-priority chose that
+ # threshold — they are not silently rerouted to the team default channel.
+ org, team = org_and_team
+ user = _make_reviewer_user(org, "[email protected]", "low-bot")
+ integration = _make_slack_integration(team, user)
+ SignalUserAutonomyConfig.objects.create(
+ user=user,
+ slack_notification_integration=integration,
+ slack_notification_channel="CUSER|#me",
+ slack_notification_min_priority=AutonomyPriority.P1,
+ )
+ _set_team_channel(team, "CTEAM|#posthog-signals")
+ # P3 is below the user's P1 threshold → no own-channel post and no team fallback.
+ report = _make_ready_report(team, priority=AutonomyPriority.P3, suggested_logins=["low-bot"])
+
+ fake_client = MagicMock()
+ with (
+ patch("products.signals.backend.slack_inbox_notifications.SlackIntegration") as slack_cls,
+ patch(
+ "products.signals.backend.slack_inbox_notifications.lookup_slack_user_id_by_email",
+ return_value=None,
+ ),
+ ):
+ slack_cls.return_value.client = fake_client
+ 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_ignores_slack_config_from_another_team(org_and_team):
org, report_team = org_and_team
@@ -521,5 +786,5 @@ def test_dispatch_sends_once_per_channel_when_reviewers_share_channel(org_and_te
call_kwargs = fake_client.chat_postMessage.call_args.kwargs
assert call_kwargs["channel"] == "C123"
# The single message still tags both reviewers that resolved to the channel.
- section_text = call_kwargs["blocks"][1]["text"]["text"]
- assert "Matched to <@U_ONE>, <@U_TWO> per code" in section_text
+ context_text = call_kwargs["blocks"][2]["elements"][0]["text"]
+ assert "👤 Suggested reviewers: <@U_ONE> <@U_TWO>" in context_text
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 00306028b90f..e759f042df7d 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -2488,6 +2488,110 @@ def _handle_channel_approval_deny(payload: dict) -> HttpResponse:
return HttpResponse(status=200)
+# Wire contract with products/signals/backend/slack_inbox_notifications.py (SIGNALS_DISMISS_REPORT_ACTION_ID).
+SIGNALS_DISMISS_REPORT_ACTION_ID = "signals_dismiss_report"
+
+
+def _dismiss_action_value(payload: dict) -> dict | None:
+ action = next(
+ (a for a in payload.get("actions", []) if a.get("action_id") == SIGNALS_DISMISS_REPORT_ACTION_ID), None
+ )
+ if not action:
+ return None
+ try:
+ value = json.loads(action.get("value", ""))
+ except (json.JSONDecodeError, TypeError):
+ return None
+ return value if isinstance(value, dict) else None
+
+
+def _extract_dismiss_hints(payload: dict) -> int | None:
+ """Integration id carried by a signals 'Dismiss' button, used for region-ownership routing."""
+ value = _dismiss_action_value(payload)
+ if not value:
+ return None
+ integration_id = value.get("integration_id")
+ return integration_id if isinstance(integration_id, int) else None
+
+
+def _handle_signals_dismiss_report(payload: dict) -> HttpResponse:
+ """Suppress a signals inbox report when a reviewer clicks 'Dismiss' in Slack."""
+ from products.signals.backend.facade.api import ( # noqa: PLC0415 — cross-product action kept off the slack import path
+ dismiss_report_from_slack,
+ )
+
+ value = _dismiss_action_value(payload)
+ slack_team_id = payload.get("team", {}).get("id")
+ if not value or not slack_team_id:
+ return HttpResponse(status=200)
+
+ integration_id = value.get("integration_id")
+ report_id = value.get("report_id")
+ report_team_id = value.get("team_id")
+ if not (isinstance(integration_id, int) and report_id and isinstance(report_team_id, int)):
+ return HttpResponse(status=200)
+
+ try:
+ # Slack webhook: no team context; scoped by PK + kind + workspace ID. The team match below
+ # ensures the report belongs to the workspace's integration before we touch it.
+ # nosemgrep: idor-lookup-without-team, idor-taint-user-input-to-model-get
+ integration = Integration.objects.get(
+ id=integration_id, kind=SLACK_INTEGRATION_KIND, integration_id=slack_team_id
+ )
+ except Integration.DoesNotExist:
+ logger.info("signals_dismiss_report_no_integration", integration_id=integration_id)
+ return HttpResponse(status=200)
+
+ if integration.team_id != report_team_id:
+ logger.warning(
+ "signals_dismiss_report_team_mismatch",
+ integration_team_id=integration.team_id,
+ report_team_id=report_team_id,
+ )
+ return HttpResponse(status=200)
+
+ slack_user_id = payload.get("user", {}).get("id", "")
+ # Only PostHog org members may dismiss — a non-member in a shared channel must not suppress reports.
+ if _is_org_member(integration, slack_user_id) is None:
+ logger.warning(
+ "signals_dismiss_report_not_org_member",
+ integration_id=integration.id,
+ slack_user_id=slack_user_id,
+ )
+ return HttpResponse(status=200)
+
+ suppressed = dismiss_report_from_slack(report_team_id, str(report_id), slack_user_id=slack_user_id)
+
+ _post_signals_dismiss_feedback(payload, dismissed=suppressed, slack_user_id=slack_user_id)
+ return HttpResponse(status=200)
+
+
+def _post_signals_dismiss_feedback(payload: dict, *, dismissed: bool, slack_user_id: str) -> None:
+ """Best-effort: replace the original message so it reads as dismissed."""
+ response_url = payload.get("response_url")
+ if not response_url:
+ return
+
+ if dismissed:
+ actor = f"<@{slack_user_id}>" if slack_user_id else "a reviewer"
+ text = f"✅ Dismissed by {actor}"
+ else:
+ text = "This report could not be dismissed — it may already be resolved or removed."
+
+ original_message = payload.get("message", {})
+ kept_blocks = [b for b in original_message.get("blocks", []) if b.get("type") != "actions"]
+ kept_blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": text}]})
+
+ try:
+ requests.post(
+ response_url,
+ json={"replace_original": True, "text": text, "blocks": kept_blocks},
+ timeout=5,
+ )
+ except requests.RequestException as e:
+ logger.warning("signals_dismiss_report_feedback_failed", error=str(e))
+
+
def _handle_terminate_task_submit(payload: dict) -> HttpResponse:
"""Start Temporal workflow for task termination and return 200 immediately."""
action = next((a for a in payload.get("actions", []) if a.get("action_id") == "posthog_code_terminate_task"), None)
@@ -2544,6 +2648,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
context = _decode_picker_context(context_token) if context_token else None
hinted_integration_id, hinted_user_id = _extract_picker_hints(payload)
terminate_integration_id, terminate_user_id = _extract_terminate_hints(payload)
+ dismiss_integration_id = _extract_dismiss_hints(payload)
requesting_user = payload.get("user", {}).get("id", "")
slack_team_id = payload.get("team", {}).get("id")
@@ -2568,6 +2673,14 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
kind=SLACK_INTEGRATION_KIND,
integration_id=slack_team_id,
).exists()
+ elif slack_team_id and dismiss_integration_id:
+ # Any reviewer who can see the inbox-item message may dismiss it (team-shared channels),
+ # so this isn't gated on a specific Slack user — only on owning the integration locally.
+ local = Integration.objects.filter( # nosemgrep: idor-lookup-without-team
+ id=dismiss_integration_id, # nosemgrep: idor-taint-user-input-to-model-get
+ kind=SLACK_INTEGRATION_KIND,
+ integration_id=slack_team_id,
+ ).exists()
proxied = _was_proxied(request)
incoming_host = request.get_host()
@@ -2652,5 +2765,7 @@ def posthog_code_interactivity_handler(request: HttpRequest) -> HttpResponse:
return _handle_channel_approval_submit(payload)
if action.get("action_id") == CHANNEL_APPROVAL_ACTION_DENY:
return _handle_channel_approval_deny(payload)
+ if action.get("action_id") == SIGNALS_DISMISS_REPORT_ACTION_ID:
+ return _handle_signals_dismiss_report(payload)
return HttpResponse(status=200)
diff --git a/products/slack_app/backend/tests/test_posthog_code_interactivity.py b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
index dee4eb023651..3632aa4dc6c6 100644
--- a/products/slack_app/backend/tests/test_posthog_code_interactivity.py
+++ b/products/slack_app/backend/tests/test_posthog_code_interactivity.py
@@ -763,3 +763,114 @@ class TestInteractivityRegionRouting(TestCase):
mock_proxy.assert_not_called()
mock_sync_connect.assert_called_once()
mock_sync_connect.return_value.start_workflow.assert_called_once()
+
+
+class TestSignalsDismissReport(TestCase):
+ def setUp(self):
+ self.client = APIClient()
+ self.signing_secret = "posthog-code-test-secret"
+
+ self.organization = Organization.objects.create(name="Dismiss Org")
+ self.team = Team.objects.create(organization=self.organization, name="Dismiss Team")
+ self.integration = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T12345",
+ sensitive_config={"access_token": "xoxb-test"},
+ )
+
+ def _make_ready_report(self):
+ from products.signals.backend.models import SignalReport
+
+ return SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="Dismissable report",
+ summary="Summary",
+ signal_count=1,
+ total_weight=1.0,
+ )
+
+ def _dismiss_payload(self, report_id: str, *, team_id: int | None = None) -> dict:
+ return {
+ "type": "block_actions",
+ "team": {"id": "T12345"},
+ "user": {"id": "U777"},
+ "response_url": "https://hooks.slack.test/response",
+ "actions": [
+ {
+ "action_id": "signals_dismiss_report",
+ "value": json.dumps(
+ {
+ "integration_id": self.integration.id,
+ "report_id": report_id,
+ "team_id": team_id if team_id is not None else self.team.id,
+ }
+ ),
+ }
+ ],
+ "message": {"ts": "1234.9999", "blocks": []},
+ }
+
+ def _post_interactivity(self, payload: dict) -> Any:
+ body_str = f"payload={json.dumps(payload)}"
+ signature, ts = sign_slack_request(body_str.encode(), self.signing_secret)
+ return self.client.post(
+ "/slack/interactivity-callback/",
+ data=body_str,
+ content_type="application/x-www-form-urlencoded",
+ HTTP_X_SLACK_SIGNATURE=signature,
+ HTTP_X_SLACK_REQUEST_TIMESTAMP=ts,
+ )
+
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.api.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_dismiss_suppresses_report_and_writes_artefact(self, mock_config, mock_requests_post, mock_is_org_member):
+ from products.signals.backend.models import SignalReport, SignalReportArtefact
+
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = MagicMock() # clicker resolves to an org member
+ report = self._make_ready_report()
+
+ response = self._post_interactivity(self._dismiss_payload(str(report.id)))
+
+ assert response.status_code == 200
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.SUPPRESSED
+ assert SignalReportArtefact.objects.filter(
+ report=report, type=SignalReportArtefact.ArtefactType.DISMISSAL
+ ).exists()
+ # The original message is replaced with a dismissed acknowledgement.
+ assert mock_requests_post.call_args.kwargs["json"]["replace_original"] is True
+
+ @patch("products.slack_app.backend.api._is_org_member")
+ @patch("products.slack_app.backend.api.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_dismiss_refuses_non_org_member(self, mock_config, mock_requests_post, mock_is_org_member):
+ from products.signals.backend.models import SignalReport
+
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ mock_is_org_member.return_value = None # clicker is not a PostHog org member
+ report = self._make_ready_report()
+
+ response = self._post_interactivity(self._dismiss_payload(str(report.id)))
+
+ assert response.status_code == 200
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.READY # not suppressed
+
+ @patch("products.slack_app.backend.api.requests.post")
+ @patch("products.slack_app.backend.api.SlackIntegration.slack_config")
+ def test_dismiss_ignores_report_from_another_team(self, mock_config, mock_requests_post):
+ from products.signals.backend.models import SignalReport
+
+ mock_config.return_value = {"SLACK_APP_SIGNING_SECRET": self.signing_secret}
+ report = self._make_ready_report()
+
+ # team_id in the button value doesn't match the integration's team.
+ response = self._post_interactivity(self._dismiss_payload(str(report.id), team_id=self.team.id + 9999))
+
+ assert response.status_code == 200
+ report.refresh_from_db()
+ assert report.status == SignalReport.Status.READY
diff --git a/tach.toml b/tach.toml
index be1b8e48e549..0791d0e28cf9 100644
--- a/tach.toml
+++ b/tach.toml
@@ -514,6 +514,7 @@ depends_on = [
"posthog",
"products.dashboards",
"products.product_analytics",
+ "products.signals",
]
layer = "modules"