: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): fold plain repository rows and mark rule state (#117276)
Julian Bez36ae62343649
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 46d049c4e128..42a00b0d3822 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -14955,9 +14955,9 @@ snapshots:scenes-code-review--narrow--light:hash: v1.k794b7964.b0b6df7bb3075410c3f16dca6f3b59fdf224a9a920c3a248c55cd995bdd8b057.eUufZJ9SurN1Xw53s2pCYPXXo8sVjLL8lWoo_N0w61kscenes-code-review--narrow-settings--dark:- hash: v1.k794b7964.f75807585937462aee625778d7523133b00275ff2c84ed902d5a09210c0fedaf.spQW_SJpd_UEf3IDFfurPSetEi9MdIMn-eiFCTepHig+ hash: v1.k794b7964.9c6a5f5f17e2ac4cab3136659c387d5b43a56c85e2bf95496b7b327c07b9d076.88qYvpqV9D3zF6qa0utW9WvCSjlWB6SMB9YH7NLtjf4scenes-code-review--narrow-settings--light:- hash: v1.k794b7964.c6e04c34a65cf5349066aadef89ee3a1b230c173003e1cc59e03de6e5306b473.8mu6cyP-4KIH5sXhG6RoEqPY-5UjPh-zKx19ysIj-Nw+ hash: v1.k794b7964.1873b9b80b23f151cb9242d485732ffb065ae99eab39338920f7e2b84393b57b.5WIpjhbiEtVFSkWgR3_KJsi5qHtqnSmIJ4cjbM86ag0scenes-code-review--review-drawer-deep--dark:hash: v1.k794b7964.416b4c6b50ff059a3449c3f80742f5518bfd794aecfbb18ece1d6bc9d4dccbf3.IDH_1hHQmlcDP3N4j7VpgvMftz2fLSa2GJfPcg6YJ_cscenes-code-review--review-drawer-deep--light:@@ -14975,17 +14975,17 @@ snapshots:scenes-code-review--running-review--light:hash: v1.k794b7964.c2a355223797720fb333a696034be89185b0da48d9041e525d4710d806e60dd9.zgiSOOYkxBSkGu3Ph6HwXbZFtGg0i8W_lqwK8MH4aG4scenes-code-review--saved-inbox-opt-ins--dark:- hash: v1.k794b7964.0892fe3f654cd46e4948b625122c9b43ed7c6f12301322669806eafc69d763a7.vmYeiaS47-UjyoG8C8bhQvDLcCFb8f6IMpzkltQL3K8+ hash: v1.k794b7964.7a38f3e4fb34402bf9347186b800559706cedaa0244425b177cc5ee2a2deba26.imt_YryGDIqYUHC0X1sEQm32A7Kwp0O7X0CgElZyCr4scenes-code-review--saved-inbox-opt-ins--light:- hash: v1.k794b7964.0d60aa38ae3d268c2389ea3057f6e1d14935741113636f8c06c3a97dac1f258a.mSHKrlFCQ2y2aM5VT7IOH0Dvltp_bXv5rZAJ7vOQnVI+ hash: v1.k794b7964.fc13d6d7b9b7b38425d4b313e2ca67bacd51e6f3357c0db8e4034ff2fcc88d9b.22Rg31qeXGO-4Pvt5RskiyN_WIF997XZ-Q6XIJlA92Qscenes-code-review--settings--dark:- hash: v1.k794b7964.0daef8e0c3df5c7ed621e700b1ef65230994d760f73a9c1a228f899aa676bbb2.3wFMt-hnApdJmLp_9PhFPF1kuoL0PJJB3FrQ-8NFfC4+ hash: v1.k794b7964.d39f24474355c7afc175616983b30f8e97f3e92aa8171751acb596e6126cf35c.fHH2ToG9E-plAUYn3MRk1cAqQsAxGlChNBTz64sHRBQscenes-code-review--settings--light:- hash: v1.k794b7964.69581bb08edcc4e804e17dc025bade6100372b699a972fdc9b0c440d02745ac7.bW_rAc4vynXaRzDU7WvMs1Ve_jEQEK56Heh5XPo8ut4+ hash: v1.k794b7964.3e125b0f0890aecc4973706c4cb20708ae2f3a6587533ed235cc5973f4eb4360.XoBApr6ZMtKG2QnaZCrjTbSrdqlxYAIaff9S1UNQYUEscenes-code-review--settings-for-member--dark:- hash: v1.k794b7964.3364746629d70964591b449a92c443e23decc6c21468484adcc02c96a8de43b0.JrvQtGoLeuhHODHm4cH0x_CRN_ucNAqj9qUsCzA6_AM+ hash: v1.k794b7964.c648e112aa9e62c36828cd719e76a5f058a4096190a7f25724d41d2b65bdbba0.vn_Ek2GuvGtLOWurgarR_JBDfNGi-KzBL-TVGHNVCNQscenes-code-review--settings-for-member--light:- hash: v1.k794b7964.79695265752e6deda9e6a38744748de25d11106ddb98e9bf3bb5e241714fb718.UmLIjl35FPDjaeSSVDq90ctHfYHVT4JzIhNt4kuUctk+ hash: v1.k794b7964.bb60679f35a0154e02cc9d6525fd9ee9f7cbfa4ba8a83a672aa1751d07938811.owYobIkt_WGA0lZTTNCY69iwaWnhddJvHimFbKRwRhkscenes-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/backend/facade/api.py b/products/review_hog/backend/facade/api.pyindex 8b1b1e987479..13e02a7a6689 100644--- a/products/review_hog/backend/facade/api.py+++ b/products/review_hog/backend/facade/api.py@@ -74,6 +74,9 @@ from products.stamphog.backend.facade.api import has_reviewable_repo_configlogger = logging.getLogger(__name__)+# The folded row names a few of its repositories, so people can tell which ones it holds.+FOLDED_PREVIEW_SIZE = 3+def list_review_skill_choices(team_id: int, user_id: int, kind: ReviewSkillKind) -> list[ReviewSkillChoice]:"""The review skills of `kind` the user can see, by name, with the user's state for each.@@ -448,13 +451,18 @@ def get_review_repository_overview(repositories = _project_repositories(team_id, user_id)listed = repositories.installation_repositories(installation_id, search)overview = RepositoryOverview(repositories.team, repositories.user, installation_id, listed)- entries, total = overview.page(listed, view=view, offset=offset, limit=limit)+ entries, total = overview.page(view=view, offset=offset, limit=limit)+ folds = view == RepositoryOverviewView.DIFFERS or (view == RepositoryOverviewView.ALL and not search.strip())+ folded = overview.folded() if folds else []claim = repositories.claim_for(installation_id)return ReviewRepositoryOverviewPage(installation_id=installation_id,claim_scope=ReviewInstallationClaimScope(claim.scope) if claim is not None else None,entries=[_overview_entry(entry) for entry in entries],total=total,+ folded=len(folded),+ folded_preview=[entry.full_name for entry in folded[:FOLDED_PREVIEW_SIZE]],+ folded_result=folded[0].my_result if folded else None,my_choices_unlike_default=overview.choices_unlike_default(),)diff --git a/products/review_hog/backend/facade/contracts.py b/products/review_hog/backend/facade/contracts.pyindex 6326f4b96758..ba18043335f6 100644--- a/products/review_hog/backend/facade/contracts.py+++ b/products/review_hog/backend/facade/contracts.py@@ -365,6 +365,10 @@ class ReviewRepositoryOverviewPage:entries: Sequence[ReviewRepositoryOverviewEntry]# Entries that match the search and the view, on every page.total: int+ # The repositories the 'differs' view leaves out. Empty for a search and for the views other than 'differs' and 'all'.+ folded: int+ folded_preview: Sequence[str]+ folded_result: AutomaticReviewDecision | Nonemy_choices_unlike_default: intdiff --git a/products/review_hog/backend/facade/enums.py b/products/review_hog/backend/facade/enums.pyindex 4886622a665e..3c912b9eed08 100644--- a/products/review_hog/backend/facade/enums.py+++ b/products/review_hog/backend/facade/enums.py@@ -121,6 +121,7 @@ class RepositoryOverviewView(LabeledStrEnum):IN_PROJECT = "in_project", "In this project"EXCEPTIONS = "exceptions", "With exceptions"MINE = "mine", "My choices"+ DIFFERS = "differs", "Different from the project"class IssuePriority(Enum):diff --git a/products/review_hog/backend/presentation/views/project_settings.py b/products/review_hog/backend/presentation/views/project_settings.pyindex b590c8d02fdf..4bddfc2fb4b2 100644--- a/products/review_hog/backend/presentation/views/project_settings.py+++ b/products/review_hog/backend/presentation/views/project_settings.py@@ -104,7 +104,8 @@ class ReviewRepositoryOverviewQuerySerializer(serializers.Serializer):required=False,default="all",help_text="'all' repositories, 'in_project' (reviewed by this project), 'exceptions' (with a repository "- "exception), or 'mine' (with the requesting user's own choice).",+ "exception), 'mine' (with the requesting user's own choice), or 'differs' (every repository except the ones "+ "this project reviews with no exception and no own choice, which the response counts as 'folded').",)offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Entries to skip.")limit = serializers.IntegerField(@@ -167,6 +168,20 @@ class ReviewRepositoryOverviewSerializer(serializers.Serializer):total = serializers.IntegerField(help_text="Repositories that match the search and the view.")has_more = serializers.BooleanField(help_text="Whether more entries follow this page.")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."+ )+ folded_preview = serializers.ListField(+ child=serializers.CharField(),+ help_text="With view 'differs', or 'all' without a search: the names of the first left-out repositories, "+ "at most 3. Empty otherwise.",+ )+ folded_result = AutomaticReviewDecisionSerializer(+ allow_null=True,+ help_text="With view 'differs', or 'all' without a search: what the requesting user's own pull requests get "+ "in every left-out repository, which is the same for all of them. Null otherwise, or when nothing is left out.",+ )my_choices_unlike_default = serializers.IntegerField(help_text="How many of the requesting user's own repository choices in this project give something other ""than their default. Counts every installation, so the search, the view, and the page do not change it."@@ -338,6 +353,9 @@ class ReviewProjectSettingsViewSet(ReviewHogProjectViewSetMixin, viewsets.Generi"total": page.total,"has_more": has_more,"next_offset": offset + len(page.entries) if has_more else None,+ "folded": page.folded,+ "folded_preview": page.folded_preview,+ "folded_result": decision_data(page.folded_result) if page.folded_result is not None else None,"my_choices_unlike_default": page.my_choices_unlike_default,}return Response(ReviewRepositoryOverviewSerializer(data).data)diff --git a/products/review_hog/backend/repository_settings.py b/products/review_hog/backend/repository_settings.pyindex 3756d02d9bd4..66cc4d61d4c8 100644--- a/products/review_hog/backend/repository_settings.py+++ b/products/review_hog/backend/repository_settings.py@@ -6,8 +6,10 @@ repositories of an installation, and a project only stores what differs from wha"""import logging-from collections.abc import Mapping, Sequence+from collections import defaultdict+from collections.abc import Iterable, Mapping, Sequencefrom dataclasses import replace+from functools import cached_propertyfrom typing import Anyfrom uuid import UUID@@ -51,9 +53,19 @@ logger = logging.getLogger(__name__)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."""- team = Team.objects.filter(id=team_id).values("name", "organization_id").first() or {}- same_organization = team.get("organization_id") == viewer_organization_id- return ProjectRef(team_id=team_id, name=team.get("name") if same_organization else None)+ return load_project_refs([team_id], viewer_organization_id=viewer_organization_id)[team_id]+++def load_project_refs(team_ids: Iterable[int], *, viewer_organization_id: Any) -> dict[int, ProjectRef]:+ """Other projects in one query, each with its name only when it is in the viewer's organization."""+ ids = set(team_ids)+ teams = {team["id"]: team for team in Team.objects.filter(id__in=ids).values("id", "name", "organization_id")}+ refs: dict[int, ProjectRef] = {}+ for team_id in ids:+ team = teams.get(team_id, {})+ same_organization = team.get("organization_id") == viewer_organization_id+ refs[team_id] = ProjectRef(team_id=team_id, name=team.get("name") if same_organization else None)+ return refs@frozen@@ -383,6 +395,7 @@ class RepositoryOverview:self.team = teamself.user = userself.installation_id = installation_id+ self.repositories = repositoriesself.rows = RepositoryOwnership.rows_for_listing((str(repository["full_name"]) for repository in repositories),(repository["id"] for repository in repositories if isinstance(repository.get("id"), int)),@@ -391,20 +404,32 @@ class RepositoryOverview:own_rows = [row for row in self.rows if row.team_id == team.id]self.rules = ProjectRuleContext.load(team.id, own_rows)self.viewer: AuthorPreferences = load_author_preferences(team.id, user_id=user.id, is_bot=False)- self._projects: dict[int, ProjectRef] = {}-- def _project(self, team_id: int) -> ProjectRef:- if team_id not in self._projects:- self._projects[team_id] = load_project_ref(team_id, viewer_organization_id=self.team.organization_id)- return self._projects[team_id]+ # Some views compute every entry, so each lookup below must not scan all rows or query per owner.+ self._rows_by_id: dict[int, list[ReviewRepository]] = defaultdict(list)+ self._rows_by_name: dict[str, list[ReviewRepository]] = defaultdict(list)+ for row in self.rows:+ if row.github_repo_id is not None:+ self._rows_by_id[row.github_repo_id].append(row)+ self._rows_by_name[row.full_name.lower()].append(row)+ owner_team_ids = {row.team_id for row in self.rows}+ if self.all_claim is not None:+ owner_team_ids.add(self.all_claim.team_id)+ owner_team_ids.discard(team.id)+ self._projects = load_project_refs(owner_team_ids, viewer_organization_id=team.organization_id)++ def _candidate_rows(self, ref: RepositoryRef) -> list[ReviewRepository]:+ """The rows that can match `ref`. Id matches come first, which keeps the result of `find_matching_row`."""+ by_id = self._rows_by_id.get(ref.github_repo_id, []) if ref.github_repo_id is not None else []+ return by_id + self._rows_by_name.get(ref.full_name.lower(), [])def entry(self, repository: Mapping[str, Any]) -> OverviewEntry:github_repo_id = repository.get("id") if isinstance(repository.get("id"), int) else Noneref = RepositoryRef(installation_id=self.installation_id, github_repo_id=github_repo_id, full_name=str(repository["full_name"]))- owner = resolve_owner(ref, self.rows, self.all_claim)- own_row = find_matching_row(ref, [row for row in self.rows if row.team_id == self.team.id])+ rows = self._candidate_rows(ref)+ owner = resolve_owner(ref, rows, self.all_claim)+ own_row = find_matching_row(ref, [row for row in rows if row.team_id == self.team.id])in_project = owner is not None and owner.team_id == self.team.idchoice = self.viewer.choice_for(ref)if in_project:@@ -424,7 +449,7 @@ class RepositoryOverview:elif in_project:owner_kind, owner_project = RepositoryOwnerKind.THIS_PROJECT, Noneelse:- owner_kind, owner_project = RepositoryOwnerKind.OTHER_PROJECT, self._project(owner.team_id)+ owner_kind, owner_project = RepositoryOwnerKind.OTHER_PROJECT, self._projects[owner.team_id]has_exception = own_row is not None and own_row.flash_for is not Nonereturn OverviewEntry(full_name=ref.full_name,@@ -447,7 +472,29 @@ class RepositoryOverview:return len(self.viewer.choices)return sum(1 for choice in self.viewer.choices if choice.mode != self.viewer.default_mode)+ @cached_property+ def all_entries(self) -> list[OverviewEntry]:+ # Every view except 'all' filters on computed entries, and the 'differs' view also counts the rest.+ return [self.entry(repository) for repository in self.repositories]++ @staticmethod+ def follows_project(entry: OverviewEntry) -> bool:+ """No exception and no own choice, so the entry gets exactly what every other such entry gets."""+ has_exception = entry.repository is not None and entry.repository.flash_for is not None+ return (+ entry.owner == RepositoryOwnerKind.THIS_PROJECT+ and entry.in_project+ and not has_exception+ and entry.my_choice is None+ )++ def folded(self) -> list[OverviewEntry]:+ """The entries the 'differs' view leaves out."""+ return [entry for entry in self.all_entries if self.follows_project(entry)]+def _in_view(self, entry: OverviewEntry, view: str) -> bool:+ if view == RepositoryOverviewView.DIFFERS:+ return not self.follows_project(entry)if view == RepositoryOverviewView.IN_PROJECT:return entry.in_projectif view == RepositoryOverviewView.EXCEPTIONS:@@ -456,15 +503,12 @@ class RepositoryOverview:return entry.my_choice is not Nonereturn True- def page(- self, repositories: Sequence[Mapping[str, Any]], *, view: str, offset: int, limit: int- ) -> tuple[list[OverviewEntry], int]:+ def page(self, *, view: str, offset: int, limit: int) -> tuple[list[OverviewEntry], int]:"""One page of entries and the total that match the view."""if view == RepositoryOverviewView.ALL:- return [self.entry(repository) for repository in repositories[offset : offset + limit]], len(repositories)- matching = [- entry for entry in (self.entry(repository) for repository in repositories) if self._in_view(entry, view)- ]+ page = self.repositories[offset : offset + limit]+ return [self.entry(repository) for repository in page], len(self.repositories)+ matching = [entry for entry in self.all_entries if self._in_view(entry, view)]return matching[offset : offset + limit], len(matching)diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.pyindex a156cafd8068..a2d31875147f 100644--- a/products/review_hog/backend/tests/test_repositories_api.py+++ b/products/review_hog/backend/tests/test_repositories_api.py@@ -362,10 +362,20 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):exceptions = self.client.get(f"{url}&view=exceptions").json()assert [entry["full_name"] for entry in exceptions["results"]] == ["example-org/docs"]+ # web follows the project with no exception and no own choice, so only the fold counts it.+ differs = self.client.get(f"{url}&view=differs").json()+ assert sorted(entry["full_name"] for entry in differs["results"]) == ["example-org/api", "example-org/docs"]+ assert (differs["folded"], differs["folded_preview"], differs["folded_result"]) == (+ 1,+ ["example-org/web"],+ {"flash": True, "reason": "own_default"},+ )page = self.client.get(f"{url}&view=in_project&limit=1").json()assert (page["total"], page["has_more"], page["next_offset"]) == (2, True, 1)+ assert everything.json()["folded"] == differs["folded"]searched = self.client.get(f"{url}&search=API").json()assert [entry["full_name"] for entry in searched["results"]] == ["example-org/api"]+ assert searched["folded"] == 0def 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 aa46f25ce9ee..0704eefc0ff9 100644--- a/products/review_hog/frontend/CodeReviewScene.stories.tsx+++ b/products/review_hog/frontend/CodeReviewScene.stories.tsx@@ -383,6 +383,9 @@ const ADA: UserBasicType = {email: '[email protected]',}+// The logged-in mock user has another id than MOCK_DEFAULT_BASIC_USER, and the rule chips mark only the viewer with "(you)".+const VIEWER: UserBasicType = { ...MOCK_DEFAULT_BASIC_USER, id: MOCK_DEFAULT_USER.id }+const members: OrganizationMemberType[] = [MOCK_DEFAULT_ORGANIZATION_MEMBER,{ ...MOCK_DEFAULT_ORGANIZATION_MEMBER, id: 'member-rose', user: MOCK_SECOND_BASIC_USER },@@ -477,7 +480,7 @@ function initialRows(): Record<string, StoryRepositoryRow> {id: 'repo-web',selected: true,flash_for: 'everyone',- people: [person(MOCK_SECOND_BASIC_USER, 'excepted'), person(MOCK_DEFAULT_BASIC_USER, 'excepted')],+ people: [person(MOCK_SECOND_BASIC_USER, 'excepted'), person(VIEWER, 'excepted')],},'example-org/api': {id: 'repo-api',@@ -510,8 +513,7 @@ function inherited(name: string, { withDefault = true }: { withDefault?: booleanconst flashFor = exception ?? storyState.project.flash_for ?? 'off'const people = exception ? row.people : storyState.project.peopleconst scope = exception ? 'repository' : 'project'- const listed = (kind: string): boolean =>- people.some((entry) => entry.kind === kind && entry.user.id === MOCK_DEFAULT_BASIC_USER.id)+ const listed = (kind: string): boolean => people.some((entry) => entry.kind === kind && entry.user.id === VIEWER.id)const decision = (flash: boolean, rule: string): AutomaticReviewDecisionApi => ({flash,reason: `${scope}_${rule}` as AutomaticReviewReasonEnumApi,@@ -647,15 +649,22 @@ const meta: Meta<typeof CodeReviewScene> = {const view = params.get('view') ?? 'all'const offset = Number(params.get('offset') ?? 0)const limit = Number(params.get('limit') ?? 50)- const entries = REPOSITORY_NAMES.filter((name) => name.includes(search))- .map(overviewEntry)- .filter(- (entry) =>- view === 'all' ||- (view === 'in_project' && entry.in_project) ||- (view === 'exceptions' && entry.exception !== null) ||- (view === 'mine' && entry.my_choice !== null)- )+ 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.+ const follows = (entry: ReviewRepositoryOverviewEntryApi): boolean =>+ entry.owner === 'this_project' &&+ entry.in_project &&+ entry.exception === null &&+ entry.my_choice === null+ const entries = matching.filter(+ (entry) =>+ view === 'all' ||+ (view === 'in_project' && entry.in_project) ||+ (view === 'exceptions' && entry.exception !== null) ||+ (view === 'mine' && entry.my_choice !== null) ||+ (view === 'differs' && !follows(entry))+ )+ const folded = view === 'differs' ? matching.filter(follows) : []const page = entries.slice(offset, offset + limit)return [200,@@ -666,6 +675,9 @@ const meta: Meta<typeof CodeReviewScene> = {total: entries.length,has_more: offset + limit < entries.length,next_offset: offset + limit < entries.length ? offset + limit : null,+ folded: folded.length,+ folded_preview: folded.slice(0, 3).map((entry) => entry.full_name),+ folded_result: folded[0]?.my_result ?? null,my_choices_unlike_default: choicesUnlikeDefault(),},]diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.tsindex 87b2a2caaa5a..85df388aedb8 100644--- a/products/review_hog/frontend/generated/api.schemas.ts+++ b/products/review_hog/frontend/generated/api.schemas.ts@@ -587,6 +587,12 @@ 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. */+ 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[]+ /** With view 'differs', or 'all' without a search: what the requesting user's own pull requests get in every left-out repository, which is the same for all of them. Null otherwise, or when nothing is left out. */+ folded_result: AutomaticReviewDecisionApi | null/** How many of the requesting user's own repository choices in this project give something other than their default. Counts every installation, so the search, the view, and the page do not change it. */my_choices_unlike_default: number}@@ -1640,12 +1646,13 @@ export type ReviewHogRepositoryOverviewRetrieveParams = {*/search?: string/**- * 'all' repositories, 'in_project' (reviewed by this project), 'exceptions' (with a repository exception), or 'mine' (with the requesting user's own choice).+ * 'all' repositories, 'in_project' (reviewed by this project), 'exceptions' (with a repository exception), 'mine' (with the requesting user's own choice), or 'differs' (every repository except the ones this project reviews with no exception and no own choice, which the response counts as 'folded').** * `all` - All repositories* * `in_project` - In this project* * `exceptions` - With exceptions* * `mine` - My choices+ * * `differs` - Different from the project* @minLength 1*/view?: ReviewHogRepositoryOverviewRetrieveView@@ -1659,6 +1666,7 @@ export const ReviewHogRepositoryOverviewRetrieveView = {InProject: 'in_project',Exceptions: 'exceptions',Mine: 'mine',+ Differs: 'differs',} as constexport type ReviewHogReviewsListParams = {diff --git a/products/review_hog/frontend/repositories/MyDefaultCell.tsx b/products/review_hog/frontend/repositories/MyDefaultCell.tsxindex 2c3e91c53d9e..1ead989c7467 100644--- a/products/review_hog/frontend/repositories/MyDefaultCell.tsx+++ b/products/review_hog/frontend/repositories/MyDefaultCell.tsx@@ -7,6 +7,7 @@ import { reviewHogSettingsLogic } from 'products/review_hog/frontend/reviewHogSeimport { DEFAULT_REVIEW_MODE_OPTIONS, myDefaultNotice } from './repositoryChoices'import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'+import { withYouIcons } from './withYouIcons'import { YouMark } from './YouMark'export function MyDefaultCell({ className }: { className?: string }): JSX.Element {@@ -30,12 +31,11 @@ export function MyDefaultCell({ className }: { className?: string }): JSX.Elemensize="small"aria-label="My default for automatic reviews"value={value}- options={DEFAULT_REVIEW_MODE_OPTIONS}+ options={withYouIcons(DEFAULT_REVIEW_MODE_OPTIONS)}onChange={(mode) => mode !== value && setMyDefault(mode)}disabledReason={disabledReason}data-attr="review-hog-default-review-mode"/>- <YouMark shown={value !== 'follow'} /></div><div className="flex flex-col gap-0.5"><div className="flex flex-wrap items-center gap-2">diff --git a/products/review_hog/frontend/repositories/PeopleList.tsx b/products/review_hog/frontend/repositories/PeopleList.tsxindex 46f1d4fc582f..25edea45a0f9 100644--- a/products/review_hog/frontend/repositories/PeopleList.tsx+++ b/products/review_hog/frontend/repositories/PeopleList.tsx@@ -32,7 +32,7 @@ export function PeopleList({return (<div className="flex flex-wrap items-center gap-1.5 text-xs">- <span className="text-secondary">{kind === 'excepted' ? 'except:' : 'People:'}</span>+ <span className="text-secondary">{kind === 'excepted' ? 'Except:' : 'People:'}</span>{listed.map((person) => (<LemonSnackkey={person.id}diff --git a/products/review_hog/frontend/repositories/RepositoriesPanes.tsx b/products/review_hog/frontend/repositories/RepositoriesPanes.tsxindex fa5e65eb2014..7838055de94f 100644--- a/products/review_hog/frontend/repositories/RepositoriesPanes.tsx+++ b/products/review_hog/frontend/repositories/RepositoriesPanes.tsx@@ -1,11 +1,13 @@import { useActions, useValues } from 'kea'-import { Fragment } from 'react'import { LemonBanner, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'+import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'+import { MyDefaultCell } from './MyDefaultCell'import { PANE_LEFT, PANE_RIGHT, PANE_ROW } from './paneClasses'import { ProjectRuleCell } from './ProjectRuleCell'+import { RepositoryFoldRow } from './RepositoryFoldRow'import { RepositoryListPager } from './RepositoryListPager'import { RepositoryListToolbar } from './RepositoryListToolbar'import { RepositoryMyCell } from './RepositoryMyCell'@@ -13,9 +15,35 @@ import { RepositoryProjectCell } from './RepositoryProjectCell'import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'+function RepositoryRow({ entry }: { entry: ReviewRepositoryOverviewEntryApi }): JSX.Element {+ return (+ <>+ <div className={`flex min-w-0 items-start px-4 pt-2.5 @min-[48rem]:pb-2.5 ${PANE_LEFT} ${PANE_ROW}`}>+ <span+ className={`min-h-7 min-w-0 truncate font-mono text-sm leading-7 font-semibold ${entry.in_project ? '' : 'text-secondary'}`}+ title={entry.full_name}+ >+ {entry.full_name}+ </span>+ </div>+ <RepositoryProjectCell+ entry={entry}+ className={`${PANE_LEFT} pt-0 @min-[48rem]:border-t @min-[48rem]:border-primary @min-[48rem]:pt-2.5`}+ />+ {/* Narrow, the two cells form one block, so only the wide layout draws a line between them. */}+ <RepositoryMyCell+ entry={entry}+ className={`${PANE_RIGHT} pt-0 @min-[48rem]:border-t @min-[48rem]:border-primary @min-[48rem]:pt-2.5`}+ />+ </>+ )+}+function RepositoryRows(): JSX.Element {- const { overview, overviewLoading, overviewLoadFailed } = useValues(reviewHogRepositoriesLogic)+ const { overview, overviewLoading, overviewLoadFailed, folding, foldOpen, foldSummary } =+ useValues(reviewHogRepositoriesLogic)const { loadOverview } = useActions(reviewHogRepositoriesLogic)+ const foldRow = folding && foldSummary ? <RepositoryFoldRow summary={foldSummary} /> : nullif (overview === null) {if (overviewLoadFailed) {@@ -41,25 +69,21 @@ function RepositoryRows(): JSX.Element {</div>)}- if (overview.results.length === 0) {+ if (overview.results.length === 0 && !foldRow) {return (<div className={`col-span-full px-4 py-3 text-xs text-secondary ${PANE_LEFT} ${PANE_ROW}`}>No repositories match.</div>)}+ // Closed, the fold row ends the list of repositories that differ. Open, it heads the full list.return (<>+ {foldOpen && foldRow}{overview.results.map((entry) => (- <Fragment key={entry.full_name}>- <RepositoryProjectCell entry={entry} className={`${PANE_LEFT} ${PANE_ROW}`} />- {/* Narrow, the two cells form one block, so only the wide layout draws a line between them. */}- <RepositoryMyCell- entry={entry}- className={`${PANE_RIGHT} pt-0 @min-[48rem]:border-t @min-[48rem]:border-primary @min-[48rem]:pt-2.5`}- />- </Fragment>+ <RepositoryRow key={entry.full_name} entry={entry} />))}+ {!foldOpen && foldRow}</>)}@@ -79,7 +103,7 @@ export function RepositoriesPanes(): JSX.Element {<div className={`flex flex-col gap-0.5 px-4 py-3 ${PANE_LEFT}`}><span className="flex flex-wrap items-center gap-2 text-sm font-semibold">This project- <LemonTag type="success" size="small">+ <LemonTag type="muted" size="small">{canEdit ? 'Admin' : 'Admin access required'}</LemonTag></span>@@ -95,7 +119,18 @@ export function RepositoriesPanes(): JSX.Element {</div><ProjectRuleCell className={`${PANE_LEFT} ${PANE_ROW}`} /><MyDefaultCell className={`${PANE_RIGHT} ${PANE_ROW}`} />+ </div>+ <div className="mt-4 grid grid-cols-1 overflow-hidden rounded border border-primary @min-[48rem]:grid-cols-[minmax(0,0.8fr)_minmax(0,1.15fr)_minmax(0,1fr)] [&>*:first-child]:border-t-0"><RepositoryListToolbar />+ {/* The personal column uses the same name as the Deep settings tables. */}+ {['Repository', 'Project', 'My preference'].map((column) => (+ <div+ key={column}+ className={`hidden px-4 py-1.5 text-xxs font-semibold tracking-wide text-secondary uppercase @min-[48rem]:block ${column === 'My preference' ? PANE_RIGHT : PANE_LEFT} ${PANE_ROW}`}+ >+ {column}+ </div>+ ))}<RepositoryRows /><RepositoryListPager /></div>diff --git a/products/review_hog/frontend/repositories/RepositoryFoldRow.tsx b/products/review_hog/frontend/repositories/RepositoryFoldRow.tsxnew file mode 100644index 000000000000..c50df708352c--- /dev/null+++ b/products/review_hog/frontend/repositories/RepositoryFoldRow.tsx@@ -0,0 +1,78 @@+import { useActions, useValues } from 'kea'++import { IconChevronRight } from '@posthog/icons'++import { PANE_LEFT, PANE_RIGHT, PANE_ROW } from './paneClasses'+import { FLASH_FOR_OPTIONS, describeResult, describeSource } from './repositoryChoices'+import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'+import { FoldSummary, reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'+import { RuleStateIcon } from './RuleStateIcon'++/** "mobile-app, infra and sdk-js", so the row says which repositories it holds. */+function previewNames(summary: FoldSummary): string {+ const names = summary.preview.map((fullName) => fullName.split('/').pop() ?? fullName)+ if (names.length < 2) {+ return names.join('')+ }+ return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`+}++/**+ * One row for every repository that follows the project with no exception and no own choice. Those+ * repositories all get the same result, so one row states it once instead of repeating it per repository.+ */+export function RepositoryFoldRow({ summary }: { summary: FoldSummary }): JSX.Element {+ const { projectSettings } = useValues(reviewHogProjectSettingsLogic)+ const { foldOpen } = useValues(reviewHogRepositoriesLogic)+ const { setFoldOpen } = useActions(reviewHogRepositoriesLogic)+ const flashFor = projectSettings?.flash_for ?? 'off'+ const rule = FLASH_FOR_OPTIONS.find((option) => option.value === flashFor)?.label ?? ''++ return (+ <>+ <button+ type="button"+ onClick={() => setFoldOpen(!foldOpen)}+ aria-expanded={foldOpen}+ className={`flex min-w-0 cursor-pointer items-start gap-1.5 px-4 py-2.5 text-left ${PANE_LEFT} ${PANE_ROW}`}+ data-attr="review-hog-repository-fold"+ >+ <IconChevronRight+ className={`mt-0.5 shrink-0 text-base transition-transform motion-reduce:transition-none ${foldOpen ? 'rotate-90' : ''}`}+ />+ <span className="flex min-w-0 flex-col">+ <span className="text-sm font-semibold">+ {foldOpen ? 'Showing all repositories' : `${summary.count} more repositories`}+ </span>+ {!foldOpen && (+ <span className="truncate text-xs text-secondary">+ {summary.count > summary.preview.length+ ? `Like ${previewNames(summary)}`+ : previewNames(summary)}+ </span>+ )}+ </span>+ </button>+ <div className={`flex min-w-0 items-center gap-2 px-4 py-2.5 text-xs ${PANE_LEFT} ${PANE_ROW}`}>+ <RuleStateIcon flashFor={flashFor} />+ <span>+ <span className="text-secondary">No exception, so the project default applies:</span>{' '}+ <span>{rule.toLowerCase()}</span>+ </span>+ </div>+ <div className={`flex min-w-0 items-center gap-2 px-4 py-2.5 text-xs ${PANE_RIGHT} ${PANE_ROW}`}>+ {summary.result && (+ <>+ <span+ className={`inline-block size-2 shrink-0 rounded-full ${summary.result.flash ? 'bg-success' : 'bg-border-bold'}`}+ />+ <span>+ <span>{`${describeResult(summary.result)} (${describeSource(summary.result)})`}</span>+ <span className="text-secondary"> · no choices of yours</span>+ </span>+ </>+ )}+ </div>+ </>+ )+}diff --git a/products/review_hog/frontend/repositories/RepositoryListPager.tsx b/products/review_hog/frontend/repositories/RepositoryListPager.tsxindex 98c0ddaed576..4724c3aaefb5 100644--- a/products/review_hog/frontend/repositories/RepositoryListPager.tsx+++ b/products/review_hog/frontend/repositories/RepositoryListPager.tsx@@ -2,15 +2,21 @@ import { useActions, useValues } from 'kea'import { LemonButton } from '@posthog/lemon-ui'+import { ReviewHogRepositoryOverviewRetrieveView } from 'products/review_hog/frontend/generated/api.schemas'+import { PANE_LEFT, PANE_ROW } from './paneClasses'import { REPOSITORIES_PAGE_SIZE, reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'export function RepositoryListPager(): JSX.Element | null {- const { overview, page, pageCount, overviewLoading } = useValues(reviewHogRepositoriesLogic)+ const { overview, page, pageCount, overviewLoading, requestView } = useValues(reviewHogRepositoriesLogic)const { setPage } = useActions(reviewHogRepositoriesLogic)if (!overview || overview.total === 0) {return null}+ // A closed fold leaves the few repositories that differ, which rarely need a second page.+ if (requestView === ReviewHogRepositoryOverviewRetrieveView.Differs && pageCount <= 1) {+ return null+ }const first = page * REPOSITORIES_PAGE_SIZE + 1const last = Math.min(overview.total, first + overview.results.length - 1)return (diff --git a/products/review_hog/frontend/repositories/RepositoryMyCell.tsx b/products/review_hog/frontend/repositories/RepositoryMyCell.tsxindex 5a5b7de6ec6c..853e52549f50 100644--- a/products/review_hog/frontend/repositories/RepositoryMyCell.tsx+++ b/products/review_hog/frontend/repositories/RepositoryMyCell.tsx@@ -1,6 +1,6 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonSelect, Link } from '@posthog/lemon-ui'+import { LemonButton, LemonSelect, type LemonSelectOptions, Link, Tooltip } from '@posthog/lemon-ui'import { urls } from 'scenes/urls'@@ -8,7 +8,7 @@ import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontimport { MyChoiceValue, myChoiceNote, myChoiceOptions, myChoiceValue, projectName } from './repositoryChoices'import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'-import { YouMark } from './YouMark'+import { withYouIcons } from './withYouIcons'/** The viewer's side of one repository: what their own pull requests get there, and their choice. */export function RepositoryMyCell({@@ -44,29 +44,50 @@ export function RepositoryMyCell({content = <span className="text-xs text-secondary">No automatic review. Not part of this project.</span>} else {const note = myChoiceNote(entry)+ const choices = myChoiceOptions(entry)+ // With a choice of your own, going back reads as removing it, the same way an exception is removed.+ const options: LemonSelectOptions<MyChoiceValue> = hasChoice+ ? [+ { options: [{ value: 'follow', label: 'Remove my choice' }] },+ { options: withYouIcons(choices.filter((option) => option.value !== 'follow')) },+ ]+ : withYouIcons(choices)content = (<div className="flex min-w-0 flex-col items-start gap-1">- <div className="flex max-w-full min-w-0 items-center gap-2">+ <span className="flex max-w-full min-w-0 items-center gap-2">+ {/* The dot answers "do my PRs here get a review" at a glance, so a column scan finds the off rows. */}+ <Tooltip+ title={+ entry.my_result.flash+ ? 'Your pull requests here get automatic reviews'+ : 'Your pull requests here get no automatic review'+ }+ >+ <span+ className={`inline-block size-2 shrink-0 rounded-full ${entry.my_result.flash ? 'bg-success' : 'bg-border-bold'}`}+ />+ </Tooltip><LemonSelect<MyChoiceValue>size="small"+ className="min-w-0 shrink"+ truncateText={{ maxWidthClass: 'max-w-full' }}aria-label={`My choice for ${name}`}value={value}- options={myChoiceOptions(entry)}+ options={options}onChange={(picked) => setMyChoice(entry, picked)}disabledReason={busyReason}data-attr="review-hog-my-choice"/>- <YouMark shown={hasChoice} />- </div>- {note && <span className="text-xs text-secondary">{note}</span>}+ </span>+ {note && <span className="pl-4 text-xs text-secondary">{note}</span>}</div>)}return (- <div className={`flex min-w-0 flex-col justify-center gap-1 px-4 py-2.5 ${className ?? ''}`}>+ <div className={`flex min-w-0 flex-col gap-1 px-4 py-2.5 ${className ?? ''}`}><span className="text-xxs font-semibold uppercase tracking-wide text-secondary @min-[48rem]:hidden">- My choice+ My preference</span>{content}{hasChoice && !entry.in_project && (diff --git a/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx b/products/review_hog/frontend/repositories/RepositoryProjectCell.tsxindex f2a75d9c424a..0e69ab186b9f 100644--- a/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx+++ b/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx@@ -1,14 +1,15 @@import { useActions, useValues } from 'kea'-import { IconPlus, IconX } from '@posthog/icons'-import { LemonButton, LemonDialog, LemonTag } from '@posthog/lemon-ui'+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 { canTakeFromOtherProject, flashForLabel, projectName } from './repositoryChoices'+import { FLASH_FOR_OPTIONS, canTakeFromOtherProject, projectName } from './repositoryChoices'import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'import { RuleControls } from './RuleControls'+import { RuleStateIcon } from './RuleStateIcon'/** The project side of one repository: whether this project reviews it, and its exception if any. */export function RepositoryProjectCell({@@ -18,7 +19,7 @@ export function RepositoryProjectCell({entry: ReviewRepositoryOverviewEntryApiclassName?: string}): JSX.Element {- const { projectSettings, canEdit } = useValues(reviewHogProjectSettingsLogic)+ const { canEdit, projectSettings } = useValues(reviewHogProjectSettingsLogic)const { installation, busyRepositories } = useValues(reviewHogRepositoriesLogic)const {includeRepository,@@ -53,96 +54,78 @@ export function RepositoryProjectCell({})}- let status: JSX.Element+ const projectFlashFor = projectSettings?.flash_for ?? 'off'+ let status: JSX.Element | nullif (entry.owner === 'other_project') {status = <span className="text-xs text-secondary">Reviewed in {projectName(entry.owner_project)}</span>} else if (!entry.in_project) {status = <span className="text-xs text-secondary">Not part of this project</span>} 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 ? (+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconPlus />}+ tooltip="Add an exception, starting from the project default"+ aria-label={`Add exception for ${name}`}+ onClick={() => addException(entry)}+ disabledReason={savingReason}+ data-attr="review-hog-repository-add-exception"+ >+ Exception+ </LemonButton>+ ) : nullstatus = (<>- <span className="text-xs text-secondary">- Project rule · {flashForLabel(projectSettings?.flash_for ?? 'off')}- </span>- {canEdit && (- <LemonButton- size="xsmall"- type="secondary"- icon={<IconPlus />}- tooltip="Add an exception, starting from the project settings"- aria-label={`Add exception for ${name}`}- onClick={() => addException(entry)}- disabledReason={savingReason}- data-attr="review-hog-repository-add-exception"- >- Exception- </LemonButton>- )}+ <Tooltip title={`Follows the project default: ${projectRule?.toLowerCase()}`}>+ <span className="flex">+ <RuleStateIcon flashFor={projectFlashFor} />+ </span>+ </Tooltip>+ {addExceptionButton}</>)} else {- status = (- <>- <LemonTag type="warning" size="small">- Exception- </LemonTag>- {canEdit && (- <LemonButton- size="xsmall"- type="tertiary"- icon={<IconX />}- tooltip="Clear the exception and follow the project settings again"- aria-label={`Clear exception for ${name}`}- onClick={() => clearException(entry)}- disabledReason={savingReason}- data-attr="review-hog-repository-clear-exception"- >- clear- </LemonButton>- )}- </>- )+ // The "Exception" tag sits on the line of the exception's own select, in RuleControls.+ status = null}return (<div className={`flex min-w-0 flex-col gap-1.5 px-4 py-2.5 ${className ?? ''}`}>- <div className="flex flex-wrap items-center gap-2">- <span- className={`min-w-0 truncate font-mono text-sm font-semibold ${entry.in_project ? '' : 'text-secondary'}`}- title={name}- >- {name}- </span>- {status}- {(canInclude || canRemove) && (- // Membership sits apart from the exception controls, so adding a repository never reads as clearing one.- <span className="ml-auto">- {canInclude ? (- <LemonButton- size="xsmall"- type="secondary"- aria-label={`Include ${name} in this project`}- onClick={include}- disabledReason={savingReason}- data-attr="review-hog-repository-include"- >- Include in project- </LemonButton>- ) : (- <LemonButton- size="xsmall"- type="tertiary"- aria-label={`Remove ${name} from this project`}- onClick={() => removeFromProject(entry)}- disabledReason={savingReason}- data-attr="review-hog-repository-remove"- >- Remove from project- </LemonButton>- )}- </span>- )}- </div>+ {(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 ? (+ <LemonButton+ size="xsmall"+ type="secondary"+ aria-label={`Include ${name} in this project`}+ onClick={include}+ disabledReason={savingReason}+ data-attr="review-hog-repository-include"+ >+ Include in project+ </LemonButton>+ ) : canRemove ? (+ <LemonButton+ size="xsmall"+ type="tertiary"+ aria-label={`Remove ${name} from this project`}+ onClick={() => removeFromProject(entry)}+ disabledReason={savingReason}+ data-attr="review-hog-repository-remove"+ >+ Remove from project+ </LemonButton>+ ) : null}+ </span>+ )}+ </div>+ )}{entry.in_project && entry.exception !== null && (<RuleControlslabel={`Exception for ${name}`}@@ -153,6 +136,12 @@ export function RepositoryProjectCell({onChangeFlashFor={(flashFor) => setExceptionFlashFor(entry, flashFor)}onAddPerson={(userId, kind) => addExceptionPerson(entry, userId, kind)}onRemovePerson={(person) => removeExceptionPerson(entry, person)}+ tag={+ <LemonTag type="warning" size="small">+ Exception+ </LemonTag>+ }+ removeException={canEdit ? { projectFlashFor, onRemove: () => clearException(entry) } : undefined}dataAttr="review-hog-repository-flash-for"/>)}diff --git a/products/review_hog/frontend/repositories/RuleControls.tsx b/products/review_hog/frontend/repositories/RuleControls.tsxindex 5601269d83b4..1f7f5a2fe132 100644--- a/products/review_hog/frontend/repositories/RuleControls.tsx+++ b/products/review_hog/frontend/repositories/RuleControls.tsx@@ -1,4 +1,4 @@-import { LemonSelect } from '@posthog/lemon-ui'+import { LemonSelect, type LemonSelectOptions } from '@posthog/lemon-ui'import type {AutomaticFlashForEnumApi,@@ -8,8 +8,14 @@ import type {import { PeopleList } from './PeopleList'import { FLASH_FOR_OPTIONS, peopleKindFor } from './repositoryChoices'+import { RuleStateIcon } from './RuleStateIcon'-/** Who gets automatic reviews, for the project settings and for a repository exception alike. */+const FLASH_FOR_OPTIONS_WITH_ICONS = FLASH_FOR_OPTIONS.map((option) => ({+ ...option,+ icon: <RuleStateIcon flashFor={option.value} />,+}))++/** Who gets automatic reviews, for the project default and for a repository exception alike. */export function RuleControls({label,flashFor,@@ -19,6 +25,8 @@ export function RuleControls({onChangeFlashFor,onAddPerson,onRemovePerson,+ removeException,+ tag,dataAttr,}: {label: string@@ -29,6 +37,10 @@ export function RuleControls({onChangeFlashFor: (flashFor: AutomaticFlashForEnumApi) => voidonAddPerson: (userId: number, kind: ReviewRepositoryPersonKindEnumApi) => voidonRemovePerson: (person: ReviewRepositoryPersonApi) => void+ /** Only for an exception: the picker then offers to remove it, above the rule values. */+ removeException?: { projectFlashFor: AutomaticFlashForEnumApi; onRemove: () => void }+ /** Sits at the right end of the select's line, such as the "Exception" tag of a repository. */+ tag?: React.ReactNodedataAttr: string}): JSX.Element {const kind = peopleKindFor(flashFor)@@ -42,21 +54,43 @@ export function RuleControls({onRemove={onRemovePerson}/>)+ const options: LemonSelectOptions<AutomaticFlashForEnumApi | 'remove'> = removeException+ ? [+ {+ options: [+ {+ value: 'remove',+ label: 'Remove exception',+ icon: <RuleStateIcon flashFor={removeException.projectFlashFor} />,+ 'data-attr': 'review-hog-repository-clear-exception',+ },+ ],+ },+ { options: FLASH_FOR_OPTIONS_WITH_ICONS },+ ]+ : FLASH_FOR_OPTIONS_WITH_ICONSreturn (- // The except list continues the "for everyone" sentence, so it shares the select's line.- <div className={kind === 'excepted' ? 'flex flex-wrap items-center gap-1.5' : 'flex flex-col gap-1.5'}>- <LemonSelect- size="small"- aria-label={label}- value={flashFor}- options={FLASH_FOR_OPTIONS}- onChange={(value) => value !== flashFor && onChangeFlashFor(value)}- disabledReason={disabledReason}- data-attr={dataAttr}- className="max-w-full self-start"- />- {/* A separate item, so a wrapped except list never starts its line with the comma. */}- {kind === 'excepted' && <span className="-ml-1 text-xs text-secondary">,</span>}+ // Both people lists sit on their own line under the select, so the select keeps one position in every mode.+ <div className="flex flex-col gap-1.5">+ <span className="flex flex-wrap items-center gap-2">+ <LemonSelect<AutomaticFlashForEnumApi | 'remove'>+ size="small"+ aria-label={label}+ value={flashFor}+ options={options}+ onChange={(value) => {+ if (value === 'remove') {+ removeException?.onRemove()+ } else if (value !== flashFor) {+ onChangeFlashFor(value)+ }+ }}+ disabledReason={disabledReason}+ data-attr={dataAttr}+ className="max-w-full self-start"+ />+ {tag && <span className="ml-auto">{tag}</span>}+ </span>{peopleList}</div>)diff --git a/products/review_hog/frontend/repositories/RuleStateIcon.tsx b/products/review_hog/frontend/repositories/RuleStateIcon.tsxnew file mode 100644index 000000000000..3fb09606f752--- /dev/null+++ b/products/review_hog/frontend/repositories/RuleStateIcon.tsx@@ -0,0 +1,19 @@+import type { AutomaticFlashForEnumApi } from 'products/review_hog/frontend/generated/api.schemas'++/** How much of the team a rule reviews: a filled circle for everyone, an open one for some people, grey for nobody. */+export function RuleStateIcon({ flashFor }: { flashFor: AutomaticFlashForEnumApi }): JSX.Element {+ return (+ <span+ className={`inline-flex shrink-0 ${flashFor === 'off' ? 'text-border-bold' : 'text-success'}`}+ aria-hidden+ >+ <svg width="12" height="12" viewBox="0 0 12 12">+ {flashFor === 'listed' ? (+ <circle cx="6" cy="6" r="4.75" fill="none" stroke="currentColor" strokeWidth="1.5" />+ ) : (+ <circle cx="6" cy="6" r="5.5" fill="currentColor" />+ )}+ </svg>+ </span>+ )+}diff --git a/products/review_hog/frontend/repositories/repositoryChoices.test.ts b/products/review_hog/frontend/repositories/repositoryChoices.test.tsindex 3c28cd56f98c..b40cbe0d54e5 100644--- a/products/review_hog/frontend/repositories/repositoryChoices.test.ts+++ b/products/review_hog/frontend/repositories/repositoryChoices.test.ts@@ -79,6 +79,16 @@ describe('repositoryChoices', () => {}),note: 'The repository alone gives: no automatic review',},+ {+ name: "an exception that names the viewer says so, since its headline reads 'everyone'",+ entry: entry({+ exception: { flash_for: 'everyone', people: [] },+ my_result: { flash: false, reason: 'repository_excepted' },+ inherited_result: { flash: false, reason: 'repository_excepted' },+ repository_result: { flash: false, reason: 'repository_excepted' },+ }),+ note: "You are on this repository's except list.",+ },{name: 'an own choice names what applies without it, and where that comes from',entry: entry({diff --git a/products/review_hog/frontend/repositories/repositoryChoices.ts b/products/review_hog/frontend/repositories/repositoryChoices.tsindex 8345de2bdc7a..e8ba208eeaf1 100644--- a/products/review_hog/frontend/repositories/repositoryChoices.ts+++ b/products/review_hog/frontend/repositories/repositoryChoices.ts@@ -13,6 +13,8 @@ import type {export interface ChoiceOption<T extends string> {value: Tlabel: string+ /** True for a value of the viewer's own. The select marks it with the person icon. */+ mine?: boolean}export const FLASH_FOR_OPTIONS: ChoiceOption<AutomaticFlashForEnumApi>[] = [@@ -21,14 +23,10 @@ export const FLASH_FOR_OPTIONS: ChoiceOption<AutomaticFlashForEnumApi>[] = [{ value: 'off', label: 'Only people who opt in' },]-export function flashForLabel(flashFor: AutomaticFlashForEnumApi): string {- return FLASH_FOR_OPTIONS.find((option) => option.value === flashFor)?.label ?? flashFor-}-export const DEFAULT_REVIEW_MODE_OPTIONS: ChoiceOption<DefaultReviewModeEnumApi>[] = [{ value: 'follow', label: 'Let each repository decide' },- { value: 'flash', label: 'On everywhere' },- { value: 'off', label: 'Off everywhere' },+ { value: 'flash', label: 'On everywhere', mine: true },+ { value: 'off', label: 'Off everywhere', mine: true },]export function defaultReviewModeLabel(mode: DefaultReviewModeEnumApi): string {@@ -70,12 +68,24 @@ export function describeResult(decision: AutomaticReviewDecisionApi): string {return decision.flash ? 'Automatic review' : 'No automatic review'}+/** A rule that names the viewer decides differently than its headline says, so the row says why. */+const PERSON_NOTES: Partial<Record<AutomaticReviewReasonEnumApi, string>> = {+ repository_excepted: "You are on this repository's except list.",+ repository_not_listed: "You are not on this repository's people list.",+ project_excepted: "You are on the project's except list.",+ project_not_listed: "You are not on the project's people list.",+}+/** The note under a repository's own choice, or null when the select already says enough. */export function myChoiceNote(entry: ReviewRepositoryOverviewEntryApi): string | null {const inherited = entry.inherited_resultif (entry.my_choice !== null) {return `Your choice. Without it: ${describeResult(inherited).toLowerCase()} (${describeSource(inherited)})`}+ const personNote = PERSON_NOTES[inherited.reason]+ if (personNote) {+ return personNote+ }// Rows on the project rule get no note: the notice under My default already covers them.const repositoryResult = entry.repository_resultif (inherited.reason === 'own_default' && entry.exception !== null && repositoryResult.flash !== inherited.flash) {@@ -116,10 +126,10 @@ export function myChoiceOptions(entry: ReviewRepositoryOverviewEntryApi): Choiceconst opposite: ReviewUserRepositoryChoiceModeEnumApi = inherited.flash ? 'off' : 'flash'const options: ChoiceOption<MyChoiceValue>[] = [{ value: 'follow', label: `${describeResult(inherited)} (${describeSource(inherited)})` },- { value: opposite, label: CHOICE_LABELS[opposite] },+ { value: opposite, label: CHOICE_LABELS[opposite], mine: true },]if (entry.my_choice !== null && entry.my_choice !== opposite) {- options.push({ value: entry.my_choice, label: CHOICE_LABELS[entry.my_choice] })+ options.push({ value: entry.my_choice, label: CHOICE_LABELS[entry.my_choice], mine: true })}return options}diff --git a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.tsindex ae8efd1b9760..0c27ed6e6022 100644--- a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts+++ b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts@@ -33,11 +33,15 @@ describe('reviewHogRepositoriesLogic', () => {let requests: string[]let overviewCalls: numberlet overviewTotal: number+ let overviewFolded: number+ let overviewViews: string[]beforeEach(() => {requests = []overviewCalls = 0overviewTotal = 0+ overviewFolded = 0+ overviewViews = []useMocks({get: {'/api/projects/:team_id/review_hog/project_settings/': () => [@@ -59,8 +63,9 @@ describe('reviewHogRepositoriesLogic', () => {can_edit: true,},],- '/api/projects/:team_id/review_hog/repository_overview/': () => {+ '/api/projects/:team_id/review_hog/repository_overview/': ({ request }) => {overviewCalls += 1+ overviewViews.push(new URL(request.url).searchParams.get('view') ?? '')return [200,{@@ -70,6 +75,9 @@ describe('reviewHogRepositoriesLogic', () => {total: overviewTotal,has_more: false,next_offset: null,+ folded: overviewFolded,+ folded_preview: overviewFolded > 0 ? ['example-org/web'] : [],+ folded_result: overviewFolded > 0 ? { flash: true, reason: 'own_default' } : null,my_choices_unlike_default: 0,},]@@ -138,6 +146,22 @@ describe('reviewHogRepositoriesLogic', () => {expect(requests).toEqual(expected)})+ it('folds the repositories that follow the project until the viewer opens the fold or searches', async () => {+ overviewFolded = 2+ await expectLogic(logic).toDispatchActions(['loadOverviewSuccess'])+ expect(overviewViews.at(-1)).toEqual('differs')++ overviewFolded = 1+ await expectLogic(logic, () => logic.actions.setFoldOpen(true)).toDispatchActions(['loadOverviewSuccess'])+ expect(overviewViews.at(-1)).toEqual('all')+ expect(logic.values.foldSummary?.count).toEqual(1)++ await expectLogic(logic, () => logic.actions.setFoldOpen(false)).toDispatchActions(['loadOverviewSuccess'])+ await expectLogic(logic, () => logic.actions.setSearch('web')).toDispatchActions(['loadOverviewSuccess'])+ // A search lists every match, so a folded repository stays one search away.+ expect(overviewViews.at(-1)).toEqual('all')+ })+it('a new exception starts as a copy of the project rule and its list', async () => {await expectLogic(logic).toDispatchActions(['loadOverviewSuccess'])diff --git a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.tsindex 54558b729c04..7e19dab20ed5 100644--- a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts+++ b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts@@ -19,6 +19,7 @@ import {} from 'products/review_hog/frontend/generated/api'import type {AutomaticFlashForEnumApi,+ AutomaticReviewDecisionApi,DefaultReviewModeEnumApi,ReviewInstallationApi,ReviewRepositoryOverviewApi,@@ -35,6 +36,13 @@ import { currentProjectId, errorMessage, reviewHogProjectSettingsLogic } from '.export const REPOSITORIES_PAGE_SIZE = 20+/** The repositories that follow the project with no exception and no own choice, shown as one folded row. */+export interface FoldSummary {+ count: number+ preview: string[]+ result: AutomaticReviewDecisionApi | null+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface reviewHogRepositoriesLogicValues {canEdit: boolean // reviewHogProjectSettingsLogic@@ -43,12 +51,16 @@ export interface reviewHogRepositoriesLogicValues {currentTeamId: number | null // teamLogicbusyRepositories: string[]connectGitHubUrl: string+ foldOpen: boolean+ foldSummary: FoldSummary | null+ folding: booleaninstallation: ReviewInstallationApi | nulloverview: ReviewRepositoryOverviewApi | nulloverviewLoadFailed: booleanoverviewLoading: booleanpage: numberpageCount: number+ requestView: ReviewHogRepositoryOverviewRetrieveViewsearch: stringselectedInstallationId: string | nullview: ReviewHogRepositoryOverviewRetrieveView@@ -164,6 +176,12 @@ export interface reviewHogRepositoriesLogicActions {entry: ReviewRepositoryOverviewEntryApiflashFor: AutomaticFlashForEnumApi}+ setFoldOpen: (foldOpen: boolean) => {+ foldOpen: boolean+ }+ setFoldSummary: (foldSummary: FoldSummary | null) => {+ foldSummary: FoldSummary | null+ }setMyChoice: (entry: ReviewRepositoryOverviewEntryApi,value: MyChoiceValue@@ -192,6 +210,12 @@ export interface reviewHogRepositoriesLogicMeta {installations: readonly ReviewInstallationApi[],selectedInstallationId: string | null) => ReviewInstallationApi | null+ folding: (view: ReviewHogRepositoryOverviewRetrieveView, search: string) => boolean+ requestView: (+ view: ReviewHogRepositoryOverviewRetrieveView,+ folding: boolean,+ foldOpen: boolean+ ) => ReviewHogRepositoryOverviewRetrieveViewpageCount: (overview: ReviewRepositoryOverviewApi | null) => numberconnectGitHubUrl: (currentTeamId: number | null) => string}@@ -238,6 +262,8 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([setSearch: (search: string) => ({ search }),setView: (view: ReviewHogRepositoryOverviewRetrieveView) => ({ view }),setPage: (page: number) => ({ page }),+ setFoldOpen: (foldOpen: boolean) => ({ foldOpen }),+ setFoldSummary: (foldSummary: FoldSummary | null) => ({ foldSummary }),includeRepository: (entry: ReviewRepositoryOverviewEntryApi) => ({ entry }),removeFromProject: (entry: ReviewRepositoryOverviewEntryApi) => ({ entry }),addException: (entry: ReviewRepositoryOverviewEntryApi) => ({ entry }),@@ -262,7 +288,7 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([repositorySaveFinished: (fullName: string) => ({ fullName }),}),- loaders(({ values }) => ({+ loaders(({ actions, values }) => ({overview: [null as ReviewRepositoryOverviewApi | null,{@@ -271,14 +297,28 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([if (!installationId) {return null}+ const view = values.requestView+ const folding = values.foldingconst overview = await reviewHogRepositoryOverviewRetrieve(currentProjectId(), {installation_id: installationId,search: values.search.trim() || undefined,- view: values.view,+ view,offset: values.page * REPOSITORIES_PAGE_SIZE,limit: REPOSITORIES_PAGE_SIZE,})breakpoint()+ // Folded or open, the unsearched list carries the fold counts, so a write while open refreshes them too.+ if (folding) {+ actions.setFoldSummary(+ overview.folded > 0+ ? {+ count: overview.folded,+ preview: overview.folded_preview,+ result: overview.folded_result,+ }+ : null+ )+ }return overview},},@@ -310,9 +350,24 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([setPage: (_, { page }) => page,setSearch: () => 0,setView: () => 0,+ setFoldOpen: () => 0,selectInstallation: () => 0,},],+ foldOpen: [+ false,+ {+ setFoldOpen: (_, { foldOpen }) => foldOpen,+ selectInstallation: () => false,+ },+ ],+ foldSummary: [+ null as FoldSummary | null,+ {+ setFoldSummary: (_, { foldSummary }) => foldSummary,+ selectInstallation: () => null,+ },+ ],overviewLoadFailed: [false,{@@ -341,6 +396,21 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([installations[0] ??null,],+ // Fold the repositories that follow the project, unless the viewer opened the fold, searches, or picked a tab.+ folding: [+ (s) => [s.view, s.search],+ (view: ReviewHogRepositoryOverviewRetrieveView, search: string): boolean =>+ view === ReviewHogRepositoryOverviewRetrieveView.All && !search.trim(),+ ],+ requestView: [+ (s) => [s.view, s.folding, s.foldOpen],+ (+ view: ReviewHogRepositoryOverviewRetrieveView,+ folding: boolean,+ foldOpen: boolean+ ): ReviewHogRepositoryOverviewRetrieveView =>+ folding && !foldOpen ? ReviewHogRepositoryOverviewRetrieveView.Differs : view,+ ],pageCount: [(s) => [s.overview],(overview: ReviewRepositoryOverviewApi | null): number =>@@ -401,6 +471,7 @@ export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([},setView: () => actions.loadOverview(),setPage: () => actions.loadOverview(),+ setFoldOpen: () => actions.loadOverview(),// A write can empty the last page. Go to the last page that still has rows.loadOverviewSuccess: ({ overview }) => {if (overview && values.page >= values.pageCount) {diff --git a/products/review_hog/frontend/repositories/withYouIcons.tsx b/products/review_hog/frontend/repositories/withYouIcons.tsxnew file mode 100644index 000000000000..9e60a8e762cc--- /dev/null+++ b/products/review_hog/frontend/repositories/withYouIcons.tsx@@ -0,0 +1,9 @@+import { IconPerson } from '@posthog/icons'+import type { LemonSelectOption } from '@posthog/lemon-ui'++import type { ChoiceOption } from './repositoryChoices'++/** Select options where a value of your own carries the person icon, so the select needs no separate "you" tag. */+export function withYouIcons<T extends string>(options: ChoiceOption<T>[]): LemonSelectOption<T>[] {+ return options.map(({ mine, ...option }) => ({ ...option, icon: mine ? <IconPerson /> : undefined }))+}diff --git a/products/review_hog/frontend/settings/FullReviewSettingsSection.tsx b/products/review_hog/frontend/settings/FullReviewSettingsSection.tsxindex c5a4e9d72974..1d5c12a82bfc 100644--- a/products/review_hog/frontend/settings/FullReviewSettingsSection.tsx+++ b/products/review_hog/frontend/settings/FullReviewSettingsSection.tsx@@ -3,7 +3,9 @@ import { useActions, useValues } from 'kea'import { LemonSelect, LemonSwitch } from '@posthog/lemon-ui'import type { UrgencyThresholdEnumApi } from 'products/review_hog/frontend/generated/api.schemas'+import { ChoiceOption } from 'products/review_hog/frontend/repositories/repositoryChoices'import { reviewHogProjectSettingsLogic } from 'products/review_hog/frontend/repositories/reviewHogProjectSettingsLogic'+import { withYouIcons } from 'products/review_hog/frontend/repositories/withYouIcons'import { YouMark } from 'products/review_hog/frontend/repositories/YouMark'import { reviewHogSettingsLogic } from 'products/review_hog/frontend/reviewHogSettingsLogic'@@ -36,11 +38,13 @@ function mineOptions<T extends string>(options: { value: T; label: string }[],projectValue: T,ownValue: T | undefined-): { value: T | 'project'; label: string }[] {+): ChoiceOption<T | 'project'>[] {const projectLabel = options.find((option) => option.value === projectValue)?.label ?? projectValuereturn [{ value: 'project', label: `Same as project (${projectLabel})` },- ...options.filter((option) => option.value !== projectValue || option.value === ownValue),+ ...options+ .filter((option) => option.value !== projectValue || option.value === ownValue)+ .map((option) => ({ ...option, mine: true })),]}@@ -106,7 +110,7 @@ export function FullReviewSettingsSection(): JSX.Element {truncateText={{ maxWidthClass: 'max-w-full' }}aria-label="Mine: Findings to post on GitHub"value={ownThreshold ?? 'project'}- options={mineOptions(THRESHOLD_OPTIONS, projectThreshold, ownThreshold)}+ options={withYouIcons(mineOptions(THRESHOLD_OPTIONS, projectThreshold, ownThreshold))}onChange={(value) =>value === 'project'? followProjectDefault('urgency_threshold')@@ -115,7 +119,6 @@ export function FullReviewSettingsSection(): JSX.Element {disabledReason={mineDisabledReason}data-attr="review-hog-urgency-threshold"/>- <YouMark shown={ownThreshold !== undefined} /></>}/>@@ -141,7 +144,7 @@ export function FullReviewSettingsSection(): JSX.Element {truncateText={{ maxWidthClass: 'max-w-full' }}aria-label="Mine: Celebrate clean reviews"value={ownCelebrate ?? 'project'}- options={mineOptions(ON_OFF_OPTIONS, projectCelebrate, ownCelebrate)}+ options={withYouIcons(mineOptions(ON_OFF_OPTIONS, projectCelebrate, ownCelebrate))}onChange={(value) =>value === 'project'? followProjectDefault('celebrate_clean_reviews')@@ -150,7 +153,6 @@ export function FullReviewSettingsSection(): JSX.Element {disabledReason={mineDisabledReason}data-attr="review-hog-celebrate-clean-reviews"/>- <YouMark shown={ownCelebrate !== undefined} /></>}/>diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex dde0f2692512..abc883efafdd 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -97842,6 +97842,12 @@ 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. */+ 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[];+ /** With view 'differs', or 'all' without a search: what the requesting user's own pull requests get in every left-out repository, which is the same for all of them. Null otherwise, or when nothing is left out. */+ folded_result: AutomaticReviewDecision | null;/** How many of the requesting user's own repository choices in this project give something other than their default. Counts every installation, so the search, the view, and the page do not change it. */my_choices_unlike_default: number;}@@ -128807,12 +128813,13 @@ export namespace Schemas {*/search?: string;/**- * 'all' repositories, 'in_project' (reviewed by this project), 'exceptions' (with a repository exception), or 'mine' (with the requesting user's own choice).+ * 'all' repositories, 'in_project' (reviewed by this project), 'exceptions' (with a repository exception), 'mine' (with the requesting user's own choice), or 'differs' (every repository except the ones this project reviews with no exception and no own choice, which the response counts as 'folded').** * `all` - All repositories* * `in_project` - In this project* * `exceptions` - With exceptions* * `mine` - My choices+ * * `differs` - Different from the project* @minLength 1*/view?: ReviewHogRepositoryOverviewRetrieveView;@@ -128826,6 +128833,7 @@ export namespace Schemas {InProject: 'in_project',Exceptions: 'exceptions',Mine: 'mine',+ Differs: 'differs',} as const;export type ReviewHogReviewsListParams = {