:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(review-hog): let each repository turn draft reviews on (#129367)
Julian Bez4ec854f872e1
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex dabfa9920846..dd98616477c8 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -16603,9 +16603,9 @@ snapshots:scenes-code-review--narrow--light:hash: v1.k794b7964.b0b6df7bb3075410c3f16dca6f3b59fdf224a9a920c3a248c55cd995bdd8b057.eUufZJ9SurN1Xw53s2pCYPXXo8sVjLL8lWoo_N0w61kscenes-code-review--narrow-settings--dark:- hash: v1.k794b7964.9c6a5f5f17e2ac4cab3136659c387d5b43a56c85e2bf95496b7b327c07b9d076.88qYvpqV9D3zF6qa0utW9WvCSjlWB6SMB9YH7NLtjf4+ hash: v1.k794b7964.52b11fe9a79ce17522d52a647e62ec76ecb88ebe85dddfe8c2686360a7a3a883.5x47v5XsNFIODB7qFXWTA3Isxoov0_yqTe3MAKQzOaYscenes-code-review--narrow-settings--light:- hash: v1.k794b7964.1873b9b80b23f151cb9242d485732ffb065ae99eab39338920f7e2b84393b57b.5WIpjhbiEtVFSkWgR3_KJsi5qHtqnSmIJ4cjbM86ag0+ hash: v1.k794b7964.3a10821212e628b1aa33299b007f893591441bdec9971eb3c6a05dd68dded637.-TsD83HNuiO98hyyyYOoKOS7_EpvW2b2GZgAhjuXda8scenes-code-review--review-drawer-deep--dark:hash: v1.k794b7964.416b4c6b50ff059a3449c3f80742f5518bfd794aecfbb18ece1d6bc9d4dccbf3.IDH_1hHQmlcDP3N4j7VpgvMftz2fLSa2GJfPcg6YJ_cscenes-code-review--review-drawer-deep--light:@@ -16623,17 +16623,17 @@ snapshots:scenes-code-review--running-review--light:hash: v1.k794b7964.317b100710a85c42982c056b8d6c6105056b7a384ba0d0e478ab6b93e4baf28b.5WQ2gVh9oGhAA8f_jyqZljHyK8mp0vppnvwV0uGtv_kscenes-code-review--saved-inbox-opt-ins--dark:- hash: v1.k794b7964.7a38f3e4fb34402bf9347186b800559706cedaa0244425b177cc5ee2a2deba26.imt_YryGDIqYUHC0X1sEQm32A7Kwp0O7X0CgElZyCr4+ hash: v1.k794b7964.2bb5f3cb349d045b8f04c581e79be4d27f2e9066cf31fee0290f0f1948ab929b.e7oP9Tq8UZNwHuygLktFBTWt-Zx3sHKXo6rVDaWSE_Escenes-code-review--saved-inbox-opt-ins--light:- hash: v1.k794b7964.fc13d6d7b9b7b38425d4b313e2ca67bacd51e6f3357c0db8e4034ff2fcc88d9b.22Rg31qeXGO-4Pvt5RskiyN_WIF997XZ-Q6XIJlA92Q+ hash: v1.k794b7964.e9530e33003f694d61ea330a73711a2d5a1b9f97c762d7682b83d930393de567.c2TWRY4lAbTH5_XjXJqKKbl0KE8STKUEznRk3KUk4Gwscenes-code-review--settings--dark:- hash: v1.k794b7964.d39f24474355c7afc175616983b30f8e97f3e92aa8171751acb596e6126cf35c.fHH2ToG9E-plAUYn3MRk1cAqQsAxGlChNBTz64sHRBQ+ hash: v1.k794b7964.01b42bcbaf1cd5c416aaa182a0271fde80a29a5fbc57f21592f1dbcb6adc0e6c.q5CqFy91VqiQcX2uGMrAWv9iURyszR_ldk6GLX64zQoscenes-code-review--settings--light:- hash: v1.k794b7964.3e125b0f0890aecc4973706c4cb20708ae2f3a6587533ed235cc5973f4eb4360.XoBApr6ZMtKG2QnaZCrjTbSrdqlxYAIaff9S1UNQYUE+ hash: v1.k794b7964.0a83e49ea4ffddf7902c0e4a78ed177be7e24deff30fb37738876e79cfa08b5e.pUHbhbCwgKCj3xdN1SqXewLiCF0z0ykHXvjVfq5-0Mcscenes-code-review--settings-for-member--dark:- hash: v1.k794b7964.c648e112aa9e62c36828cd719e76a5f058a4096190a7f25724d41d2b65bdbba0.vn_Ek2GuvGtLOWurgarR_JBDfNGi-KzBL-TVGHNVCNQ+ hash: v1.k794b7964.733445561b7ea84cebefacffe2c69461603f60dc1d2992f0d98c045c4c78e223.7RKW46z_44360alW-7V95ynREudKhb7_cHL7EI6LbVAscenes-code-review--settings-for-member--light:- hash: v1.k794b7964.bb60679f35a0154e02cc9d6525fd9ee9f7cbfa4ba8a83a672aa1751d07938811.owYobIkt_WGA0lZTTNCY69iwaWnhddJvHimFbKRwRhk+ hash: v1.k794b7964.88e71a4e9bba9cdeb2a2a588edff4ef6c3bdbb790bc6f1b1677ddf8fd13d8689.vtbgnr_efd5Mf0gLMIVPQ9yvMrarrqs7DQqsG7g3YxQscenes-dashboards-customize-breakdown-colors--customize-breakdown-colors--dark:hash: v1.k794b7964.cf89a12669d5221b2441fbfb4439b8b1b38191943438a2c1a220444148329954.B4ew6uW3gZCbPU_3vTOggsOyHojRlyvuXxh5FZnlO-0scenes-dashboards-customize-breakdown-colors--customize-breakdown-colors--light:diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex e0b56e486260..704eb7e41c8d 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -56,7 +56,7 @@ in flight, with the detail in DECISIONS.md.## Status & nextReviewHog runs end-to-end: label / UI / inbox / automatic authored-PR triggers → the Temporal pipeline → published PR review.-Automatic Standard reviews run on new PRs and pushes, including drafts unless the owner turns them off (a draft gets one review, and the next one runs when it is marked ready), but never on PRs with the `skip-agent-review` label, in every repository a project reviews, for the authors that the project rule, the repository exceptions, and each person's own choices select (`backend/automatic_review_rules.py`).+Automatic Standard reviews run on new PRs and pushes, including drafts in repositories that turn draft reviews on, unless the owner turns them off (a draft gets one review, and the next one runs when it is marked ready), but never on PRs with the `skip-agent-review` label, in every repository a project reviews, for the authors that the project rule, the repository exceptions, and each person's own choices select (`backend/automatic_review_rules.py`).The per-PR queue serializes reviews and coalesces automatic pushes into a follow-up for the latest head.The current focus is productionizing the reviewer-topology eval and tightening the finder/validator balance(validator strictness, fewer junk candidates, the coverage gap).@@ -959,7 +959,7 @@ whoever controls the run, the sandbox agent included), **MCP tools**`review-hog` feature flag) that drive the same reviews viewset with a personal API key or OAuth token, and **automatic authored-PR Flash reviews**.The automatic trigger consumes signed GitHub `pull_request` deliveries through `review_hog_authored_prs` and queues a Celery task for the ownership, identity, and rule checks.It accepts `opened`, `synchronize`, and `ready_for_review` for open PRs whose head and base belong to the delivery's repository, including drafts.-A draft is skipped (`draft_skipped`) when the PR owner turned `review_drafts` off. Its first automatic review then comes from `ready_for_review`, and `automatic_reviewed_head_sha` keeps a head that was already reviewed as a draft from a second review.+A draft is skipped (`draft_skipped`) unless its repository turned draft reviews on (`ReviewRepository.review_drafts`, default off) and the PR owner kept `review_drafts` on. A bot or an unmapped author follows the repository alone. The workflow checks both again when a queued run starts, and before it skips a draft it reads the draft state from GitHub again, because the queue drops a `ready_for_review` request for a head the run already holds. A failed read keeps the skip. A skipped draft's first automatic review then comes from `ready_for_review`, and `automatic_reviewed_head_sha` keeps a head that was already reviewed as a draft from a second review.A draft that is reviewed gets its first automatic review only: the push gate's `draft` rule skips the later pushes, and `ready_for_review` reviews everything since the last reviewed head, also when the author marks it ready without a push.A PR with the `skip-agent-review` label gets no automatic review (`label_skipped`). The task checks the payload labels, and the turn checks the labels its fetch reads from GitHub again, because `gh pr create --label` adds labels after the `opened` delivery.The turn ends before the status comment, so a skip leaves nothing on the PR. Removing the label does not start a review; comment `@posthog review` for one.diff --git a/products/review_hog/backend/automatic_reviews.py b/products/review_hog/backend/automatic_reviews.pyindex 231c3b76e8aa..7dd8a1c7872c 100644--- a/products/review_hog/backend/automatic_reviews.py+++ b/products/review_hog/backend/automatic_reviews.py@@ -8,7 +8,7 @@ from posthog.integrations import IntegrationManagerfrom posthog.otel_metrics import OtelInstrumentFactoryfrom products.review_hog.backend.automatic_review_rules import AutomaticReviewReason, decide_automatic_review-from products.review_hog.backend.models import ReviewReport, ReviewUserSettings+from products.review_hog.backend.models import ReviewReport, ReviewRepository, ReviewUserSettingsfrom products.review_hog.backend.ownership import RepositoryOwner, RepositoryOwnership, RepositoryReffrom products.review_hog.backend.pr_owner import is_active_memberfrom products.review_hog.backend.review_request_rules import full_review_published@@ -61,6 +61,16 @@ class AutomaticDispatch:run_as_user_id: int | None = None+def drafts_reviewed(team_id: int, row: ReviewRepository | None, *, author_user_id: int | None) -> bool:+ """Whether a draft gets its automatic review: the repository turned draft reviews on, and the author did not+ turn them off for their own pull requests. A bot or an unmapped author follows the repository."""+ if row is None or not row.review_drafts:+ return False+ if author_user_id is None:+ return True+ return ReviewUserSettings.load_preferences(team_id, author_user_id).review_drafts++def plan_automatic_review(repository: RepositoryRef, owner: RepositoryOwner | None, *, author_login: str, draft: bool = False) -> AutomaticDispatch:@@ -96,17 +106,15 @@ def plan_automatic_review("bot_skipped" if decision.reason == AutomaticReviewReason.BOT_SKIPPED else "not_opted_in")return AutomaticDispatch(outcome=outcome, team_id=team_id)- if decision.reason == AutomaticReviewReason.BOT_REVIEWED:+ is_bot = decision.reason == AutomaticReviewReason.BOT_REVIEWED+ # Before the bot branch, so a bot's drafts follow the repository too. A bot's mapped user is not its author.+ if draft and not drafts_reviewed(team_id, owner.row, author_user_id=None if is_bot else author_user_id):+ return AutomaticDispatch(outcome="draft_skipped", team_id=team_id)+ if is_bot:run_as_user_id = connector_user_id(team_id=team_id, installation_id=owner.installation_id)if run_as_user_id is None:return AutomaticDispatch(outcome="bot_no_connector", team_id=team_id)return AutomaticDispatch(outcome="started", team_id=team_id, run_as_user_id=run_as_user_id)- if (- draft- and author_user_id is not None- and not ReviewUserSettings.load_preferences(team_id, author_user_id).review_drafts- ):- return AutomaticDispatch(outcome="draft_skipped", team_id=team_id)return AutomaticDispatch(outcome="started", team_id=team_id, run_as_user_id=author_user_id)@@ -118,6 +126,7 @@ def automatic_flash_allowed(author_login: str,installation_id: str | None = None,github_repo_id: int | None = None,+ draft: bool = False,) -> bool:"""Whether the rules still give this pull request an automatic Flash review run as `user_id`.@@ -135,7 +144,7 @@ def automatic_flash_allowed(if owner is None or owner.team_id != team_id:return Falseref = RepositoryRef(installation_id=owner.installation_id, github_repo_id=github_repo_id, full_name=repository)- return plan_automatic_review(ref, owner, author_login=author_login).run_as_user_id == user_id+ return plan_automatic_review(ref, owner, author_login=author_login, draft=draft).run_as_user_id == user_id@frozendiff --git a/products/review_hog/backend/facade/api.py b/products/review_hog/backend/facade/api.pyindex 13e02a7a6689..b56932e47478 100644--- a/products/review_hog/backend/facade/api.py+++ b/products/review_hog/backend/facade/api.py@@ -201,6 +201,7 @@ def _repository_settings(full_name=row.full_name,selected=row.selected,flash_for=AutomaticFlashFor(row.flash_for) if row.flash_for is not None else None,+ review_drafts=row.review_drafts,people=_person_entries(people.get(row.id, [])),created_by=_user_ref(row.created_by),created_at=row.created_at,@@ -255,6 +256,7 @@ def _overview_entry(entry: OverviewEntry) -> ReviewRepositoryOverviewEntry:selected=entry.selected,repository_id=repository.id if repository is not None else None,exception=exception,+ review_drafts=repository is not None and repository.review_drafts,my_choice=ReviewUserRepositoryChoiceMode(entry.my_choice.mode) if entry.my_choice is not None else None,my_choice_id=entry.my_choice.id if entry.my_choice is not None else None,my_result=entry.my_result,@@ -294,14 +296,19 @@ def save_review_repository(github_repo_id: int | None,selected: bool | None,flash_for: AutomaticFlashFor | None | Unset = UNSET,+ review_drafts: bool | None = None,) -> ReviewRepositoryWriteOutcome:- """Include or remove a repository, or set or clear its exception. Omitted fields keep their value.+ """Include or remove a repository, set or clear its exception, or turn its draft reviews on or off.++ Omitted fields keep their value.Raises `OwnershipConflict` when another project holds the repository, and `RepositorySettingsError`when the rules forbid the write."""ref = RepositoryRef(installation_id=installation_id, github_repo_id=github_repo_id, full_name=full_name)- result = _project_repositories(team_id, user_id).save_repository(ref, selected=selected, flash_for=flash_for)+ result = _project_repositories(team_id, user_id).save_repository(+ ref, selected=selected, flash_for=flash_for, review_drafts=review_drafts+ )repository = Noneif result.repository is not None:repository = _repository_settings(result.repository, load_people(team_id, [result.repository.id]))diff --git a/products/review_hog/backend/facade/contracts.py b/products/review_hog/backend/facade/contracts.pyindex cf8abbe0ca07..051c73b20f68 100644--- a/products/review_hog/backend/facade/contracts.py+++ b/products/review_hog/backend/facade/contracts.py@@ -269,6 +269,7 @@ class ReviewRepositorySettings:full_name: strselected: boolflash_for: AutomaticFlashFor | None+ review_drafts: boolpeople: Sequence[ReviewRepositoryPersonEntry]created_by: ReviewUserRef | Nonecreated_at: datetime@@ -352,6 +353,7 @@ class ReviewRepositoryOverviewEntry:selected: boolrepository_id: UUID | Noneexception: ReviewRepositoryException | None+ review_drafts: boolmy_choice: ReviewUserRepositoryChoiceMode | Nonemy_choice_id: UUID | Nonemy_result: AutomaticReviewDecisiondiff --git a/products/review_hog/backend/migrations/0036_reviewrepository_review_drafts.py b/products/review_hog/backend/migrations/0036_reviewrepository_review_drafts.pynew file mode 100644index 000000000000..a1a67e42ac53--- /dev/null+++ b/products/review_hog/backend/migrations/0036_reviewrepository_review_drafts.py@@ -0,0 +1,17 @@+# Generated by Django 6.1.2 on 2026-11-04 12:39++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("review_hog", "0035_drop_duplicate_artefact_report_indexes"),+ ]++ operations = [+ migrations.AddField(+ model_name="reviewrepository",+ name="review_drafts",+ field=models.BooleanField(db_default=False, default=False),+ ),+ ]diff --git a/products/review_hog/backend/migrations/max_migration.txt b/products/review_hog/backend/migrations/max_migration.txtindex ef744affca41..fe76ddde58fd 100644--- a/products/review_hog/backend/migrations/max_migration.txt+++ b/products/review_hog/backend/migrations/max_migration.txt@@ -1 +1 @@-0035_drop_duplicate_artefact_report_indexes+0036_reviewrepository_review_draftsdiff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.pyindex c989c5c8c24d..aaacfa086f53 100644--- a/products/review_hog/backend/models.py+++ b/products/review_hog/backend/models.py@@ -600,8 +600,9 @@ class ReviewRepository(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):`selected` includes the repository into this project, also when another project takes allrepositories of the installation. `flash_for` is the repository exception: null follows the- project rule (`ReviewProjectSettings.flash_for`). A row that is neither selected nor an exception- has no meaning and is deleted. A repository has at most one row across all projects, so it+ project rule (`ReviewProjectSettings.flash_for`). `review_drafts` lets draft pull requests get+ their automatic review when they open. A row that is not selected, has no exception and does not+ review drafts has no meaning and is deleted. A repository has at most one row across all projects, so itbelongs to one project only."""@@ -620,6 +621,7 @@ class ReviewRepository(ModelActivityMixin, UUIDModel, TeamScopedRootMixin):full_name = models.CharField(max_length=200)selected = models.BooleanField(default=False, db_default=False)flash_for = models.CharField(max_length=20, choices=AutomaticFlashFor.choices, null=True, blank=True)+ review_drafts = models.BooleanField(default=False, db_default=False)created_by = models.ForeignKey("posthog.User", on_delete=models.SET_NULL, null=True, blank=True, related_name="+", db_constraint=False)diff --git a/products/review_hog/backend/presentation/views/project_settings.py b/products/review_hog/backend/presentation/views/project_settings.pyindex d9d3d3eddbf7..2d6e5d4feca2 100644--- a/products/review_hog/backend/presentation/views/project_settings.py+++ b/products/review_hog/backend/presentation/views/project_settings.py@@ -139,6 +139,10 @@ class ReviewRepositoryOverviewEntrySerializer(serializers.Serializer):exception = ReviewRepositoryExceptionSerializer(allow_null=True, help_text="This project's repository exception. Null when the repository follows the project.")+ review_drafts = serializers.BooleanField(+ help_text="Whether draft pull requests in this repository get their automatic review when they open. "+ "Authors who turned off reviews of their drafts still get none."+ )my_choice = serializers.ChoiceField(choices=ReviewUserRepositoryChoiceMode.choices,allow_null=True,@@ -171,7 +175,7 @@ class ReviewRepositoryOverviewSerializer(serializers.Serializer):next_offset = serializers.IntegerField(allow_null=True, help_text="Offset of the next page, or null.")folded = serializers.IntegerField(help_text="With view 'differs', or 'all' without a search: how many repositories 'differs' leaves out "- "because this project reviews them with no exception and no own choice. 0 otherwise."+ "because this project reviews them with no exception, no draft reviews and no own choice. 0 otherwise.")folded_preview = serializers.ListField(child=serializers.CharField(),@@ -207,6 +211,7 @@ def _entry_data(entry: ReviewRepositoryOverviewEntry) -> dict[str, Any]:"selected": entry.selected,"repository_id": entry.repository_id,"exception": exception,+ "review_drafts": entry.review_drafts,"my_choice": entry.my_choice,"my_choice_id": entry.my_choice_id,"my_result": decision_data(entry.my_result),diff --git a/products/review_hog/backend/presentation/views/repositories.py b/products/review_hog/backend/presentation/views/repositories.pyindex e30e612894f4..6faf7148f296 100644--- a/products/review_hog/backend/presentation/views/repositories.py+++ b/products/review_hog/backend/presentation/views/repositories.py@@ -160,6 +160,10 @@ class ReviewRepositorySerializer(serializers.Serializer):help_text="The repository exception: 'everyone', 'listed', or 'off' (opt-in only). Null when the ""repository follows the project rule.",)+ review_drafts = serializers.BooleanField(+ read_only=True,+ help_text="Whether draft pull requests in this repository get their automatic review when they open.",+ )people = serializers.SerializerMethodField(help_text="The people on the exception's two lists. Only the list that matches flash_for has an effect.")@@ -193,6 +197,11 @@ class ReviewRepositoryWriteSerializer(serializers.Serializer):help_text="The repository exception: 'everyone', 'listed', or 'off'. Null clears it, so the repository ""follows the project rule again. Omit it to keep the current value.",)+ review_drafts = serializers.BooleanField(+ required=False,+ help_text="True lets draft pull requests in this repository get their automatic review when they open. "+ "False waits until they are ready for review. Omit it to keep the current value.",+ )def validate_full_name(self, value: str) -> str:return validate_full_name(value)@@ -424,7 +433,8 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView),},summary="Save a repository's settings",- description="Include a repository into this project, remove it, or set or clear its exception. Only the "+ description="Include a repository into this project, remove it, set or clear its exception, or turn its "+ "draft reviews on or off. Only the ""provided fields change. Including a repository that another project's 'all repositories' claim covers ""takes it from that project; the response names it.",)@@ -444,6 +454,7 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericViewgithub_repo_id=data.get("github_repo_id"),selected=data.get("selected"),flash_for=flash_for,+ review_drafts=data.get("review_drafts"),)except OwnershipConflict as error:return conflict_response(error)diff --git a/products/review_hog/backend/repository_settings.py b/products/review_hog/backend/repository_settings.pyindex 2dbf8f0580d0..1a4e8517921f 100644--- a/products/review_hog/backend/repository_settings.py+++ b/products/review_hog/backend/repository_settings.py@@ -280,8 +280,12 @@ class ProjectRepositories:*,selected: bool | None = None,flash_for: str | None | Unset = UNSET,+ review_drafts: bool | None = None,) -> RepositoryWriteResult:- """Include or remove a repository, or set or clear its exception. Omitted fields keep their value."""+ """Include or remove a repository, set or clear its exception, or turn its draft reviews on or off.++ Omitted fields keep their value.+ """ref = self.verified_ref(ref)with transaction.atomic():row = find_matching_row(ref, RepositoryOwnership.rows_for(ref))@@ -296,13 +300,19 @@ class ProjectRepositories:new_flash_for = row.flash_for if row is not None else Noneelse:new_flash_for = flash_for+ new_review_drafts = review_drafts if review_drafts is not None else row is not None and row.review_draftsif not new_selected and not takes_all:if isinstance(flash_for, str):raise RepositorySettingsError("Include the repository in this project before you add an exception.")- # The repository leaves the project, so its exception goes too.+ if review_drafts:+ raise RepositorySettingsError(+ "Include the repository in this project before you turn on draft reviews."+ )+ # The repository leaves the project, so its exception and its draft setting go too.new_flash_for = None- if not new_selected and new_flash_for is None:+ new_review_drafts = False+ if not new_selected and new_flash_for is None and not new_review_drafts:if row is not None:row.delete()return RepositoryWriteResult(repository=None, taken_from=None)@@ -332,6 +342,7 @@ class ProjectRepositories:row.installation_id = ref.installation_idrow.selected = new_selectedrow.flash_for = new_flash_for+ row.review_drafts = new_review_draftstry:with transaction.atomic():row.save()@@ -480,12 +491,14 @@ class RepositoryOverview:@staticmethoddef follows_project(entry: OverviewEntry) -> bool:- """No exception and no own choice, so the entry gets exactly what every other such entry gets."""+ """No exception, no draft reviews and no own choice, so the entry gets what every other such entry gets."""has_exception = entry.repository is not None and entry.repository.flash_for is not None+ reviews_drafts = entry.repository is not None and entry.repository.review_draftsreturn (entry.owner == RepositoryOwnerKind.THIS_PROJECTand entry.in_projectand not has_exception+ and not reviews_draftsand entry.my_choice is None)diff --git a/products/review_hog/backend/temporal/activities.py b/products/review_hog/backend/temporal/activities.pyindex 67d3586b6033..e5f358166222 100644--- a/products/review_hog/backend/temporal/activities.py+++ b/products/review_hog/backend/temporal/activities.py@@ -315,6 +315,8 @@ class ReviewMeta:empty_diff: bool = Falsealready_completed: bool = Falsepr_open: bool = True+ # Only forwarded to the acting-user re-check; the workflow does not branch on it.+ draft: bool = False# Decided here so the workflow branches on a recorded result; older histories decode as the pipeline.review_design: str = REVIEW_DESIGN_PIPELINE# Why the design was chosen, for the started event. Empty on histories from before it existed.@@ -358,6 +360,11 @@ class ResolveActingUserInput:repository: str | None = Noneinstallation_id: str | None = Nonegithub_repo_id: int | None = None+ # Whether the PR was a draft when the turn fetched it, for the automatic trigger's re-check of the draft rules.+ # False in older payloads, which reviews the draft as before.+ draft: bool = False+ # Read GitHub again before a draft skip. None in older payloads, which keeps the fetched draft state.+ pr_number: int | None = None# The PR's head branch, which links a self-driving PR to its Inbox report. The fetch refuses forks,# so the branch is in the base repository. None in older payloads: such a PR then has no owner.head_branch: str | None = None@@ -968,6 +975,7 @@ def _fetch_and_persist(input: FetchPRDataInput) -> ReviewMeta:empty_diff=pr_number is None and not fetched.pr_files,already_completed=already_completed,pr_open=fetched.pr_metadata.state == "open",+ draft=fetched.pr_metadata.draft,review_design=design_choice.design,review_design_reason=design_choice.reason,lens_chunk_count=len(lens_plan.chunks) if lens_plan is not None else 0,@@ -1001,6 +1009,22 @@ async def fetch_pr_data_activity(input: FetchPRDataInput) -> ReviewMeta:return await database_sync_to_async(_fetch_and_persist, thread_sensitive=False)(input)+def _pr_draft_on_github(repository: str, pr_number: int, *, token: str, installation_id: str | None) -> bool | None:+ """The PR's draft state on GitHub now, or None when the read fails."""+ try:+ response = github_api_request(+ "GET",+ f"/repos/{repository}/pulls/{pr_number}",+ token=token,+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",+ installation_id=installation_id,+ )+ except (GitHubAPIError, GitHubRateLimitError, GitHubEgressBudgetExhausted, requests.RequestException):+ logger.warning("Could not re-read the draft state of %s#%s", repository, pr_number)+ return None+ return response.json().get("draft") is True++def _login_to_user_id(team_id: int, login: str | None) -> int | None:if not login:return None@@ -1015,14 +1039,27 @@ def _automatic_review_allowed(input: ResolveActingUserInput, acting_user_id: intreport = ReviewReport.objects.for_team(input.team_id).filter(id=input.report_id).first()if full_review_published(report):return False- return automatic_flash_allowed(- team_id=input.team_id,- repository=input.repository,- user_id=acting_user_id,- author_login=input.author_login,- installation_id=input.installation_id,- github_repo_id=input.github_repo_id,- )+ repository, user_id = input.repository, acting_user_id++ def allowed(draft: bool) -> bool:+ return automatic_flash_allowed(+ team_id=input.team_id,+ repository=repository,+ user_id=user_id,+ author_login=input.author_login,+ installation_id=input.installation_id,+ github_repo_id=input.github_repo_id,+ draft=draft,+ )++ if allowed(input.draft):+ return True+ if not input.draft or input.pr_number is None or not allowed(False):+ return False+ # The queue drops a ready request for the head this turn already holds, so a PR marked ready after the+ # fetch would stay unreviewed. Unlike the push gate, a failed read keeps the skip: the repository said no drafts.+ token, installation_id = _installation_auth(input.team_id, repository)+ return _pr_draft_on_github(repository, input.pr_number, token=token, installation_id=installation_id) is Falsedef _flash_after_full(input: ResolveActingUserInput) -> bool:@@ -2445,22 +2482,6 @@ def _track_push_gate_decided(input: GatePushInput, decision: PushGateDecision, d)-def _pr_is_draft_now(repository: str, pr_number: int, *, token: str, installation_id: str | None) -> bool:- """The PR's draft state on GitHub now. A failed read counts as ready, so the gate reviews the push."""- try:- response = github_api_request(- "GET",- f"/repos/{repository}/pulls/{pr_number}",- token=token,- endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",- installation_id=installation_id,- )- except (GitHubAPIError, GitHubRateLimitError, GitHubEgressBudgetExhausted, requests.RequestException):- logger.warning("Could not re-read the draft state of %s#%s; reviewing the push", repository, pr_number)- return False- return response.json().get("draft") is True--def _previous_turn_findings(input: GatePushInput) -> int | None:"""The findings the last counted turn kept. A turn that failed before publishing does not count."""try:@@ -2501,7 +2522,8 @@ def _gate_push(input: GatePushInput) -> PushGateDecision:# ready before this turn reads as ready. One marked ready while this turn runs does not: the queue# drops the ready request for the head this turn gates. So a draft skip reads GitHub again after the# gate's other reads, which leaves only the moment between this read and the end of the turn.- if decision.reason == "draft" and not _pr_is_draft_now(+ # A failed read counts as ready, so the gate reviews the push.+ if decision.reason == "draft" and not _pr_draft_on_github(input.repository, current.pr_metadata.number, token=token, installation_id=installation_id):draft = Falsediff --git a/products/review_hog/backend/temporal/workflow.py b/products/review_hog/backend/temporal/workflow.pyindex 20f7aa892d64..427a7f26e49d 100644--- a/products/review_hog/backend/temporal/workflow.py+++ b/products/review_hog/backend/temporal/workflow.py@@ -551,6 +551,8 @@ class ReviewPRWorkflow:repository=repository,installation_id=inputs.installation_id,github_repo_id=inputs.github_repo_id,+ draft=meta.draft,+ pr_number=meta.pr_number,head_branch=branch,review_mode=inputs.review_mode,),diff --git a/products/review_hog/backend/tests/test_acting_user.py b/products/review_hog/backend/tests/test_acting_user.pyindex d4981055e2d1..5ceefcbd55ed 100644--- a/products/review_hog/backend/tests/test_acting_user.py+++ b/products/review_hog/backend/tests/test_acting_user.py@@ -1,5 +1,7 @@from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch+import requestsfrom parameterized import parameterizedfrom social_django.models import UserSocialAuth@@ -16,6 +18,8 @@ from products.review_hog.backend.reviewer.progress import run_outcome_markersfrom products.review_hog.backend.temporal.activities import ResolveActingUserInput, _resolve_acting_userfrom products.review_hog.backend.temporal.types import TRIGGER_AUTOMATIC, TRIGGER_MANUAL, TRIGGER_STAMPHOG+ACTIVITIES = "products.review_hog.backend.temporal.activities"+_SELF = "SELF"@@ -83,6 +87,11 @@ class TestResolveActingUser(BaseTest):# No Flash after Full: a Full review published while the push waited stops it.("full_review_published", True, True, True, True, True, "PostHog", None),("placeholder_account_name", True, True, True, True, False, "installation-1234", "1234"),+ # Draft reviews are off in the repository, so a queued draft run stops when it starts.+ ("draft_in_a_repository_without_drafts", True, True, True, True, False, "PostHog", None, "draft"),+ # Marked ready after the fetch: the queue dropped the ready request, so GitHub's state decides.+ ("draft_marked_ready_after_the_fetch", True, True, True, True, False, "PostHog", None, "ready"),+ ("draft_state_unreadable", True, True, True, True, False, "PostHog", None, "unreadable"),])def test_automatic_trigger_rechecks_eligible_author(@@ -95,7 +104,9 @@ class TestResolveActingUser(BaseTest):full_published: bool,account_name: str,installation_id: str | None,+ github_state: str | None = None,) -> None:+ draft = github_state is not NoneIntegration.objects.create(team=self.team, kind="github", integration_id="1234", config={"account": {"name": account_name}})@@ -124,18 +135,34 @@ class TestResolveActingUser(BaseTest):self.user.save(update_fields=["is_active"])if not member:self.user.organization_memberships.filter(organization=self.organization).delete()- result = _resolve_acting_user(- ResolveActingUserInput(- team_id=self.team.id,- author_login="octocat",- override_user_id=self.user.id,- trigger_source=TRIGGER_AUTOMATIC,- report_id=str(report.id),- repository="posthog/PostHog",- installation_id=installation_id,+ github_pull = MagicMock()+ github_pull.json.return_value = {"draft": github_state == "draft"}+ read_error = requests.ConnectionError() if github_state == "unreadable" else None+ with (+ patch(f"{ACTIVITIES}._installation_auth", return_value=("token", "1234")),+ patch(f"{ACTIVITIES}.github_api_request", return_value=github_pull, side_effect=read_error),+ ):+ result = _resolve_acting_user(+ ResolveActingUserInput(+ team_id=self.team.id,+ author_login="octocat",+ override_user_id=self.user.id,+ trigger_source=TRIGGER_AUTOMATIC,+ report_id=str(report.id),+ repository="posthog/PostHog",+ installation_id=installation_id,+ draft=draft,+ pr_number=7,+ ))+ eligible = (+ opted_in+ and active+ and member+ and repository_added+ and not full_published+ and github_state in (None, "ready"))- eligible = opted_in and active and member and repository_added and not full_publishedassert result.acting_user_id == (self.user.id if eligible else None)# The workflow gates the automatic run on this flag after the resolve.assert result.review_authored_prs is eligiblediff --git a/products/review_hog/backend/tests/test_automatic_reviews.py b/products/review_hog/backend/tests/test_automatic_reviews.pyindex 4fe260686809..7c570953795a 100644--- a/products/review_hog/backend/tests/test_automatic_reviews.py+++ b/products/review_hog/backend/tests/test_automatic_reviews.py@@ -308,11 +308,17 @@ class TestAuthoredPRReviewTask(BaseTest):}@parameterized.expand(- [("own_flash_default",), ("listed_by_the_project",), ("repository_exception",), ("draft_by_default",)]+ [+ ("own_flash_default",),+ ("listed_by_the_project",),+ ("repository_exception",),+ ("draft_in_a_repository_that_reviews_drafts",),+ ])@patch(_START)def test_eligible_author_schedules_flash_in_the_owning_project(self, setup: str, start: MagicMock) -> None:- if setup not in ("own_flash_default", "draft_by_default"):+ drafts = setup == "draft_in_a_repository_that_reviews_drafts"+ if setup not in ("own_flash_default", "draft_in_a_repository_that_reviews_drafts"):self.preferences.preferences = {}self.preferences.save(update_fields=["preferences"])if setup == "listed_by_the_project":@@ -323,9 +329,12 @@ class TestAuthoredPRReviewTask(BaseTest):if setup == "repository_exception":self.repository.flash_for = "everyone"self.repository.save()+ if drafts:+ self.repository.review_drafts = True+ self.repository.save()started_before = _dispatch_count("started")- process_authored_pr_event.run(**self._queued_event(draft=setup == "draft_by_default"))+ process_authored_pr_event.run(**self._queued_event(draft=drafts))start.assert_called_once_with(**self._expected_start(team_id=self.team.id, user_id=self.user.id))assert _dispatch_count("started") - started_before == 1.0@@ -343,6 +352,7 @@ class TestAuthoredPRReviewTask(BaseTest):("missing_installation", "installation_mismatch"),("full_review_published", "full_review_published"),("draft_with_drafts_off", "draft_skipped"),+ ("draft_in_a_repository_without_drafts", "draft_skipped"),("skip_agent_review_label", "label_skipped"),])@@ -351,10 +361,12 @@ class TestAuthoredPRReviewTask(BaseTest):self, change: str, expected_outcome: str, start: MagicMock) -> None:queued = self._queued_event(- draft=change == "draft_with_drafts_off",+ draft=change in ("draft_with_drafts_off", "draft_in_a_repository_without_drafts"),labels=("skip-agent-review",) if change == "skip_agent_review_label" else (),)if change == "draft_with_drafts_off":+ self.repository.review_drafts = True+ self.repository.save()self.preferences.preferences = {"default_review_mode": "flash", "review_drafts": False}self.preferences.save(update_fields=["preferences"])elif change == "opted_out":@@ -387,22 +399,41 @@ class TestAuthoredPRReviewTask(BaseTest):start.assert_not_called()assert _dispatch_count(expected_outcome) - outcome_before == 1.0- @parameterized.expand([("connector_runs_it", True, "started"), ("no_connector", False, "bot_no_connector")])+ @parameterized.expand(+ [+ ("connector_runs_it", True, False, "started", False),+ ("no_connector", False, False, "bot_no_connector", False),+ ("draft_in_a_repository_without_drafts", True, True, "draft_skipped", False),+ # The connector's own draft switch is off, and it must not apply to a bot's pull request.+ ("draft_in_a_repository_that_reviews_drafts", True, True, "started", True),+ ]+ )@patch(_START)def test_bot_pull_requests_run_as_the_connector_when_the_project_reviews_bots(- self, _name: str, has_connector: bool, expected_outcome: str, start: MagicMock+ self,+ _name: str,+ has_connector: bool,+ draft: bool,+ expected_outcome: str,+ repository_drafts: bool,+ start: MagicMock,) -> None:ReviewProjectSettings.objects.for_team(self.team.id).create(team=self.team, bot_prs=ReviewProjectSettings.BotPullRequests.RUN)+ if repository_drafts:+ self.repository.review_drafts = True+ self.repository.save()+ self.preferences.preferences = {"default_review_mode": "flash", "review_drafts": False}+ self.preferences.save(update_fields=["preferences"])if not has_connector:self.integration.created_by = Noneself.integration.save(update_fields=["created_by"])outcome_before = _dispatch_count(expected_outcome)- process_authored_pr_event.run(**self._queued_event(login="dependabot[bot]"))+ process_authored_pr_event.run(**self._queued_event(login="dependabot[bot]", draft=draft))- if has_connector:+ if expected_outcome == "started":start.assert_called_once_with(**self._expected_start(team_id=self.team.id, user_id=self.user.id))else:start.assert_not_called()diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.pyindex 841a595cb66f..9d972f884d41 100644--- a/products/review_hog/backend/tests/test_repositories_api.py+++ b/products/review_hog/backend/tests/test_repositories_api.py@@ -280,7 +280,9 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):@parameterized.expand([("exception_without_ownership", {**WEB, "flash_for": "everyone"}, 400),+ ("drafts_without_ownership", {**WEB, "review_drafts": True}, 400),("nothing_to_store", {**WEB, "selected": False}, 200),+ ("drafts_off_is_nothing_to_store", {**WEB, "review_drafts": False}, 200),("unknown_to_the_installation", {**WEB, "full_name": "example-org/secret", "selected": True}, 400),("id_of_another_repository", {**WEB, "github_repo_id": 502, "selected": True}, 400),(@@ -405,6 +407,26 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):assert [entry["full_name"] for entry in searched["results"]] == ["example-org/api"]assert searched["folded"] == 0+ @patch(+ "posthog.models.integration.GitHubIntegration.list_all_cached_repositories", return_value=CACHED_REPOSITORIES+ )+ def test_draft_reviews_alone_keep_a_repository_row_out_of_the_fold(self, _cached: object) -> None:+ self._claim(self.team, ReviewInstallationClaim.Scope.ALL)+ url = self._url(f"repository_overview/?installation_id={INSTALLATION}&view=differs")++ turned_on = self.client.post(self._url("repositories/"), {**WEB, "review_drafts": True}, format="json")++ assert turned_on.status_code == 200, turned_on.json()+ assert turned_on.json()["repository"]["review_drafts"] is True+ [entry] = [entry for entry in self.client.get(url).json()["results"] if entry["full_name"] == "example-org/web"]+ assert entry["review_drafts"] is True++ turned_off = self.client.post(self._url("repositories/"), {**WEB, "review_drafts": False}, format="json")++ assert turned_off.json()["repository"] is None+ assert not ReviewRepository.objects.for_team(self.team.id).exists()+ assert "example-org/web" in self.client.get(url).json()["folded_preview"]+def test_overview_needs_a_connected_installation(self) -> None:res = self.client.get(self._url("repository_overview/?installation_id=9999"))diff --git a/products/review_hog/frontend/CodeReviewScene.stories.tsx b/products/review_hog/frontend/CodeReviewScene.stories.tsxindex 54aa89e392a5..c8d741d1411d 100644--- a/products/review_hog/frontend/CodeReviewScene.stories.tsx+++ b/products/review_hog/frontend/CodeReviewScene.stories.tsx@@ -431,6 +431,7 @@ interface StoryRepositoryRow {id: stringselected: booleanflash_for: AutomaticFlashForEnumApi | null+ review_drafts: booleanpeople: ReviewRepositoryPersonApi[]}@@ -480,15 +481,17 @@ function initialRows(): Record<string, StoryRepositoryRow> {id: 'repo-web',selected: true,flash_for: 'everyone',+ review_drafts: true,people: [person(MOCK_SECOND_BASIC_USER, 'excepted'), person(VIEWER, 'excepted')],},'example-org/api': {id: 'repo-api',selected: true,flash_for: 'listed',+ review_drafts: false,people: [person(MOCK_SECOND_BASIC_USER, 'listed'), person(ADA, 'listed')],},- 'example-org/docs': { id: 'repo-docs', selected: true, flash_for: null, people: [] },+ 'example-org/docs': { id: 'repo-docs', selected: true, flash_for: null, review_drafts: true, people: [] },}}@@ -541,6 +544,7 @@ function overviewEntry(name: string): ReviewRepositoryOverviewEntryApi {selected: row?.selected ?? false,repository_id: row?.id ?? null,exception: own && row?.flash_for ? { flash_for: row.flash_for, people: row.people } : null,+ review_drafts: own && !!row?.review_drafts,my_choice: own ? (choice?.mode ?? null) : null,my_choice_id: own ? (choice?.id ?? null) : null,my_result: own && choice ? { flash: choice.mode === 'flash', reason: 'own_repository_choice' } : base,@@ -560,14 +564,16 @@ function saveRepository(write: ReviewRepositoryWriteApi): void {id: `repo-new-${storyState.nextId++}`,selected: false,flash_for: null,+ review_drafts: false,people: [],}const next = {...current,selected: write.selected ?? current.selected,flash_for: write.flash_for !== undefined ? write.flash_for : current.flash_for,+ review_drafts: write.review_drafts ?? current.review_drafts,}- if (!next.selected && next.flash_for === null) {+ if (!next.selected && next.flash_for === null && !next.review_drafts) {delete storyState.rows[write.full_name]return}@@ -650,11 +656,12 @@ const meta: Meta<typeof CodeReviewScene> = {const offset = Number(params.get('offset') ?? 0)const limit = Number(params.get('limit') ?? 50)const matching = REPOSITORY_NAMES.filter((name) => name.includes(search)).map(overviewEntry)- // Same rule as the server: this project's settings apply with no exception and no own choice.+ // Same rule as the server: this project's settings apply with no exception, no draft reviews and no own choice.const follows = (entry: ReviewRepositoryOverviewEntryApi): boolean =>entry.owner === 'this_project' &&entry.in_project &&entry.exception === null &&+ !entry.review_drafts &&entry.my_choice === nullconst entries = matching.filter((entry) =>diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.tsindex 61d7228d1651..170fb5514505 100644--- a/products/review_hog/frontend/generated/api.schemas.ts+++ b/products/review_hog/frontend/generated/api.schemas.ts@@ -336,6 +336,8 @@ export interface ReviewRepositoryApi {* * `listed` - Automatic Flash for these people* * `off` - Automatic Flash opt-in only */readonly flash_for: AutomaticFlashForEnumApi | null+ /** Whether draft pull requests in this repository get their automatic review when they open. */+ readonly review_drafts: boolean/** The people on the exception's two lists. Only the list that matches flash_for has an effect. */readonly people: readonly ReviewRepositoryPersonApi[]/** Who added the repository. */@@ -368,6 +370,8 @@ export interface ReviewRepositoryWriteApi {* * `listed` - Automatic Flash for these people* * `off` - Automatic Flash opt-in only */flash_for?: AutomaticFlashForEnumApi | null+ /** True lets draft pull requests in this repository get their automatic review when they open. False waits until they are ready for review. Omit it to keep the current value. */+ review_drafts?: boolean}export interface ReviewRepositoryWriteResponseApi {@@ -550,6 +554,8 @@ export interface ReviewRepositoryOverviewEntryApi {repository_id: string | null/** This project's repository exception. Null when the repository follows the project. */exception: ReviewRepositoryExceptionApi | null+ /** Whether draft pull requests in this repository get their automatic review when they open. Authors who turned off reviews of their drafts still get none. */+ review_drafts: boolean/** The requesting user's own choice for this repository: 'flash', 'off', or null.** * `flash` - Flash@@ -587,7 +593,7 @@ export interface ReviewRepositoryOverviewApi {* @nullable*/next_offset: number | null- /** With view 'differs', or 'all' without a search: how many repositories 'differs' leaves out because this project reviews them with no exception and no own choice. 0 otherwise. */+ /** With view 'differs', or 'all' without a search: how many repositories 'differs' leaves out because this project reviews them with no exception, no draft reviews and no own choice. 0 otherwise. */folded: number/** With view 'differs', or 'all' without a search: the names of the first left-out repositories, at most 3. Empty otherwise. */folded_preview: string[]diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.tsindex 95214cb72e3b..131158be67a8 100644--- a/products/review_hog/frontend/generated/api.ts+++ b/products/review_hog/frontend/generated/api.ts@@ -331,7 +331,7 @@ export const getReviewHogRepositoriesCreateUrl = (projectId: string) => {}/**- * Include a repository into this project, remove it, or set or clear its exception. Only the provided fields change. Including a repository that another project's 'all repositories' claim covers takes it from that project; the response names it.+ * Include a repository into this project, remove it, set or clear its exception, or turn its draft reviews on or off. Only the provided fields change. Including a repository that another project's 'all repositories' claim covers takes it from that project; the response names it.* @summary Save a repository's settings*/export const reviewHogRepositoriesCreate = async (diff --git a/products/review_hog/frontend/generated/api.zod.ts b/products/review_hog/frontend/generated/api.zod.tsindex 602557f27bc3..55c018fe4481 100644--- a/products/review_hog/frontend/generated/api.zod.ts+++ b/products/review_hog/frontend/generated/api.zod.ts@@ -117,7 +117,7 @@ export const ReviewHogProjectSettingsPeopleCreateBody = /* @__PURE__ */ zod.obje})/**- * Include a repository into this project, remove it, or set or clear its exception. Only the provided fields change. Including a repository that another project's 'all repositories' claim covers takes it from that project; the response names it.+ * Include a repository into this project, remove it, set or clear its exception, or turn its draft reviews on or off. Only the provided fields change. Including a repository that another project's 'all repositories' claim covers takes it from that project; the response names it.* @summary Save a repository's settings*/export const reviewHogRepositoriesCreateBodyInstallationIdMax = 64@@ -157,6 +157,12 @@ export const ReviewHogRepositoriesCreateBody = /* @__PURE__ */ zod.object({.describe("The repository exception: 'everyone', 'listed', or 'off'. Null clears it, so the repository follows the project rule again. Omit it to keep the current value.\n\n\* `everyone` - Automatic Flash for everyone\n\* `listed` - Automatic Flash for these people\n\* `off` - Automatic Flash opt-in only"),+ review_drafts: zod+ .boolean()+ .optional()+ .describe(+ 'True lets draft pull requests in this repository get their automatic review when they open. False waits until they are ready for review. Omit it to keep the current value.'+ ),})/**diff --git a/products/review_hog/frontend/repositories/MyDefaultCell.tsx b/products/review_hog/frontend/repositories/MyDefaultCell.tsxindex 1ead989c7467..a317ac284ce9 100644--- a/products/review_hog/frontend/repositories/MyDefaultCell.tsx+++ b/products/review_hog/frontend/repositories/MyDefaultCell.tsx@@ -37,19 +37,17 @@ export function MyDefaultCell({ className }: { className?: string }): JSX.Elemendata-attr="review-hog-default-review-mode"/></div>- <div className="flex flex-col gap-0.5">- <div className="flex flex-wrap items-center gap-2">- <span className="text-xs text-secondary">Review my draft pull requests</span>- <LemonSwitch- aria-label="Review my draft pull requests"- checked={reviewDrafts}- onChange={(checked) => updateSettings({ review_drafts: checked })}- disabledReason={disabledReason}- data-attr="review-hog-review-drafts"- />- <YouMark shown={!reviewDrafts} />- </div>- <span className="text-xs text-secondary">Turn off to wait until your PR is ready for review.</span>+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs text-secondary">Review my draft pull requests</span>+ <LemonSwitch+ aria-label="Review my draft pull requests"+ checked={reviewDrafts}+ onChange={(checked) => updateSettings({ review_drafts: checked })}+ tooltip="When off, your drafts wait until they are ready for review, in every repository."+ disabledReason={disabledReason}+ data-attr="review-hog-review-drafts"+ />+ <YouMark shown={!reviewDrafts} /></div>{notice && (<LemonBanner type="info" className="text-xs">diff --git a/products/review_hog/frontend/repositories/RepositoryDraftsSwitch.tsx b/products/review_hog/frontend/repositories/RepositoryDraftsSwitch.tsxnew file mode 100644index 000000000000..4fb23bc52399--- /dev/null+++ b/products/review_hog/frontend/repositories/RepositoryDraftsSwitch.tsx@@ -0,0 +1,35 @@+import { useActions, useValues } from 'kea'++import { LemonSwitch } from '@posthog/lemon-ui'++import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'++import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'+import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'++/** Whether draft pull requests in one repository get their automatic review when they open. */+export function RepositoryDraftsSwitch({ entry }: { entry: ReviewRepositoryOverviewEntryApi }): JSX.Element {+ const { canEdit } = useValues(reviewHogProjectSettingsLogic)+ const { busyRepositories } = useValues(reviewHogRepositoriesLogic)+ const { setRepositoryDrafts } = useActions(reviewHogRepositoriesLogic)++ const disabledReason = !canEdit+ ? 'Only project admins can change this'+ : busyRepositories.includes(entry.full_name)+ ? 'Saving…'+ : undefined++ return (+ <span className="flex items-center gap-1.5">+ <span className="text-xs text-secondary">Drafts</span>+ <LemonSwitch+ aria-label={`Review drafts in ${entry.full_name}`}+ checked={entry.review_drafts}+ onChange={(checked) => setRepositoryDrafts(entry, checked)}+ tooltip="Drafts here get one automatic review when they open."+ disabledReason={disabledReason}+ data-attr="review-hog-repository-drafts"+ />+ </span>+ )+}diff --git a/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx b/products/review_hog/frontend/repositories/RepositoryProjectCell.tsxindex 0e69ab186b9f..729023cd4dfc 100644--- a/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx+++ b/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx@@ -6,6 +6,7 @@ import { LemonButton, LemonDialog, LemonTag, Tooltip } from '@posthog/lemon-ui'import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'import { FLASH_FOR_OPTIONS, canTakeFromOtherProject, projectName } from './repositoryChoices'+import { RepositoryDraftsSwitch } from './RepositoryDraftsSwitch'import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'import { RuleControls } from './RuleControls'@@ -36,6 +37,8 @@ export function RepositoryProjectCell({const takeable = canTakeFromOtherProject(entry, installation)const canInclude = canEdit && (entry.owner === 'none' || takeable)const canRemove = canEdit && entry.in_project && entry.selected && installation?.scope !== 'all'+ // An exception row puts the switch on the line of its select, so each row keeps one draft control.+ const draftsOnStatusLine = entry.in_project && entry.exception === nullconst include = (): void => {if (!takeable) {@@ -97,8 +100,9 @@ export function RepositoryProjectCell({{(status || canInclude || canRemove) && (<div className="flex min-h-7 flex-wrap items-center gap-2">{status}- {(canInclude || canRemove) && (- <span className="ml-auto flex items-center gap-1">+ {(canInclude || canRemove || draftsOnStatusLine) && (+ <span className="ml-auto flex items-center gap-2">+ {draftsOnStatusLine && <RepositoryDraftsSwitch entry={entry} />}{canInclude ? (<LemonButtonsize="xsmall"@@ -137,9 +141,12 @@ export function RepositoryProjectCell({onAddPerson={(userId, kind) => addExceptionPerson(entry, userId, kind)}onRemovePerson={(person) => removeExceptionPerson(entry, person)}tag={- <LemonTag type="warning" size="small">- Exception- </LemonTag>+ <span className="flex items-center gap-2">+ <LemonTag type="warning" size="small">+ Exception+ </LemonTag>+ <RepositoryDraftsSwitch entry={entry} />+ </span>}removeException={canEdit ? { projectFlashFor, onRemove: () => clearException(entry) } : undefined}dataAttr="review-hog-repository-flash-for"diff --git a/products/review_hog/frontend/repositories/repositoryChoices.test.ts b/products/review_hog/frontend/repositories/repositoryChoices.test.tsindex b40cbe0d54e5..c2b8f3c25b56 100644--- a/products/review_hog/frontend/repositories/repositoryChoices.test.ts+++ b/products/review_hog/frontend/repositories/repositoryChoices.test.ts@@ -12,6 +12,7 @@ function entry(overrides: Partial<ReviewRepositoryOverviewEntryApi>): ReviewReposelected: false,repository_id: null,exception: null,+ review_drafts: false,my_choice: null,my_choice_id: null,my_result: { flash: false, reason: 'project_opt_in' },diff --git a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.tsindex 0c27ed6e6022..3f709f7ab14f 100644--- a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts+++ b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts@@ -19,6 +19,7 @@ function entry(overrides: Partial<ReviewRepositoryOverviewEntryApi>): ReviewReposelected: false,repository_id: null,exception: null,+ review_drafts: false,my_choice: null,my_choice_id: null,my_result: { flash: true, reason: 'project_everyone' },diff --git a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.tsindex 7e19dab20ed5..094003ff4efa 100644--- a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts+++ b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts@@ -195,6 +195,13 @@ export interface reviewHogRepositoriesLogicActions {setPage: (page: number) => {page: number}+ setRepositoryDrafts: (+ entry: ReviewRepositoryOverviewEntryApi,+ reviewDrafts: boolean+ ) => {+ entry: ReviewRepositoryOverviewEntryApi+ reviewDrafts: boolean+ }setSearch: (search: string) => {search: string}@@ -272,6 +279,10 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([entry,flashFor,}),+ setRepositoryDrafts: (entry: ReviewRepositoryOverviewEntryApi, reviewDrafts: boolean) => ({+ entry,+ reviewDrafts,+ }),addExceptionPerson: (entry: ReviewRepositoryOverviewEntryApi,userId: number,@@ -577,6 +588,21 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([posthog.capture('review hog repository exception changed', { flash_for: flashFor })}},+ setRepositoryDrafts: async ({ entry, reviewDrafts }) => {+ const saved = await writeRepository(+ entry,+ async () => {+ await reviewHogRepositoriesCreate(currentProjectId(), {+ ...repositoryRef(entry),+ review_drafts: reviewDrafts,+ })+ },+ 'Could not save the draft setting. Try again.'+ )+ if (saved) {+ posthog.capture('review hog repository drafts changed', { review_drafts: reviewDrafts })+ }+ },addExceptionPerson: async ({ entry, userId, kind }) => {const repositoryId = entry.repository_idif (!repositoryId) {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 281801d9c601..44ed353d394d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -100916,6 +100916,8 @@ export namespace Schemas {* * `listed` - Automatic Flash for these people* * `off` - Automatic Flash opt-in only */readonly flash_for: AutomaticFlashForEnum | null;+ /** Whether draft pull requests in this repository get their automatic review when they open. */+ readonly review_drafts: boolean;/** The people on the exception's two lists. Only the list that matches flash_for has an effect. */readonly people: readonly ReviewRepositoryPerson[];/** Who added the repository. */@@ -101023,6 +101025,8 @@ export namespace Schemas {repository_id: string | null;/** This project's repository exception. Null when the repository follows the project. */exception: ReviewRepositoryException | null;+ /** Whether draft pull requests in this repository get their automatic review when they open. Authors who turned off reviews of their drafts still get none. */+ review_drafts: boolean;/** The requesting user's own choice for this repository: 'flash', 'off', or null.** * `flash` - Flash@@ -101060,7 +101064,7 @@ export namespace Schemas {* @nullable*/next_offset: number | null;- /** With view 'differs', or 'all' without a search: how many repositories 'differs' leaves out because this project reviews them with no exception and no own choice. 0 otherwise. */+ /** With view 'differs', or 'all' without a search: how many repositories 'differs' leaves out because this project reviews them with no exception, no draft reviews and no own choice. 0 otherwise. */folded: number;/** With view 'differs', or 'all' without a search: the names of the first left-out repositories, at most 3. Empty otherwise. */folded_preview: string[];@@ -101104,6 +101108,8 @@ export namespace Schemas {* * `listed` - Automatic Flash for these people* * `off` - Automatic Flash opt-in only */flash_for?: AutomaticFlashForEnum | null;+ /** True lets draft pull requests in this repository get their automatic review when they open. False waits until they are ready for review. Omit it to keep the current value. */+ review_drafts?: boolean;}export interface ReviewRepositoryWriteResponse {