: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
fix(signals): deliver note-only report edits to Slack as the note (#83039)
Andrew Maguire4713d516ac73
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.pyindex 02f49d593b9b..35ed70846f3a 100644--- a/products/signals/backend/scout_harness/slack_delivery.py+++ b/products/signals/backend/scout_harness/slack_delivery.py@@ -40,6 +40,11 @@ _PERMANENT_SLACK_ERROR_CODES = frozenset(ScoutSlackOutputType = Literal["finding", "report"]+# Bound on the note snapshot a note-only edit carries through the Celery payload. Slack shows at+# most SLACK_SECTION_TEXT_MAX_LEN characters after conversion, so anything past this headroom is+# never rendered; the report keeps the full note either way.+MAX_SLACK_NOTE_SNAPSHOT_LEN = 6000+# Posted as an in-thread reply under every scout Slack message, inviting @PostHog follow-ups._SCOUT_SLACK_REPLY_TEXT = "💬 If you have questions, reply in this thread and mention *`@PostHog`*!"@@ -231,10 +236,28 @@ def post_scout_emission_to_slack()+def _report_header(report: SignalReport) -> str:+ title = " ".join((report.title or "").split()) or "New scout report"+ return title if len(title) <= 150 else title[:147].rstrip() + "..."+++def _report_link_block(report: SignalReport) -> dict:+ report_url = f"{settings.SITE_URL.rstrip('/')}/project/{report.team_id}/inbox/reports/{report.id}"+ return {+ "type": "actions",+ "elements": [+ {+ "type": "button",+ "text": {"type": "plain_text", "text": "View report in PostHog"},+ "url": report_url,+ }+ ],+ }++def build_scout_report_slack_message(report: SignalReport, run: SignalScoutRun) -> tuple[list[dict], str]:scout_name = _prettify_scout_name(run.skill_name)- title = " ".join((report.title or "").split()) or "New scout report"- header = title if len(title) <= 150 else title[:147].rstrip() + "..."+ header = _report_header(report)blocks: list[dict] = [{"type": "context",@@ -248,20 +271,41 @@ def build_scout_report_slack_message(report: SignalReport, run: SignalScoutRun)if rendered_summary:blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered_summary}})- report_url = f"{settings.SITE_URL.rstrip('/')}/project/{report.team_id}/inbox/reports/{report.id}"- blocks.append(+ blocks.append(_report_link_block(report))+ fallback = f"Scout · {escape_slack_mrkdwn(scout_name)}: {escape_slack_mrkdwn(header[:200])}"+ return blocks, fallback+++def build_scout_report_note_slack_message(+ report: SignalReport, run: SignalScoutRun, note: str+) -> tuple[list[dict], str]:+ """Render a note-only report edit as the note itself, framed as an update.++ A note-only edit leaves the title and summary the report message shows unchanged, so re-sending+ `build_scout_report_slack_message` would post a message identical to the one already in the+ channel. The note is what's new, so that's what gets delivered."""+ scout_name = _prettify_scout_name(run.skill_name)+ header = _report_header(report)+ blocks: list[dict] = [{- "type": "actions",+ "type": "context","elements": [{- "type": "button",- "text": {"type": "plain_text", "text": "View report in PostHog"},- "url": report_url,+ "type": "mrkdwn",+ "text": f"*Scout · {escape_slack_mrkdwn(scout_name)}* added a note to an existing report",}],- }- )- fallback = f"Scout · {escape_slack_mrkdwn(scout_name)}: {escape_slack_mrkdwn(title[:200])}"+ },+ {"type": "header", "text": {"type": "plain_text", "text": header}},+ ]++ note_text = strip_chart_references(note.strip())+ rendered_note = truncate_slack_section(markdown_to_slack_mrkdwn(note_text))+ if rendered_note:+ blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered_note}})++ blocks.append(_report_link_block(report))+ fallback = f"Scout · {escape_slack_mrkdwn(scout_name)} added a note to: {escape_slack_mrkdwn(header[:200])}"return blocks, fallback@@ -272,6 +316,7 @@ def post_scout_report_to_slack(delivery_id: str,integration_id: int,channel: str,+ edit_note: str | None = None,) -> None:if report.team_id != run.team_id:raise ScoutSlackPermanentDeliveryError(@@ -284,7 +329,11 @@ def post_scout_report_to_slack(project_id=report.team.project_id,)channel_id = _slack_channel_id(channel)- blocks, fallback = build_scout_report_slack_message(report, run)+ blocks, fallback = (+ build_scout_report_note_slack_message(report, run, edit_note)+ if edit_note is not None+ else build_scout_report_slack_message(report, run)+ )client = SlackIntegration(integration).clienttry:response = client.chat_postMessage(diff --git a/products/signals/backend/scout_harness/slack_delivery_queue.py b/products/signals/backend/scout_harness/slack_delivery_queue.pyindex b7cc58b53d63..160342dfcfaf 100644--- a/products/signals/backend/scout_harness/slack_delivery_queue.py+++ b/products/signals/backend/scout_harness/slack_delivery_queue.py@@ -9,7 +9,11 @@ from django.db import transactionfrom posthog.exceptions_capture import capture_exceptionfrom products.signals.backend.models import SignalScoutRun-from products.signals.backend.scout_harness.slack_delivery import ScoutSlackOutputType, get_scout_slack_destination+from products.signals.backend.scout_harness.slack_delivery import (+ MAX_SLACK_NOTE_SNAPSHOT_LEN,+ ScoutSlackOutputType,+ get_scout_slack_destination,+)from products.signals.backend.tasks import enqueue_scout_slack_deliverylogger = logging.getLogger(__name__)@@ -21,8 +25,13 @@ def queue_configured_scout_slack_delivery(output_type: ScoutSlackOutputType,output_id: str,delivery_id: str | None = None,+ edit_note: str | None = None,) -> None:- """Snapshot a run's configured destination and enqueue delivery after the current commit."""+ """Snapshot a run's configured destination and enqueue delivery after the current commit.++ `edit_note` marks a note-only report edit: the delivery posts the note as an update instead of+ re-posting the report message the channel already has. Snapshotted here (rather than re-read at+ send time) because the report's work log can gain further notes before the worker runs."""try:run = SignalScoutRun.all_teams.select_related("scout_config").filter(pk=run_id).first()if run is None:@@ -45,6 +54,7 @@ def queue_configured_scout_slack_delivery(delivery_id=delivery_id or str(uuid.uuid4()),integration_id=destination.integration_id,channel=destination.channel,+ edit_note=edit_note[:MAX_SLACK_NOTE_SNAPSHOT_LEN] if edit_note is not None else None,),robust=True,)diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.pyindex ef6477b762aa..243f66325f1e 100644--- a/products/signals/backend/scout_harness/tools/report.py+++ b/products/signals/backend/scout_harness/tools/report.py@@ -1270,10 +1270,15 @@ def _do_edit_report(# and skips queueing work that would no-op.report_status = get_scout_report_status(team_id=team.id, report_id=report_id)if report_status is not None and _surfaced(report_status):+ # A note-only edit leaves the title and summary the Slack report message shows+ # unchanged, so re-posting it would duplicate the message already in the channel.+ # Deliver the note itself instead; any edit that rewrote the content re-posts the+ # report as before.queue_configured_scout_slack_delivery(run_id=run.id,output_type="report",output_id=report_id,+ edit_note=append_note if note_appended and not updated_fields else None,)return resultdiff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 6bbecd4ab720..321a9de6f3ff 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -119,6 +119,7 @@ def deliver_scout_slack_output(delivery_id: str,integration_id: int,channel: str,+ edit_note: str | None = None,) -> None:context = {"team_id": team_id,@@ -161,6 +162,7 @@ def deliver_scout_slack_output(delivery_id=delivery_id,integration_id=integration_id,channel=channel,+ edit_note=edit_note,)else:logger.warning("signals_scout.slack_delivery_output_type_invalid", **context)@@ -212,9 +214,13 @@ def enqueue_scout_slack_delivery(delivery_id: str,integration_id: int,channel: str,+ edit_note: str | None = None,) -> None:"""Publish after commit, capturing broker failures without affecting the completed emit."""try:+ # `edit_note` rides as a kwarg only when set, so every delivery without one keeps the+ # payload shape workers running the previous task signature still accept.+ extra_kwargs: dict[str, str] = {"edit_note": edit_note} if edit_note is not None else {}deliver_scout_slack_output.delay(team_id,output_type,@@ -223,6 +229,7 @@ def enqueue_scout_slack_delivery(delivery_id,integration_id,channel,+ **extra_kwargs,)except Exception as exc:capture_exception(diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.pyindex da2ae22b4986..7bd5db2453ec 100644--- a/products/signals/backend/test/test_scout_report_api.py+++ b/products/signals/backend/test/test_scout_report_api.py@@ -140,10 +140,16 @@ class TestScoutReportAPI(APIBaseTest):data={"report_id": report_id, "append_note": "Re-validated on the next run"},format="json",)+ rewritten = self.client.post(+ self._edit_url(str(run.id)),+ data={"report_id": report_id, "summary": "Rewritten summary", "append_note": "And a note"},+ format="json",+ )assert emitted.status_code == status.HTTP_200_OK, emitted.json()assert edited.status_code == status.HTTP_200_OK, edited.json()- assert enqueue.call_count == 2+ assert rewritten.status_code == status.HTTP_200_OK, rewritten.json()+ assert enqueue.call_count == 3for call in enqueue.call_args_list:assert call.kwargs["team_id"] == self.team.idassert call.kwargs["output_type"] == "report"@@ -154,6 +160,11 @@ class TestScoutReportAPI(APIBaseTest):# Emit deliveries are keyed on the report id (idempotent); each edit gets its own id.assert enqueue.call_args_list[0].kwargs["delivery_id"] == report_idassert enqueue.call_args_list[1].kwargs["delivery_id"] != report_id+ # Only the note-only edit delivers as a note; an emit and a content rewrite post the report+ # message, even when the rewrite also appended a note.+ assert enqueue.call_args_list[0].kwargs["edit_note"] is None+ assert enqueue.call_args_list[1].kwargs["edit_note"] == "Re-validated on the next run"+ assert enqueue.call_args_list[2].kwargs["edit_note"] is Nonedef test_emit_report_unsafe_suppresses_but_returns_id(self) -> None:run = _make_run(self.team)diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.pyindex 6b064ce93cf0..0b9851242ce5 100644--- a/products/signals/backend/test/test_scout_slack_delivery.py+++ b/products/signals/backend/test/test_scout_slack_delivery.py@@ -133,6 +133,75 @@ class TestScoutSlackDelivery(BaseTest):assert reply["thread_ts"] == "1785418710.000200"assert reply["blocks"][0]["type"] == "context"+ 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.+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="**Checkout** failed for many users",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000300"}+ delivery_id = "0198f2a1-4c31-7a52-9f1e-3c5d6e7f8a9b"++ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ delivery_id,+ integration.id,+ "CSCOUTS|#scout-findings",+ "Re-checked after the fix: **error rate** is back to baseline <!channel>",+ )++ call = fake_client.chat_postMessage.call_args_list[0].kwargs+ assert call["client_msg_id"] == delivery_id+ context = call["blocks"][0]["elements"][0]["text"]+ assert "added a note to an existing report" in context+ assert call["blocks"][1]["text"]["text"] == "Checkout failures"+ section = call["blocks"][2]["text"]["text"]+ assert "*error rate*" in section+ assert "<!channel>" not in section+ assert "<!channel>" in section+ assert "failed for many users" not in section+ assert call["blocks"][-1]["elements"][0]["url"] == (+ f"{settings.SITE_URL}/project/{self.team.id}/inbox/reports/{report.id}"+ )++ def test_enqueue_omits_edit_note_kwarg_when_unset(self) -> None:+ # A worker still running the previous task signature rejects an unknown kwarg, so every+ # delivery without a note must keep the exact payload shape it had before edit_note existed.+ with patch.object(deliver_scout_slack_output, "delay") as delay:+ enqueue_scout_slack_delivery(+ team_id=self.team.id,+ output_type="report",+ output_id="ddab8ee5-2bb8-4226-b145-6732d31dc344",+ run_id="e3865391-bc89-44e6-86f7-2d4405627daf",+ delivery_id="b316c1d1-6901-49eb-8223-96d4df69f67f",+ integration_id=9,+ channel="CSCOUTS|#scout-findings",+ )+ enqueue_scout_slack_delivery(+ team_id=self.team.id,+ output_type="report",+ output_id="ddab8ee5-2bb8-4226-b145-6732d31dc344",+ run_id="e3865391-bc89-44e6-86f7-2d4405627daf",+ delivery_id="c4f7d2e2-7012-4afc-9334-a7e5df70a80a",+ integration_id=9,+ channel="CSCOUTS|#scout-findings",+ edit_note="Re-validated on the next run",+ )++ assert delay.call_args_list[0].kwargs == {}+ assert delay.call_args_list[1].kwargs == {"edit_note": "Re-validated on the next run"}+def test_reply_posted_regardless_of_ai_approval(self) -> None:# The Slack follow-up invite is unconditional — no AI-approval gate on scout output.self.organization.is_ai_data_processing_approved = Falsediff --git a/products/signals/backend/test/test_signal_scout_models.py b/products/signals/backend/test/test_signal_scout_models.pyindex 9d97dfb8c785..6d88f994235d 100644--- a/products/signals/backend/test/test_signal_scout_models.py+++ b/products/signals/backend/test/test_signal_scout_models.py@@ -119,6 +119,7 @@ class TestSignalScoutModels(_ScoutTeamScopedTestMixin, BaseTest):delivery_id=str(emission.id),integration_id=17,channel="CSCOUTS|#scout-findings",+ edit_note=None,)def test_enabling_scout_logs_activity(self) -> None: