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): name the person who dismissed a report on GitHub (#100457)

posthog[bot]45eb1dd8cecf
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index d99788013696..7be28a97c1f6 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -1160,28 +1160,41 @@ class GitHubIntegrationBase:
return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
return self.close_pull_request(parsed.repository, parsed.number)
- def comment_on_pull_request(self, repository: str, pr_number: int, body: str) -> dict[str, Any]:
- """Post a comment on a pull request. ``repository`` is ``owner/repo`` or a bare repo.
+ def _post_comment(self, repository: str, number: int, body: str, *, subject: str) -> dict[str, Any]:
+ """Comment through the issue-comments endpoint, which serves issues and pull requests alike.
- PR comments use the issues endpoint (a PR is an issue for commenting purposes).
+ The endpoint cannot tell the caller which of the two it wrote to, and a GET to find out
+ would cost a request per comment. So the caller names the subject, and an error says
+ "issue" or "pull request" as the caller knows it to be.
"""
repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
response = self._installation_authenticated_post(
- f"https://api.github.com/repos/{repo_path}/issues/{pr_number}/comments",
+ f"https://api.github.com/repos/{repo_path}/issues/{number}/comments",
endpoint="/repos/{owner}/{repo}/issues/{issue_number}/comments",
json_body={"body": body},
)
if response is None:
- return {"success": False, "error": "Network error commenting on pull request"}
+ return {"success": False, "error": f"Network error commenting on {subject}"}
if response.status_code != 201:
return {
"success": False,
- "error": f"Failed to comment on pull request: {response.text}",
+ "error": f"Failed to comment on {subject}: {response.text}",
"status_code": response.status_code,
}
return {"success": True}
+ def comment_on_issue(self, repository: str, issue_number: int, body: str) -> dict[str, Any]:
+ """Post a comment on an issue. ``repository`` is ``owner/repo`` or a bare repo."""
+ return self._post_comment(repository, issue_number, body, subject="issue")
+
+ def comment_on_pull_request(self, repository: str, pr_number: int, body: str) -> dict[str, Any]:
+ """Post a comment on a pull request. ``repository`` is ``owner/repo`` or a bare repo.
+
+ PR comments use the issues endpoint (a PR is an issue for commenting purposes).
+ """
+ return self._post_comment(repository, pr_number, body, subject="pull request")
+
def comment_on_pull_request_from_url(self, pr_url: str, body: str) -> dict[str, Any]:
"""Post a comment on a pull request by its HTML URL."""
parsed = self.parse_pull_request_url(pr_url)
diff --git a/products/signals/backend/github_actor.py b/products/signals/backend/github_actor.py
new file mode 100644
index 000000000000..7ab8ddba62e2
--- /dev/null
+++ b/products/signals/backend/github_actor.py
@@ -0,0 +1,48 @@
+"""The GitHub handle of the person behind a report transition.
+
+Suppressing or resolving a report closes the implementation pull request and the tracker issue
+through the team's GitHub App, so GitHub credits the App for both closes and the person who made
+the call is invisible on GitHub. The comment we leave next to the close is the only place that can
+carry them, and this module renders the mention it uses.
+
+Only a GitHub login is ever rendered. A PostHog name or email address would put an identity into a
+repository whose audience we do not know, and it would link to nothing on GitHub.
+
+Best-effort by contract: the report is already dismissed by the time any of this runs, so a handle
+that will not resolve degrades to an unattributed comment instead of holding up the close.
+"""
+
+from __future__ import annotations
+
+import re
+
+import structlog
+
+from posthog.models.user import User
+
+logger = structlog.get_logger(__name__)
+
+# The mention is interpolated into markdown we post to GitHub, and a login reaches us from
+# integration config rather than from GitHub's API on every read. GitHub itself allows only these
+# characters in a login, so anything else is not a handle worth rendering.
+GITHUB_LOGIN_PATTERN = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$")
+
+
+def github_mention_for_user(user_id: int | None) -> str | None:
+ """The actor's ``@handle`` for a GitHub comment, or ``None`` when no handle resolves.
+
+ ``None`` covers every case where naming somebody would be wrong or impossible: an automated
+ transition with no person behind it, a person who never connected a GitHub identity, and a
+ lookup that failed.
+ """
+ if user_id is None:
+ return None
+ try:
+ user = User.objects.filter(id=user_id).first()
+ login = user.get_github_login() if user is not None else None
+ except Exception:
+ logger.warning("signals.github_actor_lookup_failed", user_id=user_id, exc_info=True)
+ return None
+ if not login or not GITHUB_LOGIN_PATTERN.match(login):
+ return None
+ return f"@{login}"
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index 67395fb2968f..21721483108c 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -3,9 +3,10 @@
import re
from dataclasses import replace
from datetime import datetime
-from typing import TYPE_CHECKING, Literal, cast
+from typing import TYPE_CHECKING, Literal
from uuid import NAMESPACE_URL, uuid5
+from django.conf import settings
from django.db.models import Q
import structlog
@@ -14,6 +15,7 @@ from posthog.dataclasses import frozen
from posthog.models.github_integration_base import GitHubIntegrationBase
from posthog.models.integration import GitHubIntegration
+from products.signals.backend.github_actor import github_mention_for_user
from products.signals.backend.models import (
SignalActorKind,
SignalReport,
@@ -296,20 +298,28 @@ def report_ids_for_implementation_pr(*, team_id: int, repository: str, pr_number
PrCloseReason = Literal["suppressed", "snoozed", "resolved"]
-# Left on the PR before it's closed, so anyone looking at the PR sees why it was closed and how to undo it.
-_PR_CLOSE_COMMENT_TEMPLATE = (
- "🔕 Closing this PR because the linked PostHog report was {action}.\n\n"
- "If that wasn't intended, restore the report in PostHog and reopen this PR."
-)
-_PR_CLOSE_COMMENTS: dict[PrCloseReason, str] = {
- reason: _PR_CLOSE_COMMENT_TEMPLATE.format(action=reason)
- for reason in cast(tuple[PrCloseReason, ...], ("suppressed", "snoozed"))
-}
-# A resolved report never reopens, so the undo advice above does not apply to it.
-_PR_CLOSE_COMMENTS["resolved"] = (
- "🔕 Closing this PR because the linked PostHog report was resolved without it.\n\n"
- "If that wasn't intended, reopen this PR."
-)
+
+def _pr_close_comment(reason: PrCloseReason, *, report_link: str, actor_mention: str | None) -> str:
+ """What the PR says about its own close.
+
+ Left on the PR before it closes, so anyone reading the PR sees why it closed, who decided it,
+ and how to undo it. The close itself goes out under the team's GitHub App, so this comment is
+ the only place the person behind it can appear.
+ """
+ if reason == "resolved":
+ opening = (
+ f"🔕 Closing this PR because {actor_mention} resolved the {report_link} without it."
+ if actor_mention
+ else f"🔕 Closing this PR because the {report_link} was resolved without it."
+ )
+ # A resolved report never reopens, so the restore advice below does not apply to it.
+ return f"{opening}\n\nIf that wasn't intended, reopen this PR."
+ opening = (
+ f"🔕 Closing this PR because {actor_mention} {reason} the {report_link}."
+ if actor_mention
+ else f"🔕 Closing this PR because the {report_link} was {reason}."
+ )
+ return f"{opening}\n\nIf that wasn't intended, restore the report in PostHog and reopen this PR."
def _close_implementation_pr(
@@ -318,6 +328,7 @@ def _close_implementation_pr(
*,
reason: PrCloseReason = "suppressed",
pr: ImplementationPr,
+ actor_user_id: int | None = None,
) -> bool:
"""Best-effort: comment on and close the GitHub PR attached to this report.
@@ -408,7 +419,15 @@ def _close_implementation_pr(
return False
# Explain first, close second. A failed comment should not stop the close.
- comment_outcome = github.comment_on_pull_request(parsed.repository, parsed.number, _PR_CLOSE_COMMENTS[reason])
+ comment_outcome = github.comment_on_pull_request(
+ parsed.repository,
+ parsed.number,
+ _pr_close_comment(
+ reason,
+ report_link=f"[linked PostHog report]({settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id})",
+ actor_mention=github_mention_for_user(actor_user_id),
+ ),
+ )
if not comment_outcome.get("success"):
logger.warning(
"close_implementation_pr_comment_failed",
@@ -443,13 +462,18 @@ def _close_implementation_pr(
return False
-def close_implementation_pr_for_report(team_id: int, report_id: str, *, reason: PrCloseReason = "suppressed") -> bool:
+def close_implementation_pr_for_report(
+ team_id: int, report_id: str, *, reason: PrCloseReason = "suppressed", actor_user_id: int | None = None
+) -> bool:
try:
if not SignalReport.objects.filter(team_id=team_id, id=report_id).exists():
return False
closed = False
for pr in fetch_implementation_prs_for_reports([str(report_id)], team_id=team_id).get(str(report_id), []):
- closed = _close_implementation_pr(team_id, report_id, reason=reason, pr=pr) or closed
+ closed = (
+ _close_implementation_pr(team_id, report_id, reason=reason, pr=pr, actor_user_id=actor_user_id)
+ or closed
+ )
return closed
except Exception:
logger.exception("close_implementation_pr_lookup_failed", report_id=str(report_id))
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index 396de5c62078..7ffce7c4ff69 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -275,6 +275,10 @@ def close_pr_when_report_dismissed(
from products.signals.backend.tasks import close_dismissed_report_pr, close_report_tracker_issue # noqa: PLC0415
prior_status = getattr(instance, "_prior_status", None)
+ # The person who asked for this transition, when a caller set it before the save. GitHub
+ # credits the App for the close, so the comment left beside it is the only place they appear.
+ # Absent on every automated transition (PR webhook, judges, temporal), which stays unattributed.
+ actor_user_id = getattr(instance, "_transition_actor_user_id", None)
reason = _pr_close_reason(
instance,
created=created,
@@ -290,13 +294,17 @@ def close_pr_when_report_dismissed(
report_id = str(instance.id)
if getattr(instance, "_status_from_pr_state", False) and instance.status == SignalReport.Status.RESOLVED:
transaction.on_commit(
- lambda: close_report_tracker_issue.delay(report_id=report_id, team_id=team_id, completed=True)
+ lambda: close_report_tracker_issue.delay(
+ report_id=report_id, team_id=team_id, completed=True, actor_user_id=actor_user_id
+ )
)
elif instance.status == SignalReport.Status.DELETED:
# A deleted report leaves the inbox for good, so nothing will ever answer its work
# item. The issue closes as not done, because no pull request completed the work.
transaction.on_commit(
- lambda: close_report_tracker_issue.delay(report_id=report_id, team_id=team_id, completed=False)
+ lambda: close_report_tracker_issue.delay(
+ report_id=report_id, team_id=team_id, completed=False, actor_user_id=actor_user_id
+ )
)
return
@@ -308,6 +316,7 @@ def close_pr_when_report_dismissed(
report_id=report_id,
team_id=team_id,
reason=reason,
+ actor_user_id=actor_user_id,
)
)
diff --git a/products/signals/backend/report_actions.py b/products/signals/backend/report_actions.py
index ad61fbf72127..8b4b13662a26 100644
--- a/products/signals/backend/report_actions.py
+++ b/products/signals/backend/report_actions.py
@@ -49,6 +49,9 @@ def suppress_report_from_slack(
)
return False
+ # Name the clicker in the comments the receiver leaves on GitHub, when the Slack identity
+ # resolved to a PostHog user. An unresolved click stays unattributed.
+ report._transition_actor_user_id = user_id # type: ignore[attr-defined]
report.save(update_fields=updated_fields)
# Attribute to the resolved PostHog user when the caller mapped the Slack click to one;
# fall back to system if not. Either way the slack_user_id stays in the content as the
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 39f480209cab..753addd0c4ca 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -95,11 +95,15 @@ _SCOUT_SLACK_RETRY_MAX_SECONDS = 3600
max_retries=0,
)
@with_team_scope()
-def close_dismissed_report_pr(report_id: str, team_id: int, reason: PrCloseReason = "suppressed") -> None:
- close_implementation_pr_for_report(team_id, report_id, reason=reason)
+def close_dismissed_report_pr(
+ report_id: str, team_id: int, reason: PrCloseReason = "suppressed", actor_user_id: int | None = None
+) -> None:
+ close_implementation_pr_for_report(team_id, report_id, reason=reason, actor_user_id=actor_user_id)
# Suppression and snoozing are reversible. Keep their tracker issue open for a restored report.
if reason == "resolved":
- close_report_tracker_issue.delay(report_id=report_id, team_id=team_id, completed=False)
+ close_report_tracker_issue.delay(
+ report_id=report_id, team_id=team_id, completed=False, actor_user_id=actor_user_id
+ )
@shared_task(
@@ -109,8 +113,12 @@ def close_dismissed_report_pr(report_id: str, team_id: int, reason: PrCloseReaso
max_retries=5,
)
@with_team_scope()
-def close_report_tracker_issue(self, report_id: str, team_id: int, completed: bool = False) -> None:
- if close_tracker_issue_for_report(team_id=team_id, report_id=report_id, completed=completed):
+def close_report_tracker_issue(
+ self, report_id: str, team_id: int, completed: bool = False, actor_user_id: int | None = None
+) -> None:
+ if close_tracker_issue_for_report(
+ team_id=team_id, report_id=report_id, completed=completed, actor_user_id=actor_user_id
+ ):
return
retry_needed = (
SignalReportTrackerIssue.objects.for_team(team_id)
diff --git a/products/signals/backend/test/test_dismissal_pr_close.py b/products/signals/backend/test/test_dismissal_pr_close.py
index 088ff1b96471..070ace219e48 100644
--- a/products/signals/backend/test/test_dismissal_pr_close.py
+++ b/products/signals/backend/test/test_dismissal_pr_close.py
@@ -6,6 +6,7 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
from posthog.models.team.team import Team
+from posthog.models.user import User
from products.signals.backend.implementation_pr import (
PrCloseReason,
@@ -40,27 +41,41 @@ class TestClosePrWhenReportDismissed(BaseTest):
@parameterized.expand(
[
- ("suppressed", SignalReport.Status.READY, SignalReport.Status.SUPPRESSED, {}, "suppressed"),
+ ("suppressed", SignalReport.Status.READY, SignalReport.Status.SUPPRESSED, {}, "suppressed", False),
(
"snooze_from_ready",
SignalReport.Status.READY,
SignalReport.Status.POTENTIAL,
{"snooze_for": 5},
"snoozed",
+ False,
+ ),
+ ("snooze_from_resolved", SignalReport.Status.RESOLVED, SignalReport.Status.POTENTIAL, {}, "snoozed", False),
+ # A caller that named itself must reach the task, or the comment on the PR can only
+ # say the report was dismissed, never by whom.
+ (
+ "suppressed_by_a_caller",
+ SignalReport.Status.READY,
+ SignalReport.Status.SUPPRESSED,
+ {},
+ "suppressed",
+ True,
),
- ("snooze_from_resolved", SignalReport.Status.RESOLVED, SignalReport.Status.POTENTIAL, {}, "snoozed"),
]
)
def test_archive_transition_enqueues_close_task(
- self, _name, source_status, new_status, transition_kwargs, expected_reason
+ self, _name, source_status, new_status, transition_kwargs, expected_reason, with_actor
):
report = self._create_report(report_status=source_status)
+ if with_actor:
+ report._transition_actor_user_id = self.user.id # type: ignore[attr-defined]
with patch("products.signals.backend.tasks.close_dismissed_report_pr") as mock_task:
self._save_transition(report, new_status, **transition_kwargs)
mock_task.delay.assert_called_once_with(
report_id=str(report.id),
team_id=self.team.id,
reason=expected_reason,
+ actor_user_id=self.user.id if with_actor else None,
)
def test_full_save_on_dismiss_enqueues_close_task(self):
@@ -73,6 +88,7 @@ class TestClosePrWhenReportDismissed(BaseTest):
report_id=str(report.id),
team_id=self.team.id,
reason="suppressed",
+ actor_user_id=None,
)
def test_full_save_without_status_change_does_not_enqueue(self):
@@ -129,7 +145,9 @@ class TestClosePrWhenReportDismissed(BaseTest):
pr_state=SignalReportAssignment.PrState.MERGED,
)
- mock_task.delay.assert_called_once_with(report_id=str(report.id), team_id=self.team.id, completed=True)
+ mock_task.delay.assert_called_once_with(
+ report_id=str(report.id), team_id=self.team.id, completed=True, actor_user_id=None
+ )
def test_deleting_a_report_enqueues_a_tracker_close(self):
# A deleted report never returns to the inbox, so its tracker issue would otherwise stay
@@ -139,7 +157,9 @@ class TestClosePrWhenReportDismissed(BaseTest):
with patch("products.signals.backend.tasks.close_report_tracker_issue") as mock_task:
self._save_transition(report, SignalReport.Status.DELETED)
- mock_task.delay.assert_called_once_with(report_id=str(report.id), team_id=self.team.id, completed=False)
+ mock_task.delay.assert_called_once_with(
+ report_id=str(report.id), team_id=self.team.id, completed=False, actor_user_id=None
+ )
def test_pr_closed_webhook_does_not_enqueue_for_any_linked_report(self):
reports = [self._create_report(), self._create_report()]
@@ -180,7 +200,7 @@ class TestCloseDismissedReportPrTask(BaseTest):
def test_task_invokes_close_helper_with_team_report_and_reason(self):
with patch("products.signals.backend.tasks.close_implementation_pr_for_report") as mock_close:
close_dismissed_report_pr(report_id="report-1", team_id=self.team.id, reason="snoozed")
- mock_close.assert_called_once_with(self.team.id, "report-1", reason="snoozed")
+ mock_close.assert_called_once_with(self.team.id, "report-1", reason="snoozed", actor_user_id=None)
class TestCloseImplementationPrForReport(BaseTest):
@@ -286,6 +306,39 @@ class TestCloseImplementationPrForReport(BaseTest):
assert pr.state == "closed"
assert pr.merged is False
+ @parameterized.expand(
+ [
+ ("connected_github_identity", "octocat", "@octocat suppressed"),
+ ("no_github_identity", None, ") was suppressed"),
+ # A login reaches us from stored integration config, so a value that is not a handle
+ # must not be interpolated into a comment on somebody's repository.
+ ("login_that_is_not_a_handle", "not a login!", ") was suppressed"),
+ ]
+ )
+ def test_comment_names_the_actor_and_links_the_report(self, _name: str, login: str | None, expected: str):
+ github = MagicMock()
+ github.get_pull_request.return_value = {"success": True, "state": "open", "merged": False}
+ github.comment_on_pull_request.return_value = {"success": True}
+ github.close_pull_request.return_value = {"success": True, "number": 123, "state": "closed"}
+ with (
+ patch(
+ "products.signals.backend.implementation_pr.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ),
+ patch.object(User, "get_github_login", return_value=login),
+ ):
+ assert (
+ close_implementation_pr_for_report(self.team.id, str(self.report.id), actor_user_id=self.user.id)
+ is True
+ )
+
+ comment_body = github.comment_on_pull_request.call_args.args[2]
+ assert expected in comment_body
+ if login != "octocat":
+ assert "@" not in comment_body
+ # The report link carries the attribution GitHub cannot: it names everyone who acted.
+ assert f"/project/{self.team.id}/inbox/reports/{self.report.id})" in comment_body
+
def test_returns_false_and_skips_github_without_linked_pr(self):
self.assignment.pr_url = None
self.assignment.repository = None
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 92ab11c7dc0e..56f3597b508f 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -2148,7 +2148,10 @@ class TestSignalReportSuppressionAPI(APIBaseTest):
content_type="application/json",
)
assert response.status_code == status.HTTP_200_OK, response.json()
- mock_task.delay.assert_called_once_with(report_id=str(report.id), team_id=self.team.id, reason="resolved")
+ # The caller rides along so the comment on the PR can name who resolved the report.
+ mock_task.delay.assert_called_once_with(
+ report_id=str(report.id), team_id=self.team.id, reason="resolved", actor_user_id=self.user.id
+ )
def test_state_transition_response_includes_source_products(self):
report = self._create_report()
diff --git a/products/signals/backend/test/test_tracker_issues.py b/products/signals/backend/test/test_tracker_issues.py
index d0c65d82a377..baa4b27c2e70 100644
--- a/products/signals/backend/test/test_tracker_issues.py
+++ b/products/signals/backend/test/test_tracker_issues.py
@@ -9,7 +9,7 @@ from django.utils import timezone
from celery.exceptions import Retry
from rest_framework.exceptions import ValidationError as DRFValidationError
-from posthog.models import Team
+from posthog.models import Team, User
from posthog.models.integration import (
GitHubIntegration,
GitHubIntegrationError,
@@ -244,6 +244,41 @@ def test_close_tracker_issue_is_recorded_once(team):
close_issue.assert_called_once_with("web", 12, completed=False)
[email protected]("comment_fails", [False, True])
+def test_tracker_issue_comment_names_the_actor_and_never_blocks_the_close(team, comment_fails):
+ # The close goes out under the GitHub App, so this comment is the only place the person who
+ # dismissed the report appears. A comment that fails must still leave the issue closed:
+ # an issue left open grows the backlog the close exists to prevent.
+ integration = _connect_tracker(team, "github")
+ report = _make_report(team)
+ user = User.objects.create_user(email="[email protected]", password=None, first_name="Dismisser")
+ SignalReportTrackerIssue.all_teams.create(
+ team=team,
+ report=report,
+ integration=integration,
+ provider="github",
+ status=SignalReportTrackerIssue.Status.CREATED,
+ external_context={"repository": "web", "number": 12},
+ )
+
+ with (
+ patch.object(User, "get_github_login", return_value="octocat"),
+ patch.object(
+ GitHubIntegration,
+ "comment_on_issue",
+ side_effect=GitHubIntegrationError("boom") if comment_fails else None,
+ ) as comment,
+ patch.object(GitHubIntegration, "close_issue") as close_issue,
+ ):
+ assert close_tracker_issue_for_report(team_id=team.id, report_id=str(report.id), actor_user_id=user.id) is True
+
+ close_issue.assert_called_once_with("web", 12, completed=False)
+ body = comment.call_args.args[2]
+ assert "@octocat closed the" in body
+ assert f"/project/{team.id}/inbox/reports/{report.id})" in body
+
+
@pytest.mark.django_db
def test_completed_report_closes_tracker_issue_as_completed(team):
integration = _connect_tracker(team, "github")
diff --git a/products/signals/backend/tracker_issues.py b/products/signals/backend/tracker_issues.py
index 999f1cec8f4c..a134b4ce5f29 100644
--- a/products/signals/backend/tracker_issues.py
+++ b/products/signals/backend/tracker_issues.py
@@ -31,6 +31,7 @@ from posthog.models.integration import (
external_issue_url,
)
+from products.signals.backend.github_actor import github_mention_for_user
from products.signals.backend.models import SignalReport, SignalReportTrackerIssue, SignalTeamConfig
logger = structlog.get_logger(__name__)
@@ -354,6 +355,39 @@ def link_pull_request_to_tracker_issue(*, team_id: int, report_id: str, pr_url:
return False
+def _close_notice(*, report_link: str, actor_mention: str | None) -> str:
+ """What the issue says about its own close.
+
+ One wording covers every close, because the ``completed`` flag alone cannot name the verb: an
+ uncompleted close is a dismissal, a delete, or a resolve that needed no pull request. The
+ report page holds the detail, and the mention names the person GitHub cannot — the close goes
+ out under the team's GitHub App.
+ """
+ if actor_mention:
+ return f"🔕 {actor_mention} closed the {report_link} in PostHog, so this issue is closed too."
+ return f"🔕 The {report_link} was closed in PostHog, so this issue is closed too."
+
+
+def _comment_before_close(tracker: SignalReportTrackerIssue, *, report_link: str, actor_mention: str | None) -> None:
+ """Best-effort note on the issue naming who closed the report. Only GitHub takes one today.
+
+ Explain first, close second, as the implementation pull request does. A failed comment must
+ not stop the close: an issue left open would grow the backlog this close exists to prevent,
+ while a missing comment costs only the attribution.
+ """
+ if tracker.provider != Integration.IntegrationKind.GITHUB or tracker.integration is None:
+ return
+ context = tracker.external_context or {}
+ try:
+ GitHubIntegration(tracker.integration).comment_on_issue(
+ context["repository"],
+ int(context["number"]),
+ _close_notice(report_link=report_link, actor_mention=actor_mention),
+ )
+ except Exception:
+ logger.warning("signals.tracker_issue_close_comment_failed", tracker_id=str(tracker.id), exc_info=True)
+
+
def _close_provider_issue(tracker: SignalReportTrackerIssue, *, completed: bool) -> None:
integration = tracker.integration
if integration is None:
@@ -372,7 +406,9 @@ def _close_provider_issue(tracker: SignalReportTrackerIssue, *, completed: bool)
raise ValueError(f"Unsupported tracker provider {tracker.provider}")
-def close_tracker_issue_for_report(*, team_id: int, report_id: str, completed: bool = False) -> bool:
+def close_tracker_issue_for_report(
+ *, team_id: int, report_id: str, completed: bool = False, actor_user_id: int | None = None
+) -> bool:
"""Close the report's tracker issue once the report is dismissed or completed. Never raises.
A dismissed report will not produce a pull request, so its work item is finished. Leaving it
@@ -388,6 +424,12 @@ def close_tracker_issue_for_report(*, team_id: int, report_id: str, completed: b
if tracker is None or tracker.closed_at is not None:
return False
+ report_url = f"{settings.SITE_URL}/project/{team_id}/inbox/reports/{report_id}"
+ _comment_before_close(
+ tracker,
+ report_link=f"[linked PostHog report]({report_url})",
+ actor_mention=github_mention_for_user(actor_user_id),
+ )
_close_provider_issue(tracker, completed=completed)
tracker.closed_at = timezone.now()
tracker.save(update_fields=["closed_at", "updated_at"])
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 12beb7f9f945..a13cd109951d 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -2226,6 +2226,7 @@ class SignalReportViewSet(
# Hide the report from the list immediately while signal deletion continues asynchronously.
updated_fields = report.transition_to(SignalReport.Status.DELETED)
+ report._transition_actor_user_id = self._request_attribution().user_id # type: ignore[attr-defined]
report.save(update_fields=updated_fields)
return Response({"status": "deletion_started", "report_id": report_id}, status=status.HTTP_202_ACCEPTED)
@@ -2677,6 +2678,10 @@ class SignalReportViewSet(
# superseded and the receiver closes it. The PR-merge webhook resolves through
# transition_to directly and never sets this, so a merged PR is left alone.
report._close_pr_on_resolve = target_status == SignalReport.Status.RESOLVED # type: ignore[attr-defined]
+ # Name the caller in the comments the receiver leaves on the linked pull request
+ # and tracker issue. An external agent keeps its user principal, so it names the
+ # person who ran it rather than nobody.
+ report._transition_actor_user_id = self._request_attribution().user_id # type: ignore[attr-defined]
report.save(update_fields=updated_fields)
@@ -2967,6 +2972,7 @@ class SignalReportViewSet(
resolved_via_merged_pr = report.status == SignalReport.Status.RESOLVED and pr_merged
if report.status != SignalReport.Status.SUPPRESSED and not resolved_via_merged_pr:
updated_fields = report.transition_to(SignalReport.Status.SUPPRESSED)
+ report._transition_actor_user_id = attribution.user_id # type: ignore[attr-defined]
report.save(update_fields=updated_fields)
SignalReportArtefact.append_dismissal(
team_id=self.team.id,