:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): refine inbox Slack notifications and thread signal evidence (#62393)
Michael Matlokab06886be5023
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.pyindex 52dac75bd1e5..3f4d6a1c2971 100644--- a/products/signals/backend/slack_inbox_notifications.py+++ b/products/signals/backend/slack_inbox_notifications.py@@ -57,12 +57,13 @@ _PRIORITY_ORDER: tuple[str, ...] = (AutonomyPriority.P4,)+# Only the two highest priorities get a red, alarming emoji; the rest use a calmer severity gradient._SLACK_PRIORITY_LABELS: dict[str, str] = {- AutonomyPriority.P0: "🆘 P0",- AutonomyPriority.P1: "‼️ P1",- AutonomyPriority.P2: "❗ P2",- AutonomyPriority.P3: "⚠️ P3",- AutonomyPriority.P4: "👀 P4",+ AutonomyPriority.P0: "‼️ P0",+ AutonomyPriority.P1: "❗ P1",+ AutonomyPriority.P2: "🟠 P2",+ AutonomyPriority.P3: "🟡 P3",+ AutonomyPriority.P4: "🔵 P4",}_SOURCE_PRODUCT_LABELS: dict[str, str] = {@@ -294,9 +295,9 @@ def _build_message_blocks(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] + "..."+ header_text = (+ title_line if len(title_line) <= _SLACK_HEADER_MAX_LEN else title_line[: _SLACK_HEADER_MAX_LEN - 3] + "..."+ )meta_parts: list[str] = []if priority:@@ -379,6 +380,157 @@ def _build_message_blocks(return blocks, fallback_text+# Bound how many evidence signals we post into a thread so a large report can't flood a channel.+_MAX_THREAD_SIGNALS = 30+# Slack section text caps at 3000 chars; leave headroom for the ellipsis.+_SIGNAL_CONTENT_MAX_LEN = 2900++# Explicit "Product · Signal type" labels, mirroring `signalCardSourceLine` in the canonical Inbox UI+# (PostHog Code's apps/code/.../detail/SignalCard.tsx). Keep in sync with it.+_SIGNAL_SOURCE_LINES: dict[tuple[str, str], str] = {+ ("error_tracking", "issue_created"): "Error tracking · New issue",+ ("error_tracking", "issue_reopened"): "Error tracking · Issue reopened",+ ("error_tracking", "issue_spiking"): "Error tracking · Volume spike",+ ("session_replay", "session_problem"): "Session replay · Session problem",+ ("session_replay", "session_segment_cluster"): "Session replay · Session segment cluster",+ ("session_replay", "session_analysis_cluster"): "Session replay · Session analysis cluster",+ ("llm_analytics", "evaluation"): "AI observability · Evaluation",+ ("zendesk", "ticket"): "Zendesk · Ticket",+ ("github", "issue"): "GitHub · Issue",+ ("linear", "issue"): "Linear · Issue",+ ("pganalyze", "issue"): "pganalyze · Issue",+}+++def _prettify_scout_name(skill_name: str) -> str:+ """Turn a scout's skill_name (e.g. "signals-scout-error-tracking") into a label (e.g. "Error tracking")."""+ cleaned = skill_name.removeprefix("signals-scout-").replace("-", " ").replace("_", " ").strip()+ return cleaned[:1].upper() + cleaned[1:] if cleaned else ""+++def _signal_source_line(source_product: str, source_type: str, extra: dict | None = None) -> str:+ """Human-readable "Product · Signal type" line, mirroring `signalCardSourceLine` in the canonical Inbox UI."""+ explicit = _SIGNAL_SOURCE_LINES.get((source_product, source_type))+ if explicit is not None:+ return explicit+ if source_product == "error_tracking":+ type_label = source_type.replace("_", " ")+ return f"Error tracking · {type_label}" if type_label else "Error tracking"+ if source_product == "signals_scout" and source_type == "cross_source_issue":+ skill_name = extra.get("skill_name") if isinstance(extra, dict) else None+ pretty = _prettify_scout_name(skill_name) if isinstance(skill_name, str) else ""+ return f"Scout · {pretty}" if pretty else "Scout · Cross-source issue"+ product_label = source_product.replace("_", " ")+ type_label = source_type.replace("_", " ")+ return f"{product_label} · {type_label}" if type_label else product_label+++def _is_safe_http_url(value: object) -> bool:+ # mrkdwn link injection guard: only plain http(s) URLs without the chars that break `<url|text>`.+ if not isinstance(value, str):+ return False+ if not (value.startswith("http://") or value.startswith("https://")):+ return False+ return not any(char in value for char in ("<", ">", "|"))+++def _signal_detail_parts(source_product: str, extra: dict) -> list[str]:+ """A compact, source-specific metadata line mirroring the inbox SignalCard footer."""+ parts: list[str] = []+ if source_product == "github":+ number = extra.get("number")+ if number is not None:+ parts.append(f"#{_escape_mrkdwn(str(number))}")+ labels = extra.get("labels")+ if isinstance(labels, list) and labels:+ parts.append(", ".join(_escape_mrkdwn(str(label)) for label in labels[:5]))+ if _is_safe_http_url(extra.get("html_url")):+ parts.append(f"<{extra['html_url']}|View on GitHub>")+ elif source_product == "zendesk":+ if extra.get("priority"):+ parts.append(f"Priority: {_escape_mrkdwn(str(extra['priority']))}")+ if extra.get("status"):+ parts.append(f"Status: {_escape_mrkdwn(str(extra['status']))}")+ if _is_safe_http_url(extra.get("url")):+ parts.append(f"<{extra['url']}|Open ticket>")+ elif source_product == "llm_analytics":+ if extra.get("model"):+ parts.append(f"Model: {_escape_mrkdwn(str(extra['model']))}")+ if extra.get("provider"):+ parts.append(f"Provider: {_escape_mrkdwn(str(extra['provider']))}")+ trace_id = extra.get("trace_id")+ if trace_id:+ parts.append(f"Trace: `{_escape_mrkdwn(str(trace_id)[:12])}…`")+ elif source_product == "error_tracking":+ fingerprint = extra.get("fingerprint")+ if fingerprint:+ text = str(fingerprint)+ short = text if len(text) <= 14 else text[:14] + "…"+ parts.append(f"Fingerprint: `{_escape_mrkdwn(short)}`")+ elif source_product == "session_replay":+ if extra.get("problem_type"):+ parts.append(f"Problem: {_escape_mrkdwn(str(extra['problem_type']).replace('_', ' '))}")+ return parts+++def _build_signal_thread_blocks(signal: dict) -> tuple[list[dict], str]:+ """Render one evidence signal as Slack blocks, mirroring an inbox SignalCard."""+ source_product = str(signal.get("source_product") or "")+ source_type = str(signal.get("source_type") or "")+ raw_extra = signal.get("extra")+ extra = raw_extra if isinstance(raw_extra, dict) else {}+ try:+ weight = float(signal.get("weight") or 0.0)+ except (TypeError, ValueError):+ weight = 0.0++ source_line = _escape_mrkdwn(_signal_source_line(source_product, source_type, extra))+ header_line = f"*{source_line}* · Weight: {weight:.1f}"+ blocks: list[dict] = [{"type": "context", "elements": [{"type": "mrkdwn", "text": header_line}]}]++ content = (signal.get("content") or "").strip()+ if content:+ if len(content) > _SIGNAL_CONTENT_MAX_LEN:+ content = content[: _SIGNAL_CONTENT_MAX_LEN - 1].rstrip() + "…"+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": _escape_mrkdwn(content)}})++ detail_parts = _signal_detail_parts(source_product, extra)+ if detail_parts:+ blocks.append({"type": "context", "elements": [{"type": "mrkdwn", "text": " · ".join(detail_parts)}]})++ # Slack parses mrkdwn mentions in `text` (push notifications, search) even with blocks present, so both+ # the source line (escaped above) and content are escaped here too.+ fallback = source_line if not content else f"{source_line}: {_escape_mrkdwn(content[:120])}"+ return blocks, fallback+++def _post_signal_evidence_thread(+ slack: SlackIntegration,+ channel_id: str,+ thread_ts: str,+ signals: list[dict],+) -> None:+ """Post each evidence signal as a reply in the notification's Slack thread. Best-effort."""+ for signal in signals[:_MAX_THREAD_SIGNALS]:+ blocks, text = _build_signal_thread_blocks(signal)+ try:+ slack.client.chat_postMessage(channel=channel_id, thread_ts=thread_ts, blocks=blocks, text=text)+ except Exception:+ logger.exception("Failed to post signal evidence to inbox notification thread")++ # The overflow note reflects signals intentionally withheld by the cap — not transient post failures.+ overflow = max(0, len(signals) - _MAX_THREAD_SIGNALS)+ if overflow > 0:+ try:+ slack.client.chat_postMessage(+ channel=channel_id,+ thread_ts=thread_ts,+ text=f"+{overflow} more {'signal' if overflow == 1 else 'signals'} in PostHog",+ )+ except Exception:+ logger.exception("Failed to post signal evidence overflow note to inbox notification thread")++class _ChannelRoute:"""One Slack channel and the reviewers routed to it (mentioned only there)."""@@ -448,8 +600,15 @@ def dispatch_inbox_item_notifications(report_id: str,team_id: int,source_products: list[str] | None = None,+ signals: list[dict] | None = None,) -> int:- """Send Slack notifications for a newly-ready report. Returns count of messages sent.+ """Send Slack notifications for a newly-ready report.++ Returns the number of top-level notification messages sent (one per destination+ channel); threaded evidence replies are not included in the count.++ When ``signals`` is provided, each evidence signal is posted as a reply in the+ notification's thread, mirroring the inbox UI so reviewers can scan it from Slack.Best-effort: per-destination Slack errors are logged, not raised."""@@ -511,8 +670,11 @@ def dispatch_inbox_item_notifications(implementation_pr_url=implementation_pr_url,dismiss_button_value=dismiss_button_value,)- slack.client.chat_postMessage(channel=channel_id, blocks=blocks, text=text)+ response = slack.client.chat_postMessage(channel=channel_id, blocks=blocks, text=text)sent += 1+ 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)except Exception:logger.exception("Failed to deliver signals inbox-item Slack notification", extra=log_context)return sentdiff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.pyindex 3b9a083a949b..c02cd288f458 100644--- a/products/signals/backend/temporal/inbox_notification.py+++ b/products/signals/backend/temporal/inbox_notification.py@@ -98,7 +98,12 @@ def _send_report_inbox_notifications(team_id: int, report_id: str) -> int:# 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)+ return dispatch_inbox_item_notifications(+ report_id=report_id,+ team_id=team_id,+ source_products=source_products,+ signals=signals,+ )@temporalio.activity.defndiff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.pyindex 6e6a0561aa6a..96168821b5c6 100644--- a/products/signals/backend/test/test_slack_inbox_notifications.py+++ b/products/signals/backend/test/test_slack_inbox_notifications.py@@ -19,9 +19,12 @@ from products.signals.backend.models import ()from products.signals.backend.report_generation.research import ActionabilityChoicefrom products.signals.backend.slack_inbox_notifications import (+ _MAX_THREAD_SIGNALS,_build_message_blocks,+ _build_signal_thread_blocks,_meets_min_priority,_resolve_reviewer_mentions,+ _signal_source_line,_summary_excerpt,dispatch_inbox_item_notifications,)@@ -91,9 +94,9 @@ def test_build_message_blocks_includes_recipient_and_posthog_code_button() -> Noreviewer_mentions=["<@U123>"],)- assert blocks[0]["text"]["text"] == "📬 Checkout errors spiked"+ assert blocks[0]["text"]["text"] == "Checkout errors spiked"section_text = blocks[1]["text"]["text"]- assert section_text.startswith("*‼️ P1 · Error tracking*")+ assert section_text.startswith("*❗ P1 · Error tracking*")assert "Error rate rose after deploy." in section_textassert "Ignored second line." not in section_text# A mention in plain_text would render as the raw token, never pinging anyone.@@ -117,7 +120,7 @@ def test_build_message_blocks_mentions_every_routed_reviewer() -> None:reviewer_mentions=["<@U1>", "<@U2>"],)- assert blocks[1]["text"]["text"] == "*❗ P2*"+ assert blocks[1]["text"]["text"] == "*🟠 P2*"assert blocks[2]["elements"][0]["text"] == "👤 Suggested reviewers: <@U1> <@U2>"@@ -131,7 +134,7 @@ def test_build_message_blocks_includes_repository_in_metadata_line() -> None:repository="PostHog/posthog",)- assert blocks[1]["text"]["text"] == "*❗ P2 · Error tracking · PostHog/posthog*"+ assert blocks[1]["text"]["text"] == "*🟠 P2 · Error tracking · PostHog/posthog*"def test_build_message_blocks_escapes_mrkdwn_in_llm_derived_fields() -> None:@@ -221,11 +224,11 @@ def test_build_message_blocks_appends_dismiss_button_last_with_action_id() -> No@pytest.mark.parametrize(("priority", "expected_priority_label"),[- (AutonomyPriority.P0, "🆘 P0"),- (AutonomyPriority.P1, "‼️ P1"),- (AutonomyPriority.P2, "❗ P2"),- (AutonomyPriority.P3, "⚠️ P3"),- (AutonomyPriority.P4, "👀 P4"),+ (AutonomyPriority.P0, "‼️ P0"),+ (AutonomyPriority.P1, "❗ P1"),+ (AutonomyPriority.P2, "🟠 P2"),+ (AutonomyPriority.P3, "🟡 P3"),+ (AutonomyPriority.P4, "🔵 P4"),],)def test_build_message_blocks_prefixes_priority_with_emoji(priority: str, expected_priority_label: str) -> None:@@ -408,8 +411,8 @@ def test_dispatch_sends_to_configured_reviewer(org_and_team):assert call_kwargs["channel"] == "C123"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 · Error tracking*")+ assert blocks[0]["text"]["text"] == "Test report"+ 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}"@@ -788,3 +791,199 @@ def test_dispatch_sends_once_per_channel_when_reviewers_share_channel(org_and_te# The single message still tags both reviewers that resolved to the channel.context_text = call_kwargs["blocks"][2]["elements"][0]["text"]assert "👤 Suggested reviewers: <@U_ONE> <@U_TWO>" in context_text+++ ("source_product", "source_type", "expected"),+ [+ # Explicit labels mirror the canonical Inbox UI's signalCardSourceLine.+ ("error_tracking", "issue_created", "Error tracking · New issue"),+ ("error_tracking", "issue_spiking", "Error tracking · Volume spike"),+ ("session_replay", "session_problem", "Session replay · Session problem"),+ ("session_replay", "session_analysis_cluster", "Session replay · Session analysis cluster"),+ ("llm_analytics", "evaluation", "AI observability · Evaluation"),+ ("github", "issue", "GitHub · Issue"),+ ("zendesk", "ticket", "Zendesk · Ticket"),+ ("linear", "issue", "Linear · Issue"),+ ("pganalyze", "issue", "pganalyze · Issue"),+ # Unknown error-tracking type falls back to the humanized source type.+ ("error_tracking", "weird_type", "Error tracking · weird type"),+ # No source type → no trailing separator.+ ("error_tracking", "", "Error tracking"),+ # Unknown product/type humanizes both halves.+ ("logs", "alert_state_change", "logs · alert state change"),+ ("unknown_thing", "", "unknown thing"),+ ],+)+def test_signal_source_line(source_product: str, source_type: str, expected: str) -> None:+ assert _signal_source_line(source_product, source_type) == expected+++ ("skill_name", "expected"),+ [+ # A scout's skill name becomes the label.+ ("signals-scout-error-tracking", "Scout · Error tracking"),+ ("signals-scout-revenue-analytics", "Scout · Revenue analytics"),+ # No usable skill name → generic scout label.+ ("", "Scout · Cross-source issue"),+ ],+)+def test_signal_source_line_scout_uses_skill_name(skill_name: str, expected: str) -> None:+ extra = {"skill_name": skill_name} if skill_name else {}+ assert _signal_source_line("signals_scout", "cross_source_issue", extra) == expected+++def test_build_signal_thread_blocks_renders_header_content_and_github_details() -> None:+ signal = {+ "source_product": "github",+ "source_type": "issue",+ "weight": 2.5,+ "content": "Users report the export button does nothing",+ "extra": {+ "number": 42,+ "labels": ["bug", "export"],+ "html_url": "https://github.com/PostHog/posthog/issues/42",+ },+ }+ blocks, fallback = _build_signal_thread_blocks(signal)++ assert blocks[0]["elements"][0]["text"] == "*GitHub · Issue* · Weight: 2.5"+ assert blocks[1]["text"]["text"] == "Users report the export button does nothing"+ detail = blocks[2]["elements"][0]["text"]+ assert "#42" in detail+ assert "bug, export" in detail+ assert "<https://github.com/PostHog/posthog/issues/42|View on GitHub>" in detail+ assert fallback.startswith("GitHub · Issue:")+++def test_build_signal_thread_blocks_escapes_content_to_block_mention_injection() -> None:+ signal = {+ "source_product": "logs",+ "source_type": "alert",+ "weight": 1.0,+ "content": "<!here> ping & <@U999>",+ "extra": {},+ }+ blocks, fallback = _build_signal_thread_blocks(signal)+ content_text = blocks[1]["text"]["text"]+ assert "<!here>" not in content_text+ assert "<@U999>" not in content_text+ assert "<!here>" in content_text+ # The fallback `text` also reaches Slack mention parsing, so it must be escaped too.+ assert "<!here>" not in fallback+ assert "<@U999>" not in fallback+ assert "<!here>" in fallback+++def test_build_signal_thread_blocks_escapes_source_line_in_header_and_fallback() -> None:+ # An unknown source type flows verbatim into the source line, so it must be escaped both places.+ signal = {+ "source_product": "custom",+ "source_type": "<@U42>",+ "weight": 1.0,+ "content": "body",+ "extra": {},+ }+ blocks, fallback = _build_signal_thread_blocks(signal)+ header_text = blocks[0]["elements"][0]["text"]+ assert "<@U42>" not in header_text+ assert "<@U42>" not in fallback+ assert "<@U42>" in header_text+ assert "<@U42>" in fallback+++def test_build_signal_thread_blocks_rejects_unsafe_detail_url() -> None:+ signal = {+ "source_product": "zendesk",+ "source_type": "ticket",+ "weight": 1.0,+ "content": "Ticket body",+ "extra": {"priority": "high", "status": "open", "url": "javascript:alert(1)"},+ }+ blocks, _ = _build_signal_thread_blocks(signal)+ detail = blocks[2]["elements"][0]["text"]+ assert "Priority: high" in detail+ assert "Status: open" in detail+ assert "javascript:" not in detail+++def test_dispatch_posts_signal_evidence_into_thread(org_and_team):+ org, team = org_and_team+ user = _make_reviewer_user(org, "[email protected]", "thread-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.P1, suggested_logins=["thread-bot"])++ signals = [+ {+ "source_product": "error_tracking",+ "source_type": "issue_created",+ "weight": 3.0,+ "content": "Boom",+ "extra": {"fingerprint": "abc123"},+ },+ {"source_product": "github", "source_type": "issue", "weight": 1.0, "content": "Bug", "extra": {"number": 7}},+ ]++ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1700000000.000100"}+ 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_THREAD",+ ),+ ):+ slack_cls.return_value.client = fake_client+ sent = dispatch_inbox_item_notifications(str(report.id), team.id, signals=signals)++ assert sent == 1+ # 1 top-level message + 2 threaded evidence replies.+ assert fake_client.chat_postMessage.call_count == 3+ thread_calls = [c for c in fake_client.chat_postMessage.call_args_list if c.kwargs.get("thread_ts")]+ assert len(thread_calls) == 2+ assert all(c.kwargs["thread_ts"] == "1700000000.000100" for c in thread_calls)+ assert all(c.kwargs["channel"] == "C123" for c in thread_calls)+++def test_dispatch_caps_thread_signals_and_posts_overflow_note(org_and_team):+ org, team = org_and_team+ user = _make_reviewer_user(org, "[email protected]", "overflow-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.P1, suggested_logins=["overflow-bot"])++ extra_count = 5+ signals = [+ {"source_product": "logs", "source_type": "alert", "weight": 1.0, "content": f"signal {i}", "extra": {}}+ for i in range(_MAX_THREAD_SIGNALS + extra_count)+ ]++ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1700000000.000100"}+ 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_OVERFLOW",+ ),+ ):+ slack_cls.return_value.client = fake_client+ sent = dispatch_inbox_item_notifications(str(report.id), team.id, signals=signals)++ assert sent == 1+ # 1 top-level + _MAX_THREAD_SIGNALS evidence replies + 1 overflow note.+ assert fake_client.chat_postMessage.call_count == 1 + _MAX_THREAD_SIGNALS + 1+ overflow_call = fake_client.chat_postMessage.call_args_list[-1]+ assert f"+{extra_count} more signals in PostHog" in overflow_call.kwargs["text"]