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): update scout report slack messages in place on edit (#115396)

posthog[bot]09704199ee78
diff --git a/products/signals/backend/migrations/0173_signalreportslackthread_kind_target_reply_ts.py b/products/signals/backend/migrations/0173_signalreportslackthread_kind_target_reply_ts.py
new file mode 100644
index 000000000000..e0c6dc303eb1
--- /dev/null
+++ b/products/signals/backend/migrations/0173_signalreportslackthread_kind_target_reply_ts.py
@@ -0,0 +1,34 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0172_signalscoutconfig_precheck_disabled"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalreportslackthread",
+ name="kind",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("inbox_notification", "Inbox notification"),
+ ("scout_report", "Scout report"),
+ ("scout_report_note", "Scout report note"),
+ ],
+ max_length=32,
+ null=True,
+ ),
+ ),
+ migrations.AddField(
+ model_name="signalreportslackthread",
+ name="target",
+ field=models.CharField(blank=True, max_length=64, null=True),
+ ),
+ migrations.AddField(
+ model_name="signalreportslackthread",
+ name="reply_ts",
+ field=models.JSONField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 39e0b450c984..f258ccfc5ea4 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0172_signalscoutconfig_precheck_disabled
+0173_signalreportslackthread_kind_target_reply_ts
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 21a576d1bfbc..61dc64153154 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1138,8 +1138,16 @@ class SignalReportSlackThread(UUIDModel):
A notification invites the reader to reply in the thread and mention PostHog, which starts a
task. Without this row that task has no way back to the report it discusses, so the work never
reaches the report's own timeline.
+
+ A scout report row also lets a later delivery of the same report update its message in place
+ instead of posting the report again.
"""
+ class Kind(models.TextChoices):
+ INBOX_NOTIFICATION = "inbox_notification", "Inbox notification"
+ SCOUT_REPORT = "scout_report", "Scout report"
+ SCOUT_REPORT_NOTE = "scout_report_note", "Scout report note"
+
objects = EnvironmentScopedManager()
all_teams = models.Manager() # noqa: DJ012
@@ -1155,6 +1163,13 @@ class SignalReportSlackThread(UUIDModel):
channel = models.CharField(max_length=64)
# Slack `ts` of the notification message, which is also its thread's root.
thread_ts = models.CharField(max_length=64)
+ # Null on rows written before the kind was recorded. Those rows never match an in-place update.
+ kind = models.CharField(max_length=32, choices=Kind, null=True, blank=True)
+ # The destination as configured, before Slack resolves it. A member target is a `U…` id here,
+ # while `channel` holds the `D…` direct message that Slack opened for it.
+ target = models.CharField(max_length=64, null=True, blank=True)
+ # Slack `ts` of each threaded reply of a scout report, in summary chunk order.
+ reply_ts = models.JSONField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.py
index 19eb4075bb78..fab00547154a 100644
--- a/products/signals/backend/scout_harness/slack_delivery.py
+++ b/products/signals/backend/scout_harness/slack_delivery.py
@@ -19,7 +19,7 @@ from posthog.redis import get_client
from posthog.slack.formatting import channel_id_from_target, escape_slack_mrkdwn
from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN, slack_markdown_block
-from products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRun
+from products.signals.backend.models import SignalReport, SignalReportSlackThread, SignalScoutEmission, SignalScoutRun
from products.signals.backend.report_urls import ReportLinkSource, build_report_url
from products.signals.backend.scout_harness.slack_charts import (
ChartRenderBudget,
@@ -36,7 +36,11 @@ from products.signals.backend.slack_formatting import (
split_markdown_by_headings,
strip_chart_references,
)
-from products.signals.backend.slack_report_threads import record_report_slack_thread
+from products.signals.backend.slack_report_threads import (
+ record_report_slack_thread,
+ record_scout_report_slack_replies,
+ scout_report_slack_message,
+)
from products.slack_app.backend.facade.api import slack_followup_invite
logger = structlog.get_logger(__name__)
@@ -64,6 +68,11 @@ _PERMANENT_SLACK_ERROR_CODES = frozenset(
# with one of these when it cannot reach one. Neither code is permanent, so a chart Slack cannot
# fetch would otherwise retry and then drop a report that used to post as text.
_BLOCK_REJECTION_ERROR_CODES = frozenset({"invalid_blocks", "invalid_blocks_format"})
+# chat.update answers with one of these when the earlier message is gone or can no longer change.
+# The delivery then posts a new message, as it did before the first post.
+_STALE_MESSAGE_ERROR_CODES = frozenset(
+ {"message_not_found", "cant_update_message", "edit_window_closed", "channel_not_found"}
+)
_SCOUT_SLACK_REPLY_PACE_SECONDS = 1
ScoutSlackOutputType = Literal["finding", "report"]
@@ -528,16 +537,35 @@ def _post_scout_report_thread_replies(
fallback: str,
schedule_retry: ScoutSlackReplyRetryScheduler,
chunk_offset: int = 0,
+ conversation: str | None = None,
+ reply_ts: list[str] | None = None,
+ record_reply_ts: Callable[[list[str]], None] | None = None,
) -> None:
"""Post the remaining summary chunks as threaded replies under an already-delivered lead.
+ A chunk whose reply is already in the thread (`reply_ts`) updates that reply in place, and
+ replies past the last chunk are deleted, so a re-delivered report does not repeat its thread.
+ `conversation` is the channel Slack posted into, which chat.update needs for a direct message.
+
Best-effort per reply: the lead already carries the report link, so a failed chunk logs and the
delivery still succeeds rather than re-posting the lead on retry."""
if not isinstance(thread_ts, str) or not thread_ts:
return
-
- def _post_reply(index: int, blocks: list[dict]) -> None:
- client.chat_postMessage( # type: ignore[attr-defined]
+ known_ts = list(reply_ts or [])
+ update_channel = conversation or channel_id
+
+ def _post_reply(index: int, blocks: list[dict]) -> str:
+ existing_ts = known_ts[index] if index < len(known_ts) else ""
+ if existing_ts:
+ try:
+ client.chat_update( # type: ignore[attr-defined]
+ channel=update_channel, ts=existing_ts, blocks=blocks, text=fallback
+ )
+ return existing_ts
+ except SlackApiError as exc:
+ if slack_api_error_code(exc) not in _STALE_MESSAGE_ERROR_CODES:
+ raise
+ response = client.chat_postMessage( # type: ignore[attr-defined]
channel=channel_id,
thread_ts=thread_ts,
blocks=blocks,
@@ -550,6 +578,17 @@ def _post_scout_report_thread_replies(
unfurl_links=False,
unfurl_media=False,
)
+ posted_ts = response.get("ts") if hasattr(response, "get") else None
+ return posted_ts if isinstance(posted_ts, str) else ""
+
+ def _remember(index: int, ts: str) -> None:
+ if index >= len(known_ts):
+ known_ts.extend([""] * (index + 1 - len(known_ts)))
+ known_ts[index] = ts
+
+ def _record() -> None:
+ if record_reply_ts is not None:
+ record_reply_ts(known_ts)
for index, blocks in enumerate(reply_blocks):
chunk_index = chunk_offset + index
@@ -558,7 +597,7 @@ def _post_scout_report_thread_replies(
# in this worker, but do not send it as one burst that consumes a retry per section.
time.sleep(_SCOUT_SLACK_REPLY_PACE_SECONDS)
try:
- _post_reply(chunk_index, blocks)
+ _remember(chunk_index, _post_reply(chunk_index, blocks))
except Exception as exc:
error_code = slack_api_error_code(exc) if isinstance(exc, SlackApiError) else None
logger.warning(
@@ -571,6 +610,7 @@ def _post_scout_report_thread_replies(
)
if error_code in _PERMANENT_SLACK_ERROR_CODES:
continue
+ _record()
schedule_retry(
_slack_retry_after_seconds(exc) or 60,
reply_blocks[index:],
@@ -580,6 +620,22 @@ def _post_scout_report_thread_replies(
)
return
+ end = chunk_offset + len(reply_blocks)
+ _delete_scout_report_replies(client, conversation=update_channel, reply_ts=known_ts[end:])
+ del known_ts[end:]
+ _record()
+
+
+def _delete_scout_report_replies(client: object, *, conversation: str, reply_ts: list[str]) -> None:
+ """Delete threaded replies that the current report no longer has. Best-effort per reply."""
+ for ts in reply_ts:
+ if not ts:
+ continue
+ try:
+ client.chat_delete(channel=conversation, ts=ts) # type: ignore[attr-defined]
+ except Exception:
+ logger.warning("scout_slack_report_thread_reply_delete_failed", channel=conversation, exc_info=True)
+
def _post_scout_report_lead_message(
client: WebClient,
@@ -588,14 +644,19 @@ def _post_scout_report_lead_message(
delivery_id: str,
blocks: list[dict],
fallback: str,
+ update_ts: str | None = None,
) -> SlackResponse:
"""Post the report's channel message, and post it again without the charts if Slack refuses them.
+ With `update_ts`, update that message in `channel_id` instead of posting a new one.
+
A chart Slack cannot fetch takes the whole message down, so on any deployment Slack cannot reach
a chart-bearing report would never arrive. The prose and the report link are the message; the
charts are the extra, and the report still draws every one of them in the inbox."""
def _post(message_blocks: list[dict]) -> SlackResponse:
+ if update_ts is not None:
+ return client.chat_update(channel=channel_id, ts=update_ts, blocks=message_blocks, text=fallback)
return client.chat_postMessage(
channel=channel_id,
blocks=message_blocks,
@@ -721,15 +782,48 @@ def post_scout_report_to_slack(
*messages.lead_blocks,
*_scout_invite_footer(integration, scout_team_id=run.team_id, channel_id=channel_id),
]
+ # A full delivery of a report already in this destination updates that message in place, so an
+ # edit does not post the whole report again. A note-only edit is new content and always posts.
+ existing = (
+ scout_report_slack_message(
+ team_id=report.team_id,
+ report_id=str(report.id),
+ slack_workspace_id=integration.integration_id,
+ target=channel_id,
+ )
+ if edit_note is None
+ else None
+ )
try:
_ensure_dm_recipient_eligible(slack, channel_id)
- response = _post_scout_report_lead_message(
- client,
- channel_id=channel_id,
- delivery_id=delivery_id,
- blocks=lead_blocks,
- fallback=messages.fallback,
- )
+ response = None
+ if existing is not None:
+ try:
+ response = _post_scout_report_lead_message(
+ client,
+ channel_id=existing.channel,
+ delivery_id=delivery_id,
+ blocks=lead_blocks,
+ fallback=messages.fallback,
+ update_ts=existing.thread_ts,
+ )
+ except SlackApiError as exc:
+ if slack_api_error_code(exc) not in _STALE_MESSAGE_ERROR_CODES:
+ raise
+ logger.info(
+ "signals_scout.slack_report_update_target_gone",
+ report_id=str(report.id),
+ error_code=slack_api_error_code(exc),
+ )
+ existing = None
+ if response is None:
+ response = _post_scout_report_lead_message(
+ client,
+ channel_id=channel_id,
+ delivery_id=delivery_id,
+ blocks=lead_blocks,
+ fallback=messages.fallback,
+ )
except SlackApiError as exc:
error_code = slack_api_error_code(exc)
if error_code in _PERMANENT_SLACK_ERROR_CODES:
@@ -739,18 +833,48 @@ def post_scout_report_to_slack(
) from exc
raise
- thread_ts = response.get("ts")
- if thread_ts:
- record_report_slack_thread(
- slack_workspace_id=integration.integration_id,
+ logger.info(
+ "signals_scout.slack_report_delivered",
+ report_id=str(report.id),
+ delivery_id=delivery_id,
+ updated_in_place=existing is not None,
+ )
+
+ if existing is not None:
+ thread_ts: object = existing.thread_ts
+ # The conversation Slack posted into, which for a member target is the direct message it
+ # opened rather than the id we sent. An inbound mention names the conversation.
+ conversation = existing.channel
+ reply_ts = existing.reply_ts
+ else:
+ thread_ts = response.get("ts")
+ conversation = str(response.get("channel") or channel_id)
+ reply_ts = []
+ if thread_ts:
+ record_report_slack_thread(
+ slack_workspace_id=integration.integration_id,
+ team_id=report.team_id,
+ report_id=str(report.id),
+ integration_id=integration.id,
+ channel=conversation,
+ thread_ts=str(thread_ts),
+ kind=(
+ SignalReportSlackThread.Kind.SCOUT_REPORT
+ if edit_note is None
+ else SignalReportSlackThread.Kind.SCOUT_REPORT_NOTE
+ ),
+ target=channel_id if edit_note is None else None,
+ )
+
+ def _record_reply_ts(posted: list[str]) -> None:
+ record_scout_report_slack_replies(
team_id=report.team_id,
- report_id=str(report.id),
- integration_id=integration.id,
- # The conversation Slack posted into, which for a member target is the direct message
- # it opened rather than the id we sent. An inbound mention names the conversation.
- channel=str(response.get("channel") or channel_id),
+ slack_workspace_id=integration.integration_id,
+ channel=conversation,
thread_ts=str(thread_ts),
+ reply_ts=posted,
)
+
if threaded:
_post_scout_report_thread_replies(
client,
@@ -760,4 +884,11 @@ def post_scout_report_to_slack(
reply_blocks=messages.reply_blocks,
fallback=messages.fallback,
schedule_retry=schedule_thread_reply_retry,
+ conversation=conversation,
+ reply_ts=reply_ts,
+ record_reply_ts=_record_reply_ts,
)
+ elif reply_ts:
+ # The report was threaded before and is not now, so its lead carries the whole summary.
+ _delete_scout_report_replies(client, conversation=conversation, reply_ts=reply_ts)
+ _record_reply_ts([])
diff --git a/products/signals/backend/slack_inbox_notifications.py b/products/signals/backend/slack_inbox_notifications.py
index 939a03d290f6..5d5781fd2fb2 100644
--- a/products/signals/backend/slack_inbox_notifications.py
+++ b/products/signals/backend/slack_inbox_notifications.py
@@ -38,6 +38,7 @@ from products.signals.backend.models import (
AutonomyPriority,
SignalReport,
SignalReportArtefact,
+ SignalReportSlackThread,
SignalTeamConfig,
SignalUserAutonomyConfig,
)
@@ -704,6 +705,7 @@ def _deliver_route_notification(
integration_id=route.integration.id,
channel=str(posted_channel or channel_id),
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)
diff --git a/products/signals/backend/slack_report_threads.py b/products/signals/backend/slack_report_threads.py
index 0afe779b95a5..0d86feedd043 100644
--- a/products/signals/backend/slack_report_threads.py
+++ b/products/signals/backend/slack_report_threads.py
@@ -14,13 +14,32 @@ from collections.abc import Sequence
from django.db import IntegrityError
+from posthog.dataclasses import frozen
+
from products.signals.backend.models import SignalReportSlackThread
logger = logging.getLogger(__name__)
+@frozen
+class ScoutReportSlackMessage:
+ """A scout report message already in Slack, which a later delivery updates in place."""
+
+ channel: str
+ thread_ts: str
+ reply_ts: list[str]
+
+
def record_report_slack_thread(
- *, team_id: int, report_id: str, integration_id: int | None, slack_workspace_id: str, channel: str, thread_ts: str
+ *,
+ team_id: int,
+ report_id: str,
+ integration_id: int | None,
+ slack_workspace_id: str,
+ channel: str,
+ thread_ts: str,
+ kind: SignalReportSlackThread.Kind,
+ target: str | None = None,
) -> None:
"""Record that `thread_ts` in `channel` is a notification thread for this report."""
try:
@@ -28,7 +47,13 @@ def record_report_slack_thread(
slack_workspace_id=slack_workspace_id,
channel=channel,
thread_ts=thread_ts,
- defaults={"team_id": team_id, "report_id": report_id, "integration_id": integration_id},
+ defaults={
+ "team_id": team_id,
+ "report_id": report_id,
+ "integration_id": integration_id,
+ "kind": kind,
+ "target": target,
+ },
)
except IntegrityError:
# The thread is already claimed — by a concurrent delivery of the same message, or by
@@ -42,6 +67,67 @@ def record_report_slack_thread(
)
+def scout_report_slack_message(
+ *, team_id: int, report_id: str, slack_workspace_id: str, target: str | None = None, thread_ts: str | None = None
+) -> ScoutReportSlackMessage | None:
+ """The latest scout report message for this report at `target`, or the one rooted at `thread_ts`.
+
+ Fails open: an unreadable link means post, since a duplicate message beats a lost report."""
+ filters: dict[str, str] = {}
+ if target is not None:
+ filters["target"] = target
+ if thread_ts is not None:
+ filters["thread_ts"] = thread_ts
+ try:
+ row = (
+ SignalReportSlackThread.objects.for_team(team_id)
+ .filter(
+ report_id=report_id,
+ slack_workspace_id=slack_workspace_id,
+ kind=SignalReportSlackThread.Kind.SCOUT_REPORT,
+ **filters,
+ )
+ .order_by("-created_at")
+ .values_list("channel", "thread_ts", "reply_ts")
+ .first()
+ )
+ except Exception:
+ logger.exception(
+ "Failed to read the Slack message for signal report %s",
+ report_id,
+ extra={"team_id": team_id, "report_id": report_id},
+ )
+ return None
+ if row is None:
+ return None
+ channel, root_ts, reply_ts = row
+ return ScoutReportSlackMessage(channel=channel, thread_ts=root_ts, reply_ts=_reply_ts_list(reply_ts))
+
+
+def record_scout_report_slack_replies(
+ *, team_id: int, slack_workspace_id: str, channel: str, thread_ts: str, reply_ts: list[str]
+) -> None:
+ """Store the `ts` of each threaded reply, so a later delivery can update the replies in place."""
+ try:
+ SignalReportSlackThread.objects.for_team(team_id).filter(
+ slack_workspace_id=slack_workspace_id,
+ channel=channel,
+ thread_ts=thread_ts,
+ kind=SignalReportSlackThread.Kind.SCOUT_REPORT,
+ ).update(reply_ts=reply_ts)
+ except Exception:
+ logger.exception(
+ "Failed to record the Slack thread replies for a signal report",
+ extra={"team_id": team_id, "channel": channel},
+ )
+
+
+def _reply_ts_list(value: object) -> list[str]:
+ if not isinstance(value, list):
+ return []
+ return [str(ts) if ts else "" for ts in value]
+
+
def report_id_for_slack_thread(*, team_id: int, slack_workspace_id: str, channel: str, thread_ts: str) -> str | None:
"""The report a Slack thread is about, or None when the thread is not a notification thread.
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 6732e511aaec..5147782a98df 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -69,6 +69,7 @@ from products.signals.backend.scout_harness.slack_delivery import (
slack_api_error_code,
)
from products.signals.backend.slack_inbox_notifications import dispatch_reviewer_added_notifications
+from products.signals.backend.slack_report_threads import record_scout_report_slack_replies, scout_report_slack_message
from products.signals.backend.tracker_issues import close_tracker_issue_for_report, link_pull_request_to_tracker_issue
from products.tasks.backend.facade.repo_activity import RepositoryCommitActivityError
@@ -375,6 +376,29 @@ def deliver_scout_slack_thread_replies(
)
return
+ # The earlier attempt recorded the replies it reached, so this one updates those instead of
+ # posting them again.
+ message = (
+ scout_report_slack_message(
+ team_id=team_id,
+ report_id=report_id,
+ slack_workspace_id=integration.integration_id,
+ thread_ts=thread_ts,
+ )
+ if report_id is not None
+ else None
+ )
+
+ def _record_reply_ts(posted: list[str]) -> None:
+ if message is not None:
+ record_scout_report_slack_replies(
+ team_id=team_id,
+ slack_workspace_id=integration.integration_id,
+ channel=message.channel,
+ thread_ts=thread_ts,
+ reply_ts=posted,
+ )
+
_post_scout_report_thread_replies(
slack.client,
channel_id=channel_id,
@@ -384,6 +408,9 @@ def deliver_scout_slack_thread_replies(
fallback=fallback,
schedule_retry=_schedule_retry,
chunk_offset=chunk_offset,
+ conversation=message.channel if message is not None else None,
+ reply_ts=message.reply_ts if message is not None else None,
+ record_reply_ts=_record_reply_ts,
)
diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.py
index eabf442a236d..2172b5420428 100644
--- a/products/signals/backend/test/test_scout_slack_delivery.py
+++ b/products/signals/backend/test/test_scout_slack_delivery.py
@@ -17,7 +17,7 @@ from posthog.models.integration import Integration
from posthog.redis import get_client
from posthog.slack.markdown import SLACK_MARKDOWN_TEXT_MAX_LEN
-from products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRun
+from products.signals.backend.models import SignalReport, SignalReportSlackThread, SignalScoutEmission, SignalScoutRun
from products.signals.backend.scout_harness.slack_charts import CHART_BLOCK_ID_PREFIX as PREFIX
from products.signals.backend.scout_harness.slack_delivery import (
MAX_SCOUT_SLACK_DM_TARGETS,
@@ -230,6 +230,79 @@ class TestScoutSlackDelivery(BaseTest):
thread_ts="1785418710.000200",
) == str(report.id)
+ @parameterized.expand(
+ [
+ ("channel", "CSCOUTS|#scout-findings", "CSCOUTS", False, None, True),
+ # A member target posts into the direct message Slack opens, so the update must name it.
+ ("direct_message", "U123ABC45|@andy", "D123ABC45", False, None, True),
+ # An inbox notification in the same channel is not this scout's message.
+ ("inbox_row_in_channel", "CSCOUTS|#scout-findings", "CSCOUTS", True, None, False),
+ # The first message was deleted in Slack, so the report posts again.
+ ("message_deleted", "CSCOUTS|#scout-findings", "CSCOUTS", False, "message_not_found", False),
+ ]
+ )
+ def test_redelivered_report_updates_its_message_in_place(
+ self, _name, channel_config, posted_channel, inbox_row_only, update_error, updated_in_place
+ ) -> None:
+ emission = self._make_emission()
+ report = SignalReport.objects.create(
+ team=self.team, status=SignalReport.Status.READY, title="Checkout failures", summary="First draft."
+ )
+ integration = Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.SLACK, integration_id="T_SCOUTS"
+ )
+ fake_client = MagicMock()
+ fake_client.chat_postMessage.side_effect = [
+ {"ts": "1785418710.000100", "channel": posted_channel},
+ {"ts": "1785418710.000200", "channel": posted_channel},
+ ]
+ if update_error:
+ fake_client.chat_update.side_effect = SlackApiError(
+ message=update_error, response=FakeSlackResponse({"error": update_error})
+ )
+
+ def deliver(delivery_id: str) -> None:
+ deliver_scout_slack_output.run(
+ self.team.id,
+ "report",
+ str(report.id),
+ str(emission.scout_run_id),
+ delivery_id,
+ integration.id,
+ channel_config,
+ thread_reports=False,
+ )
+
+ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:
+ slack_integration.return_value.client = fake_client
+ if inbox_row_only:
+ SignalReportSlackThread.objects.for_team(self.team.id).create(
+ team=self.team,
+ report=report,
+ integration=integration,
+ slack_workspace_id="T_SCOUTS",
+ channel=posted_channel,
+ thread_ts="1785418700.000100",
+ kind=SignalReportSlackThread.Kind.INBOX_NOTIFICATION,
+ )
+ else:
+ deliver("01864f4c-6957-7d3f-8d85-1d775e527265")
+ report.summary = "Edited draft with a new date."
+ report.save()
+ deliver("01864f4c-6957-7d3f-8d85-1d775e527266")
+
+ posts = fake_client.chat_postMessage.call_args_list
+ if not updated_in_place:
+ assert "Edited draft with a new date." in posts[-1].kwargs["blocks"][2]["text"]
+ if inbox_row_only:
+ fake_client.chat_update.assert_not_called()
+ return
+ assert len(posts) == 1
+ update = fake_client.chat_update.call_args.kwargs
+ assert update["channel"] == posted_channel
+ assert update["ts"] == "1785418710.000100"
+ assert "Edited draft with a new date." in update["blocks"][2]["text"]
+
def test_note_only_edit_delivers_the_note_instead_of_the_report(self) -> None:
# Without the edit_note branch a note-only edit re-posts the full report message, which is
# byte-identical to the one already in the channel and reads as a duplicate.
@@ -500,6 +573,63 @@ class TestScoutSlackDelivery(BaseTest):
assert "second one" in markdown_texts[0]
assert calls[0].kwargs["blocks"][-1]["type"] == "context"
+ @parameterized.expand(
+ [
+ ("same_sections", "Lead line.\n\n## First\nNew first.\n\n## Second\nNew second.", 2, 0),
+ ("sections_removed", "Only a lead line now.", 0, 2),
+ ]
+ )
+ def test_redelivered_threaded_report_updates_its_replies_in_place(
+ self, _name, edited_summary, expected_updated_replies, expected_deleted_replies
+ ) -> None:
+ emission = self._make_emission()
+ report = SignalReport.objects.create(
+ team=self.team,
+ status=SignalReport.Status.READY,
+ title="Checkout failures",
+ summary="Lead line.\n\n## First\nOld first.\n\n## Second\nOld second.",
+ )
+ integration = Integration.objects.create(
+ team=self.team, kind=Integration.IntegrationKind.SLACK, integration_id="T_SCOUTS"
+ )
+ fake_client = MagicMock()
+ fake_client.chat_postMessage.side_effect = [
+ {"ts": "1785418710.000100", "channel": "CSCOUTS"},
+ {"ts": "1785418710.000101", "channel": "CSCOUTS"},
+ {"ts": "1785418710.000102", "channel": "CSCOUTS"},
+ ]
+
+ def deliver(delivery_id: str) -> None:
+ deliver_scout_slack_output.run(
+ self.team.id,
+ "report",
+ str(report.id),
+ str(emission.scout_run_id),
+ delivery_id,
+ integration.id,
+ "CSCOUTS|#scout-findings",
+ thread_reports=True,
+ )
+
+ with (
+ patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration,
+ patch("products.signals.backend.scout_harness.slack_delivery.time.sleep"),
+ ):
+ slack_integration.return_value.client = fake_client
+ deliver("01864f4c-6957-7d3f-8d85-1d775e527265")
+ report.summary = edited_summary
+ report.save()
+ deliver("01864f4c-6957-7d3f-8d85-1d775e527266")
+
+ assert fake_client.chat_postMessage.call_count == 3
+ updated_ts = [call.kwargs["ts"] for call in fake_client.chat_update.call_args_list]
+ assert (
+ updated_ts
+ == ["1785418710.000100", "1785418710.000101", "1785418710.000102"][: 1 + expected_updated_replies]
+ )
+ deleted_ts = [call.kwargs["ts"] for call in fake_client.chat_delete.call_args_list]
+ assert deleted_ts == ["1785418710.000101", "1785418710.000102"][:expected_deleted_replies]
+
def test_threaded_report_schedules_a_rate_limited_reply(self) -> None:
emission = self._make_emission()
report = SignalReport.objects.create(
diff --git a/products/signals/backend/test/test_slack_report_threads.py b/products/signals/backend/test/test_slack_report_threads.py
index e9f919a3512b..66cf2e6122ca 100644
--- a/products/signals/backend/test/test_slack_report_threads.py
+++ b/products/signals/backend/test/test_slack_report_threads.py
@@ -51,6 +51,7 @@ def test_only_the_recorded_thread_resolves_to_the_report(team, channel, thread_t
integration_id=_integration(team).id,
channel="CTEAM",
thread_ts="1700000000.000100",
+ kind=SignalReportSlackThread.Kind.INBOX_NOTIFICATION,
)
resolved = report_id_for_slack_thread(
@@ -82,6 +83,7 @@ def test_thread_recorded_for_another_teams_report_does_not_resolve(team, boundar
integration_id=_integration(other_team).id,
channel="CTEAM",
thread_ts="1700000000.000100",
+ kind=SignalReportSlackThread.Kind.INBOX_NOTIFICATION,
)
assert report_id_for_slack_thread(
@@ -110,6 +112,7 @@ def test_re_recording_the_same_thread_keeps_the_first_report(team, second_worksp
integration_id=integration.id,
channel="CTEAM",
thread_ts="1700000000.000100",
+ kind=SignalReportSlackThread.Kind.INBOX_NOTIFICATION,
)
assert SignalReportSlackThread.objects.for_team(team.id).count() == (1 if second_workspace == "T123" else 2)
diff --git a/products/slack_app/backend/tests/test_followup_forwarding.py b/products/slack_app/backend/tests/test_followup_forwarding.py
index 584d620919d2..0f778dafb8d4 100644
--- a/products/slack_app/backend/tests/test_followup_forwarding.py
+++ b/products/slack_app/backend/tests/test_followup_forwarding.py
@@ -267,7 +267,12 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
def test_task_from_a_report_notification_thread_lands_on_the_report(
self, _name, from_report_thread, failure_stage, mock_slack_cls, _mock_execute_workflow
):
- from products.signals.backend.models import SignalReport, SignalReportAction, SignalReportArtefact
+ from products.signals.backend.models import (
+ SignalReport,
+ SignalReportAction,
+ SignalReportArtefact,
+ SignalReportSlackThread,
+ )
from products.signals.backend.slack_report_threads import record_report_slack_thread
mock_slack_instance = MagicMock()
@@ -287,6 +292,7 @@ class TestCreatePostHogCodeTaskForRepoActivity(TestCase):
integration_id=self.integration.id,
channel="C123",
thread_ts="1234.5678",
+ kind=SignalReportSlackThread.Kind.INBOX_NOTIFICATION,
)
inputs = _make_inputs(self.integration.id, self.user.id)