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): let reviewers opt in to GitHub assignment on inbox PRs (#96321)

posthog[bot]0278a60f1510
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 6ef95a2591cb..d272c4cc289f 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -24,6 +24,15 @@ closure. The shared-PR guard checks both assignment and task-backed links, and
keeps the PR open while another unfinished report uses it. GitHub must confirm
the PR is open and unmerged before PostHog comments or closes it.
+`reviewer_pr_assignment` queues an after-commit task that adds a report's suggested reviewers as GitHub assignees.
+It runs when a PR URL first reaches a report, and when a person adds a reviewer to a report that already has a reviewable PR.
+Only reviewers who set `github_assign_on_pull_request` on their `SignalUserAutonomyConfig` are assigned, and the default is off.
+The task reads the latest `suggested_reviewers` row, so a reviewer removed from the list is not assigned later.
+Assignment is additive, so nothing here removes an assignee and a reviewer somebody added by hand stays on the PR.
+Closed and merged PRs are skipped.
+Every GitHub failure is logged without blocking the sync, the claim, or the reviewer edit that queued it.
+One PR can back several reports, and each report queues its own task, so the PR ends up with the union of qualifying reviewers.
+
Fallback reads do not require a data migration. This does not replay webhook
events that were missed before the fix; those reports need a subsequent event
or explicit reconciliation.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 92c6ec6d5c1e..dec928e1c0b0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7601,9 +7601,9 @@ snapshots:
scenes-app-inbox-scene--self-driving-verdict-pending--light:
hash: v1.k794b7964.18a04e43d0b1598e406b105dcdfe548f7d26376ad3ba606401c6795ae3ea1b1f.8uOUfAOgA04AY2GECIDr5Mf98040a17lVfVUA3QpRGM
scenes-app-inbox-scene--settings--dark:
- hash: v1.k794b7964.1af5812ea7514da4b7682c458680777a3465755635fe3bd55c63d9003f5dbf35.Tn_xNyX_ZAAAwef19CcNR9ODGCkFlv_x89jNmmECg2Q
+ hash: v1.k794b7964.56e6e806e53ad186a6e7eca6aeb2b691e95e2c6d27de81d6539406d3c946e73c.lQbazW62nbdlf-uOlroYbXxWnrbL5kDefBDHOvKHkFw
scenes-app-inbox-scene--settings--light:
- hash: v1.k794b7964.dd753e8a7abdbfa5891a5b2c62da90282c08aa5e3a608a20cafdd3b35628cfa5._lag-pvviMbZ2S8iO_qLEgggn2Tv4UKDraQEzVgLlYA
+ hash: v1.k794b7964.86fff9ce30a1cd376c9fd259ad22f99edadaa6cb66c75c18f10df207f0a2ff11.QTCPpndHx79lzLxyqzbZMOyaXjYXC_tGZj06-UQsQiA
scenes-app-inbox-scene--triage--dark:
hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eo
scenes-app-inbox-scene--triage--light:
@@ -7741,25 +7741,29 @@ snapshots:
scenes-app-inbox-scoutwritescopespicker--with-granted-scopes--light:
hash: v1.k794b7964.b3f53357dbbbc84b6580fa82faf34538e4f6e4e3c15691c14848541cae742227.I9ecpLcQZZ47Wrm82d-qMSDOzcmvbXUSlgD_VSYMUrg
scenes-app-inbox-selfdrivingsection--daily-limit-reached--dark:
- hash: v1.k794b7964.6bb86cc044462ca9b5d59151d279fb763b8ffc1918c913a4ba5786e9714a9675.F8GMUyNcVBI5ASlEgXgZaNW4sL-8zvLioKKu0JVua34
+ hash: v1.k794b7964.69ce4baa2544ecb014be73be66ea26b07711546838a529e1ecc31ffc34f2af56.XZMsxseOg8qWoHNMRWbgu6Ae9nlB-bPk0rLXGDa-lcs
scenes-app-inbox-selfdrivingsection--daily-limit-reached--light:
- hash: v1.k794b7964.09d9141ceb1ff5059446b3e4583b800a7a1484945eb2a2ae021ee11adfb5a54a.TEhNbKPIY7p3Wgy1AP-qVErXN8NjGZibeZBtzIKxw7w
+ hash: v1.k794b7964.b6721831e5715a9cfb279937c0080c13d25ed0ea3bf8460f9edd6abf8b92acbf.UxuexKk4f3iuOl3ZMz3tPeOL40pDsnUUp66p5isN5iA
scenes-app-inbox-selfdrivingsection--daily-limit-set--dark:
hash: v1.k794b7964.3fa4e975d9966a9bc3557d63ff5017a07d8b2428cec986c16f386c8d0f341022.UVEV2Z_N7DdU_THXbBI8uEURPwirfncvsbjodaYYmVY
scenes-app-inbox-selfdrivingsection--daily-limit-set--light:
hash: v1.k794b7964.219716b5c72f7c5fc968cd475c15536bf10734cff3200a34c89f162f3ab62b80.j-EMqzNiG7OjMvEVhhQkAYxwkbvWKi3iSsGmwaFN1I0
scenes-app-inbox-selfdrivingsection--disabled--dark:
- hash: v1.k794b7964.9c00d82a802ea3747ecb8103976d2e9ec72e10ef7b4218b8a94a2ae109047e4e.J724EJP49eq-Nmb6i-xbzg15ap2rBI6sRph2z-aIn2I
+ hash: v1.k794b7964.071a28e3ab3abce2710a949e50f8de965df209331a157db20dd69dce715b2847.r_kgmkiy6YRYoWVIw5ulrR_CBoCjwMQzVSsRF7OEcv4
scenes-app-inbox-selfdrivingsection--disabled--light:
- hash: v1.k794b7964.4d826910ae7ac8562380f11fda97e336bd221d328a146766249d07f310773ba8.HK0vgBXyANWRwWSk3juGunet3UaBLQNFNnoq2NpYA-s
+ hash: v1.k794b7964.178259484871df5abf309f7eeb353a93cf0f66422b7f7dd0251528a622eb6c16.GKEmpHunYzDJ3pPWI44ZGFDJtxN0pBM82Y7zAkSnChg
+ scenes-app-inbox-selfdrivingsection--git-hub-assignment-on--dark:
+ hash: v1.k794b7964.fdf6252fecf8caf2be0cdb6d8e44d6e35d4ae3e03ac9b000a34ccd010d90e9c8.uDpQbLO8JlmHKRa9exi2KIKbxfo42e2PB3YQpIdPiFE
+ scenes-app-inbox-selfdrivingsection--git-hub-assignment-on--light:
+ hash: v1.k794b7964.68b75610d1b49fe25451736ec8369bb96142714f05cb7c7930a837ec2d06a36f.VKfjM0_AmlmZLZ20LjETXpH3LYbuBJHKnkuuyv2WqVI
scenes-app-inbox-selfdrivingsection--no-daily-limit--dark:
hash: v1.k794b7964.3e355e2b561a2a3b3d38b00258e51531d6e9116d42129731a3c4b71bf6cb5e7e.VxAxGwO-zZ-B9OtgXOMp53Lvq5dOJjbs-qh60r-bT88
scenes-app-inbox-selfdrivingsection--no-daily-limit--light:
hash: v1.k794b7964.9837d5c2833b8def4c88c221e6ab65699e274a2515b210320b49f13ea0572a0a.hqgSLSsKWsmf3zXL3sEwl6kOe1jzwGeG-Fd0Zpoek70
scenes-app-inbox-selfdrivingsection--personal-default--dark:
- hash: v1.k794b7964.3e355e2b561a2a3b3d38b00258e51531d6e9116d42129731a3c4b71bf6cb5e7e.w0F2JmpN8qW-IWxh6c8DNhd2ipQW8pmSkNsYNkRD8Y0
+ hash: v1.k794b7964.24ced759b7b95ec1f8103e3b4eb150f5cb36b1a3d5d5231b98c3e52783707a77.isVQpWqSVqdGNjo3daqgwb_QJ7rmInIYEPL2L3TA_F4
scenes-app-inbox-selfdrivingsection--personal-default--light:
- hash: v1.k794b7964.9837d5c2833b8def4c88c221e6ab65699e274a2515b210320b49f13ea0572a0a.VRNeiMzZoqUTG5CHNsUYUBicIUDYvJKShp6072WLLWA
+ hash: v1.k794b7964.d82d81d1f9d06fb3ccede3c5ca3d00a61ae5f0f61c7c5af729a610fe9ca1953a.vlmxxVfAFDADdCWfjqF_Md36hGF1NRa4nnlmxQXPMug
scenes-app-inbox-selfdrivingsection--personal-override--dark:
hash: v1.k794b7964.aa42dc763078e1431c621efad3dae9f298485890910510fccd861fb1bc9f7d77.Go-OjRKiACFptGQ39DNGs4H4H83nh48PwJQBaoW59CI
scenes-app-inbox-selfdrivingsection--personal-override--light:
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 5ec9edd6ff9e..248f5259a860 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -58,6 +58,9 @@ GITHUB_ACCOUNT_NAME_HEAL_COOLDOWN_SECONDS = 5 * 60
# for a process that dies mid-heal, so it just has to outlast the 10s request timeout.
GITHUB_ACCOUNT_NAME_HEAL_CLAIM_TTL_SECONDS = 60
+# GitHub's add-assignees endpoint caps a single call at 10 logins and silently drops the rest.
+MAX_PR_ASSIGNEES = 10
+
# Reactions cost one extra round trip per reacted comment, and GitHub offers no way to fetch them in
# bulk, so bound the fan-out. Set high enough that a real pull request never reaches it: past this
# point a comment renders without its pills, which is worse than the extra requests.
@@ -1160,6 +1163,52 @@ class GitHubIntegrationBase:
return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
return self.comment_on_pull_request(parsed.repository, parsed.number, body)
+ def add_pull_request_assignees(self, repository: str, pr_number: int, assignees: Iterable[str]) -> dict[str, Any]:
+ """Add assignees to a pull request. ``repository`` is ``owner/repo`` or a bare repo.
+
+ Additive only. GitHub's add-assignees endpoint never removes an assignee, so a caller
+ cannot unassign anybody by leaving them out of ``assignees``, and calling it again with a
+ login that is already assigned changes nothing. GitHub also drops a login without push
+ access to the repository instead of failing the request, so the returned ``assignees``
+ list reports who is on the pull request rather than who was asked for.
+
+ Assignees use the issues endpoint (a PR is an issue for assignment purposes).
+ """
+ wanted = list(dict.fromkeys(login for login in assignees if login))[:MAX_PR_ASSIGNEES]
+ if not wanted:
+ return {"success": True, "assignees": []}
+
+ 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}/assignees",
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/assignees",
+ json_body={"assignees": wanted},
+ )
+ if response is None:
+ return {"success": False, "error": "Network error assigning pull request"}
+ if response.status_code != 201:
+ return {
+ "success": False,
+ "error": f"Failed to assign pull request: {response.text}",
+ "status_code": response.status_code,
+ }
+ try:
+ issue = response.json()
+ except Exception:
+ issue = {}
+ assigned = [
+ entry["login"] for entry in (issue.get("assignees") or []) if isinstance(entry, dict) and entry.get("login")
+ ]
+ return {"success": True, "assignees": assigned}
+
+ def add_pull_request_assignees_from_url(self, pr_url: str, assignees: Iterable[str]) -> dict[str, Any]:
+ """Add assignees to a pull request by its HTML URL."""
+ parsed = self.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
+ return self.add_pull_request_assignees(parsed.repository, parsed.number, assignees)
+
def get_pull_request_checks(self, repository: str, pr_number: int) -> dict[str, Any]:
"""Fetch the CI status for a PR — GitHub Actions check runs plus commit statuses from external
CI and GitHub Apps, merged into one normalized list (mirrors the checks GitHub shows on the PR page).
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 6dd53d189671..3eb2bf2565bb 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -765,6 +765,63 @@ class TestGitHubIntegrationModel(BaseTest):
assert result["success"] is True
assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/42/comments"
+ def test_add_pull_request_assignees_posts_to_issues_endpoint(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=201)
+ # GitHub returns the issue, and drops any login without push access without failing.
+ mock_response.json.return_value = {"assignees": [{"login": "alice"}]}
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
+ result = github.add_pull_request_assignees("PostHog/posthog", 123, ["alice", "outsider"])
+ assert result == {"success": True, "assignees": ["alice"]}
+ # Assignees go through the issues endpoint, not /pulls.
+ assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/123/assignees"
+ assert mock_post.call_args.kwargs["json_body"] == {"assignees": ["alice", "outsider"]}
+
+ @parameterized.expand(
+ [
+ ("empty", []),
+ ("all_blank", ["", None]),
+ ]
+ )
+ def test_add_pull_request_assignees_skips_github_when_nothing_to_assign(self, _name: str, assignees: list):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ with patch.object(github, "_installation_authenticated_post") as mock_post:
+ result = github.add_pull_request_assignees("PostHog/posthog", 123, assignees)
+ assert result == {"success": True, "assignees": []}
+ mock_post.assert_not_called()
+
+ def test_add_pull_request_assignees_dedupes_and_caps_at_ten(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=201)
+ mock_response.json.return_value = {"assignees": []}
+ requested = ["alice", "alice", *[f"user{i}" for i in range(12)]]
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
+ github.add_pull_request_assignees("PostHog/posthog", 123, requested)
+ sent = mock_post.call_args.kwargs["json_body"]["assignees"]
+ assert sent == ["alice", *[f"user{i}" for i in range(9)]]
+
+ def test_add_pull_request_assignees_reports_a_github_error(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=422, text="Validation Failed")
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response):
+ result = github.add_pull_request_assignees("PostHog/posthog", 123, ["alice"])
+ assert result["success"] is False
+ assert result["status_code"] == 422
+
+ def test_add_pull_request_assignees_from_url_parses_and_posts(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=201)
+ mock_response.json.return_value = {"assignees": [{"login": "alice"}]}
+ with patch.object(github, "_installation_authenticated_post", return_value=mock_response) as mock_post:
+ result = github.add_pull_request_assignees_from_url("https://github.com/PostHog/posthog/pull/42", ["alice"])
+ assert result["success"] is True
+ assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/42/assignees"
+
@parameterized.expand(
[
(
diff --git a/products/signals/backend/migrations/0120_signaluserautonomyconfig_github_assign.py b/products/signals/backend/migrations/0120_signaluserautonomyconfig_github_assign.py
new file mode 100644
index 000000000000..bc1f6ca8428c
--- /dev/null
+++ b/products/signals/backend/migrations/0120_signaluserautonomyconfig_github_assign.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.17 on 2026-09-08 06:50
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0119_squash_2026_09_07_schema_addons"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signaluserautonomyconfig",
+ name="github_assign_on_pull_request",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index ec9ded6c2549..1f409ee3e5f4 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0119_squash_2026_09_07_schema_addons
+0120_signaluserautonomyconfig_github_assign
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index f5b155b76b03..bb91dde480af 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -208,6 +208,9 @@ class SignalUserAutonomyConfig(UUIDModel):
# When null, every prioritized report notifies. A report with no priority then
# notifies only on the reviewer-added path (see slack_inbox_notifications).
slack_notification_min_priority = models.CharField(max_length=2, choices=AutonomyPriority, null=True, blank=True)
+ # Off by default because assignment is visible to everyone on the pull request, so a reviewer
+ # has to ask for it rather than be volunteered.
+ github_assign_on_pull_request = models.BooleanField(default=False, db_default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
diff --git a/products/signals/backend/report_assignments.py b/products/signals/backend/report_assignments.py
index 81a883471e55..820415bbb557 100644
--- a/products/signals/backend/report_assignments.py
+++ b/products/signals/backend/report_assignments.py
@@ -17,6 +17,7 @@ from posthog.models.user import User
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.models import InvalidStatusTransition, SignalReport, SignalReportAssignment
+from products.signals.backend.reviewer_pr_assignment import schedule_reviewer_pr_assignment
logger = structlog.get_logger(__name__)
@@ -283,6 +284,7 @@ def sync_task_pull_request_to_assignments(
if not changed:
continue
+ pr_url_is_new = assignment.pr_url != pr_url
assignment.pr_url = pr_url
assignment.repository = repository
assignment.pr_number = parsed.number
@@ -290,6 +292,13 @@ def sync_task_pull_request_to_assignments(
assignment.pr_merged = assignment_merged
assignment.save()
_apply_pr_report_state(report, assignment_state)
+ if pr_url_is_new:
+ schedule_reviewer_pr_assignment(
+ team_id=team_id,
+ report_id=str(report_id),
+ pr_url=pr_url,
+ pr_state=assignment_state,
+ )
updated += 1
return updated
@@ -401,6 +410,13 @@ def claim_report(
activity="assignment_changed",
detail=Detail(name=locked_report.title, changes=changes),
)
+ if before["implementation_pr"] != after["implementation_pr"]:
+ schedule_reviewer_pr_assignment(
+ team_id=locked_report.team_id,
+ report_id=str(locked_report.id),
+ pr_url=assignment.pr_url,
+ pr_state=assignment.pr_state,
+ )
return assignment
@@ -464,5 +480,12 @@ def update_assignments_for_pull_request(
if changed or missing_pr or assignment._state.adding:
assignment.save()
_apply_pr_report_state(report, pr_state)
+ if missing_pr:
+ schedule_reviewer_pr_assignment(
+ team_id=report.team_id,
+ report_id=str(report.id),
+ pr_url=assignment.pr_url,
+ pr_state=pr_state,
+ )
updated += 1
return updated
diff --git a/products/signals/backend/reviewer_pr_assignment.py b/products/signals/backend/reviewer_pr_assignment.py
new file mode 100644
index 000000000000..c489e8aca381
--- /dev/null
+++ b/products/signals/backend/reviewer_pr_assignment.py
@@ -0,0 +1,206 @@
+"""Add a report's opted-in suggested reviewers as GitHub assignees on its implementation PR.
+
+A reviewer whose workflow is GitHub's "Assigned to me" never sees an inbox PR otherwise, because
+every self-driving pull request opens with no assignee. Opt-in only, through
+`SignalUserAutonomyConfig.github_assign_on_pull_request`, and best effort throughout: a GitHub
+failure must never break the claim, sync, or reviewer edit that triggered it.
+"""
+
+from __future__ import annotations
+
+import json
+
+from django.db import transaction
+
+import structlog
+
+from posthog.models.integration import GitHubIntegration
+
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportAssignment,
+ SignalUserAutonomyConfig,
+)
+from products.signals.backend.report_generation.resolve_reviewers import (
+ normalized_github_logins_from_reviewer_payloads,
+ resolve_org_github_login_to_users,
+)
+
+logger = structlog.get_logger(__name__)
+
+# Assign only while the pull request can still be reviewed. UNKNOWN is included because a PR whose
+# state could not be read is far more often open than closed, and the task re-reads the real state
+# from GitHub before it assigns.
+ASSIGNABLE_PR_STATES = frozenset(
+ {
+ SignalReportAssignment.PrState.OPEN,
+ SignalReportAssignment.PrState.DRAFT,
+ SignalReportAssignment.PrState.UNKNOWN,
+ }
+)
+
+
+def schedule_reviewer_pr_assignment(
+ *,
+ team_id: int,
+ report_id: str,
+ pr_url: str | None,
+ pr_state: str | None,
+) -> None:
+ """Queue reviewer assignment for a report's pull request, after the current transaction commits.
+
+ Enqueued on commit so nothing is assigned if the write rolls back, and so the GitHub calls run
+ on a worker instead of holding up a claim, a PR sync, or a reviewer edit. `robust=True` keeps a
+ broker outage from failing a write that already committed.
+ """
+ # A null state reads as unknown, the same way the rest of the assignment code reads the column,
+ # so a row that never recorded a state is not silently skipped forever.
+ if not pr_url or (pr_state or SignalReportAssignment.PrState.UNKNOWN) not in ASSIGNABLE_PR_STATES:
+ return
+
+ # noqa: PLC0415 because `tasks` imports this module for the task body, so a module-level
+ # import here would be a cycle.
+ from products.signals.backend.tasks import assign_reviewers_on_implementation_pr # noqa: PLC0415
+
+ transaction.on_commit(
+ lambda: assign_reviewers_on_implementation_pr.delay(
+ team_id=team_id,
+ report_id=str(report_id),
+ pr_url=pr_url,
+ ),
+ robust=True,
+ )
+
+
+def opted_in_reviewer_logins(*, team_id: int, report_id: str) -> list[str]:
+ """GitHub logins of the report's current suggested reviewers who opted in to PR assignment.
+
+ Reads only the latest `suggested_reviewers` row, which is the live reviewer set, so a reviewer
+ removed from the list is not assigned on the next pull request event.
+ """
+ latest = (
+ SignalReportArtefact.objects.filter(
+ report_id=report_id,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ )
+ .order_by("-created_at")
+ .first()
+ )
+ if latest is None:
+ return []
+ try:
+ payloads = json.loads(latest.content)
+ except (json.JSONDecodeError, TypeError, ValueError):
+ return []
+ if not isinstance(payloads, list):
+ return []
+
+ logins = normalized_github_logins_from_reviewer_payloads(payloads)
+ if not logins:
+ return []
+ login_to_user = resolve_org_github_login_to_users(team_id, logins)
+ if not login_to_user:
+ return []
+
+ opted_in_user_ids = set(
+ SignalUserAutonomyConfig.objects.filter(
+ user_id__in={user.id for user in login_to_user.values()},
+ github_assign_on_pull_request=True,
+ ).values_list("user_id", flat=True)
+ )
+ return sorted(login for login, user in login_to_user.items() if user.id in opted_in_user_ids)
+
+
+def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: str) -> list[str]:
+ """Add the report's opted-in reviewers to its pull request. Returns the logins GitHub accepted.
+
+ Never unassigns: GitHub's add-assignees endpoint is additive, so a reviewer somebody assigned by
+ hand stays on the pull request. Returns an empty list when there is nothing to do or the call
+ failed, and raises nothing.
+ """
+ if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():
+ return []
+
+ logins = opted_in_reviewer_logins(team_id=team_id, report_id=report_id)
+ if not logins:
+ return []
+
+ parsed = GitHubIntegration.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return []
+
+ try:
+ github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ except Exception:
+ logger.exception(
+ "signals.reviewer_pr_assignment.integration_lookup_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ )
+ return []
+ if github is None:
+ return []
+
+ # A pull request closed or merged since the assignment was queued must not be reopened in
+ # somebody's assigned list, so re-read the state here rather than trusting the queued snapshot.
+ try:
+ pr = github.get_pull_request(parsed.repository, parsed.number)
+ except Exception:
+ logger.exception(
+ "signals.reviewer_pr_assignment.pr_fetch_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ )
+ return []
+ if not pr.get("success"):
+ logger.warning(
+ "signals.reviewer_pr_assignment.pr_fetch_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ error=pr.get("error"),
+ )
+ return []
+ if pr.get("merged") or pr.get("state") == "closed":
+ return []
+
+ try:
+ result = github.add_pull_request_assignees(parsed.repository, parsed.number, logins)
+ except Exception:
+ logger.exception(
+ "signals.reviewer_pr_assignment.assign_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ )
+ return []
+ if not result.get("success"):
+ logger.warning(
+ "signals.reviewer_pr_assignment.assign_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ error=result.get("error"),
+ )
+ return []
+
+ assigned = list(result.get("assignees") or [])
+ # Counts only: GitHub logins are member PII and must not reach logs. A `requested` above
+ # `assigned` means GitHub dropped a login, usually one without push access to the repository.
+ logger.info(
+ "signals.reviewer_pr_assignment.assigned",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ requested=len(logins),
+ assigned=len(assigned),
+ )
+ return assigned
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index c5a7dc012123..05c08f383882 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -410,6 +410,7 @@ class SignalUserAutonomyConfigSerializer(serializers.ModelSerializer):
"slack_notification_integration_id",
"slack_notification_channel",
"slack_notification_min_priority",
+ "github_assign_on_pull_request",
"created_at",
"updated_at",
]
@@ -427,6 +428,13 @@ class SignalUserAutonomyConfigSerializer(serializers.ModelSerializer):
"Null means notify on every priority. When set, reports without a priority judgment do not notify."
)
},
+ "github_assign_on_pull_request": {
+ "help_text": (
+ "Whether to add this user as a GitHub assignee on implementation pull requests for "
+ "reports that suggest them as reviewer. Off by default. Assignment is additive, so "
+ "turning it off never removes an assignee from a pull request that already has one."
+ )
+ },
}
@@ -455,6 +463,14 @@ class SignalUserAutonomyConfigCreateSerializer(serializers.Serializer):
"P0 is highest. Null = notify for every priority. When set, reports without a priority judgment do not notify."
),
)
+ github_assign_on_pull_request = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Add this user as a GitHub assignee on implementation pull requests for reports that "
+ "suggest them as reviewer. Off by default. Turning it off stops future assignment and "
+ "never removes an existing assignee."
+ ),
+ )
class SignalReportRefundSerializer(serializers.ModelSerializer):
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 94d2f4c51e22..74f0ca7d7ea6 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -36,6 +36,7 @@ from products.signals.backend.report_generation.repo_activity import (
rebuild_repository_activity,
repository_activity_needs_rebuild,
)
+from products.signals.backend.reviewer_pr_assignment import assign_reviewers_to_pull_request
from products.signals.backend.scout_harness.inactivity import sweep_inactive_scouts
from products.signals.backend.scout_harness.slack_delivery import (
DELIVERABLE_REPORT_STATUSES,
@@ -320,6 +321,22 @@ def send_reviewer_added_slack_notifications(
)
+@shared_task(
+ name="products.signals.backend.tasks.assign_reviewers_on_implementation_pr",
+ ignore_result=True,
+ max_retries=0,
+)
+@with_team_scope()
+def assign_reviewers_on_implementation_pr(team_id: int, report_id: str, pr_url: str) -> None:
+ """Add a report's opted-in suggested reviewers as GitHub assignees on its implementation PR.
+
+ Runs on a worker because the GitHub calls (integration probe, PR read, assign) must not hold up
+ the claim, sync, or reviewer edit that queued it. Best-effort end to end, so the assigner
+ reports its own failures and this never retries: the next pull request event queues it again.
+ """
+ assign_reviewers_to_pull_request(team_id=team_id, report_id=report_id, pr_url=pr_url)
+
+
def _capture_refund_sync_event(refund: SignalReportRefund, event: str, extra: dict[str, object]) -> None:
organization = refund.team.organization
with ph_scoped_capture() as capture:
diff --git a/products/signals/backend/test/test_reviewer_pr_assignment.py b/products/signals/backend/test/test_reviewer_pr_assignment.py
new file mode 100644
index 000000000000..9e41fb0929ec
--- /dev/null
+++ b/products/signals/backend/test/test_reviewer_pr_assignment.py
@@ -0,0 +1,343 @@
+import json
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from social_django.models import UserSocialAuth
+
+from posthog.models import Organization, Team, User
+from posthog.models.organization import OrganizationMembership
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportAssignment,
+ SignalUserAutonomyConfig,
+)
+from products.signals.backend.report_assignments import (
+ claim_report,
+ sync_task_pull_request_to_assignments,
+ update_assignments_for_pull_request,
+)
+from products.signals.backend.reviewer_pr_assignment import (
+ assign_reviewers_to_pull_request,
+ opted_in_reviewer_logins,
+ schedule_reviewer_pr_assignment,
+)
+from products.signals.backend.task_run_artefacts import record_implementation_task
+
+# Task/TaskRun ORM models needed to build cross-product fixtures; the tasks facade exposes DTOs only.
+from products.tasks.backend.models import Task, TaskRun
+
+PR_URL = "https://github.com/PostHog/posthog/pull/123"
+
+
+def org_and_team():
+ org = Organization.objects.create(name="pr-assign-org")
+ team = Team.objects.create(organization=org, name="pr-assign-team")
+ yield org, team
+ team.delete()
+ org.delete()
+
+
+def _make_reviewer(org: Organization, login: str, *, opted_in: bool) -> User:
+ user = User.objects.create(email=f"{login}@example.com", first_name="Reviewer")
+ OrganizationMembership.objects.create(user=user, organization=org)
+ UserSocialAuth.objects.create(user=user, provider="github", uid=f"gh-{login}", extra_data={"login": login})
+ SignalUserAutonomyConfig.objects.create(user=user, github_assign_on_pull_request=opted_in)
+ return user
+
+
+def _make_report(team: Team, *reviewer_rows: list[str]) -> SignalReport:
+ report = SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, title="Report", summary="Summary", signal_count=1, total_weight=1.0
+ )
+ for logins in reviewer_rows:
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"github_login": login} for login in logins]),
+ )
+ return report
+
+
+def _open_pr_github() -> MagicMock:
+ github = MagicMock()
+ github.get_pull_request.return_value = {"success": True, "state": "open", "draft": False, "merged": False}
+ github.add_pull_request_assignees.return_value = {"success": True, "assignees": ["opted-in"]}
+ return github
+
+
+class TestOptedInReviewerLogins:
+ @pytest.mark.django_db
+ def test_only_opted_in_reviewers_are_returned(self, org_and_team):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-in", opted_in=True)
+ _make_reviewer(org, "opted-out", opted_in=False)
+ report = _make_report(team, ["opted-in", "opted-out"])
+
+ assert opted_in_reviewer_logins(team_id=team.id, report_id=str(report.id)) == ["opted-in"]
+
+ @pytest.mark.django_db
+ def test_reviewer_without_a_config_row_is_not_assigned(self, org_and_team):
+ org, team = org_and_team
+ user = User.objects.create(email="[email protected]", first_name="Reviewer")
+ OrganizationMembership.objects.create(user=user, organization=org)
+ UserSocialAuth.objects.create(user=user, provider="github", uid="gh-nobody", extra_data={"login": "nobody"})
+ report = _make_report(team, ["nobody"])
+
+ assert opted_in_reviewer_logins(team_id=team.id, report_id=str(report.id)) == []
+
+ @pytest.mark.django_db
+ def test_reviewer_dropped_from_the_latest_row_is_not_assigned(self, org_and_team):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-in", opted_in=True)
+ _make_reviewer(org, "removed", opted_in=True)
+ # suggested_reviewers is append-only and latest-wins, so only the newest row is live.
+ report = _make_report(team, ["opted-in", "removed"], ["opted-in"])
+
+ assert opted_in_reviewer_logins(team_id=team.id, report_id=str(report.id)) == ["opted-in"]
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize("content", ["not json", '{"github_login": "opted-in"}'])
+ def test_unreadable_reviewers_row_yields_nothing(self, org_and_team, content: str):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-in", opted_in=True)
+ report = _make_report(team)
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=content,
+ )
+
+ assert opted_in_reviewer_logins(team_id=team.id, report_id=str(report.id)) == []
+
+
+class TestAssignReviewersToPullRequest:
+ @pytest.mark.django_db
+ def test_opted_in_reviewers_are_added_as_assignees(self, org_and_team):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-in", opted_in=True)
+ _make_reviewer(org, "opted-out", opted_in=False)
+ report = _make_report(team, ["opted-in", "opted-out"])
+ github = _open_pr_github()
+
+ with patch(
+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assigned = assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
+
+ assert assigned == ["opted-in"]
+ github.add_pull_request_assignees.assert_called_once_with("PostHog/posthog", 123, ["opted-in"])
+
+ @pytest.mark.django_db
+ def test_no_opted_in_reviewers_skips_github_entirely(self, org_and_team):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-out", opted_in=False)
+ report = _make_report(team, ["opted-out"])
+
+ with patch(
+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository"
+ ) as mock_lookup:
+ assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []
+ mock_lookup.assert_not_called()
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ "pr",
+ [
+ {"success": True, "state": "closed", "draft": False, "merged": False},
+ {"success": True, "state": "closed", "draft": False, "merged": True},
+ ],
+ ids=["closed", "merged"],
+ )
+ def test_a_closed_pull_request_is_not_assigned(self, org_and_team, pr: dict):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-in", opted_in=True)
+ report = _make_report(team, ["opted-in"])
+ github = _open_pr_github()
+ github.get_pull_request.return_value = pr
+
+ with patch(
+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []
+ github.add_pull_request_assignees.assert_not_called()
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ ("failing_call", "outcome"),
+ [
+ ("get_pull_request", Exception("boom")),
+ ("add_pull_request_assignees", Exception("boom")),
+ ("add_pull_request_assignees", {"success": False, "error": "Failed to assign pull request"}),
+ ],
+ ids=["pr_read_raises", "assign_raises", "assign_reports_failure"],
+ )
+ def test_a_github_failure_is_swallowed(self, org_and_team, failing_call: str, outcome: object):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-in", opted_in=True)
+ report = _make_report(team, ["opted-in"])
+ github = _open_pr_github()
+ if isinstance(outcome, Exception):
+ getattr(github, failing_call).side_effect = outcome
+ else:
+ getattr(github, failing_call).return_value = outcome
+
+ with patch(
+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []
+
+ @pytest.mark.django_db
+ def test_a_report_from_another_team_is_not_assigned(self, org_and_team):
+ org, team = org_and_team
+ other_team = Team.objects.create(organization=org, name="other-team")
+ _make_reviewer(org, "opted-in", opted_in=True)
+ report = _make_report(other_team, ["opted-in"])
+
+ with patch(
+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository"
+ ) as mock_lookup:
+ assert assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) == []
+ mock_lookup.assert_not_called()
+
+
+class TestScheduleReviewerPrAssignment:
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ ("pr_url", "pr_state", "expected"),
+ [
+ (PR_URL, SignalReportAssignment.PrState.OPEN, True),
+ (PR_URL, SignalReportAssignment.PrState.DRAFT, True),
+ (PR_URL, SignalReportAssignment.PrState.UNKNOWN, True),
+ (PR_URL, SignalReportAssignment.PrState.CLOSED, False),
+ (PR_URL, SignalReportAssignment.PrState.MERGED, False),
+ (PR_URL, None, True),
+ (None, SignalReportAssignment.PrState.OPEN, False),
+ ],
+ )
+ def test_only_a_reviewable_pull_request_queues_work(
+ self, org_and_team, pr_url: str | None, pr_state: str, expected: bool
+ ):
+ _, team = org_and_team
+ report = _make_report(team)
+
+ with patch("products.signals.backend.tasks.assign_reviewers_on_implementation_pr.delay") as mock_delay:
+ schedule_reviewer_pr_assignment(team_id=team.id, report_id=str(report.id), pr_url=pr_url, pr_state=pr_state)
+
+ assert mock_delay.called is expected
+
+
+class TestPullRequestLinkingQueuesAssignment:
+ """Wiring guards for each path where a PR URL first reaches a report. A hook that silently
+ stops firing leaves the feature dead with every unit test above still green."""
+
+ @pytest.fixture(autouse=True)
+ def _queued(self):
+ with patch("products.signals.backend.tasks.assign_reviewers_on_implementation_pr.delay") as mock_delay:
+ self.mock_delay = mock_delay
+ yield
+
+ @pytest.mark.django_db(transaction=True)
+ def test_claiming_a_report_with_a_pull_request_queues_assignment(self, org_and_team):
+ _, team = org_and_team
+ report = _make_report(team)
+ user = User.objects.create(email="[email protected]")
+
+ with patch(
+ "products.signals.backend.report_assignments.GitHubIntegration.first_for_team_repository",
+ return_value=None,
+ ):
+ claim_report(
+ report=report,
+ actor=ArtefactAttribution.from_user(user.id),
+ user=user,
+ was_impersonated=False,
+ pr_url=PR_URL,
+ release=False,
+ )
+
+ self.mock_delay.assert_called_once_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
+
+ @pytest.mark.django_db(transaction=True)
+ def test_reclaiming_the_same_pull_request_does_not_requeue(self, org_and_team):
+ _, team = org_and_team
+ report = _make_report(team)
+ user = User.objects.create(email="[email protected]")
+
+ with patch(
+ "products.signals.backend.report_assignments.GitHubIntegration.first_for_team_repository",
+ return_value=None,
+ ):
+ for _ in range(2):
+ claim_report(
+ report=report,
+ actor=ArtefactAttribution.from_user(user.id),
+ user=user,
+ was_impersonated=False,
+ pr_url=PR_URL,
+ release=False,
+ )
+
+ assert self.mock_delay.call_count == 1
+
+ @pytest.mark.django_db(transaction=True)
+ def test_syncing_a_task_pull_request_queues_assignment_once(self, org_and_team):
+ _, team = org_and_team
+ report = _make_report(team)
+ task = Task.objects.create(team=team, title="Implementation", description="", origin_product="signals")
+ record_implementation_task(team_id=team.id, report_id=str(report.id), task_id=str(task.id))
+
+ for _ in range(2):
+ sync_task_pull_request_to_assignments(team_id=team.id, task_id=str(task.id), pr_url=PR_URL, pr_state="open")
+
+ self.mock_delay.assert_called_once_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
+
+ @pytest.mark.django_db(transaction=True)
+ def test_a_merged_task_pull_request_is_not_queued(self, org_and_team):
+ _, team = org_and_team
+ report = _make_report(team)
+ task = Task.objects.create(team=team, title="Implementation", description="", origin_product="signals")
+ record_implementation_task(team_id=team.id, report_id=str(report.id), task_id=str(task.id))
+
+ sync_task_pull_request_to_assignments(
+ team_id=team.id, task_id=str(task.id), pr_url=PR_URL, pr_state="merged", pr_merged=True
+ )
+
+ self.mock_delay.assert_not_called()
+
+ @pytest.mark.django_db(transaction=True)
+ def test_a_webhook_that_first_links_the_pull_request_queues_assignment(self, org_and_team):
+ _, team = org_and_team
+ report = _make_report(team)
+ task = Task.objects.create(team=team, title="Implementation", description="", origin_product="signals")
+ record_implementation_task(team_id=team.id, report_id=str(report.id), task_id=str(task.id))
+ # A task run carries the PR while the assignment row does not, which is the state the
+ # webhook resolves the link from.
+ TaskRun.objects.create(
+ team=team,
+ task=task,
+ status=TaskRun.Status.COMPLETED,
+ output={"pr_url": PR_URL},
+ )
+ SignalReportAssignment.all_teams.filter(report=report).update(
+ pr_url=None, repository=None, pr_number=None, pr_state=SignalReportAssignment.PrState.UNKNOWN
+ )
+ self.mock_delay.reset_mock()
+
+ update_assignments_for_pull_request(
+ team_ids=[team.id],
+ repository="PostHog/posthog",
+ pr_number=123,
+ pr_state=SignalReportAssignment.PrState.OPEN,
+ )
+
+ self.mock_delay.assert_called_once_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
index af0ac9298d9a..79a515a3ef5c 100644
--- a/products/signals/backend/test/test_signal_report_artefact_api.py
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -23,7 +23,12 @@ from products.signals.backend.artefact_schemas import (
SuggestedReviewers,
TaskRunArtefact,
)
-from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact
+from products.signals.backend.models import (
+ ArtefactAttribution,
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportAssignment,
+)
from products.signals.backend.reviewer_correction_notes import ForwardedCorrectionNotes
# Task ORM model needed to build cross-product fixtures; the tasks facade exposes DTOs only.
@@ -274,6 +279,49 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
assert kwargs["team_id"] == self.team.id
assert kwargs["exclude_user_id"] == self.user.id
+ @parameterized.expand(
+ [
+ ("open_pr", SignalReportAssignment.PrState.OPEN, True),
+ ("merged_pr", SignalReportAssignment.PrState.MERGED, False),
+ ("no_pr", None, False),
+ ]
+ )
+ def test_put_adding_reviewer_queues_github_assignment_for_a_reviewable_pr(
+ self, _name: str, pr_state: str | None, expected: bool
+ ):
+ # A reviewer added after the PR opened still reaches GitHub's "Assigned to me", which is
+ # the wiring this feature depends on. A closed PR and a report with no PR queue nothing.
+ report = self._create_report()
+ artefact = self._create_artefact(report, content=[{"github_login": "alice"}])
+ if pr_state is not None:
+ SignalReportAssignment.objects.create(
+ team_id=self.team.id,
+ report_id=report.id,
+ pr_url="https://github.com/PostHog/posthog/pull/7",
+ repository="posthog/posthog",
+ pr_number=7,
+ pr_state=pr_state,
+ pr_merged=pr_state == SignalReportAssignment.PrState.MERGED,
+ )
+
+ with (
+ patch("products.signals.backend.tasks.assign_reviewers_on_implementation_pr.delay") as mock_delay,
+ patch("products.signals.backend.views.send_reviewer_added_slack_notifications"),
+ patch(
+ "products.signals.backend.auto_start.maybe_autostart_from_report_artefacts",
+ new_callable=AsyncMock,
+ ),
+ ):
+ with self.captureOnCommitCallbacks(execute=True):
+ response = self.client.put(
+ self._detail_url(str(report.id), str(artefact.id)),
+ data=json.dumps({"content": [{"github_login": "alice"}, {"github_login": "bob"}]}),
+ content_type="application/json",
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert mock_delay.called is expected
+
def test_put_removing_reviewer_does_not_notify(self):
# Removing a reviewer is not an add, so nobody is pinged.
report = self._create_report()
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index f639bd5a3093..1dbff8678b28 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -128,6 +128,7 @@ from products.signals.backend.report_generation.resolve_reviewers import (
)
from products.signals.backend.report_generation.reviewer_telemetry import capture_suggested_reviewers_resolved
from products.signals.backend.reviewer_correction_notes import ReviewerCorrection, forward_reviewer_correction_note
+from products.signals.backend.reviewer_pr_assignment import schedule_reviewer_pr_assignment
from products.signals.backend.serializers import (
CommitDiffResponseSerializer,
PullRequestChecksResponseSerializer,
@@ -3897,6 +3898,17 @@ def append_suggested_reviewers(
actor_user_id=attribution.user_id,
)
+ # Only on an add: assignment is additive, so a removal leaves the pull request alone.
+ if added_logins:
+ assignment = SignalReportAssignment.all_teams.filter(team_id=team.id, report_id=report_id).first()
+ if assignment is not None:
+ schedule_reviewer_pr_assignment(
+ team_id=team.id,
+ report_id=str(report_id),
+ pr_url=assignment.pr_url,
+ pr_state=assignment.pr_state,
+ )
+
# The same correction also steers the scouts that route on the logins it changed, which
# is the only return path a scout has for routing memory it already cached — but only for
# a genuine team edit. An impersonated operator edit is not team ownership evidence, so it
@@ -4539,6 +4551,8 @@ class SignalUserAutonomyConfigView(APIView):
defaults["autostart_priority"] = validated.get("autostart_priority")
if "slack_notification_min_priority" in serializer.initial_data:
defaults["slack_notification_min_priority"] = validated.get("slack_notification_min_priority")
+ if "github_assign_on_pull_request" in serializer.initial_data:
+ defaults["github_assign_on_pull_request"] = validated.get("github_assign_on_pull_request", False)
if "slack_notification_channel" in serializer.initial_data:
defaults["slack_notification_channel"] = validated.get("slack_notification_channel") or None
if "slack_notification_integration_id" in serializer.initial_data:
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index fe8da561720f..a59a15586dee 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4397,6 +4397,8 @@ export interface SignalUserAutonomyConfigApi {
* * `P3` - P3
* * `P4` - P4 */
slack_notification_min_priority?: AutonomyPriorityEnumApi | BlankEnumApi | null
+ /** Whether to add this user as a GitHub assignee on implementation pull requests for reports that suggest them as reviewer. Off by default. Assignment is additive, so turning it off never removes an assignee from a pull request that already has one. */
+ github_assign_on_pull_request?: boolean
readonly created_at: string
readonly updated_at: string
}
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 16879f554dcb..3f1f38a7191b 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1891,4 +1891,10 @@ export const UsersSignalAutonomyCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Minimum report priority that triggers a Slack notification. P0 is highest. Null means notify on every priority. When set, reports without a priority judgment do not notify.\n\n\* `P0` - P0\n\* `P1` - P1\n\* `P2` - P2\n\* `P3` - P3\n\* `P4` - P4'
),
+ github_assign_on_pull_request: zod
+ .boolean()
+ .optional()
+ .describe(
+ 'Whether to add this user as a GitHub assignee on implementation pull requests for reports that suggest them as reviewer. Off by default. Assignment is additive, so turning it off never removes an assignee from a pull request that already has one.'
+ ),
})
diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
index 7349c3c9c063..1678172ef05c 100644
--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
@@ -17,6 +17,8 @@ interface CardState {
myThreshold?: string | null
dailyLimit?: number | null
reportsToday?: number
+ /** Personal opt-in to being added as a GitHub assignee on the implementation PR. */
+ githubAssign?: boolean
}
function Card({
@@ -25,6 +27,7 @@ function Card({
myThreshold = null,
dailyLimit = null,
reportsToday = 0,
+ githubAssign = false,
}: CardState): JSX.Element {
useStorybookMocks({
get: {
@@ -42,6 +45,7 @@ function Card({
autostart_priority: myThreshold,
slack_notification_channel: null,
slack_notification_min_priority: null,
+ github_assign_on_pull_request: githubAssign,
},
'/api/environments/:team_id/integrations/': { results: [] },
},
@@ -89,6 +93,11 @@ export const PersonalDefault: Story = {
render: () => <Card myThreshold={null} />,
}
+// Personal GitHub assignment opted in: the row's switch reads on.
+export const GitHubAssignmentOn: Story = {
+ render: () => <Card githubAssign />,
+}
+
// Master switch off: both thresholds are hidden and only the reassurance copy shows.
export const Disabled: Story = {
render: () => <Card enabled={false} />,
diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
index a3fa00eb1037..6f8278ae0935 100644
--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
@@ -296,6 +296,36 @@ function DailyReportLimit(): JSX.Element {
)
}
+/**
+ * Per-user opt-in to being added as a GitHub assignee on the implementation PR for reports that
+ * suggest this user as reviewer. Off by default, because being assigned is visible to everybody on
+ * the pull request. Renders regardless of the auto-start toggle: a PR opened by hand from the inbox
+ * assigns reviewers too.
+ */
+function GitHubAssignmentRow(): JSX.Element {
+ const { autonomyConfig, autonomyConfigLoading, githubAssignUpdating } = useValues(userAutonomyLogic)
+ const { setGithubAssignOnPullRequest } = useActions(userAutonomyLogic)
+
+ return (
+ <div className="flex items-start justify-between gap-2 px-2.5 py-1.5">
+ <div className="flex flex-col gap-0.5 min-w-0 flex-1">
+ <span className="text-xs text-secondary">Assign me on GitHub</span>
+ <p className="text-[11px] text-tertiary leading-snug mb-0">
+ Add you as an assignee on PRs for reports that suggest you as reviewer, across all your projects.
+ </p>
+ </div>
+ <LemonSwitch
+ checked={autonomyConfig?.github_assign_on_pull_request ?? false}
+ loading={githubAssignUpdating}
+ disabledReason={autonomyConfigLoading && autonomyConfig === null ? 'Loading settings' : undefined}
+ onChange={setGithubAssignOnPullRequest}
+ aria-label="Assign me on GitHub pull requests"
+ data-attr="signals-github-assign-on-pull-request"
+ />
+ </div>
+ )
+}
+
/**
* Team-wide PR-generation control, backed by `autostart_enabled` and `default_autostart_priority`
* on `signalTeamConfigLogic`. The inline switch is the master opt-out for autonomous inbox PRs;
@@ -400,6 +430,9 @@ export function SelfDrivingSection(): JSX.Element {
Reports still arrive and notify your team.
</p>
)}
+ <div className="border-t border-primary">
+ <GitHubAssignmentRow />
+ </div>
<div className="border-t border-primary">
<DailyReportLimit />
</div>
diff --git a/products/signals/frontend/inbox/logics/userAutonomyLogic.ts b/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
index a9c1b8d8e20b..ad2ad054248f 100644
--- a/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
+++ b/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
@@ -13,6 +13,7 @@ export interface userAutonomyLogicValues {
autonomyConfig: SignalUserAutonomyConfig | null
autonomyConfigLoading: boolean
autostartPriorityUpdating: boolean
+ githubAssignUpdating: boolean
slackPickersExpanded: boolean
}
@@ -21,6 +22,9 @@ export interface userAutonomyLogicActions {
autostartPrioritySettled: () => {
value: true
}
+ githubAssignSettled: () => {
+ value: true
+ }
loadAutonomyConfig: () => any
loadAutonomyConfigFailure: (
error: string,
@@ -39,6 +43,9 @@ export interface userAutonomyLogicActions {
setAutostartPriority: (priority: SignalReportPriority | null) => {
priority: SignalReportPriority | null
}
+ setGithubAssignOnPullRequest: (enabled: boolean) => {
+ enabled: boolean
+ }
setSlackPickersExpanded: (expanded: boolean) => {
expanded: boolean
}
@@ -59,10 +66,11 @@ export type userAutonomyLogicType = MakeLogicType<userAutonomyLogicValues, userA
/**
* Per-user Self-driving autonomy override. Wraps the `users/@me/signal_autonomy`
- * endpoint via `api.signalUserAutonomy`. The only field surfaced here is the PR
- * auto-start priority threshold; when set it overrides the team default for
- * reports suggesting this user as reviewer, and `null` inherits the team default
- * (see the backend `_effective_threshold`).
+ * endpoint via `api.signalUserAutonomy`. Every field here applies to reports that
+ * suggest this user as reviewer: the PR auto-start priority threshold, which
+ * overrides the team default when set and inherits it when `null` (see the backend
+ * `_effective_threshold`); the Slack notification destination; and whether to add
+ * this user as a GitHub assignee on the implementation PR.
*/
export const userAutonomyLogic = kea<userAutonomyLogicType>([
path(['scenes', 'inbox', 'logics', 'userAutonomyLogic']),
@@ -78,6 +86,10 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
channel?: string | null
minPriority?: SignalReportPriority | null
}) => ({ updates }),
+ // Opt in to being added as a GitHub assignee on PRs for reports suggesting this user.
+ setGithubAssignOnPullRequest: (enabled: boolean) => ({ enabled }),
+ // Fires when the GitHub assignment POST settles, releasing the switch's save guard.
+ githubAssignSettled: true,
// Ephemeral view state: whether the workspace/channel pickers are revealed. Lets a user
// with multiple workspaces (and nothing saved yet) open the pickers to pick one.
setSlackPickersExpanded: (expanded: boolean) => ({ expanded }),
@@ -100,6 +112,10 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
...(state ?? { autostart_priority: null }),
autostart_priority: priority,
}),
+ setGithubAssignOnPullRequest: (state, { enabled }) => ({
+ ...(state ?? { autostart_priority: null }),
+ github_assign_on_pull_request: enabled,
+ }),
updateSlackNotifications: (state, { updates }) => ({
...(state ?? { autostart_priority: null }),
...('integrationId' in updates
@@ -119,6 +135,15 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
autostartPrioritySettled: () => false,
},
],
+ // Same guard as `autostartPriorityUpdating`: the switch stays disabled for the whole save
+ // window, so it cannot fire a second, racing update.
+ githubAssignUpdating: [
+ false,
+ {
+ setGithubAssignOnPullRequest: () => true,
+ githubAssignSettled: () => false,
+ },
+ ],
slackPickersExpanded: [
false,
{
@@ -145,6 +170,24 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
actions.loadAutonomyConfig()
}
},
+ setGithubAssignOnPullRequest: async ({ enabled }) => {
+ let success = true
+ try {
+ await api.signalUserAutonomy.update({ github_assign_on_pull_request: enabled })
+ } catch (error: any) {
+ success = false
+ lemonToast.error(error?.detail ?? error?.message ?? 'Failed to update GitHub assignment setting')
+ } finally {
+ actions.githubAssignSettled()
+ captureInboxSettingsChanged({
+ setting: 'github_assign_on_pull_request',
+ newValue: enabled,
+ success,
+ scope: 'user',
+ })
+ actions.loadAutonomyConfig()
+ }
+ },
updateSlackNotifications: async ({ updates }) => {
// Send only the keys the caller passed so unrelated fields (e.g. autostart_priority) aren't wiped.
const body: Partial<SignalUserAutonomyConfig> = {}
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index 03e237866055..dbbae94a759a 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -371,6 +371,7 @@ export interface SignalUserAutonomyConfig {
slack_notification_integration_id?: number | null
slack_notification_channel?: string | null
slack_notification_min_priority?: SignalReportPriority | null
+ github_assign_on_pull_request?: boolean
created_at?: string
updated_at?: string
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d7004f31727d..62f1620b9293 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -79492,6 +79492,8 @@ export namespace Schemas {
* * `P3` - P3
* * `P4` - P4 */
slack_notification_min_priority?: AutonomyPriorityEnum | BlankEnum | null;
+ /** Whether to add this user as a GitHub assignee on implementation pull requests for reports that suggest them as reviewer. Off by default. Assignment is additive, so turning it off never removes an assignee from a pull request that already has one. */
+ github_assign_on_pull_request?: boolean;
readonly created_at: string;
readonly updated_at: string;
}