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): shorten inbox slack notification and drop evidence thread (#125865)

Dylan Martin49390782a455
diff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.py
index f01d08d72426..17ed7f54d564 100644
--- a/products/signals/backend/slack_formatting.py
+++ b/products/signals/backend/slack_formatting.py
@@ -299,6 +299,24 @@ _OPEN_MARKDOWN_LINK_RE = re.compile(r"\[[^\[\]]*\]\([^()]*$|\[[^\[\]]*$")
_MIN_LINE_BREAK_FILL = 0.6
+# Bounds the sentence scan: each candidate end re-checks the prefix for an open link, so an
+# unclosed `[` followed by many sentence ends would otherwise cost quadratic time on a long line.
+_FIRST_SENTENCE_SCAN_LIMIT = 2000
+
+
+def first_sentence(text: str) -> str:
+ """The text up to its first sentence end, or all of it when no sentence end is found.
+
+ A sentence end inside a Markdown link, such as `[see e.g. this](https://…)`, is skipped, so the
+ link reaches Slack whole."""
+ text = text.strip()
+ window = text[:_FIRST_SENTENCE_SCAN_LIMIT]
+ for match in _SENTENCE_END_RE.finditer(window):
+ if _OPEN_MARKDOWN_LINK_RE.search(window[: match.end()]) is None:
+ return window[: match.end()].strip()
+ return text
+
+
def _pull_back_before_open_link(window: str, index: int) -> int:
"""Move a cut back before a Markdown link it would otherwise split, or leave it alone."""
match = _OPEN_MARKDOWN_LINK_RE.search(window[:index])
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index a1a15c48521d..83a400c48df1 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -18,7 +18,7 @@ from __future__ import annotations
import re
import json
import logging
-from collections.abc import Callable, Collection, Iterable
+from collections.abc import Collection, Iterable
from django.conf import settings
@@ -57,7 +57,7 @@ from products.signals.backend.report_generation.resolve_reviewers import (
from products.signals.backend.report_urls import ReportLinkSource, build_report_url
from products.signals.backend.scout_authorship import report_is_hidden_from_inbox
from products.signals.backend.slack_formatting import (
- is_safe_slack_http_url as _is_safe_http_url,
+ first_sentence as _first_sentence,
prepare_slack_markdown as _prepare_markdown,
strip_chart_references as _strip_chart_references,
)
@@ -73,7 +73,7 @@ _ACTIONABLE_VALUES = frozenset(
logger = logging.getLogger(__name__)
-_SUMMARY_EXCERPT_MAX_LEN = 600
+_SUMMARY_EXCERPT_MAX_LEN = 280
_SLACK_HEADER_MAX_LEN = 150
_INBOX_INVITE_UTM_TAGS = "utm_source=posthog&utm_campaign=signals_inbox&utm_medium=slack"
# Bound message size / avoid pinging a crowd.
@@ -303,18 +303,18 @@ def _cap_excerpt(text: str) -> str:
def _summary_excerpt(summary: str) -> str:
- """First line of the report description only, capped at 600 characters."""
+ """First sentence of the report description's first line, capped at 280 characters."""
text = summary.strip()
if not text:
return ""
first_line = text.splitlines()[0].strip()
if not first_line:
return ""
- return _cap_excerpt(first_line)
+ return _cap_excerpt(_first_sentence(first_line))
def _impact_excerpt(summary: str) -> str:
- """First paragraph of the summary's `## Impact` section, capped at 600 characters."""
+ """First sentence of the summary's `## Impact` section, capped at 280 characters."""
match = _IMPACT_SECTION.search(summary)
if match is None:
return ""
@@ -322,7 +322,7 @@ def _impact_excerpt(summary: str) -> str:
if not section:
return ""
first_paragraph = re.split(r"\n\s*\n", section, maxsplit=1)[0]
- return _cap_excerpt(" ".join(line.strip() for line in first_paragraph.splitlines()))
+ return _cap_excerpt(_first_sentence(" ".join(line.strip() for line in first_paragraph.splitlines())))
def _display_title(title: str | None) -> str:
@@ -381,159 +381,6 @@ def _build_message_blocks(report: SignalReport, *, reviewer_mentions: list[str])
return blocks, _escape_mrkdwn(title_line)
-# Bound how many evidence signals we post into a thread so a large report can't flood a channel.
-_MAX_THREAD_SIGNALS = 30
-# Explicit "Product · Signal type" labels, mirroring `signalCardSourceLine` in the canonical Inbox UI
-# (PostHog Desktop'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",
- ("replay_vision", "scanner_finding"): "Replay Vision · Scanner finding",
- ("llm_analytics", "evaluation"): "AI observability · Evaluation",
- ("llm_analytics", "evaluation_report"): "AI observability · Evaluation report",
- ("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 _labelled_detail_parts(extra: dict, fields: tuple[tuple[str, str], ...]) -> list[str]:
- """`Label: value` parts for each named key that carries a truthy value, in the given order."""
- return [f"{label}: {_escape_mrkdwn(str(extra[key]))}" for key, label in fields if extra.get(key)]
-
-
-def _github_detail_parts(extra: dict) -> list[str]:
- parts: list[str] = []
- 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>")
- return parts
-
-
-def _zendesk_detail_parts(extra: dict) -> list[str]:
- parts = _labelled_detail_parts(extra, (("priority", "Priority"), ("status", "Status")))
- if _is_safe_http_url(extra.get("url")):
- parts.append(f"<{extra['url']}|Open ticket>")
- return parts
-
-
-def _llm_analytics_detail_parts(extra: dict) -> list[str]:
- parts = _labelled_detail_parts(extra, (("model", "Model"), ("provider", "Provider")))
- trace_id = extra.get("trace_id")
- if trace_id:
- parts.append(f"Trace: `{_escape_mrkdwn(str(trace_id)[:12])}…`")
- return parts
-
-
-def _session_replay_detail_parts(extra: dict) -> list[str]:
- problem_type = extra.get("problem_type")
- if not problem_type:
- return []
- return [f"Problem: {_escape_mrkdwn(str(problem_type).replace('_', ' '))}"]
-
-
-_SIGNAL_DETAIL_BUILDERS: dict[str, Callable[[dict], list[str]]] = {
- "github": _github_detail_parts,
- "zendesk": _zendesk_detail_parts,
- "llm_analytics": _llm_analytics_detail_parts,
- "session_replay": _session_replay_detail_parts,
-}
-
-
-def _signal_detail_parts(source_product: str, extra: dict) -> list[str]:
- """A compact, source-specific metadata line mirroring the inbox SignalCard footer."""
- builder = _SIGNAL_DETAIL_BUILDERS.get(source_product)
- return builder(extra) if builder is not None else []
-
-
-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 {}
-
- source_line = _escape_mrkdwn(_signal_source_line(source_product, source_type, extra))
- header_line = f"*{source_line}*"
- blocks: list[dict] = [{"type": "context", "elements": [{"type": "mrkdwn", "text": header_line}]}]
-
- content = (signal.get("content") or "").strip()
- if content:
- # Slack renders the signal's Markdown itself, so the content goes out as written. Escaping
- # comes first: a trailing cut can then only shorten an already-inert token, never leave a
- # live mention behind.
- blocks.append(_markdown_block(_prepare_markdown(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 destination and the reviewers routed to it (mentioned only there).
@@ -659,9 +506,8 @@ def _deliver_route_notification(
route: _ChannelRoute,
*,
trigger: str,
- signals: list[dict] | None = None,
) -> bool:
- """Post one report notification to a route's destination (with optional evidence thread).
+ """Post one report notification to a route's destination.
Shared by the report-ready and reviewer-added dispatchers. Returns True if the top-level
message was sent. Best-effort: Slack errors are logged, not raised.
@@ -700,8 +546,6 @@ def _deliver_route_notification(
# id we sent. An inbound mention names the conversation, so that is what the link records.
posted_channel = response.get("channel") if hasattr(response, "get") else None
if thread_ts:
- # Recorded before the evidence replies, so a failure posting those still leaves the
- # thread resolvable back to the report.
record_report_slack_thread(
slack_workspace_id=route.integration.integration_id,
team_id=report.team_id,
@@ -711,8 +555,6 @@ def _deliver_route_notification(
thread_ts=str(thread_ts),
kind=SignalReportSlackThread.Kind.INBOX_NOTIFICATION,
)
- 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)
_capture_notification_delivered(report, route, trigger=trigger, delivered=delivered)
@@ -724,12 +566,11 @@ def _deliver_to_routes(
routes: list[_ChannelRoute],
*,
trigger: str,
- signals: list[dict] | None = None,
) -> int:
"""Post the report to every route, returning how many top-level messages were sent."""
sent = 0
for route in routes:
- if _deliver_route_notification(report, route, trigger=trigger, signals=signals):
+ if _deliver_route_notification(report, route, trigger=trigger):
sent += 1
return sent
@@ -766,18 +607,11 @@ def _capture_notification_delivered(
logger.exception("Failed to capture signals_inbox_notification_delivered for report %s", report.id)
-def dispatch_inbox_item_notifications(
- report_id: str,
- team_id: int,
- signals: list[dict] | None = None,
-) -> int:
+def dispatch_inbox_item_notifications(report_id: str, team_id: int) -> int:
"""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.
+ Returns the number of notification messages sent (one per destination channel). Evidence is
+ not posted to Slack: the report shows it in a normalized form, so the message links there.
Best-effort: per-destination Slack errors are logged, not raised.
"""
@@ -836,7 +670,7 @@ def dispatch_inbox_item_notifications(
)
return 0
- sent = _deliver_to_routes(report, routes, trigger="report_ready", signals=signals)
+ sent = _deliver_to_routes(report, routes, trigger="report_ready")
logger.info(
"dispatch_inbox_item_notifications: complete",
extra={"report_id": report_id, "team_id": team_id, "messages_sent": sent, "routes": len(routes)},
diff --git a/products/signals/backend/temporal/inbox_notification.py b/products/signals/backend/temporal/inbox_notification.py
index 360ec41299f1..f2af99ae75d0 100644
--- a/products/signals/backend/temporal/inbox_notification.py
+++ b/products/signals/backend/temporal/inbox_notification.py
@@ -146,7 +146,7 @@ def _send_report_inbox_notifications(team_id: int, report_id: str) -> int:
logger.info("inbox notification skipped: team gone", report_id=report_id, team_id=team_id)
return 0
- # Re-fetched at send time so a deferred notification reflects the current signals.
+ # Re-fetched at send time so a deferred write-back reflects the current signals.
signals = _fetch_signals_for_notification(team, report_id)
# Point any support ticket that raised this report at it. Shares this function's READY guard.
@@ -170,11 +170,7 @@ def _send_report_inbox_notifications(team_id: int, report_id: str) -> int:
return 0
try:
- sent = dispatch_inbox_item_notifications(
- report_id=report_id,
- team_id=team_id,
- signals=signals,
- )
+ sent = dispatch_inbox_item_notifications(report_id=report_id, team_id=team_id)
except Exception:
# Release so a retry or a later settle can still send the card.
_release_inbox_notification_claim(team_id, report_id)
diff --git a/products/signals/backend/test/test_slack_inbox_notifications.py b/products/signals/backend/test/test_slack_inbox_notifications.py
index 1f5fe40b5d06..214f9d2faae8 100644
--- a/products/signals/backend/test/test_slack_inbox_notifications.py
+++ b/products/signals/backend/test/test_slack_inbox_notifications.py
@@ -27,12 +27,9 @@ from products.signals.backend.models import (
)
from products.signals.backend.report_generation.research import ActionabilityChoice
from 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,
dispatch_reviewer_added_notifications,
@@ -67,13 +64,24 @@ def test_meets_min_priority(report_priority: str | None, min_priority: str | Non
assert _meets_min_priority(report_priority, min_priority) is expected
-def test_summary_excerpt_uses_first_line_only() -> None:
- assert _summary_excerpt("First line.\nSecond line should not appear.") == "First line."
+ ("summary", "expected"),
+ [
+ ("First line.\nSecond line should not appear.", "First line."),
+ ("First sentence. Second sentence should not appear.", "First sentence."),
+ (
+ "See [the e.g. chart](https://example.com/a. b) now. Then more.",
+ "See [the e.g. chart](https://example.com/a. b) now.",
+ ),
+ ],
+)
+def test_summary_excerpt_uses_first_sentence_only(summary: str, expected: str) -> None:
+ assert _summary_excerpt(summary) == expected
-def test_summary_excerpt_truncates_first_line_at_600_chars() -> None:
+def test_summary_excerpt_truncates_first_sentence_at_280_chars() -> None:
long_line = "x" * 650
- assert len(_summary_excerpt(long_line)) == 600
+ assert len(_summary_excerpt(long_line)) == 280
assert _summary_excerpt(long_line).endswith("...")
@@ -102,9 +110,10 @@ def test_build_message_blocks_includes_recipient_and_open_in_posthog_button() ->
team_id=42,
title="fix(checkout): Checkout errors spiked",
summary=(
- "Error rate rose after deploy.\nIgnored second line.\n\n"
+ "Error rate rose after deploy. Ignored second sentence.\nIgnored second line.\n\n"
"## Problem\n\nThe payment form throws.\n\n"
- "## Impact\n\nAbout **300 buyers** could not pay\nin the last hour.\n\nA second paragraph stays out.\n\n"
+ "## Impact\n\nAbout **300 buyers** could not pay\nin the last hour. Ignored second sentence.\n\n"
+ "A second paragraph stays out.\n\n"
"## Expected impact\n\nFailures should drop to zero."
),
signal_count=12,
@@ -870,324 +879,6 @@ def test_dispatch_sends_once_per_channel_when_reviewers_share_channel(org_and_te
assert "👤 Suggested owners: <@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"),
- ("replay_vision", "scanner_finding", "Replay Vision · Scanner finding"),
- ("llm_analytics", "evaluation", "AI observability · Evaluation"),
- ("llm_analytics", "evaluation_report", "AI observability · Evaluation report"),
- ("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*"
- assert blocks[1]["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:")
-
-
- ("source_product", "extra", "expected_detail"),
- [
- (
- "zendesk",
- {"priority": "urgent", "status": "pending", "url": "https://support.example.com/tickets/7"},
- "Priority: urgent · Status: pending · <https://support.example.com/tickets/7|Open ticket>",
- ),
- (
- "llm_analytics",
- {"model": "claude-opus-5", "provider": "anthropic", "trace_id": "0123456789abcdefghij"},
- "Model: claude-opus-5 · Provider: anthropic · Trace: `0123456789ab…`",
- ),
- ("session_replay", {"problem_type": "rage_click_loop"}, "Problem: rage click loop"),
- ],
-)
-def test_build_signal_thread_blocks_renders_source_specific_details(
- source_product: str, extra: dict, expected_detail: str
-) -> None:
- signal = {"source_product": source_product, "source_type": "ticket", "content": "body", "extra": extra}
- blocks, _ = _build_signal_thread_blocks(signal)
- assert blocks[2]["elements"][0]["text"] == expected_detail
-
-
- ("source_product", "extra"),
- [
- ("zendesk", {}),
- ("llm_analytics", {}),
- ("session_replay", {}),
- ("logs", {"service": "ingestion"}),
- ],
-)
-def test_build_signal_thread_blocks_omits_empty_detail_block(source_product: str, extra: dict) -> None:
- signal = {"source_product": source_product, "source_type": "ticket", "content": "body", "extra": extra}
- blocks, _ = _build_signal_thread_blocks(signal)
- assert [block["type"] for block in blocks] == ["context", "markdown"]
-
-
-def test_build_signal_thread_blocks_escapes_mrkdwn_in_source_specific_details() -> None:
- # Detail values come from the source payload, so they must not carry a live mention into Slack.
- signal = {
- "source_product": "llm_analytics",
- "source_type": "evaluation",
- "content": "body",
- "extra": {"model": "<@U42>", "provider": "<!channel>"},
- }
- blocks, _ = _build_signal_thread_blocks(signal)
- detail = blocks[2]["elements"][0]["text"]
- assert "<@U42>" not in detail
- assert "<!channel>" not in detail
- # Both values must survive as escaped text, so dropping a field outright also fails.
- assert "Model: &lt;@U42&gt;" in detail
- assert "Provider: &lt;!channel&gt;" in detail
-
-
-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"]
- assert "<!here>" not in content_text
- assert "<@U999>" not in content_text
- assert "&lt;!here&gt;" 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 "&lt;!here&gt;" 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 "&lt;@U42&gt;" in header_text
- assert "&lt;@U42&gt;" 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_build_signal_thread_blocks_delivers_markdown_for_slack_to_render() -> None:
- # Slack renders the Markdown, so headings, emphasis, links, and table cells reach it as the
- # author wrote them. Converting to mrkdwn here dropped the links inside a table: the converter
- # lifted the table out before it converted anything, then put the cells back untouched.
- signal = {
- "source_product": "github",
- "source_type": "issue",
- "weight": 1.0,
- "content": (
- "## Bug\n**Export** is broken, see [issue](https://example.com/i?a=1&b=2)\n- step one\n\n"
- "| PR | Status |\n| --- | --- |\n| [#42 fix export](https://example.com/pull/42) | ready |"
- ),
- "extra": {},
- }
- blocks, _ = _build_signal_thread_blocks(signal)
- content_text = blocks[1]["text"]
- assert "## Bug" in content_text
- # The link destination reaches Slack byte for byte, `&` included. Escaping it to `&amp;` here
- # put that entity in the rendered link's href and broke the query string.
- assert "**Export** is broken, see [issue](https://example.com/i?a=1&b=2)" in content_text
- assert "- step one" in content_text
- assert "| [#42 fix export](https://example.com/pull/42) | ready |" in content_text
-
-
-def test_build_signal_thread_blocks_neutralizes_injection_in_markdown_content() -> None:
- # Slack reads its own tokens inside a markdown block, so untrusted content must not keep a live
- # one — neither a broadcast nor a `<url|label>` link whose label hides where it points.
- signal = {
- "source_product": "github",
- "source_type": "issue",
- "weight": 1.0,
- "content": "**Heads up** <!here> and <@U999> and a fake <https://evil.com|click here>",
- "extra": {},
- }
- blocks, _ = _build_signal_thread_blocks(signal)
- content_text = blocks[1]["text"]
- assert "**Heads up**" in content_text # the Markdown itself is left for Slack to render
- assert "<!here>" not in content_text
- assert "<@U999>" not in content_text
- assert "<https://evil.com|click here>" not in content_text
- assert "&lt;!here&gt;" in content_text
- assert "&lt;@U999&gt;" in content_text
- assert "&lt;https://evil.com|click here&gt;" in content_text
-
-
-def test_build_signal_thread_blocks_never_turns_a_markdown_link_into_a_mention() -> None:
- # A markdown link pointing at `!channel` / `@U123` used to reach Slack as a live broadcast: the
- # mrkdwn converter rewrote every `[text](dest)` into Slack's `<dest|label>` token form, whatever
- # the destination was. Delivering the Markdown as written can synthesize no token at all.
- signal = {
- "source_product": "github",
- "source_type": "issue",
- "weight": 1.0,
- "content": "[ping everyone](!channel) and [dm me](@U12345678) but [real](https://example.com) is fine",
- "extra": {},
- }
- blocks, _ = _build_signal_thread_blocks(signal)
- content_text = blocks[1]["text"]
- assert "<!channel" not in content_text
- assert "<@U12345678" not in content_text
- assert "[ping everyone](!channel)" in content_text
- assert "[real](https://example.com)" in content_text
-
-
-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"]
-
-
@pytest.mark.django_db
def test_reviewer_added_notifies_added_reviewer_on_own_channel(org_and_team):
# Someone manually added to a READY, actionable report is pinged on their own channel,