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 open self-driving PRs ready for review (#98665)

posthog[bot]9c0dbf830713
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index d272c4cc289f..955e1b790c04 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -33,6 +33,17 @@ 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.
+`reviewer_pr_ready` queues a second after-commit task that takes the PR out of draft.
+Self-driving PRs open as drafts, and a draft only runs a narrowed CI matrix, so a reviewer who wants the full signal has to mark the PR ready and wait for that matrix to start over.
+Each suggested reviewer resolves to `github_open_pull_request_ready` on their `SignalUserAutonomyConfig`, falling back to `default_open_pull_request_ready` on `SignalTeamConfig` when it is null, and the PR opens ready if any of them resolves to true.
+Reviewers resolve by stored `user_uuid` first and by GitHub login only for entries that carry no uuid, so an org member who never connected GitHub still decides.
+A report whose reviewers resolve to no PostHog user follows the team default alone.
+Both settings default to draft.
+Unlike assignment, this runs only where a PR URL first reaches a report, never on a later reviewer edit, so no later event re-queues it.
+GitHub is asked to mark ready through the GraphQL `markPullRequestReadyForReview` mutation, because REST cannot undraft a PR.
+That same call reads the PR's timeline and refuses to move a PR whose draft state a person has already moved, which is what makes "a re-drafted PR stays draft" hold even when the queued job runs long after the link.
+A PR that is already ready, is closed or merged, or carries the `no-ci` label is left alone, and every GitHub failure is logged without blocking the write that queued it.
+
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 2f2f48dc663c..1ce574cd67b3 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7885,9 +7885,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.435685ca19bb5fcb1b208fa860113032c3bfe579e939ca18b659dda8d2c2835f.YLRLqkZZipYWoNuhZn6Xq_Ae5lD_s8j9MywPBHuarHg
+ hash: v1.k794b7964.50705f30642679b4254e32e0287c65ae31125b28d9748bac83326e461c7580f1.38uhbQQ5yYrdBVeVEcGqDQ8QTqo9YtkJz36Qfu7YfMQ
scenes-app-inbox-scene--settings--light:
- hash: v1.k794b7964.f5e30682c7adefcbdb563be476a18576c1b6bd59d1b2e3259b0c6d04fdaa57fd.Qpi3kFMb4UkXItf4OELwnGuLhBKc4USvZYoIayXFP1M
+ hash: v1.k794b7964.7abae9cb09b2bf1daa3779bb82100c9dddad3e9c8a8c95ddd8891ec61eb2c078.TtUmePwpdGLSCTje_xVNKqhbEjBgRBVplvDjx8kCc3c
scenes-app-inbox-scene--triage--dark:
hash: v1.k794b7964.77e43b36fdcd81befecf4de80e489050f525840924ec6ddef37c23a9179dbe8a.B3qkZFYBncFaPn2EBg4cBoYu_LIwW29imNwBdLXF5eo
scenes-app-inbox-scene--triage--light:
@@ -8057,41 +8057,45 @@ 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.c9f0b2588ef2a74f4410ad5a2ebed6023da8940565710c6d29698d42c7078f6f.gxSe5pFZCt06ykzwQ157aa_guht-Kl_QYaI9HLgpUjw
+ hash: v1.k794b7964.b552c9956f5b5a6b8c86665b5bf51a75cfd00211d35e8c0eb78887524b090817.IK2oYzKraEFQx1pz6sYjw648i8RgfiTphlBBAoqtjyI
scenes-app-inbox-selfdrivingsection--daily-limit-reached--light:
- hash: v1.k794b7964.c02491a0ac406a9f43a25a3c402d835875a2863417a902c1a858dc8843c3bd3c.E1uGSqsZQbR45Fi_SpQ8eeYacnIFWbVrwlM7dlZnLEg
+ hash: v1.k794b7964.4d67adc5510406cd98c872278d3525be878d2c1b48b3a0c1cbf6ed6d39b6d007.c1GlBJLgWqdEOAkGRaI3nhU-UGWemHf4Hqq3U0rL6n4
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.d29da3e118b86cc87a30e0e563db0b90decac4fba872f7c9398e86f3d0a318ec.V4DmJc60chPoHPrtv0Nu30l2GnI7snxwC5dPI8eNvdU
+ hash: v1.k794b7964.356b45822035a24f8a6d2470546f47ab97e2ce7a6920ab5ab6c7e758c0b09527.d4B_z-KCjjbEvdn7tHYzYZyMlBWUJPz6PIO6pJQAYhw
scenes-app-inbox-selfdrivingsection--disabled--light:
- hash: v1.k794b7964.5d9d01cb5f060c6048619c75f1521e8863d563bbffc6c71283bf65138c5afaa4.3NrtglOY205kI2yCz1hFwguqfuFa2vm9B3pTbWSDlqQ
+ hash: v1.k794b7964.c68ce60f96bf110f9138efe005febc6502ec3892f94e0ebb913886fbad7b41bb.M6beePjYmpPnl--ln_30DXADcEOn3PDMwhG8jgfdqxM
scenes-app-inbox-selfdrivingsection--git-hub-assignment-on--dark:
- hash: v1.k794b7964.c74a1825180cbf356dad0ae3f0192a723b929126dc73cf782114ee59891f4ede.iKIVtyY_BZMLchvjNM5dNdtqHqXGJ0gHMs84ZtgPOKY
+ hash: v1.k794b7964.d3914b7ba024e1ec5701e1cdabcd22ae2b35bf01e7302c7787eafd8291ac4d7b.ZGIeUKjF07sjbVZ6nSTVJMIr_725KuAQCB5YFaauWbg
scenes-app-inbox-selfdrivingsection--git-hub-assignment-on--light:
- hash: v1.k794b7964.733edaf44245b2f3d53bec632aede7bae0e9d5b99f99248b8743fa973f18a84f.2MHUMxET0bTwJiXj_s6CWzSV1CjCpErnS42zMgdKk9Y
+ hash: v1.k794b7964.4ec0418b27d02987dee36437efae8e5da7b563f040ee4436d86d583a347aba45.yneCokblzCiuIyXV0AeRTd-6uHxfhFRznfHMnIN7FDM
scenes-app-inbox-selfdrivingsection--issue-tracker-configured--dark:
- hash: v1.k794b7964.f4dddb7a07c2f309dde68c8b1cab786ff8365ad5fe0972b6f91e5fe38e2cfd69.lKM1EdNPOvVRcy3VoSvPARuBVddPqNNdD4_46vWbi-0
+ hash: v1.k794b7964.be19e707da4b6ab6fea6a519b0d98292adc24c65b3785778f88c39dbc55c45b5.clYd6voejcwUEC5cMIAVY-kF2Nq0hBzPuFTK1vxzW0M
scenes-app-inbox-selfdrivingsection--issue-tracker-configured--light:
- hash: v1.k794b7964.1bbd3734cd76d05f02460dfa9e73ec8c775d735dceb1915f0a034b48cb41d551.vR0oB58UM5nsB9zbp4iXs4aRHsgimQlHpdmoeXjqd20
+ hash: v1.k794b7964.c6210ff2863d0727d6d789950f74e84383d1b7b5e84bdb750da3f06e659a1279.r-CqmDkAVoNB2Xm3O2I0f3W5b0XWFNbbqkWXyVkKHwM
scenes-app-inbox-selfdrivingsection--issue-tracker-unavailable--dark:
- hash: v1.k794b7964.39714af86ffcbf6085cffb182a42190419974d9dc0617b8e4810c2c39149fdb2.fEB8kLRblV6ONVo8OtXuPhNgD90F83N9UBvcNZsXBJc
+ hash: v1.k794b7964.cc719ae38ec59531b78003222ff8662e86f263e35b8ea41ac8c42c09369227ab.ShzcW9Ks0KNtuLlLrx08Nl97Y5bXGEP6mBKU5cmDnkc
scenes-app-inbox-selfdrivingsection--issue-tracker-unavailable--light:
- hash: v1.k794b7964.8903ca8efc20c68efde8e5a00efe31d8e0dde9dcb8cbc1aef440ac223dabdc5a.ppgy141yzVPEXrO0eW8jU-G2lGagYr3UZovv3mwyDRs
+ hash: v1.k794b7964.5cd4422635384d0bde5d07fbc81487df9e6f7f8c14c6a9324c4985c4b32c68a2.xWbAE4IvQazaV_OlE5hiWozUYBLV4UkTJOCpby9VBgs
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.39714af86ffcbf6085cffb182a42190419974d9dc0617b8e4810c2c39149fdb2.IZWlGWQ7FEqCGc_j7jn6oQvJmyMddoBUHwX6y2el1qs
+ hash: v1.k794b7964.cc719ae38ec59531b78003222ff8662e86f263e35b8ea41ac8c42c09369227ab.FIvoSElhmxNRuM80-BvdlOqEtmSJZSLWDze3iAip9fQ
scenes-app-inbox-selfdrivingsection--personal-default--light:
- hash: v1.k794b7964.8903ca8efc20c68efde8e5a00efe31d8e0dde9dcb8cbc1aef440ac223dabdc5a.ISalvq0MHCdiayMOzFM5EDTW_xfso5O1vJKuWaXd8IA
+ hash: v1.k794b7964.5cd4422635384d0bde5d07fbc81487df9e6f7f8c14c6a9324c4985c4b32c68a2.VyT07ldKlDmkAaFMwNQyw_US7EZkZSGJ3iWe5MOEmaw
scenes-app-inbox-selfdrivingsection--personal-override--dark:
hash: v1.k794b7964.aa42dc763078e1431c621efad3dae9f298485890910510fccd861fb1bc9f7d77.Go-OjRKiACFptGQ39DNGs4H4H83nh48PwJQBaoW59CI
scenes-app-inbox-selfdrivingsection--personal-override--light:
hash: v1.k794b7964.11bb568d4acedc2c8471037b636ccceffd9d5132b2831c86911cb3c03dc0e761.Av0epOul8ebcU34b5lat7cvdImPzSkTHhwuYPkfV3WA
+ scenes-app-inbox-selfdrivingsection--pull-request-ready-for-review--dark:
+ hash: v1.k794b7964.6e31905b3f878f3cb1be53adf4c6fd68795fe70d276735dc2468247cbdd0e754.ze8xkMkOZUFemvscgrTpm21_RDh_1GeFMJrSZyTZ6xc
+ scenes-app-inbox-selfdrivingsection--pull-request-ready-for-review--light:
+ hash: v1.k794b7964.9514ba4604e35f46cb598fe1ffc0c4302300c6978cc76f42f8b89c6135f6b629.VhrSJsMWlmzJzVDMDUmfqJpskAsRJ0Dxe3gApxUbKVo
scenes-app-inbox-signal-cards--all-sources--dark:
hash: v1.k794b7964.8220c14a1dc6de9d9aa2fa2fa829bff1d19230cf7cdb947906b3fee3ead37d98.BBzXUXAId7C0u5sasTEYZBdaqZjXRU20paQFY6thp3s
scenes-app-inbox-signal-cards--all-sources--light:
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 6aa33fbafa3d..93f748c35d14 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -377,6 +377,7 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {
"autostart_base_branches": "base branch overrides",
"issue_tracking_integration": "issue tracker",
"issue_tracking_config": "issue tracker target",
+ "default_open_pull_request_ready": "PRs open as",
},
"OAuthApplication": {
"_provisioning_config": "provisioning config",
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 6c7b5148ebc4..d99788013696 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -8,7 +8,7 @@ operations that are shared between :class:`GitHubIntegration` (team-scoped) and
import json
import time
import uuid
-from collections.abc import Iterable, Mapping
+from collections.abc import Collection, Iterable, Mapping
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Literal, TypedDict, cast
@@ -1550,23 +1550,34 @@ class GitHubIntegrationBase:
return False
return True
- def _gh_graphql(self, query: str, variables: dict[str, Any], *, endpoint: str, timeout: int = 10) -> dict:
+ def _gh_graphql(
+ self,
+ query: str,
+ variables: dict[str, Any],
+ *,
+ endpoint: str,
+ timeout: int = 10,
+ retry_transient: bool = True,
+ ) -> dict:
"""Authenticated POST to the GitHub GraphQL API. Returns the ``data`` object.
GraphQL queries are read-only, so a POST retry on transient failures is safe —
hence ``retry_transient=True`` on the shared :meth:`api_request` lifecycle, plus an
extra retry loop here for GitHub's 200-with-``errors`` transient server errors that
- the status-code retry can't catch.
+ the status-code retry can't catch. A mutation passes ``retry_transient=False``: a
+ network error can arrive after GitHub already ran the write, so a repeat is the
+ caller's decision to make, not this method's.
"""
errors: Any = None
- for attempt in range(self._GRAPHQL_TRANSIENT_ATTEMPTS):
+ attempts = self._GRAPHQL_TRANSIENT_ATTEMPTS if retry_transient else 1
+ for attempt in range(attempts):
response = self.api_request(
"POST",
"/graphql",
endpoint=endpoint,
json_body={"query": query, "variables": variables},
timeout=timeout,
- retry_transient=True,
+ retry_transient=retry_transient,
)
if response.status_code != 200:
raise GitHubIntegrationError(
@@ -1585,7 +1596,7 @@ class GitHubIntegrationBase:
# No data — a hard failure. Retry GitHub's transient server errors; raise the rest.
if not self._graphql_errors_are_transient(errors):
break
- if attempt < self._GRAPHQL_TRANSIENT_ATTEMPTS - 1:
+ if attempt < attempts - 1:
logger.info(
"GitHubIntegration: retrying transient GraphQL error",
endpoint=endpoint,
@@ -1678,6 +1689,104 @@ class GitHubIntegrationBase:
"updated_at": pr.get("updatedAt"),
}
+ # Labels are read alongside the draft state so one round trip answers both "is there anything to
+ # do" and "is the caller allowed to do it", instead of a second call between the read and the write.
+ _PR_READY_STATE_QUERY = """
+ query($owner: String!, $repo: String!, $number: Int!) {
+ repository(owner: $owner, name: $repo) {
+ pullRequest(number: $number) {
+ id
+ isDraft
+ state
+ labels(first: 100) { nodes { name } }
+ timelineItems(itemTypes: [READY_FOR_REVIEW_EVENT, CONVERT_TO_DRAFT_EVENT], first: 1) {
+ nodes { __typename }
+ }
+ }
+ }
+ }
+ """
+
+ _MARK_PR_READY_MUTATION = """
+ mutation($pullRequestId: ID!) {
+ markPullRequestReadyForReview(input: { pullRequestId: $pullRequestId }) {
+ pullRequest { isDraft }
+ }
+ }
+ """
+
+ def mark_pull_request_ready_for_review(
+ self, repository: str, pr_number: int, *, skip_labels: Collection[str] = ()
+ ) -> dict[str, Any]:
+ """Take a draft pull request out of draft. ``repository`` is ``owner/repo`` or a bare repo.
+
+ GraphQL rather than REST because REST cannot do it: ``PATCH /repos/{owner}/{repo}/pulls/{n}``
+ ignores ``draft``, and ``markPullRequestReadyForReview`` is the only endpoint that undrafts.
+
+ Only ever moves a pull request that has never left the draft state it opened in. A pull
+ request somebody already marked ready, or put back into draft, keeps whatever they chose,
+ however long the caller took to get here.
+
+ Returns ``{"success": True, "changed": ...}``. ``changed`` is False when there was nothing
+ to do, with ``reason`` naming which of the guards stopped it: ``not_draft`` for a pull
+ request already ready, ``closed`` for one that is closed or merged, ``draft_state_decided``
+ for one whose draft state a person has already moved, or ``label`` when it carries one of
+ ``skip_labels`` (matched case-insensitively). A pull request GitHub would not
+ return, and a mutation it rejected, come back as ``{"success": False, "error": ...}``;
+ transport failures raise :class:`GitHubIntegrationError`, and rate limits and a denied egress
+ budget raise, as everywhere else on this client.
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ owner, _, repo = repo_path.partition("/")
+
+ data = self._gh_graphql(
+ self._PR_READY_STATE_QUERY,
+ {"owner": owner, "repo": repo, "number": pr_number},
+ endpoint="/graphql:pullRequestReadyState",
+ )
+ pr = ((data or {}).get("repository") or {}).get("pullRequest")
+ if not pr:
+ return {"success": False, "error": f"Pull request not found: {repo_path}#{pr_number}"}
+ if pr.get("state") != "OPEN":
+ return {"success": True, "changed": False, "reason": "closed"}
+ if not pr.get("isDraft"):
+ return {"success": True, "changed": False, "reason": "not_draft"}
+ # Somebody already moved this pull request between draft and ready, so its current draft
+ # state is a decision rather than the state it opened in. Reading the timeline is what makes
+ # that durable: a caller that queues this work cannot otherwise tell a pull request that was
+ # always a draft from one a person put back into draft while the call waited.
+ # Count the returned nodes, never `totalCount`: GitHub ignores the `itemTypes` filter when it
+ # computes that field, so it reports every timeline item and would match any busy pull request.
+ if (pr.get("timelineItems") or {}).get("nodes") or []:
+ return {"success": True, "changed": False, "reason": "draft_state_decided"}
+
+ unwanted = {label.casefold() for label in skip_labels}
+ if unwanted:
+ names = {
+ node["name"].casefold()
+ for node in ((pr.get("labels") or {}).get("nodes") or [])
+ if isinstance(node, dict) and isinstance(node.get("name"), str)
+ }
+ if names & unwanted:
+ return {"success": True, "changed": False, "reason": "label"}
+
+ node_id = pr.get("id")
+ if not isinstance(node_id, str):
+ return {"success": False, "error": f"Pull request has no node id: {repo_path}#{pr_number}"}
+
+ # No transient retry: a network error can land after GitHub already undrafted the pull
+ # request, and a repeat would then fight a reviewer who redrafted it in between.
+ result = self._gh_graphql(
+ self._MARK_PR_READY_MUTATION,
+ {"pullRequestId": node_id},
+ endpoint="/graphql:markPullRequestReadyForReview",
+ retry_transient=False,
+ )
+ marked = ((result or {}).get("markPullRequestReadyForReview") or {}).get("pullRequest")
+ if not marked:
+ return {"success": False, "error": f"Failed to mark pull request ready: {repo_path}#{pr_number}"}
+ return {"success": True, "changed": True}
+
# Pull requests per aliased CI-rollup query. Each alias reads one PR and the check rollup of its
# head commit, so a batch this size stays well inside GitHub's GraphQL node limit. A longer list
# is split across several calls, and a failure in any of them raises without the batches that
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 1c2ccade19d0..ee5b62dc3365 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -2439,6 +2439,68 @@ class TestGitHubIntegrationPullRequestBabysitSnapshot(BaseTest):
assert result["success"] is False
+class TestGitHubIntegrationMarkPullRequestReadyForReview(BaseTest):
+ def _github(self) -> GitHubIntegration:
+ return GitHubIntegration(_create_github_integration(self.team))
+
+ @staticmethod
+ def _state(
+ *,
+ is_draft: bool = True,
+ state: str = "OPEN",
+ labels: list[str] | None = None,
+ draft_transitions: int = 0,
+ ) -> dict:
+ return {
+ "repository": {
+ "pullRequest": {
+ "id": "PR_node1",
+ "isDraft": is_draft,
+ "state": state,
+ "labels": {"nodes": [{"name": name} for name in labels or []]},
+ "timelineItems": {"nodes": [{"__typename": "ReadyForReviewEvent"}] * draft_transitions},
+ }
+ }
+ }
+
+ def test_a_draft_is_undrafted_by_node_id(self):
+ # REST cannot undraft a pull request, so the mutation and the node id it needs are the whole
+ # feature: read the state, then mark ready with the id that read returned.
+ responses = [self._state(), {"markPullRequestReadyForReview": {"pullRequest": {"isDraft": False}}}]
+
+ with patch.object(GitHubIntegration, "_gh_graphql", side_effect=responses) as mock_graphql:
+ result = self._github().mark_pull_request_ready_for_review("acme/widgets", 7)
+
+ assert result == {"success": True, "changed": True}
+ mutation_call = mock_graphql.call_args_list[1]
+ assert mutation_call.args[1] == {"pullRequestId": "PR_node1"}
+ assert mutation_call.kwargs["retry_transient"] is False
+
+ @parameterized.expand(
+ [
+ ("already_ready", {"is_draft": False}, (), "not_draft"),
+ ("closed", {"state": "CLOSED"}, (), "closed"),
+ ("merged", {"state": "MERGED"}, (), "closed"),
+ ("skip_label", {"labels": ["No-CI"]}, ("no-ci",), "label"),
+ # A pull request somebody already moved between draft and ready keeps what they chose,
+ # however long a queued caller took to arrive.
+ ("draft_state_decided", {"draft_transitions": 1}, (), "draft_state_decided"),
+ ]
+ )
+ def test_nothing_is_mutated_when_a_guard_stops_it(self, _name, overrides, skip_labels, reason):
+ with patch.object(GitHubIntegration, "_gh_graphql", return_value=self._state(**overrides)) as mock_graphql:
+ result = self._github().mark_pull_request_ready_for_review("acme/widgets", 7, skip_labels=skip_labels)
+
+ assert result == {"success": True, "changed": False, "reason": reason}
+ mock_graphql.assert_called_once()
+
+ def test_an_unreadable_pull_request_reports_failure(self):
+ with patch.object(GitHubIntegration, "_gh_graphql", return_value={"repository": {"pullRequest": None}}):
+ result = self._github().mark_pull_request_ready_for_review("acme/widgets", 7)
+
+ assert result["success"] is False
+
+
class TestGitHubIntegrationPullRequestCiStatuses(BaseTest):
def _github(self) -> GitHubIntegration:
return GitHubIntegration(_create_github_integration(self.team))
diff --git a/products/signals/backend/migrations/0128_open_pull_request_ready_settings.py b/products/signals/backend/migrations/0128_open_pull_request_ready_settings.py
new file mode 100644
index 000000000000..4cd7cb3fcc8d
--- /dev/null
+++ b/products/signals/backend/migrations/0128_open_pull_request_ready_settings.py
@@ -0,0 +1,22 @@
+# Generated by Django 5.2.17 on 2026-09-10 18:04
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("signals", "0127_untrack_signalreport_conversation"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="signalteamconfig",
+ name="default_open_pull_request_ready",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ migrations.AddField(
+ model_name="signaluserautonomyconfig",
+ name="github_open_pull_request_ready",
+ field=models.BooleanField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 0f66021efe96..5a885b4d4d7c 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0127_untrack_signalreport_conversation
+0128_open_pull_request_ready_settings
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 3f346a24a9a6..0d0d0e0275e7 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -179,6 +179,9 @@ class SignalTeamConfig(ModelActivityMixin, UUIDModel):
related_name="+",
)
issue_tracking_config = models.JSONField(default=dict, db_default={}, blank=True)
+ # Off by default, because a ready pull request runs the full CI matrix on every push, which is
+ # runner spend a team has to choose. Read only for a reviewer with no preference of their own.
+ default_open_pull_request_ready = models.BooleanField(default=False, db_default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@@ -223,6 +226,10 @@ class SignalUserAutonomyConfig(UUIDModel):
# 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)
+ # Null follows `SignalTeamConfig.default_open_pull_request_ready`, because the right answer
+ # differs per person: a reviewer who reads their inbox pull requests anyway gains nothing from
+ # the draft state and pays a round trip for it.
+ github_open_pull_request_ready = models.BooleanField(null=True, blank=True)
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 820415bbb557..eb48f8f4294b 100644
--- a/products/signals/backend/report_assignments.py
+++ b/products/signals/backend/report_assignments.py
@@ -18,6 +18,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
+from products.signals.backend.reviewer_pr_ready import schedule_open_pull_request_ready
logger = structlog.get_logger(__name__)
@@ -299,6 +300,12 @@ def sync_task_pull_request_to_assignments(
pr_url=pr_url,
pr_state=assignment_state,
)
+ schedule_open_pull_request_ready(
+ team_id=team_id,
+ report_id=str(report_id),
+ pr_url=pr_url,
+ pr_state=assignment_state,
+ )
updated += 1
return updated
@@ -417,6 +424,12 @@ def claim_report(
pr_url=assignment.pr_url,
pr_state=assignment.pr_state,
)
+ schedule_open_pull_request_ready(
+ team_id=locked_report.team_id,
+ report_id=str(locked_report.id),
+ pr_url=assignment.pr_url,
+ pr_state=assignment.pr_state,
+ )
return assignment
@@ -487,5 +500,11 @@ def update_assignments_for_pull_request(
pr_url=assignment.pr_url,
pr_state=pr_state,
)
+ schedule_open_pull_request_ready(
+ 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_ready.py b/products/signals/backend/reviewer_pr_ready.py
new file mode 100644
index 000000000000..f993fdf0ae70
--- /dev/null
+++ b/products/signals/backend/reviewer_pr_ready.py
@@ -0,0 +1,226 @@
+"""Open a report's implementation pull request ready for review when a suggested reviewer asked for it.
+
+Every self-driving pull request opens as a draft, and a draft only runs a narrowed CI matrix, so a
+reviewer who wants to know whether the change is green has to mark it ready by hand and then wait
+for the full matrix to start from scratch. Draft stays the default, because a ready pull request
+runs the full matrix on every push and that is runner spend somebody has to choose. Opt-in through
+`SignalUserAutonomyConfig.github_open_pull_request_ready` over
+`SignalTeamConfig.default_open_pull_request_ready`, and best effort throughout: a GitHub failure
+must never break the claim, sync, or webhook that triggered it.
+"""
+
+from __future__ import annotations
+
+import json
+
+from django.db import transaction
+
+import structlog
+
+from posthog.models import User
+from posthog.models.integration import GitHubIntegration
+
+from products.signals.backend.models import (
+ SignalReport,
+ SignalReportArtefact,
+ SignalReportAssignment,
+ SignalTeamConfig,
+ SignalUserAutonomyConfig,
+)
+from products.signals.backend.report_generation.resolve_reviewers import (
+ normalized_github_logins_from_reviewer_payloads,
+ resolve_org_github_login_to_users,
+ resolve_org_users_by_uuid,
+)
+
+logger = structlog.get_logger(__name__)
+
+# A draft carrying this label is an explicit "do not spend runners on this", so marking it ready
+# would override the clearer instruction. The label is a repository convention, so a repository that
+# does not use it simply never matches.
+SKIP_READY_LABELS = frozenset({"no-ci"})
+
+# Only a pull request that could still be a draft is worth a GitHub call. UNKNOWN is included
+# because a row that never recorded a state is far more often a live pull request than a closed one,
+# and the task re-reads the real draft state from GitHub before it marks anything ready.
+FLIPPABLE_PR_STATES = frozenset(
+ {
+ SignalReportAssignment.PrState.DRAFT,
+ SignalReportAssignment.PrState.UNKNOWN,
+ }
+)
+
+
+def schedule_open_pull_request_ready(
+ *,
+ team_id: int,
+ report_id: str,
+ pr_url: str | None,
+ pr_state: str | None,
+) -> None:
+ """Queue the ready-for-review transition for a report's pull request, after the current commit.
+
+ Only the paths where a pull request first reaches a report call this, so no later event re-queues
+ it. The worker guards the rest: a pull request whose draft state a person has already moved is
+ left alone, which is what holds even when this job sits in a backlog behind them.
+
+ Enqueued on commit so nothing is marked ready if the write rolls back, and so the GitHub calls
+ run on a worker instead of holding up a claim or a webhook. `robust=True` keeps a broker outage
+ from failing a write that already committed.
+ """
+ if not pr_url or (pr_state or SignalReportAssignment.PrState.UNKNOWN) not in FLIPPABLE_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 open_implementation_pr_for_review # noqa: PLC0415
+
+ transaction.on_commit(
+ lambda: open_implementation_pr_for_review.delay(
+ team_id=team_id,
+ report_id=str(report_id),
+ pr_url=pr_url,
+ ),
+ robust=True,
+ )
+
+
+def _resolved_reviewer_users(*, team_id: int, report_id: str) -> list[User]:
+ """The report's current suggested reviewers that resolve to a PostHog user in this team's org.
+
+ Reads only the latest `suggested_reviewers` row, which is the live reviewer set, so a reviewer
+ removed from the list no longer decides anything.
+ """
+ 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 []
+ reviewer_rows = [row for row in payloads if isinstance(row, dict)]
+
+ # A reviewer is a PostHog user, not a GitHub account: an org member who never connected GitHub is
+ # stored by uuid with a null login, and reviewer identity gives the uuid precedence over a login
+ # that could since have been reassigned. Resolving logins alone would drop the first group and
+ # silently fall back to the team default for them.
+ uuid_to_user = resolve_org_users_by_uuid(
+ team_id, (str(row["user_uuid"]) for row in reviewer_rows if row.get("user_uuid"))
+ )
+ login_to_user = resolve_org_github_login_to_users(
+ team_id,
+ normalized_github_logins_from_reviewer_payloads(row for row in reviewer_rows if not row.get("user_uuid")),
+ )
+
+ # A union rather than a per-row walk: this answers one yes/no question over the whole reviewer
+ # set, so reviewer order carries nothing, and taking the resolvers' own output avoids matching a
+ # stored uuid against a live one by hand.
+ return list({user.id: user for user in (*uuid_to_user.values(), *login_to_user.values())}.values())
+
+
+def should_open_pull_request_ready(*, team_id: int, report_id: str) -> bool:
+ """Whether this report's pull request should open ready for review rather than draft.
+
+ Resolved per suggested reviewer, using their own setting and falling back to the team default,
+ then unioned, since one reviewer wanting the full CI matrix is not in conflict with another
+ reviewer's preference. A team that turned the default on gets it for reports whose reviewers
+ resolve to no PostHog user either, because that setting means "our self-driving pull requests
+ open ready".
+ """
+ team_default = bool(
+ SignalTeamConfig.objects.filter(team_id=team_id)
+ .values_list("default_open_pull_request_ready", flat=True)
+ .first()
+ )
+
+ users = _resolved_reviewer_users(team_id=team_id, report_id=report_id)
+ if not users:
+ return team_default
+
+ preferences = dict(
+ SignalUserAutonomyConfig.objects.filter(user_id__in={user.id for user in users}).values_list(
+ "user_id", "github_open_pull_request_ready"
+ )
+ )
+
+ def resolved_for(user: User) -> bool:
+ preference = preferences.get(user.id)
+ return team_default if preference is None else preference
+
+ return any(resolved_for(user) for user in users)
+
+
+def open_pull_request_ready_for_review(*, team_id: int, report_id: str, pr_url: str) -> bool:
+ """Take the report's pull request out of draft when its reviewers asked for that. Returns whether it moved.
+
+ Returns False when there was nothing to do, which covers nobody opting in and a pull request
+ that is already ready, closed, or labelled `no-ci`. A failed call also returns False, and this
+ raises nothing.
+ """
+ if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():
+ return False
+
+ if not should_open_pull_request_ready(team_id=team_id, report_id=report_id):
+ return False
+
+ parsed = GitHubIntegration.parse_pull_request_url(pr_url)
+ if parsed is None:
+ return False
+
+ try:
+ github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
+ except Exception:
+ logger.exception(
+ "signals.reviewer_pr_ready.integration_lookup_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ )
+ return False
+ if github is None:
+ return False
+
+ try:
+ result = github.mark_pull_request_ready_for_review(
+ parsed.repository, parsed.number, skip_labels=SKIP_READY_LABELS
+ )
+ except Exception:
+ logger.exception(
+ "signals.reviewer_pr_ready.mark_ready_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ )
+ return False
+ if not result.get("success"):
+ logger.warning(
+ "signals.reviewer_pr_ready.mark_ready_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ error=result.get("error"),
+ )
+ return False
+
+ changed = bool(result.get("changed"))
+ logger.info(
+ "signals.reviewer_pr_ready.evaluated",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ changed=changed,
+ reason=result.get("reason"),
+ )
+ return changed
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index dc3aa542cbd6..aac86822f05d 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -294,6 +294,14 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
"pause until local midnight. Null means unlimited."
),
)
+ default_open_pull_request_ready = serializers.BooleanField(
+ required=False,
+ help_text=(
+ "Whether self-driving pull requests open ready for review instead of draft, so the full CI "
+ "matrix starts when the pull request is created. False by default. A reviewer's own "
+ "github_open_pull_request_ready overrides this for reports that suggest them as reviewer."
+ ),
+ )
reports_generated_today = serializers.SerializerMethodField(
help_text=(
"How many reports first became visible in the inbox during the current project-timezone "
@@ -341,6 +349,7 @@ class SignalTeamConfigSerializer(serializers.ModelSerializer):
"issue_tracking_integration",
"issue_tracking_config",
"max_reports_per_day",
+ "default_open_pull_request_ready",
"reports_generated_today",
"daily_report_limit_reached",
"created_at",
@@ -480,6 +489,7 @@ class SignalUserAutonomyConfigSerializer(serializers.ModelSerializer):
"slack_notification_channel",
"slack_notification_min_priority",
"github_assign_on_pull_request",
+ "github_open_pull_request_ready",
"created_at",
"updated_at",
]
@@ -505,6 +515,14 @@ class SignalUserAutonomyConfigSerializer(serializers.ModelSerializer):
"turning it off never removes an assignee from a pull request that already has one."
)
},
+ "github_open_pull_request_ready": {
+ "help_text": (
+ "Whether implementation pull requests for reports that suggest this user as reviewer "
+ "open ready for review instead of draft, so the full CI matrix starts right away. "
+ "Null follows the project's default_open_pull_request_ready. Applies only when the "
+ "pull request is created; a pull request somebody converts back to draft stays draft."
+ )
+ },
}
@@ -554,6 +572,15 @@ class SignalUserAutonomyConfigCreateSerializer(serializers.Serializer):
"never removes an existing assignee."
),
)
+ github_open_pull_request_ready = serializers.BooleanField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "Open implementation pull requests for reports that suggest this user as reviewer ready "
+ "for review instead of draft, so the full CI matrix runs without anybody clicking Ready. "
+ "Null follows the project default. A ready pull request runs the full matrix on every push."
+ ),
+ )
def validate(self, attrs: dict) -> dict:
if attrs.get("slack_notification_direct_message") and attrs.get("slack_notification_channel"):
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index bd3013178aca..62f5738fd49b 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -38,6 +38,7 @@ from products.signals.backend.report_generation.repo_activity import (
repository_activity_needs_rebuild,
)
from products.signals.backend.reviewer_pr_assignment import assign_reviewers_to_pull_request
+from products.signals.backend.reviewer_pr_ready import open_pull_request_ready_for_review
from products.signals.backend.scout_harness.inactivity import sweep_inactive_scouts
from products.signals.backend.scout_harness.slack_delivery import (
DELIVERABLE_REPORT_STATUSES,
@@ -408,6 +409,22 @@ def assign_reviewers_on_implementation_pr(team_id: int, report_id: str, pr_url:
assign_reviewers_to_pull_request(team_id=team_id, report_id=report_id, pr_url=pr_url)
+@shared_task(
+ name="products.signals.backend.tasks.open_implementation_pr_for_review",
+ ignore_result=True,
+ max_retries=0,
+)
+@with_team_scope()
+def open_implementation_pr_for_review(team_id: int, report_id: str, pr_url: str) -> None:
+ """Take a report's implementation PR out of draft when its suggested reviewers asked for that.
+
+ Runs on a worker for the same reason as reviewer assignment: the GitHub calls must not hold up
+ the claim, sync, or webhook that queued it. Best-effort end to end, so this never retries.
+ Unlike assignment, a retry could also fight a reviewer who redrafted the pull request in between.
+ """
+ open_pull_request_ready_for_review(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_ready.py b/products/signals/backend/test/test_reviewer_pr_ready.py
new file mode 100644
index 000000000000..f31eafb344f5
--- /dev/null
+++ b/products/signals/backend/test/test_reviewer_pr_ready.py
@@ -0,0 +1,388 @@
+import json
+
+import pytest
+from posthog.test.base import APIBaseTest
+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,
+ SignalTeamConfig,
+ 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_ready import (
+ open_pull_request_ready_for_review,
+ schedule_open_pull_request_ready,
+ should_open_pull_request_ready,
+)
+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-ready-org")
+ team = Team.objects.create(organization=org, name="pr-ready-team")
+ yield org, team
+ team.delete()
+ org.delete()
+
+
+def _make_reviewer(org: Organization, login: str, *, wants_ready: bool | None) -> 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_open_pull_request_ready=wants_ready)
+ return user
+
+
+def _make_member_without_github(org: Organization, *, wants_ready: bool | None) -> User:
+ user = User.objects.create(email="[email protected]", first_name="Reviewer")
+ OrganizationMembership.objects.create(user=user, organization=org)
+ SignalUserAutonomyConfig.objects.create(user=user, github_open_pull_request_ready=wants_ready)
+ return user
+
+
+def _make_report_with_payloads(team: Team, payloads: list[dict]) -> SignalReport:
+ report = SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, title="Report", summary="Summary", signal_count=1, total_weight=1.0
+ )
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps(payloads),
+ )
+ return report
+
+
+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 _set_team_default(team: Team, value: bool) -> None:
+ SignalTeamConfig.objects.update_or_create(team=team, defaults={"default_open_pull_request_ready": value})
+
+
+def _draft_pr_github() -> MagicMock:
+ github = MagicMock()
+ github.mark_pull_request_ready_for_review.return_value = {"success": True, "changed": True}
+ return github
+
+
+class TestShouldOpenPullRequestReady:
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ ("preferences", "team_default", "expected"),
+ [
+ ([True], False, True),
+ ([False], False, False),
+ ([None], False, False),
+ ([None], True, True),
+ # One reviewer wanting the full CI matrix does not conflict with another's preference.
+ ([True, False], False, True),
+ ([False], True, False),
+ ([True, None], False, True),
+ ],
+ ids=["opted_in", "opted_out", "inherits_off", "inherits_on", "mixed", "overrides_team_on", "one_of_two"],
+ )
+ def test_the_reviewer_setting_wins_over_the_team_default(
+ self, org_and_team, preferences: list[bool | None], team_default: bool, expected: bool
+ ):
+ org, team = org_and_team
+ _set_team_default(team, team_default)
+ logins = []
+ for index, preference in enumerate(preferences):
+ login = f"reviewer{index}"
+ _make_reviewer(org, login, wants_ready=preference)
+ logins.append(login)
+ report = _make_report(team, logins)
+
+ assert should_open_pull_request_ready(team_id=team.id, report_id=str(report.id)) is expected
+
+ @pytest.mark.django_db
+ def test_a_reviewer_without_a_config_row_follows_the_team_default(self, org_and_team):
+ org, team = org_and_team
+ _set_team_default(team, True)
+ 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 should_open_pull_request_ready(team_id=team.id, report_id=str(report.id)) is True
+
+ @pytest.mark.django_db
+ def test_a_reviewer_dropped_from_the_latest_row_no_longer_decides(self, org_and_team):
+ org, team = org_and_team
+ _make_reviewer(org, "removed", wants_ready=True)
+ _make_reviewer(org, "kept", wants_ready=None)
+ # suggested_reviewers is append-only and latest-wins, so only the newest row is live.
+ report = _make_report(team, ["removed", "kept"], ["kept"])
+
+ assert should_open_pull_request_ready(team_id=team.id, report_id=str(report.id)) is False
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize("team_default", [True, False])
+ def test_a_report_with_no_resolvable_reviewer_follows_the_team_default(self, org_and_team, team_default: bool):
+ _, team = org_and_team
+ _set_team_default(team, team_default)
+ report = _make_report(team, ["nobody-we-know"])
+
+ assert should_open_pull_request_ready(team_id=team.id, report_id=str(report.id)) is team_default
+
+ @pytest.mark.django_db
+ def test_a_team_that_never_touched_the_setting_stays_on_draft(self, org_and_team):
+ org, team = org_and_team
+ _make_reviewer(org, "inheriting", wants_ready=None)
+ report = _make_report(team, ["inheriting"])
+
+ assert should_open_pull_request_ready(team_id=team.id, report_id=str(report.id)) is False
+
+
+class TestReviewersWithoutAGithubAccount:
+ @pytest.mark.django_db
+ def test_a_reviewer_stored_by_uuid_still_decides(self, org_and_team):
+ # An org member who never connected GitHub is stored by uuid with a null login, so resolving
+ # logins alone would drop them and silently fall back to the team default.
+ org, team = org_and_team
+ user = _make_member_without_github(org, wants_ready=True)
+ report = _make_report_with_payloads(team, [{"user_uuid": str(user.uuid), "github_login": None}])
+
+ assert should_open_pull_request_ready(team_id=team.id, report_id=str(report.id)) is True
+
+ @pytest.mark.django_db
+ def test_a_uuid_entry_does_not_pick_up_the_preference_behind_its_stale_login(self, org_and_team):
+ # Reviewer identity gives the uuid precedence, so a login that has since been reassigned to
+ # somebody else must not lend that person's preference to this entry.
+ org, team = org_and_team
+ opted_out = _make_member_without_github(org, wants_ready=False)
+ _make_reviewer(org, "reassigned", wants_ready=True)
+ report = _make_report_with_payloads(team, [{"user_uuid": str(opted_out.uuid), "github_login": "reassigned"}])
+
+ assert should_open_pull_request_ready(team_id=team.id, report_id=str(report.id)) is False
+
+
+class TestOpenPullRequestReadyForReview:
+ @pytest.mark.django_db
+ def test_an_opted_in_reviewer_marks_the_pull_request_ready(self, org_and_team):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-in", wants_ready=True)
+ report = _make_report(team, ["opted-in"])
+ github = _draft_pr_github()
+
+ with patch(
+ "products.signals.backend.reviewer_pr_ready.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assert open_pull_request_ready_for_review(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) is True
+
+ # `no-ci` has to reach GitHub as a guard, not be resolved after the PR is out of draft.
+ github.mark_pull_request_ready_for_review.assert_called_once_with(
+ "PostHog/posthog", 123, skip_labels=frozenset({"no-ci"})
+ )
+
+ @pytest.mark.django_db
+ def test_no_opted_in_reviewer_skips_github_entirely(self, org_and_team):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-out", wants_ready=False)
+ report = _make_report(team, ["opted-out"])
+
+ with patch(
+ "products.signals.backend.reviewer_pr_ready.GitHubIntegration.first_for_team_repository"
+ ) as mock_lookup:
+ assert open_pull_request_ready_for_review(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) is False
+ mock_lookup.assert_not_called()
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ "outcome",
+ [
+ Exception("boom"),
+ {"success": False, "error": "Failed to mark pull request ready"},
+ {"success": True, "changed": False, "reason": "label"},
+ ],
+ ids=["raises", "reports_failure", "guard_stopped_it"],
+ )
+ def test_a_github_failure_or_guard_is_swallowed(self, org_and_team, outcome: object):
+ org, team = org_and_team
+ _make_reviewer(org, "opted-in", wants_ready=True)
+ report = _make_report(team, ["opted-in"])
+ github = _draft_pr_github()
+ if isinstance(outcome, Exception):
+ github.mark_pull_request_ready_for_review.side_effect = outcome
+ else:
+ github.mark_pull_request_ready_for_review.return_value = outcome
+
+ with patch(
+ "products.signals.backend.reviewer_pr_ready.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assert open_pull_request_ready_for_review(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) is False
+
+ @pytest.mark.django_db
+ def test_a_report_from_another_team_is_not_touched(self, org_and_team):
+ org, team = org_and_team
+ other_team = Team.objects.create(organization=org, name="other-team")
+ _make_reviewer(org, "opted-in", wants_ready=True)
+ report = _make_report(other_team, ["opted-in"])
+
+ with patch(
+ "products.signals.backend.reviewer_pr_ready.GitHubIntegration.first_for_team_repository"
+ ) as mock_lookup:
+ assert open_pull_request_ready_for_review(team_id=team.id, report_id=str(report.id), pr_url=PR_URL) is False
+ mock_lookup.assert_not_called()
+
+
+class TestScheduleOpenPullRequestReady:
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ ("pr_url", "pr_state", "expected"),
+ [
+ (PR_URL, SignalReportAssignment.PrState.DRAFT, True),
+ (PR_URL, SignalReportAssignment.PrState.UNKNOWN, True),
+ (PR_URL, None, True),
+ # Nothing to undraft, so no GitHub round trip is worth queuing.
+ (PR_URL, SignalReportAssignment.PrState.OPEN, False),
+ (PR_URL, SignalReportAssignment.PrState.CLOSED, False),
+ (PR_URL, SignalReportAssignment.PrState.MERGED, False),
+ (None, SignalReportAssignment.PrState.DRAFT, False),
+ ],
+ )
+ def test_only_a_pull_request_that_could_be_a_draft_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.open_implementation_pr_for_review.delay") as mock_delay:
+ schedule_open_pull_request_ready(
+ team_id=team.id, report_id=str(report.id), pr_url=pr_url, pr_state=pr_state
+ )
+
+ assert mock_delay.called is expected
+
+
+class TestPullRequestLinkingQueuesTheReadyTransition:
+ """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. These are also what keeps
+ the transition to once per pull request: nothing re-queues it after the link is recorded, so a
+ reviewer who converts the pull request back to draft is never overridden."""
+
+ @pytest.fixture(autouse=True)
+ def _queued(self):
+ with patch("products.signals.backend.tasks.open_implementation_pr_for_review.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_it_once(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,
+ )
+
+ 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_syncing_a_task_pull_request_queues_it_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="draft"
+ )
+
+ 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_webhook_that_first_links_the_pull_request_queues_it(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.DRAFT,
+ )
+
+ self.mock_delay.assert_called_once_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
+
+
+class TestOpenPullRequestReadyAPI(APIBaseTest):
+ ENDPOINT = "/api/users/@me/signal_autonomy/"
+
+ def test_the_setting_round_trips_back_to_following_the_project_default(self):
+ # The partial update is hand-rolled per field, so clearing the override has to store null
+ # rather than false: false opts the reviewer out of a project default they wanted.
+ assert self.client.post(self.ENDPOINT, {"github_open_pull_request_ready": True}).status_code == 200
+ assert SignalUserAutonomyConfig.objects.get(user=self.user).github_open_pull_request_ready is True
+
+ response = self.client.post(self.ENDPOINT, {"github_open_pull_request_ready": None})
+
+ assert response.status_code == 200
+ assert response.json()["github_open_pull_request_ready"] is None
+ assert SignalUserAutonomyConfig.objects.get(user=self.user).github_open_pull_request_ready is None
+
+ def test_another_setting_does_not_wipe_it(self):
+ self.client.post(self.ENDPOINT, {"github_open_pull_request_ready": True})
+
+ self.client.post(self.ENDPOINT, {"github_assign_on_pull_request": True})
+
+ assert SignalUserAutonomyConfig.objects.get(user=self.user).github_open_pull_request_ready is True
diff --git a/products/signals/backend/test/test_signal_team_config_api.py b/products/signals/backend/test/test_signal_team_config_api.py
index ba9b81810cb3..a7877014116b 100644
--- a/products/signals/backend/test/test_signal_team_config_api.py
+++ b/products/signals/backend/test/test_signal_team_config_api.py
@@ -243,6 +243,15 @@ class TestSignalTeamConfigAPI(APIBaseTest):
None,
{"acme/web": "staging"},
),
+ (
+ "pr_state",
+ "default_open_pull_request_ready",
+ True,
+ "PRs open as",
+ "changed",
+ False,
+ True,
+ ),
]
)
def test_update_is_recorded_in_the_activity_log(self, _name, field, sent, label, action, before, after):
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 8f51c5a29d26..8931e8b7912e 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -4690,6 +4690,8 @@ class SignalUserAutonomyConfigView(APIView):
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 "github_open_pull_request_ready" in serializer.initial_data:
+ defaults["github_open_pull_request_ready"] = validated.get("github_open_pull_request_ready")
if "slack_notification_channel" in serializer.initial_data:
defaults["slack_notification_channel"] = validated.get("slack_notification_channel") or None
integration_in_request = "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 cc4f710bd0d0..2a275d2c41dc 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4466,6 +4466,11 @@ export interface SignalUserAutonomyConfigApi {
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
+ /**
+ * Whether implementation pull requests for reports that suggest this user as reviewer open ready for review instead of draft, so the full CI matrix starts right away. Null follows the project's default_open_pull_request_ready. Applies only when the pull request is created; a pull request somebody converts back to draft stays draft.
+ * @nullable
+ */
+ github_open_pull_request_ready?: boolean | null
readonly created_at: string
readonly updated_at: string
}
@@ -4495,6 +4500,11 @@ export interface SignalUserAutonomyConfigCreateApi {
slack_notification_min_priority?: AutonomyPriorityEnumApi | null
/** 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. */
github_assign_on_pull_request?: boolean
+ /**
+ * Open implementation pull requests for reports that suggest this user as reviewer ready for review instead of draft, so the full CI matrix runs without anybody clicking Ready. Null follows the project default. A ready pull request runs the full matrix on every push.
+ * @nullable
+ */
+ github_open_pull_request_ready?: boolean | null
}
export type SignalsProcessingListParams = {
diff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.ts
index 09fe00da7030..59fa46c85d33 100644
--- a/products/signals/frontend/generated/api.zod.ts
+++ b/products/signals/frontend/generated/api.zod.ts
@@ -1925,4 +1925,10 @@ export const UsersSignalAutonomyCreateBody = /* @__PURE__ */ zod.object({
.describe(
'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.'
),
+ github_open_pull_request_ready: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Open implementation pull requests for reports that suggest this user as reviewer ready for review instead of draft, so the full CI matrix runs without anybody clicking Ready. Null follows the project default. A ready pull request runs the full matrix on every push.'
+ ),
})
diff --git a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
index f3ece6cd4858..dc5d421b5224 100644
--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.stories.tsx
@@ -19,6 +19,10 @@ interface CardState {
reportsToday?: number
/** Personal opt-in to being added as a GitHub assignee on the implementation PR. */
githubAssign?: boolean
+ /** Whether the project opens self-driving PRs ready for review instead of draft. */
+ projectPrReady?: boolean
+ /** Personal override for that, or null to follow the project ("Default"). */
+ myPrReady?: boolean | null
/** Connected integrations the issue tracker picker can choose from. */
integrations?: Record<string, unknown>[]
/** Integration id the project already tracks issues in, and where inside it they land. */
@@ -35,6 +39,8 @@ function Card({
dailyLimit = null,
reportsToday = 0,
githubAssign = false,
+ projectPrReady = false,
+ myPrReady = null,
integrations = [],
issueTrackingIntegration = null,
issueTrackingConfig = {},
@@ -51,6 +57,7 @@ function Card({
max_reports_per_day: dailyLimit,
reports_generated_today: reportsToday,
daily_report_limit_reached: dailyLimit != null && reportsToday >= dailyLimit,
+ default_open_pull_request_ready: projectPrReady,
},
'/api/users/@me/signal_autonomy/': {
id: 'auto-1',
@@ -58,6 +65,7 @@ function Card({
slack_notification_channel: null,
slack_notification_min_priority: null,
github_assign_on_pull_request: githubAssign,
+ github_open_pull_request_ready: myPrReady,
},
'/api/projects/:team_id/integrations/': { results: integrations },
},
@@ -110,6 +118,11 @@ export const GitHubAssignmentOn: Story = {
render: () => <Card githubAssign />,
}
+// A reviewer who opted into the full CI matrix inside a project that still defaults to draft.
+export const PullRequestReadyForReview: Story = {
+ render: () => <Card myPrReady />,
+}
+
// 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 3501ceebce5e..2cf380bddc52 100644
--- a/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
+++ b/products/signals/frontend/inbox/components/config/SelfDrivingSection.tsx
@@ -57,6 +57,13 @@ const THRESHOLD_SEGMENTS = PRIORITY_THRESHOLD_OPTIONS.map(({ value }) => ({
const MY_THRESHOLD_DEFAULT_VALUE = '__default__'
const MY_THRESHOLD_SEGMENTS = [{ value: MY_THRESHOLD_DEFAULT_VALUE, label: 'Default' }, ...THRESHOLD_SEGMENTS]
+const PR_STATE_SEGMENTS = [
+ { value: 'draft', label: 'Draft' },
+ { value: 'ready', label: 'Ready for review' },
+]
+const MY_PR_STATE_DEFAULT_VALUE = '__default__'
+const MY_PR_STATE_SEGMENTS = [{ value: MY_PR_STATE_DEFAULT_VALUE, label: 'Default' }, ...PR_STATE_SEGMENTS]
+
function BaseBranchOverrideRows(): JSX.Element | null {
const { baseBranchOverrides, teamConfigUpdating } = useValues(signalTeamConfigLogic)
const { updateBaseBranchOverride, removeBaseBranchOverride } = useActions(signalTeamConfigLogic)
@@ -520,6 +527,67 @@ function GitHubAssignmentRow(): JSX.Element {
)
}
+/**
+ * Whether self-driving PRs skip the draft state. Draft stays the default because a ready PR runs
+ * the full CI matrix on every push, and the personal control overrides the project one because one
+ * reviewer's workflow differs from their teammate's. Renders regardless of the auto-start toggle:
+ * a PR opened by hand from the inbox goes through the same transition.
+ */
+function PullRequestStateRows(): JSX.Element {
+ const { defaultOpenPullRequestReady, teamConfigUpdating } = useValues(signalTeamConfigLogic)
+ const { patchTeamConfig } = useActions(signalTeamConfigLogic)
+ const { autonomyConfig, autonomyConfigLoading, openPullRequestReadyUpdating } = useValues(userAutonomyLogic)
+ const { setOpenPullRequestReady } = useActions(userAutonomyLogic)
+
+ const mine = autonomyConfig?.github_open_pull_request_ready
+ const myState = mine == null ? MY_PR_STATE_DEFAULT_VALUE : mine ? 'ready' : 'draft'
+
+ return (
+ <div className="flex flex-col gap-2 px-2.5 py-1.5">
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-secondary">Self-driving PRs open as</span>
+ <LemonSegmentedButton
+ size="xsmall"
+ fullWidth
+ className="max-w-xs"
+ value={defaultOpenPullRequestReady ? 'ready' : 'draft'}
+ options={PR_STATE_SEGMENTS}
+ disabledReason={teamConfigUpdating ? 'Saving changes' : undefined}
+ onChange={(next) => patchTeamConfig({ default_open_pull_request_ready: next === 'ready' })}
+ />
+ <p className="text-[11px] text-tertiary leading-snug mb-0">
+ Ready for review can run more checks and request reviews. Your repository settings control these
+ actions. Draft lets your team inspect the change first.
+ </p>
+ </div>
+ <div className="flex flex-col gap-1">
+ <span className="text-xs text-secondary">PRs for my review open as</span>
+ <LemonSegmentedButton
+ size="xsmall"
+ fullWidth
+ className="max-w-xs"
+ value={myState}
+ options={MY_PR_STATE_SEGMENTS}
+ disabledReason={
+ openPullRequestReadyUpdating
+ ? 'Saving changes'
+ : autonomyConfigLoading && autonomyConfig === null
+ ? 'Loading settings'
+ : undefined
+ }
+ onChange={(next) =>
+ setOpenPullRequestReady(next === MY_PR_STATE_DEFAULT_VALUE ? null : next === 'ready')
+ }
+ />
+ <p className="text-[11px] text-tertiary leading-snug mb-0">
+ This choice applies to all projects where reports suggest you as a reviewer. It overrides each
+ project setting. A PR stays in draft if someone moves it back to draft.
+ </p>
+ </div>
+ </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;
@@ -624,6 +692,9 @@ export function SelfDrivingSection(): JSX.Element {
Reports still arrive and notify your team.
</p>
)}
+ <div className="border-t border-primary">
+ <PullRequestStateRows />
+ </div>
<div className="border-t border-primary">
<GitHubAssignmentRow />
</div>
diff --git a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
index 82193663e44d..e120c382ef42 100644
--- a/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
+++ b/products/signals/frontend/inbox/logics/signalTeamConfigLogic.ts
@@ -29,6 +29,7 @@ export interface signalTeamConfigLogicValues {
baseBranchOverrides: BaseBranchOverride[]
dailyReportLimitReached: boolean
defaultAutostartPriority: SignalReportPriority
+ defaultOpenPullRequestReady: boolean
draftBaseBranchBranch: string
draftBaseBranchIntegrationId: number | null
draftBaseBranchRepo: string
@@ -133,6 +134,7 @@ export interface signalTeamConfigLogicMeta {
defaultAutostartPriority: (teamConfig: SignalTeamConfig | null) => SignalReportPriority
baseBranchOverrides: (teamConfig: SignalTeamConfig | null) => BaseBranchOverride[]
maxReportsPerDay: (teamConfig: SignalTeamConfig | null) => number | null
+ defaultOpenPullRequestReady: (teamConfig: SignalTeamConfig | null) => boolean
issueTrackerIntegrationId: (teamConfig: SignalTeamConfig | null) => number | null
issueTrackerConfig: (teamConfig: SignalTeamConfig | null) => Record<string, string>
selectedIssueTrackerIntegrationId: (
@@ -312,6 +314,10 @@ export const signalTeamConfigLogic = kea<signalTeamConfigLogicType>([
(s) => [s.teamConfig],
(teamConfig: SignalTeamConfig | null): number | null => teamConfig?.max_reports_per_day ?? null,
],
+ defaultOpenPullRequestReady: [
+ (s) => [s.teamConfig],
+ (teamConfig: SignalTeamConfig | null): boolean => teamConfig?.default_open_pull_request_ready ?? false,
+ ],
issueTrackerIntegrationId: [
(s) => [s.teamConfig],
(teamConfig: SignalTeamConfig | null): number | null => teamConfig?.issue_tracking_integration ?? null,
diff --git a/products/signals/frontend/inbox/logics/userAutonomyLogic.ts b/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
index 735811d4461b..a2c634bea4a7 100644
--- a/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
+++ b/products/signals/frontend/inbox/logics/userAutonomyLogic.ts
@@ -86,6 +86,7 @@ export interface userAutonomyLogicValues {
autonomyConfigLoading: boolean
autostartPriorityUpdating: boolean
githubAssignUpdating: boolean
+ openPullRequestReadyUpdating: boolean
slackNotificationsSaving: boolean
slackPickersExpanded: boolean
}
@@ -113,12 +114,18 @@ export interface userAutonomyLogicActions {
autonomyConfig: SignalUserAutonomyConfig | null
payload?: any
}
+ openPullRequestReadySettled: () => {
+ value: true
+ }
setAutostartPriority: (priority: SignalReportPriority | null) => {
priority: SignalReportPriority | null
}
setGithubAssignOnPullRequest: (enabled: boolean) => {
enabled: boolean
}
+ setOpenPullRequestReady: (ready: boolean | null) => {
+ ready: boolean | null
+ }
setSlackPickersExpanded: (expanded: boolean) => {
expanded: boolean
}
@@ -137,8 +144,9 @@ export type userAutonomyLogicType = MakeLogicType<userAutonomyLogicValues, userA
* 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.
+ * `_effective_threshold`); the Slack notification destination; whether to add
+ * this user as a GitHub assignee on the implementation PR; and whether that PR opens
+ * ready for review instead of draft, which also inherits the team default when `null`.
*/
export const userAutonomyLogic = kea<userAutonomyLogicType>([
path(['scenes', 'inbox', 'logics', 'userAutonomyLogic']),
@@ -157,6 +165,12 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
setGithubAssignOnPullRequest: (enabled: boolean) => ({ enabled }),
// Fires when the GitHub assignment POST settles, releasing the switch's save guard.
githubAssignSettled: true,
+ // Whether PRs for reports suggesting this user open ready for review. Null follows the
+ // project default rather than pinning an answer, so a project that changes its mind moves
+ // this user with it.
+ setOpenPullRequestReady: (ready: boolean | null) => ({ ready }),
+ // Fires when the ready-for-review POST settles, releasing that control's save guard.
+ openPullRequestReadySettled: 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 }),
@@ -183,6 +197,10 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
...(state ?? { autostart_priority: null }),
github_assign_on_pull_request: enabled,
}),
+ setOpenPullRequestReady: (state, { ready }) => ({
+ ...(state ?? { autostart_priority: null }),
+ github_open_pull_request_ready: ready,
+ }),
updateSlackNotifications: (state, { updates }) => ({
...(state ?? { autostart_priority: null }),
...('integrationId' in updates
@@ -211,6 +229,14 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
githubAssignSettled: () => false,
},
],
+ // Same guard again: the control stays disabled for the whole save window.
+ openPullRequestReadyUpdating: [
+ false,
+ {
+ setOpenPullRequestReady: () => true,
+ openPullRequestReadySettled: () => false,
+ },
+ ],
// Covers the POST itself, which `autonomyConfigLoading` only reflects once it resolves.
slackNotificationsSaving: [
false,
@@ -263,6 +289,24 @@ export const userAutonomyLogic = kea<userAutonomyLogicType>([
actions.loadAutonomyConfig()
}
},
+ setOpenPullRequestReady: async ({ ready }) => {
+ let success = true
+ try {
+ await api.signalUserAutonomy.update({ github_open_pull_request_ready: ready })
+ } catch (error: any) {
+ success = false
+ lemonToast.error(error?.detail ?? error?.message ?? 'Failed to update pull request state setting')
+ } finally {
+ actions.openPullRequestReadySettled()
+ captureInboxSettingsChanged({
+ setting: 'github_open_pull_request_ready',
+ newValue: ready,
+ success,
+ scope: 'user',
+ })
+ actions.loadAutonomyConfig()
+ }
+ },
updateSlackNotifications: async ({ updates }) => {
const body = slackNotificationBody(updates)
let success = true
diff --git a/products/signals/frontend/inbox/types.ts b/products/signals/frontend/inbox/types.ts
index fa4bd7b21eb7..c8154b85353b 100644
--- a/products/signals/frontend/inbox/types.ts
+++ b/products/signals/frontend/inbox/types.ts
@@ -381,6 +381,8 @@ export interface SignalUserAutonomyConfig {
slack_notification_channel?: string | null
slack_notification_min_priority?: SignalReportPriority | null
github_assign_on_pull_request?: boolean
+ /** Whether PRs for reports suggesting this user open ready for review. Null follows the project default. */
+ github_open_pull_request_ready?: boolean | null
created_at?: string
updated_at?: string
}
@@ -403,6 +405,8 @@ export interface SignalTeamConfig {
issue_tracking_config?: Record<string, string>
/** Daily cap on new reports surfacing to the inbox (project-timezone day). Null means unlimited. */
max_reports_per_day?: number | null
+ /** Whether self-driving PRs open ready for review instead of draft. A reviewer's own setting overrides it. */
+ default_open_pull_request_ready?: boolean
/** Read-only: reports that first became visible today (project timezone). Never send in a patch. */
reports_generated_today?: number
/** Read-only: whether the daily report limit is reached, pausing new report generation until local midnight. Never send in a patch. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f50c39be4c98..361163dffa72 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -80568,6 +80568,11 @@ export namespace Schemas {
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;
+ /**
+ * Whether implementation pull requests for reports that suggest this user as reviewer open ready for review instead of draft, so the full CI matrix starts right away. Null follows the project's default_open_pull_request_ready. Applies only when the pull request is created; a pull request somebody converts back to draft stays draft.
+ * @nullable
+ */
+ github_open_pull_request_ready?: boolean | null;
readonly created_at: string;
readonly updated_at: string;
}
@@ -80597,6 +80602,11 @@ export namespace Schemas {
slack_notification_min_priority?: AutonomyPriorityEnum | null;
/** 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. */
github_assign_on_pull_request?: boolean;
+ /**
+ * Open implementation pull requests for reports that suggest this user as reviewer ready for review instead of draft, so the full CI matrix runs without anybody clicking Ready. Null follows the project default. A ready pull request runs the full matrix on every push.
+ * @nullable
+ */
+ github_open_pull_request_ready?: boolean | null;
}
export interface SlackChannel {