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(alerts): keep a slack alert's opening message current (#114250)

Jimmy Zhu04ea935d4448
diff --git a/posthog/slack/channels.py b/posthog/slack/channels.py
index 86ae1056d102..1563eb6a6d65 100644
--- a/posthog/slack/channels.py
+++ b/posthog/slack/channels.py
@@ -173,6 +173,17 @@ def post_message(
)
+def update_message(
+ slack: SlackIntegration,
+ channel_id: str,
+ ts: str,
+ blocks: list[dict[str, Any]],
+ text: str,
+) -> SlackResponse:
+ """Replace a message the app posted. Slack keeps its place in the channel and marks it edited."""
+ return slack.client.chat_update(channel=channel_id, ts=ts, blocks=blocks, text=text)
+
+
def join_channel(slack: SlackIntegration, channel_id: str) -> str | None:
"""Join the channel so the retried post lands. Returns Slack's error code when it refused.
diff --git a/products/alerts_platform/backend/delivery/dispatch.py b/products/alerts_platform/backend/delivery/dispatch.py
index 498a41e15d2e..ec6d9c4ab933 100644
--- a/products/alerts_platform/backend/delivery/dispatch.py
+++ b/products/alerts_platform/backend/delivery/dispatch.py
@@ -5,16 +5,25 @@ it. Which destinations an alert has is resolved before this, so a change to that
reaches no transport.
"""
+from django.utils import timezone
+
+import structlog
+
from products.alerts_platform.backend.delivery.message import AlertMessage, build_message
+from products.alerts_platform.backend.delivery.root_state import state_line
from products.alerts_platform.backend.delivery.telemetry import record_delivery
from products.alerts_platform.backend.delivery.thread_store import ThreadBusy, ThreadKey, ThreadStore
-from products.alerts_platform.backend.delivery.transport import DeliveryTransport, MessageHandle
+from products.alerts_platform.backend.delivery.transport import DeliveryTransport, MessageHandle, RootEditor
from products.alerts_platform.backend.facade.contracts import (
AlertDestinationData,
AnnouncedTransition,
EvaluationAnnouncement,
IncidentAction,
)
+from products.alerts_platform.backend.logic.platform_reads import alert_snapshot
+from products.alerts_platform.backend.temporal.metrics import increment_root_edit_failures, safe_record
+
+logger = structlog.get_logger(__name__)
def deliver(
@@ -72,6 +81,11 @@ def deliver(
except Exception:
thread_store.release(claim)
raise
+ if claim.handle is not None:
+ # A reply landed under an opening message, so the opening message catches up. It runs
+ # before `delivered` releases the claim, so edits to one root happen in send order and
+ # a slow edit cannot land after a newer one.
+ _edit_root(transport=transport, team_id=team_id, target=target, root=claim.handle, key=key)
thread_store.delivered(claim, sent)
if busy:
@@ -100,6 +114,30 @@ def _send(
return sent
+def _edit_root(
+ *,
+ transport: DeliveryTransport,
+ team_id: int,
+ target: AlertDestinationData,
+ root: MessageHandle,
+ key: ThreadKey,
+) -> None:
+ """Puts the group's current state on the message that opened its conversation.
+
+ Best effort: the reply already landed, so a failed edit is logged and never fails the send.
+ """
+ if not isinstance(transport, RootEditor) or not root.root_content:
+ return
+ try:
+ snapshot = alert_snapshot(team_id, key.configuration_id, key.grouping_key)
+ line = state_line(snapshot, episode_started_at=key.episode_started_at, as_of=timezone.now())
+ if line is not None:
+ transport.edit_root(team_id=team_id, target=target, root=root, state_line=line)
+ except Exception:
+ logger.exception("alerts_platform.root_edit_failed", provider=transport.provider)
+ safe_record(increment_root_edit_failures, transport.provider)
+
+
def _thread_key(
*,
configuration_id: str,
diff --git a/products/alerts_platform/backend/delivery/message.py b/products/alerts_platform/backend/delivery/message.py
index 5b2f7eed4f39..a39a2dbbebe6 100644
--- a/products/alerts_platform/backend/delivery/message.py
+++ b/products/alerts_platform/backend/delivery/message.py
@@ -83,6 +83,11 @@ class AlertMessage:
return (self.data_link, view_alert) if self.data_link is not None else (view_alert,)
+def state_symbol(kind: AlertEventKind) -> str:
+ """The symbol a message about `kind` leads with, so an edited root matches its own messages."""
+ return _SYMBOLS[kind]
+
+
def alert_url(project_id: int, configuration_id: str) -> str:
# pinned: the platform alert page route in products/alerts_platform/manifest.tsx.
return absolute_uri(f"/project/{project_id}/platform-alerts/{configuration_id}")
diff --git a/products/alerts_platform/backend/delivery/root_state.py b/products/alerts_platform/backend/delivery/root_state.py
new file mode 100644
index 000000000000..5a0656f34451
--- /dev/null
+++ b/products/alerts_platform/backend/delivery/root_state.py
@@ -0,0 +1,32 @@
+"""The current-state line an edited root message shows.
+
+Built from the group's recorded state when the edit happens, never from the delivery that
+triggered it. A retried or late delivery then cannot put an older state back on the root.
+"""
+
+from datetime import datetime
+
+from products.alerts_platform.backend.delivery.message import state_symbol
+from products.alerts_platform.backend.facade.contracts import AlertEventKind, PlatformAlertSnapshot
+from products.alerts_platform.backend.facade.enums import PlatformAlertState
+
+
+def state_line(snapshot: PlatformAlertSnapshot | None, *, episode_started_at: datetime, as_of: datetime) -> str | None:
+ """The line for the firing that opened this thread, or None when no line is certain.
+
+ None leaves the root as it is. That covers a group with no recorded state, and an errored,
+ broken or snoozed group, which is a different conversation from the firing this root opened.
+ """
+ if snapshot is None:
+ return None
+ when = as_of.strftime("%H:%M UTC")
+ # The lifecycle keeps `firing_started_at` only while its firing is open, so equality means
+ # the firing this root announced has not ended.
+ episode_open = snapshot.firing_started_at == episode_started_at
+ if episode_open and snapshot.state == PlatformAlertState.FIRING:
+ return f"{state_symbol(AlertEventKind.FIRING)} Still firing as of {when}"
+ # Shown only for the two states a reader of a firing expects. A later firing has its own root,
+ # so this one reads as resolved even while the group fires again.
+ if not episode_open and snapshot.state in (PlatformAlertState.NOT_FIRING, PlatformAlertState.FIRING):
+ return f"{state_symbol(AlertEventKind.RESOLVED)} Resolved as of {when}"
+ return None
diff --git a/products/alerts_platform/backend/delivery/slack.py b/products/alerts_platform/backend/delivery/slack.py
index fe64f84d2ea3..556c770a5b2c 100644
--- a/products/alerts_platform/backend/delivery/slack.py
+++ b/products/alerts_platform/backend/delivery/slack.py
@@ -19,6 +19,7 @@ from posthog.slack.channels import (
header_block,
post_message,
section_block,
+ update_message,
)
from posthog.slack.formatting import escape_slack_mrkdwn
@@ -65,6 +66,14 @@ def blocks_for(message: AlertMessage) -> list[dict[str, Any]]:
return blocks
+def _with_state_line(blocks: list[dict[str, Any]], state_line: str) -> list[dict[str, Any]]:
+ """The opening blocks unchanged, with the state line above the buttons `blocks_for` ends with.
+
+ The state line is platform text, built from a state and a time, so it is not escaped.
+ """
+ return [*blocks[:-1], context_block(state_line), blocks[-1]]
+
+
class SlackTransport:
provider = PROVIDER
@@ -85,14 +94,12 @@ class SlackTransport:
raise DeliveryError("This Slack destination is missing its workspace or channel.")
slack = SlackIntegration(self._integration(team_id=team_id, workspace_id=workspace_id), source=EGRESS_SOURCE)
+ blocks = blocks_for(message)
+ # The one place the alert's name reaches mrkdwn: the header renders plain text.
+ text = escape_slack_mrkdwn(message.title)
try:
response = post_message(
- slack,
- channel,
- blocks_for(message),
- # The one place the alert's name reaches mrkdwn: the header renders plain text.
- escape_slack_mrkdwn(message.title),
- thread_ts=in_reply_to.external_ref.get("ts") if in_reply_to else None,
+ slack, channel, blocks, text, thread_ts=in_reply_to.external_ref.get("ts") if in_reply_to else None
)
except SlackApiError as error:
# A refusal a person can fix, such as a channel the bot has left, rather than a
@@ -101,7 +108,29 @@ class SlackTransport:
timestamp = response.get("ts")
if not timestamp:
raise DeliveryError("Slack accepted the message but returned no timestamp to reply to.")
- return MessageHandle(external_ref={"channel": channel, "ts": timestamp})
+ # An opening message keeps what it posted, so an edit can restate it word for word.
+ root_content = {"blocks": blocks, "text": text} if in_reply_to is None else None
+ return MessageHandle(external_ref={"channel": channel, "ts": timestamp}, root_content=root_content)
+
+ def edit_root(self, *, team_id: int, target: AlertDestinationData, root: MessageHandle, state_line: str) -> None:
+ workspace_id = target.get("slack_workspace_id")
+ channel = root.external_ref.get("channel")
+ ts = root.external_ref.get("ts")
+ if workspace_id is None or not channel or not ts or not root.root_content:
+ raise DeliveryError("This Slack conversation has no opening message to edit.")
+ slack = SlackIntegration(self._integration(team_id=team_id, workspace_id=workspace_id), source=EGRESS_SOURCE)
+ try:
+ update_message(
+ slack,
+ channel,
+ ts,
+ _with_state_line(root.root_content["blocks"], state_line),
+ # Screen readers read the fallback text rather than the blocks, so it carries the
+ # current state too.
+ f"{root.root_content['text']} ({state_line})",
+ )
+ except SlackApiError as error:
+ raise DeliveryError(f"Slack refused the edit: {error.response.get('error')}") from error
def _integration(self, *, team_id: int, workspace_id: int) -> Integration:
# Scoped by team as well as by id. The destination names an integration, and nothing
diff --git a/products/alerts_platform/backend/delivery/thread_store.py b/products/alerts_platform/backend/delivery/thread_store.py
index 893abc8c681e..6c6e6e733cd9 100644
--- a/products/alerts_platform/backend/delivery/thread_store.py
+++ b/products/alerts_platform/backend/delivery/thread_store.py
@@ -142,7 +142,11 @@ class DatabaseThreadStore:
if not taken:
raise ThreadBusy(f"thread {thread.id} is being posted to by another send")
- handle = MessageHandle(external_ref=thread.external_ref) if thread.external_ref else None
+ handle = (
+ MessageHandle(external_ref=thread.external_ref, root_content=thread.root_message)
+ if thread.external_ref
+ else None
+ )
return ThreadClaim(thread_id=str(thread.id), evaluation_key=evaluation_key, handle=handle, claimed_at=now)
def delivered(self, claim: ThreadClaim, handle: MessageHandle | None) -> None:
@@ -160,6 +164,7 @@ class DatabaseThreadStore:
# move the thread onto itself, so a later message would reply to a reply.
if handle is not None and not thread.external_ref:
fields["external_ref"] = handle.external_ref
+ fields["root_message"] = handle.root_content
self._fenced(claim).update(**fields)
def release(self, claim: ThreadClaim) -> None:
diff --git a/products/alerts_platform/backend/delivery/transport.py b/products/alerts_platform/backend/delivery/transport.py
index 807f84630189..4a33b2a21ad9 100644
--- a/products/alerts_platform/backend/delivery/transport.py
+++ b/products/alerts_platform/backend/delivery/transport.py
@@ -5,7 +5,7 @@ handed. What to say is decided before this, and where to send is resolved before
transport that gains a provider needs no change anywhere else.
"""
-from typing import Protocol
+from typing import Any, Protocol, runtime_checkable
from posthog.dataclasses import frozen
@@ -19,9 +19,13 @@ class MessageHandle:
`external_ref` is the provider's own handle, for example `{"channel": ..., "ts": ...}` for
Slack. Only the transport that issued one reads it.
+
+ `root_content` is what a transport that can edit its posts sent to open a conversation, so a
+ later edit keeps it. It is set only on the handle of that opening message.
"""
external_ref: dict[str, str]
+ root_content: dict[str, Any] | None = None
class DeliveryError(Exception):
@@ -55,3 +59,16 @@ class DeliveryTransport(Protocol):
be a second statement of the same fact, free to disagree with it.
"""
...
+
+
+@runtime_checkable
+class RootEditor(Protocol):
+ """A transport that can update the message that opened a conversation.
+
+ The opening content stays as it was posted, because it is the only record of what fired that
+ the thread does not repeat. Only the current-state line changes.
+ """
+
+ def edit_root(self, *, team_id: int, target: AlertDestinationData, root: MessageHandle, state_line: str) -> None:
+ """Rewrites the opening message with `state_line` under its original content."""
+ ...
diff --git a/products/alerts_platform/backend/logic/platform_reads.py b/products/alerts_platform/backend/logic/platform_reads.py
index cb214db27dcc..136f4ac39345 100644
--- a/products/alerts_platform/backend/logic/platform_reads.py
+++ b/products/alerts_platform/backend/logic/platform_reads.py
@@ -89,3 +89,13 @@ def get_configuration(
"""One configuration, or None when it does not exist or the caller may not read its kind."""
row = _readable(team_id, source_kinds).filter(id=configuration_id).first()
return None if row is None else _configuration_view(row)
+
+
+def alert_snapshot(team_id: int, configuration_id: str, grouping_key: str) -> PlatformAlertSnapshot | None:
+ """One group's current runtime state, or None when the platform has recorded none."""
+ alert = (
+ PlatformAlert.objects.for_team(team_id)
+ .filter(configuration_id=configuration_id, grouping_key=grouping_key)
+ .first()
+ )
+ return instance_view(alert) if alert is not None else None
diff --git a/products/alerts_platform/backend/migrations/0007_platformalertthread_root_message.py b/products/alerts_platform/backend/migrations/0007_platformalertthread_root_message.py
new file mode 100644
index 000000000000..d3df2d00ea25
--- /dev/null
+++ b/products/alerts_platform/backend/migrations/0007_platformalertthread_root_message.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-08 22:31
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("alerts_platform", "0006_source_kind_choices"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="platformalertthread",
+ name="root_message",
+ field=models.JSONField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/alerts_platform/backend/migrations/max_migration.txt b/products/alerts_platform/backend/migrations/max_migration.txt
index e98e35718399..86815eeac496 100644
--- a/products/alerts_platform/backend/migrations/max_migration.txt
+++ b/products/alerts_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0006_source_kind_choices
+0007_platformalertthread_root_message
diff --git a/products/alerts_platform/backend/models/platform_alert.py b/products/alerts_platform/backend/models/platform_alert.py
index 495619dcf775..c800c5cbf3c0 100644
--- a/products/alerts_platform/backend/models/platform_alert.py
+++ b/products/alerts_platform/backend/models/platform_alert.py
@@ -160,6 +160,10 @@ class PlatformAlertThread(TeamScopedRootMixin, UUIDModel):
# The provider's own handle, `{"channel": ..., "ts": ...}` for Slack. Opaque to everything
# but the transport that issued it.
external_ref = models.JSONField(default=dict)
+ # What the transport posted to open the conversation, so an edit to it keeps what fired and
+ # changes only the current state. Opaque to everything but that transport. Null for a
+ # provider that cannot edit a message it posted.
+ root_message = models.JSONField(null=True, blank=True)
# Evaluations already delivered into this conversation, newest last. Capped, because a
# thread lives as long as its firing and the list only has to outlive a retry.
diff --git a/products/alerts_platform/backend/temporal/metrics.py b/products/alerts_platform/backend/temporal/metrics.py
index beb8af64268b..3120c2d0277f 100644
--- a/products/alerts_platform/backend/temporal/metrics.py
+++ b/products/alerts_platform/backend/temporal/metrics.py
@@ -112,6 +112,14 @@ def increment_describer_failures(source: str) -> None:
).add(1)
+def increment_root_edit_failures(provider: str) -> None:
+ """An opening message could not be brought up to date, so it shows an older state."""
+ get_metric_meter({"provider": provider}).create_counter(
+ "alerts_platform_root_edit_failures_total",
+ "Opening messages left showing an older state because the edit failed",
+ ).add(1)
+
+
def increment_deliveries_previewed(source: str) -> None:
get_metric_meter({"source": source}).create_counter(
"alerts_platform_deliveries_previewed_total",
diff --git a/products/alerts_platform/backend/tests/test_delivery_dispatch.py b/products/alerts_platform/backend/tests/test_delivery_dispatch.py
index 09b8b3e75cb2..c426f7491d3b 100644
--- a/products/alerts_platform/backend/tests/test_delivery_dispatch.py
+++ b/products/alerts_platform/backend/tests/test_delivery_dispatch.py
@@ -75,6 +75,33 @@ class FakeTransport:
return self.handle
+class EditingTransport(FakeTransport):
+ """A transport that can edit its opening message, like Slack."""
+
+ def __init__(
+ self,
+ handle: MessageHandle | None = None,
+ edit_error: Exception | None = None,
+ store: "RecordingThreadStore | None" = None,
+ ) -> None:
+ super().__init__(handle=handle)
+ self.edit_error = edit_error
+ self.store = store
+ self.edits: list[tuple[MessageHandle, str]] = []
+ # What the store had recorded as delivered at the moment of each edit.
+ self.delivered_at_edit: list[list[str]] = []
+
+ def edit_root(self, *, team_id: int, target: AlertDestinationData, root: MessageHandle, state_line: str) -> None:
+ self.edits.append((root, state_line))
+ if self.store is not None:
+ self.delivered_at_edit.append([k for keys in self.store.delivered_keys.values() for k in keys])
+ if self.edit_error:
+ raise self.edit_error
+
+
+OPENING = MessageHandle(external_ref={"ts": "morning"}, root_content={"blocks": [], "text": "API errors is firing"})
+
+
class RecordingThreadStore(NullThreadStore):
"""Keeps what a real store would keep, so the key dispatch builds is observable."""
@@ -161,6 +188,38 @@ class TestDeliveryDispatch(SimpleTestCase):
assert [handle for _, handle in resolve.sends] == [MessageHandle(external_ref={"ts": "morning"})]
assert [handle for _, handle in second.sends] == [None]
+ def test_a_reply_brings_the_opening_message_up_to_the_current_state(self) -> None:
+ store = RecordingThreadStore()
+ transport = EditingTransport(handle=OPENING, store=store)
+
+ with (
+ patch("products.alerts_platform.backend.delivery.dispatch.alert_snapshot", return_value=None),
+ patch("products.alerts_platform.backend.delivery.dispatch.state_line", return_value="Resolved") as state,
+ ):
+ self._deliver(transport, store, _announcement(AlertEventKind.FIRING, FIRST_FIRING), "eval-1")
+ assert transport.edits == []
+ self._deliver(transport, store, _announcement(AlertEventKind.RESOLVED, FIRST_FIRING), "eval-2")
+
+ assert transport.edits == [(OPENING, "Resolved")]
+ assert state.call_args.kwargs["episode_started_at"] == FIRST_FIRING
+ # The edit runs while the reply's claim is held, so a later send cannot overtake it.
+ assert transport.delivered_at_edit == [["eval-1"]]
+
+ def test_a_failed_edit_does_not_fail_the_reply_that_landed(self) -> None:
+ store = RecordingThreadStore()
+ transport = EditingTransport(handle=OPENING, edit_error=DeliveryError("message_not_found"))
+
+ with (
+ patch("products.alerts_platform.backend.delivery.dispatch.alert_snapshot", return_value=None),
+ patch("products.alerts_platform.backend.delivery.dispatch.state_line", return_value="Resolved"),
+ ):
+ self._deliver(transport, store, _announcement(AlertEventKind.FIRING, FIRST_FIRING), "eval-1")
+ self._deliver(transport, store, _announcement(AlertEventKind.RESOLVED, FIRST_FIRING), "eval-2")
+
+ assert len(transport.sends) == 2
+ assert len(transport.edits) == 1
+ assert list(store.delivered_keys.values()) == [["eval-1", "eval-2"]]
+
def test_two_groups_firing_together_do_not_share_a_thread(self) -> None:
store = RecordingThreadStore()
transport = FakeTransport()
diff --git a/products/alerts_platform/backend/tests/test_delivery_root_state.py b/products/alerts_platform/backend/tests/test_delivery_root_state.py
new file mode 100644
index 000000000000..35e536f0aeeb
--- /dev/null
+++ b/products/alerts_platform/backend/tests/test_delivery_root_state.py
@@ -0,0 +1,79 @@
+import uuid
+from datetime import UTC, datetime
+
+from posthog.test.base import APIBaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.models import Team
+from posthog.models.scoping import team_scope
+
+from products.alerts_platform.backend.delivery.root_state import state_line
+from products.alerts_platform.backend.facade.contracts import PlatformAlertSnapshot
+from products.alerts_platform.backend.facade.enums import PlatformAlertState
+from products.alerts_platform.backend.logic.platform_reads import alert_snapshot
+from products.alerts_platform.backend.models import PlatformAlert, PlatformAlertConfiguration
+
+EPISODE = datetime(2026, 10, 8, 14, 0, tzinfo=UTC)
+LATER_EPISODE = datetime(2026, 10, 8, 16, 0, tzinfo=UTC)
+AS_OF = datetime(2026, 10, 8, 14, 32, tzinfo=UTC)
+
+
+def _snapshot(state: PlatformAlertState, firing_started_at: datetime | None) -> PlatformAlertSnapshot:
+ return PlatformAlertSnapshot(
+ id=uuid.uuid4(),
+ grouping_key="",
+ state=state,
+ firing_started_at=firing_started_at,
+ last_notified_at=None,
+ snooze_until=None,
+ )
+
+
+class TestRootStateLine(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("this_firing_continues", PlatformAlertState.FIRING, EPISODE, "\U0001f534 Still firing as of 14:32 UTC"),
+ ("resolved", PlatformAlertState.NOT_FIRING, None, "\U0001f7e2 Resolved as of 14:32 UTC"),
+ ("a_later_firing", PlatformAlertState.FIRING, LATER_EPISODE, "\U0001f7e2 Resolved as of 14:32 UTC"),
+ ("errored", PlatformAlertState.ERRORED, EPISODE, None),
+ ("snoozed", PlatformAlertState.SNOOZED, EPISODE, None),
+ ]
+ )
+ def test_the_line_follows_the_recorded_state_of_this_firing(
+ self, _name: str, state: PlatformAlertState, firing_started_at: datetime | None, expected: str | None
+ ) -> None:
+ line = state_line(_snapshot(state, firing_started_at), episode_started_at=EPISODE, as_of=AS_OF)
+
+ assert line == expected
+
+ def test_a_group_with_no_recorded_state_leaves_the_root_alone(self) -> None:
+ assert state_line(None, episode_started_at=EPISODE, as_of=AS_OF) is None
+
+
+class TestAlertSnapshot(APIBaseTest):
+ def test_it_reads_the_named_group_of_this_team_only(self) -> None:
+ with team_scope(self.team.id):
+ configuration = PlatformAlertConfiguration.objects.create(
+ team_id=self.team.id,
+ name="API errors",
+ source_kind=PlatformAlertConfiguration.SourceKind.LOGS,
+ source_config={},
+ check_interval_minutes=1,
+ )
+ for grouping_key, state in (
+ ("checkout", PlatformAlertState.FIRING),
+ ("search", PlatformAlertState.NOT_FIRING),
+ ):
+ PlatformAlert.objects.create(
+ team_id=self.team.id, configuration=configuration, grouping_key=grouping_key, state=state
+ )
+
+ snapshot = alert_snapshot(self.team.id, str(configuration.id), "checkout")
+
+ assert snapshot is not None
+ assert snapshot.state == PlatformAlertState.FIRING
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+ assert alert_snapshot(other_team.id, str(configuration.id), "checkout") is None
diff --git a/products/alerts_platform/backend/tests/test_delivery_slack.py b/products/alerts_platform/backend/tests/test_delivery_slack.py
index 0d63f4477258..27e63c53258f 100644
--- a/products/alerts_platform/backend/tests/test_delivery_slack.py
+++ b/products/alerts_platform/backend/tests/test_delivery_slack.py
@@ -110,16 +110,38 @@ class TestSlackTransport(APIBaseTest):
)
return handle, slack_integration.return_value.client.chat_postMessage
- def test_a_send_returns_the_handle_a_reply_needs(self) -> None:
+ def test_an_opening_send_returns_the_handle_and_content_a_later_edit_needs(self) -> None:
handle, post = self._send()
- assert handle == MessageHandle(external_ref={"channel": "C-ENG", "ts": "1700000000.1"})
+ assert handle.external_ref == {"channel": "C-ENG", "ts": "1700000000.1"}
+ assert handle.root_content == {"blocks": blocks_for(MESSAGE), "text": post.call_args.kwargs["text"]}
assert post.call_args.kwargs["thread_ts"] is None
- def test_a_reply_goes_into_the_thread_it_names(self) -> None:
- _, post = self._send(in_reply_to=MessageHandle(external_ref={"channel": "C-ENG", "ts": "1699999999.9"}))
+ def test_a_reply_goes_into_the_thread_it_names_and_keeps_no_content(self) -> None:
+ handle, post = self._send(in_reply_to=MessageHandle(external_ref={"channel": "C-ENG", "ts": "1699999999.9"}))
assert post.call_args.kwargs["thread_ts"] == "1699999999.9"
+ assert handle.root_content is None
+
+ def test_an_edit_keeps_the_opening_content_and_adds_the_state_above_the_buttons(self) -> None:
+ opening = blocks_for(MESSAGE)
+ root = MessageHandle(
+ external_ref={"channel": "C-ENG", "ts": "1700000000.1"},
+ root_content={"blocks": opening, "text": "API errors is firing"},
+ )
+
+ with patch("products.alerts_platform.backend.delivery.slack.SlackIntegration") as slack_integration:
+ SlackTransport().edit_root(
+ team_id=self.team.id, target=self.target, root=root, state_line="Resolved as of 14:32 UTC"
+ )
+ update = slack_integration.return_value.client.chat_update
+
+ assert update.call_args.kwargs["channel"] == "C-ENG"
+ assert update.call_args.kwargs["ts"] == "1700000000.1"
+ assert update.call_args.kwargs["text"] == "API errors is firing (Resolved as of 14:32 UTC)"
+ blocks = update.call_args.kwargs["blocks"]
+ assert [*blocks[:-2], blocks[-1]] == opening
+ assert blocks[-2] == {"type": "context", "elements": [{"type": "mrkdwn", "text": "Resolved as of 14:32 UTC"}]}
def test_a_workspace_another_team_owns_is_refused(self) -> None:
# An unscoped lookup finds the integration by id alone and sends into it.
diff --git a/products/alerts_platform/backend/tests/test_delivery_thread_store.py b/products/alerts_platform/backend/tests/test_delivery_thread_store.py
index 335745a9c5ad..98a302756ade 100644
--- a/products/alerts_platform/backend/tests/test_delivery_thread_store.py
+++ b/products/alerts_platform/backend/tests/test_delivery_thread_store.py
@@ -62,21 +62,25 @@ class TestDatabaseThreadStore(APIBaseTest):
assert self.store.claim(key, "eval-1") is None
def test_a_later_evaluation_replies_to_the_message_that_opened_the_thread(self) -> None:
+ root = MessageHandle(
+ external_ref={"channel": "C-ENG", "ts": "1"},
+ root_content={"blocks": [{"type": "header"}], "text": "API errors is firing"},
+ )
key = self._key()
opener = self.store.claim(key, "eval-1")
assert opener is not None
- self.store.delivered(opener, MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"}))
+ self.store.delivered(opener, root)
resolve = self.store.claim(key, "eval-2")
assert resolve is not None
- assert resolve.handle == MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"})
+ assert resolve.handle == root
# A reply's own handle must not replace the root's, or the next message would reply to
# a reply and the conversation would walk away from where it started.
self.store.delivered(resolve, MessageHandle(external_ref={"channel": "C-ENG", "ts": "2"}))
third = self.store.claim(key, "eval-3")
assert third is not None
- assert third.handle == MessageHandle(external_ref={"channel": "C-ENG", "ts": "1"})
+ assert third.handle == root
@parameterized.expand([("fresh", timedelta(seconds=1), True), ("stale", PENDING_CLAIM_TTL * 2, False)])
def test_a_claim_blocks_another_send_until_it_goes_stale(