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(review-hog): let project members turn repository reviews on (#129941)

Julian Bez8ce5291f0dfd
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index 4454d3afee14..e92e1b052bd5 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -341,6 +341,8 @@ Automatic Flash uses your existing severity threshold and never resolves comment
The switch sets your `default_review_mode` preference to `flash` or `follow` through `PATCH /api/projects/<project_id>/review_hog/settings/`.
Project admins choose which repositories the project reviews, and who gets automatic Flash there, through the `review_hog/project_settings`, `review_hog/installation_claims`, and `review_hog/repositories` endpoints.
+Any project member can turn a repository on through `review_hog/repositories`: include it into the project's selection, raise its exception, or turn its draft reviews on.
+Turning a repository down or removing it stays with admins.
The Code review settings page calls automatic reviews **Standard** and requested reviews **Deep**.
Project defaults appear beside personal preferences. Personal repository choices take priority over personal defaults and project rules.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 22cf388f6b35..04c3722d140c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -16639,9 +16639,9 @@ snapshots:
scenes-code-review--settings--light:
hash: v1.k794b7964.0a83e49ea4ffddf7902c0e4a78ed177be7e24deff30fb37738876e79cfa08b5e.pUHbhbCwgKCj3xdN1SqXewLiCF0z0ykHXvjVfq5-0Mc
scenes-code-review--settings-for-member--dark:
- hash: v1.k794b7964.733445561b7ea84cebefacffe2c69461603f60dc1d2992f0d98c045c4c78e223.7RKW46z_44360alW-7V95ynREudKhb7_cHL7EI6LbVA
+ hash: v1.k794b7964.e4b568aac66c7ab86b6151c5a32c2cea36fe0310f4d36d012f0e25bb56f7bfef.kLp7JRbStiH5W8QoZx-yoiJ5o2Z6AhvUiYI0i5jWuX4
scenes-code-review--settings-for-member--light:
- hash: v1.k794b7964.88e71a4e9bba9cdeb2a2a588edff4ef6c3bdbb790bc6f1b1677ddf8fd13d8689.vtbgnr_efd5Mf0gLMIVPQ9yvMrarrqs7DQqsG7g3YxQ
+ hash: v1.k794b7964.69f98fd880ff9f8aa2d3d371350dcaca07560df977d60f9b529b009f1518102d.TnaWmd5W-f4Z1ukz3Rd3ftpAIwQqjkKcIYJGwguNUbQ
scenes-dashboards-customize-breakdown-colors--customize-breakdown-colors--dark:
hash: v1.k794b7964.cf89a12669d5221b2441fbfb4439b8b1b38191943438a2c1a220444148329954.B4ew6uW3gZCbPU_3vTOggsOyHojRlyvuXxh5FZnlO-0
scenes-dashboards-customize-breakdown-colors--customize-breakdown-colors--light:
diff --git a/products/review_hog/backend/facade/api.py b/products/review_hog/backend/facade/api.py
index b56932e47478..530037aacc2a 100644
--- a/products/review_hog/backend/facade/api.py
+++ b/products/review_hog/backend/facade/api.py
@@ -16,6 +16,7 @@ from products.review_hog.backend.activity_logging import installation_account_na
from products.review_hog.backend.automatic_review_rules import load_people
from products.review_hog.backend.facade.contracts import (
UNSET,
+ AdminOnlyChangeError,
RepositoryNotFoundError,
ReviewDetail,
ReviewInstallationClaimInfo,
@@ -297,17 +298,18 @@ def save_review_repository(
selected: bool | None,
flash_for: AutomaticFlashFor | None | Unset = UNSET,
review_drafts: bool | None = None,
+ raise_only: bool = False,
) -> ReviewRepositoryWriteOutcome:
"""Include or remove a repository, set or clear its exception, or turn its draft reviews on or off.
- Omitted fields keep their value.
+ Omitted fields keep their value. With `raise_only`, the write may only turn the repository's reviews up.
- Raises `OwnershipConflict` when another project holds the repository, and `RepositorySettingsError`
- when the rules forbid the write.
+ Raises `OwnershipConflict` when another project holds the repository, `RepositorySettingsError`
+ when the rules forbid the write, and `AdminOnlyChangeError` when a `raise_only` write turns reviews down.
"""
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, review_drafts=review_drafts
+ ref, selected=selected, flash_for=flash_for, review_drafts=review_drafts, raise_only=raise_only
)
repository = None
if result.repository is not None:
@@ -321,13 +323,22 @@ def delete_review_repository(team_id: int, user_id: int, repository_id: UUID) ->
def add_review_repository_person(
- team_id: int, user_id: int, repository_id: UUID | None, *, person_user_id: int, kind: ReviewRepositoryPersonKind
+ team_id: int,
+ user_id: int,
+ repository_id: UUID | None,
+ *,
+ person_user_id: int,
+ kind: ReviewRepositoryPersonKind,
+ raise_only: bool = False,
) -> bool:
"""Add a person to a list of a repository exception, or of the project rule when `repository_id` is None.
True when added, False when the person was already on the list. Raises `PersonNotActiveMemberError`, and
- `RepositoryNotFoundError` when the project has no such repository.
+ `RepositoryNotFoundError` when the project has no such repository. With `raise_only`, the user may only
+ add themselves to a repository's 'listed' list, and anything else raises `AdminOnlyChangeError`.
"""
+ if raise_only and (repository_id is None or person_user_id != user_id or kind != ReviewRepositoryPersonKind.LISTED):
+ raise AdminOnlyChangeError("Project members can only add themselves to a repository's people list.")
repositories = _project_repositories(team_id, user_id)
repository = None
if repository_id is not None:
diff --git a/products/review_hog/backend/facade/contracts.py b/products/review_hog/backend/facade/contracts.py
index 051c73b20f68..4b43d1dd88d1 100644
--- a/products/review_hog/backend/facade/contracts.py
+++ b/products/review_hog/backend/facade/contracts.py
@@ -209,6 +209,10 @@ class PersonNotActiveMemberError(Exception):
"""The user to add to a people list is not an active member of the project's organization."""
+class AdminOnlyChangeError(Exception):
+ """A project member asked for a change that only project admins can make. The API answers 403."""
+
+
@frozen
class ProjectRef:
"""Another project, named only inside its own organization."""
diff --git a/products/review_hog/backend/presentation/views/repositories.py b/products/review_hog/backend/presentation/views/repositories.py
index 6faf7148f296..e8f0ea596746 100644
--- a/products/review_hog/backend/presentation/views/repositories.py
+++ b/products/review_hog/backend/presentation/views/repositories.py
@@ -5,7 +5,7 @@ from uuid import UUID
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field, extend_schema_view
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound, ValidationError
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.permissions import SAFE_METHODS, BasePermission
from rest_framework.request import Request
from rest_framework.response import Response
@@ -35,6 +35,7 @@ from products.review_hog.backend.facade.api import (
)
from products.review_hog.backend.facade.contracts import (
UNSET,
+ AdminOnlyChangeError,
AutomaticReviewDecision,
OwnershipConflict,
PersonNotActiveMemberError,
@@ -379,6 +380,22 @@ class EffectiveTeamStrictManagementPermission(EffectiveTeamMemberPermission):
return request.method in SAFE_METHODS or view.is_effective_team_admin()
+class EffectiveTeamRaiseOnlyPermission(EffectiveTeamMemberPermission):
+ """Members read and may run the view's `member_write_actions`. Every other write needs an admin.
+
+ Those actions turn reviews only up for a member, and refuse anything else themselves.
+ """
+
+ message = "You don't have sufficient permissions in the project."
+
+ def has_permission(self, request: Request, view: Any) -> bool:
+ if not super().has_permission(request, view):
+ return False
+ if request.method in SAFE_METHODS or view.is_effective_team_admin():
+ return True
+ return view.action in view.member_write_actions
+
+
@extend_schema_view(
destroy=extend_schema(
summary="Remove a repository's settings",
@@ -389,12 +406,14 @@ class EffectiveTeamStrictManagementPermission(EffectiveTeamMemberPermission):
class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericViewSet):
"""The repositories this project has settings for: selected repositories and repository exceptions.
- Project members can read them. Only project admins can change them, and every change goes to the
- activity log. A repository has settings in one project at most.
+ Project members can read them and turn a repository's reviews up. Only project admins can turn them
+ down or remove them. Every change goes to the activity log. A repository has settings in one project
+ at most.
"""
scope_object = "review_hog"
- permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamStrictManagementPermission]
+ permission_classes = [PostHogFeatureFlagPermission, EffectiveTeamRaiseOnlyPermission]
+ member_write_actions = ("create", "add_person")
posthog_feature_flag = "review-hog"
serializer_class = ReviewRepositorySerializer
path_parameters = {
@@ -427,6 +446,7 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
responses={
200: OpenApiResponse(response=ReviewRepositoryWriteResponseSerializer, description="The saved settings."),
400: OpenApiResponse(response=ReviewHogSettingsErrorSerializer, description="The rules forbid the write."),
+ 403: OpenApiResponse(description="A project member asked to turn the repository's reviews down."),
409: OpenApiResponse(
response=ReviewHogSettingsErrorSerializer,
description="Another project already has settings for the repository.",
@@ -436,7 +456,8 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
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.",
+ "takes it from that project; the response names it. Project members can only turn reviews up: include "
+ "a repository, raise its exception, or turn draft reviews on. Everything else needs a project admin.",
)
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
serializer = ReviewRepositoryWriteSerializer(data=request.data)
@@ -455,7 +476,10 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
selected=data.get("selected"),
flash_for=flash_for,
review_drafts=data.get("review_drafts"),
+ raise_only=not self.is_effective_team_admin(),
)
+ except AdminOnlyChangeError as error:
+ raise PermissionDenied(str(error))
except OwnershipConflict as error:
return conflict_response(error)
except RepositorySettingsError as error:
@@ -471,9 +495,11 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
200: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was already on it."),
201: OpenApiResponse(response=ReviewRepositorySerializer, description="The person was added."),
400: OpenApiResponse(description="The user is not an active member of this project's organization."),
+ 403: OpenApiResponse(description="A project member asked to add someone else, or to the 'excepted' list."),
},
summary="Add a person to a repository exception list",
- description="Add a project member to the 'listed' or 'excepted' list of the repository exception.",
+ description="Add a project member to the 'listed' or 'excepted' list of the repository exception. A "
+ "project member who is not an admin can only add themselves to the 'listed' list.",
)
@action(detail=True, methods=["POST"], url_path="people", required_scopes=["review_hog:write"])
def add_person(self, request: Request, **kwargs: Any) -> Response:
@@ -487,7 +513,10 @@ class ReviewRepositoryViewSet(ReviewHogProjectViewSetMixin, viewsets.GenericView
repository.id,
person_user_id=serializer.validated_data["user_id"],
kind=ReviewRepositoryPersonKind(serializer.validated_data["kind"]),
+ raise_only=not self.is_effective_team_admin(),
)
+ except AdminOnlyChangeError as error:
+ raise PermissionDenied(str(error))
except PersonNotActiveMemberError as error:
raise not_active_member_error(error)
except RepositoryNotFoundError:
diff --git a/products/review_hog/backend/repository_settings.py b/products/review_hog/backend/repository_settings.py
index 1a4e8517921f..551120e0d16b 100644
--- a/products/review_hog/backend/repository_settings.py
+++ b/products/review_hog/backend/repository_settings.py
@@ -31,6 +31,7 @@ from products.review_hog.backend.automatic_review_rules import (
)
from products.review_hog.backend.facade.contracts import (
UNSET,
+ AdminOnlyChangeError,
AutomaticReviewDecision,
GitHubRepositoryListError,
OwnershipConflict,
@@ -39,9 +40,15 @@ from products.review_hog.backend.facade.contracts import (
RepositorySettingsError,
Unset,
)
-from products.review_hog.backend.facade.enums import AutomaticReviewReason, RepositoryOverviewView, RepositoryOwnerKind
+from products.review_hog.backend.facade.enums import (
+ AutomaticFlashFor,
+ AutomaticReviewReason,
+ RepositoryOverviewView,
+ RepositoryOwnerKind,
+)
from products.review_hog.backend.models import (
ReviewInstallationClaim,
+ ReviewProjectSettings,
ReviewRepository,
ReviewRepositoryPerson,
ReviewUserRepositoryChoice,
@@ -51,6 +58,8 @@ from products.review_hog.backend.preferences import DefaultReviewMode
logger = logging.getLogger(__name__)
+FLASH_FOR_RANK = {AutomaticFlashFor.OFF: 0, AutomaticFlashFor.LISTED: 1, AutomaticFlashFor.EVERYONE: 2}
+
def load_project_ref(team_id: int, *, viewer_organization_id: Any) -> ProjectRef:
"""Another project, with its name only when it is in the viewer's organization."""
@@ -274,6 +283,53 @@ class ProjectRepositories:
self._delete_rows(claim.installation_id, only_unselected=False)
claim.delete()
+ def _listed_people_get_excepted(self, row: ReviewRepository | None, old_flash_for: str | None) -> bool:
+ """Whether someone reviewed under "listed" today would be on the except list once the repository is at "everyone".
+
+ Both lists stay stored across mode changes, so one person can be on the listed list and the except list.
+ """
+ if row is None:
+ return False
+ people = ReviewRepositoryPerson.objects.for_team(self.team_id)
+ listed_source = people.filter(repository=row) if old_flash_for else people.filter(repository__isnull=True)
+ listed = listed_source.filter(kind=ReviewRepositoryPerson.Kind.LISTED).values("user_id")
+ return people.filter(repository=row, kind=ReviewRepositoryPerson.Kind.EXCEPTED, user_id__in=listed).exists()
+
+ def _check_raise_only(
+ self,
+ ref: RepositoryRef,
+ row: ReviewRepository | None,
+ claim: ReviewInstallationClaim | None,
+ new_selected: bool,
+ new_flash_for: str | None,
+ new_review_drafts: bool,
+ ) -> None:
+ """Refuse a write that turns the repository's reviews down or reaches past this project."""
+ if claim is None:
+ raise AdminOnlyChangeError("Only project admins can start reviewing a new GitHub installation.")
+ old_selected = row is not None and row.selected
+ old_flash_for = row.flash_for if row is not None else None
+ old_review_drafts = row is not None and row.review_drafts
+ if new_selected != old_selected:
+ if not new_selected:
+ raise AdminOnlyChangeError("Only project admins can remove a repository from the project.")
+ all_claim = RepositoryOwnership.all_claim(ref.installation_id)
+ if all_claim is not None and all_claim.team_id != self.team_id:
+ raise AdminOnlyChangeError("Only project admins can take a repository from another project.")
+ if new_flash_for != old_flash_for:
+ current = AutomaticFlashFor(old_flash_for or ReviewProjectSettings.load(self.team_id).flash_for)
+ goes_up = new_flash_for is not None and (
+ FLASH_FOR_RANK[AutomaticFlashFor(new_flash_for)] > FLASH_FOR_RANK[current]
+ )
+ if not goes_up:
+ raise AdminOnlyChangeError("Only project admins can turn automatic reviews down for a repository.")
+ if current == AutomaticFlashFor.LISTED and self._listed_people_get_excepted(row, old_flash_for):
+ raise AdminOnlyChangeError(
+ "Only project admins can raise this repository to everyone, because it would stop reviews for someone on its list."
+ )
+ if old_review_drafts and not new_review_drafts:
+ raise AdminOnlyChangeError("Only project admins can turn off draft reviews.")
+
def save_repository(
self,
ref: RepositoryRef,
@@ -281,10 +337,11 @@ class ProjectRepositories:
selected: bool | None = None,
flash_for: str | None | Unset = UNSET,
review_drafts: bool | None = None,
+ raise_only: bool = False,
) -> RepositoryWriteResult:
"""Include or remove a repository, set or clear its exception, or turn its draft reviews on or off.
- Omitted fields keep their value.
+ Omitted fields keep their value. With `raise_only`, the write may only turn the repository's reviews up.
"""
ref = self.verified_ref(ref)
with transaction.atomic():
@@ -292,6 +349,9 @@ class ProjectRepositories:
if row is not None and row.team_id != self.team_id:
project = self._project(row.team_id)
raise OwnershipConflict(f"{ref.full_name} is already reviewed in {project.label}.", project)
+ if row is not None:
+ # Every write saves the whole row, so two writes in flight would each restore the other's old fields.
+ row = ReviewRepository.objects.for_team(self.team_id).select_for_update().filter(pk=row.pk).first()
claim = self.claim_for(ref.installation_id)
takes_all = claim is not None and claim.scope == ReviewInstallationClaim.Scope.ALL
was_selected = row is not None and row.selected
@@ -301,6 +361,8 @@ class ProjectRepositories:
else:
new_flash_for = flash_for
new_review_drafts = review_drafts if review_drafts is not None else row is not None and row.review_drafts
+ if raise_only:
+ self._check_raise_only(ref, row, claim, new_selected, new_flash_for, new_review_drafts)
if not new_selected and not takes_all:
if isinstance(flash_for, str):
diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.py
index 9d972f884d41..2e27246d2978 100644
--- a/products/review_hog/backend/tests/test_repositories_api.py
+++ b/products/review_hog/backend/tests/test_repositories_api.py
@@ -84,6 +84,76 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):
assert getattr(self.client, method)(self._url(path), body, format="json").status_code in (200, 201)
+ @parameterized.expand(
+ [
+ ("turn_on_for_everyone", "all", None, {"flash_for": "everyone"}, 200),
+ ("include_into_selected", "selected", None, {"selected": True}, 200),
+ ("raise_listed_to_everyone", "all", {"flash_for": "listed"}, {"flash_for": "everyone"}, 200),
+ (
+ "raise_listed_to_everyone_over_a_listed_and_excepted_person",
+ "all",
+ {"flash_for": "listed", "people": ["listed", "excepted"]},
+ {"flash_for": "everyone"},
+ 403,
+ ),
+ ("turn_drafts_on", "all", None, {"review_drafts": True}, 200),
+ ("lower_everyone_to_off", "all", {"flash_for": "everyone"}, {"flash_for": "off"}, 403),
+ ("clear_the_exception", "all", {"flash_for": "everyone"}, {"flash_for": None}, 403),
+ ("pin_the_project_default", "all", None, {"flash_for": "off"}, 403),
+ ("remove_from_the_project", "selected", {"selected": True}, {"selected": False}, 403),
+ ("turn_drafts_off", "all", {"review_drafts": True}, {"review_drafts": False}, 403),
+ ("take_from_another_project", "selected_while_other_claims_all", None, {"selected": True}, 403),
+ ]
+ )
+ def test_members_can_only_turn_repository_reviews_up(
+ self, _name: str, claim_scope: str, row: dict | None, body: dict, expected_status: int
+ ) -> None:
+ if claim_scope == "selected_while_other_claims_all":
+ self._claim(self.other_team, ReviewInstallationClaim.Scope.ALL)
+ claim_scope = "selected"
+ self._claim(self.team, claim_scope)
+ if row is not None:
+ fields = {key: value for key, value in row.items() if key != "people"}
+ repository = ReviewRepository.objects.for_team(self.team.id).create(
+ team=self.team, installation_id=INSTALLATION, github_repo_id=501, full_name="example-org/web", **fields
+ )
+ for kind in row.get("people", []):
+ ReviewRepositoryPerson.objects.for_team(self.team.id).create(
+ team=self.team, repository=repository, user=self.user, kind=kind
+ )
+ before = list(ReviewRepository.objects.unscoped().values("team_id", "selected", "flash_for", "review_drafts"))
+ self._set_level(OrganizationMembership.Level.MEMBER)
+
+ res = self.client.post(self._url("repositories/"), {**WEB, **body}, format="json")
+
+ assert res.status_code == expected_status, res.json()
+ after = list(ReviewRepository.objects.unscoped().values("team_id", "selected", "flash_for", "review_drafts"))
+ assert (after == before) is (expected_status == 403)
+
+ @parameterized.expand(
+ [
+ ("add_myself_to_listed", "post", "people/", "me", "listed", 201),
+ ("add_someone_else", "post", "people/", "other", "listed", 403),
+ ("add_myself_to_excepted", "post", "people/", "me", "excepted", 403),
+ ("delete_the_repository", "delete", "", None, None, 403),
+ ]
+ )
+ def test_members_cannot_narrow_a_repository_exception(
+ self, _name: str, method: str, suffix: str, who: str | None, kind: str | None, expected_status: int
+ ) -> None:
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._claim(self.team, ReviewInstallationClaim.Scope.ALL)
+ repository = ReviewRepository.objects.for_team(self.team.id).create(
+ team=self.team, installation_id=INSTALLATION, full_name="example-org/web", flash_for="listed"
+ )
+ self._set_level(OrganizationMembership.Level.MEMBER)
+ body = {"user_id": (self.user if who == "me" else other).id, "kind": kind} if who else None
+
+ res = getattr(self.client, method)(self._url(f"repositories/{repository.id}/{suffix}"), body, format="json")
+
+ assert res.status_code == expected_status
+ assert ReviewRepository.objects.for_team(self.team.id).filter(id=repository.id).exists()
+
@parameterized.expand(ADMIN_WRITES)
def test_admin_of_an_environment_cannot_change_the_parent_project(self, path: str, method: str, body: dict) -> None:
self._set_level(OrganizationMembership.Level.MEMBER)
diff --git a/products/review_hog/frontend/CodeReviewScene.stories.tsx b/products/review_hog/frontend/CodeReviewScene.stories.tsx
index c8d741d1411d..ffd641390d2e 100644
--- a/products/review_hog/frontend/CodeReviewScene.stories.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.stories.tsx
@@ -905,7 +905,8 @@ export const SettingsForMember: Story = {
)
).toBeVisible()
await expect(await canvas.findByText('example-org/web')).toBeVisible()
- await expect(canvas.queryByText('Include in project')).not.toBeInTheDocument()
+ await expect(canvas.getAllByText('Include in project').length).toBeGreaterThan(0)
+ await expect(canvas.queryByText('Remove from project')).not.toBeInTheDocument()
await expect(canvas.queryByLabelText('Add exception for example-org/docs')).not.toBeInTheDocument()
},
}
diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.ts
index 131158be67a8..18835f8733dc 100644
--- a/products/review_hog/frontend/generated/api.ts
+++ b/products/review_hog/frontend/generated/api.ts
@@ -313,8 +313,9 @@ export const getReviewHogRepositoriesListUrl = (projectId: string) => {
/**
* The repositories this project has settings for: selected repositories and repository exceptions.
*
- * Project members can read them. Only project admins can change them, and every change goes to the
- * activity log. A repository has settings in one project at most.
+ * Project members can read them and turn a repository's reviews up. Only project admins can turn them
+ * down or remove them. Every change goes to the activity log. A repository has settings in one project
+ * at most.
*/
export const reviewHogRepositoriesList = async (
projectId: string,
@@ -331,7 +332,7 @@ export const getReviewHogRepositoriesCreateUrl = (projectId: string) => {
}
/**
- * 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.
+ * 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. Project members can only turn reviews up: include a repository, raise its exception, or turn draft reviews on. Everything else needs a project admin.
* @summary Save a repository's settings
*/
export const reviewHogRepositoriesCreate = async (
@@ -371,7 +372,7 @@ export const getReviewHogRepositoriesPeopleCreateUrl = (projectId: string, id: s
}
/**
- * Add a project member to the 'listed' or 'excepted' list of the repository exception.
+ * Add a project member to the 'listed' or 'excepted' list of the repository exception. A project member who is not an admin can only add themselves to the 'listed' list.
* @summary Add a person to a repository exception list
*/
export const reviewHogRepositoriesPeopleCreate = async (
diff --git a/products/review_hog/frontend/generated/api.zod.ts b/products/review_hog/frontend/generated/api.zod.ts
index 55c018fe4481..c3b6f0e87102 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, 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.
+ * 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. Project members can only turn reviews up: include a repository, raise its exception, or turn draft reviews on. Everything else needs a project admin.
* @summary Save a repository's settings
*/
export const reviewHogRepositoriesCreateBodyInstallationIdMax = 64
@@ -166,7 +166,7 @@ export const ReviewHogRepositoriesCreateBody = /* @__PURE__ */ zod.object({
})
/**
- * Add a project member to the 'listed' or 'excepted' list of the repository exception.
+ * Add a project member to the 'listed' or 'excepted' list of the repository exception. A project member who is not an admin can only add themselves to the 'listed' list.
* @summary Add a person to a repository exception list
*/
export const ReviewHogRepositoriesPeopleCreateBody = /* @__PURE__ */ zod.object({
diff --git a/products/review_hog/frontend/repositories/RepositoryDraftsSwitch.tsx b/products/review_hog/frontend/repositories/RepositoryDraftsSwitch.tsx
index 4fb23bc52399..d4b5b87a859c 100644
--- a/products/review_hog/frontend/repositories/RepositoryDraftsSwitch.tsx
+++ b/products/review_hog/frontend/repositories/RepositoryDraftsSwitch.tsx
@@ -13,11 +13,12 @@ export function RepositoryDraftsSwitch({ entry }: { entry: ReviewRepositoryOverv
const { busyRepositories } = useValues(reviewHogRepositoriesLogic)
const { setRepositoryDrafts } = useActions(reviewHogRepositoriesLogic)
- const disabledReason = !canEdit
- ? 'Only project admins can change this'
- : busyRepositories.includes(entry.full_name)
- ? 'Saving…'
- : undefined
+ const disabledReason =
+ !canEdit && entry.review_drafts
+ ? 'Only project admins can turn this off'
+ : busyRepositories.includes(entry.full_name)
+ ? 'Saving…'
+ : undefined
return (
<span className="flex items-center gap-1.5">
diff --git a/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx b/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx
index 729023cd4dfc..844583c91add 100644
--- a/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx
+++ b/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx
@@ -3,7 +3,11 @@ import { useActions, useValues } from 'kea'
import { IconPlus } from '@posthog/icons'
import { LemonButton, LemonDialog, LemonTag, Tooltip } from '@posthog/lemon-ui'
-import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'
+import type {
+ AutomaticFlashForEnumApi,
+ ReviewInstallationApi,
+ ReviewRepositoryOverviewEntryApi,
+} from 'products/review_hog/frontend/generated/api.schemas'
import { FLASH_FOR_OPTIONS, canTakeFromOtherProject, projectName } from './repositoryChoices'
import { RepositoryDraftsSwitch } from './RepositoryDraftsSwitch'
@@ -12,6 +16,35 @@ import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'
import { RuleControls } from './RuleControls'
import { RuleStateIcon } from './RuleStateIcon'
+/** Any member may include a repository nobody claims yet under a "selected" claim. Taking one stays with admins. */
+function canIncludeRepository(
+ entry: ReviewRepositoryOverviewEntryApi,
+ installation: ReviewInstallationApi | null,
+ canEdit: boolean,
+ takeable: boolean
+): boolean {
+ if (entry.owner === 'none') {
+ return canEdit || installation?.scope === 'selected'
+ }
+ return canEdit && takeable
+}
+
+/** Below "everyone" the button turns the repository on, which any member may do. At "everyone" an
+ * exception can only narrow the repository, so only admins get the button. */
+function addExceptionCopy(
+ name: string,
+ projectFlashFor: AutomaticFlashForEnumApi,
+ canEdit: boolean
+): { label: string; ariaLabel: string } | null {
+ if (projectFlashFor !== 'everyone') {
+ return { label: 'Turn on', ariaLabel: `Turn on automatic reviews for ${name}` }
+ }
+ if (!canEdit) {
+ return null
+ }
+ return { label: 'Exception', ariaLabel: `Add exception for ${name}` }
+}
+
/** The project side of one repository: whether this project reviews it, and its exception if any. */
export function RepositoryProjectCell({
entry,
@@ -35,7 +68,7 @@ export function RepositoryProjectCell({
const name = entry.full_name
const savingReason = busyRepositories.includes(name) ? 'Saving…' : undefined
const takeable = canTakeFromOtherProject(entry, installation)
- const canInclude = canEdit && (entry.owner === 'none' || takeable)
+ const canInclude = canIncludeRepository(entry, installation, canEdit, 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 === null
@@ -66,18 +99,18 @@ export function RepositoryProjectCell({
} else if (entry.exception === null) {
// A row on the project rule carries no text, only the project icon: the project default above says the rest once.
const projectRule = FLASH_FOR_OPTIONS.find((option) => option.value === projectFlashFor)?.label
- const addExceptionButton = canEdit ? (
+ const addCopy = addExceptionCopy(name, projectFlashFor, canEdit)
+ const addExceptionButton = addCopy ? (
<LemonButton
size="xsmall"
type="secondary"
icon={<IconPlus />}
- tooltip="Add an exception, starting from the project default"
- aria-label={`Add exception for ${name}`}
+ aria-label={addCopy.ariaLabel}
onClick={() => addException(entry)}
disabledReason={savingReason}
data-attr="review-hog-repository-add-exception"
>
- Exception
+ {addCopy.label}
</LemonButton>
) : null
status = (
diff --git a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts
index 3f709f7ab14f..134903f4101b 100644
--- a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts
+++ b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts
@@ -5,6 +5,7 @@ import { initKeaTests } from '~/test/init'
import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'
+import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'
import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'
const ROSE = { id: 202, uuid: 'user-202', email: '[email protected]', hedgehog_config: null }
@@ -163,15 +164,30 @@ describe('reviewHogRepositoriesLogic', () => {
expect(overviewViews.at(-1)).toEqual('all')
})
- it('a new exception starts as a copy of the project rule and its list', async () => {
+ it.each([
+ [
+ 'everyone',
+ 'copies the project rule and its except list',
+ [
+ 'POST repository {"installation_id":"41","full_name":"example-org/web","github_repo_id":1001,"flash_for":"everyone"}',
+ 'POST person repo-web {"user_id":202,"kind":"excepted"}',
+ ],
+ ],
+ [
+ 'off',
+ 'turns the repository on for everyone',
+ [
+ 'POST repository {"installation_id":"41","full_name":"example-org/web","github_repo_id":1001,"flash_for":"everyone"}',
+ ],
+ ],
+ ] as const)('under a project default of %s, a new exception %s', async (projectFlashFor, _behavior, expected) => {
await expectLogic(logic).toDispatchActions(['loadOverviewSuccess'])
+ const settings = reviewHogProjectSettingsLogic.values.projectSettings
+ reviewHogProjectSettingsLogic.actions.loadProjectSettingsSuccess({ ...settings!, flash_for: projectFlashFor })
await expectLogic(logic, () => logic.actions.addException(entry({}))).toFinishAllListeners()
- expect(requests).toEqual([
- 'POST repository {"installation_id":"41","full_name":"example-org/web","github_repo_id":1001,"flash_for":"everyone"}',
- 'POST person repo-web {"user_id":202,"kind":"excepted"}',
- ])
+ expect(requests).toEqual(expected)
})
it('changing my default reloads the list, because the default decides every inherited result', async () => {
diff --git a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts
index 094003ff4efa..a12bd5230fc6 100644
--- a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts
+++ b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts
@@ -31,7 +31,7 @@ import { ReviewHogRepositoryOverviewRetrieveView } from 'products/review_hog/fro
import { reviewHogSettingsLogic } from 'products/review_hog/frontend/reviewHogSettingsLogic'
import type { ReviewProjectSettingsApi } from '../generated/api.schemas'
-import { MyChoiceValue, peopleKindFor } from './repositoryChoices'
+import { MyChoiceValue } from './repositoryChoices'
import { currentProjectId, errorMessage, reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'
export const REPOSITORIES_PAGE_SIZE = 20
@@ -531,23 +531,25 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([
},
addException: async ({ entry }) => {
const project = values.projectSettings
- const flashFor = project?.flash_for ?? 'off'
- const kind = peopleKindFor(flashFor)
- const people = kind ? (project?.people ?? []).filter((person) => person.kind === kind) : []
+ // Below "everyone" the exception turns the repository on, which any member may do. At "everyone" it
+ // copies the project rule with its except list, so adding it changes nothing yet.
+ const excepted =
+ project?.flash_for === 'everyone'
+ ? project.people.filter((person) => person.kind === 'excepted')
+ : []
const saved = await writeRepository(
entry,
async () => {
- // The exception starts as a copy of the project rule, so adding it changes nothing yet.
const response = await reviewHogRepositoriesCreate(currentProjectId(), {
...repositoryRef(entry),
- flash_for: flashFor,
+ flash_for: 'everyone',
})
const repositoryId = response.repository?.id
- if (repositoryId && kind) {
- for (const person of people) {
+ if (repositoryId) {
+ for (const person of excepted) {
await reviewHogRepositoriesPeopleCreate(currentProjectId(), repositoryId, {
user_id: person.user.id,
- kind,
+ kind: 'excepted',
})
}
}
@@ -555,7 +557,7 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([
'Could not add the exception. Try again.'
)
if (saved) {
- posthog.capture('review hog repository exception added', { flash_for: flashFor })
+ posthog.capture('review hog repository exception added', { flash_for: 'everyone' })
}
},
clearException: async ({ entry }) => {