: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): settings tab with project rules and personal choices (#113818)
Julian Bez17843434a5fc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 18a64c0b30e1..6e539d36c715 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9881,9 +9881,9 @@ snapshots:scenes-app-data-warehouse-sql-editor--bi-measure-display--light:hash: v1.k794b7964.c8e9eb07cf403a27ecbaa5ff93899bbafee4f194653d2b967e46dcb1e5910073.0O9yXMzXEZk83pH3eJ69yNfa2KUR5pULsgaHg8syyH4scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:- hash: v1.k794b7964.ba547f3a41ec2e8b517142f1a6549848e39ce50da6245a8185117128424b5fc6.mto7EGXrYQwr6BBCyPfkDZS_fYGuYIb_k6KbIkShjQY+ hash: v1.k794b7964.6309ca3f3ecb88032969e856079e14cda460aa306a5172863693ff8a95ea011c.dIXWRHfmipDgezW97RK0MYne72aosXhe0o1S_uXrt_wscenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:- hash: v1.k794b7964.f17b0a24d40667261252cd224fc879c6303e143cdb46582ea0c3d58516a96508.B3zMdPmNMyvPT29AsSlyzi2TOsGlD40QZz4jThEmkXY+ hash: v1.k794b7964.d60ca4f154f5b6aa7dfe97f5907d32aeb07d408ef2ccfdd9b86bd8880c17ba6b.m2J3D-2Zw-ub5S6SSZk2MFZf3rAXWA6146N6UMKx2Xoscenes-app-data-warehouse-sql-editor--bi-numeric-bins--dark:hash: v1.k794b7964.1313c706915c92807e91e24cceeb57db1d66dfc0b41c9b674ee3b91320d952f8.TK0iXH4j6c7piySgpcruvXiCY_SNbAAZzXkW70NOSDUscenes-app-data-warehouse-sql-editor--bi-numeric-bins--light:@@ -14445,33 +14445,37 @@ snapshots:scenes-app-workflows-createaitaskconnectors--unavailable-connector--light:hash: v1.k794b7964.c4fdab3ab5190ace67d354d7010b49cbd37e9ec72feaa3fab9760d1f1010c8b0.S5qBDGrQNUo7qygcV1_MG_nu9RWeaMnoOFrYdhnV97Escenes-code-review--default--dark:- hash: v1.k794b7964.b33a0c3ec9d3743910d83bf6fc9e8e8df50243a9fcc4e9829429bee7df637fcc.b_1XIxTY9N2TEsb_TJUEhr_PuMJwuuk6tmJ6vgNPKNI+ hash: v1.k794b7964.26b2a9ccdfeb46f046c6d2caebd8c7ea3ec38717b21ac5e286d275a54d9c88e8.2taQjxsp5Ghzsi2NHa7T4gGeLzILDTz1vhH6Jae69uIscenes-code-review--default--light:- hash: v1.k794b7964.25e78fe975e3493ea0553b856b0f04a5f400c7d9b5e5d2430be6ccf9180d6124.-MB_Cb1sluGuZ5l0mKOzA_Ve5LA6dZf-ximsFGZ8Fj0+ hash: v1.k794b7964.a3b8f7ed2c6e1650be2a70b83cc057f0c5268c26f694e873ad9a9c54df8843da.2f9sqMQluNLN-TDVXouIvVMhwHntcpKLb87unaTUo_Uscenes-code-review--flag-disabled-for-staff--dark:hash: v1.k794b7964.af1b6736f5a6e6ffb329599ed7407d25dbee0939861cd554e0c94b84b2970a7c.HwLX1pgZqjpFAoG4ni16T0wtf1PJQkw0Evr2jBw2vG4scenes-code-review--flag-disabled-for-staff--light:hash: v1.k794b7964.a71251e301794f51a0a9140ab1442fada37b1cc0fb54095a5eb19499e0cb1b34.3GhhJCqNfLkY2WdBTTn0LHJifxiCqyEJ7viaHaoCoGAscenes-code-review--internal-features--dark:- hash: v1.k794b7964.f6fb596ec6cb9c4ff96fe685204c35cf6620d81ec0b4c267397e5260b4cba319.BC-PojonLRRIkCmE1w06SMLHAj3vNpBDmwz1Lqy6DQg+ hash: v1.k794b7964.a61b916676bea5494ff48e295b83eb92e1c9850a651be1c3530ac5fd322c8408.5Tp4Sn4kG5SN3u3i7Opqr0DkyO84D0w-xxXmFOSa28Iscenes-code-review--internal-features--light:- hash: v1.k794b7964.cc5e5c672572877fbae0c266e6b3a320a20666c6c058b9245364754bd5a0ad98.5IL4ttzXBh-wBA2axgr4Sg8RQirVQDZUS2aVOAO7Y0w+ hash: v1.k794b7964.25bbf6757d423d75229154f1ebfd502382a84b5a8103fe2a7a3d28864895cacb.owi4aYj4U1shMo5kWlIFeLYX9Z8PlpZBTHSRtqPMff0scenes-code-review--narrow--dark:- hash: v1.k794b7964.05d25786fae644e7fa985bd997708d94de95f69d1b2ddd4e3fa797f12a39e2ea.6daW2P95kD6OWHL3Dp3UsaCEdjNTltcu82kl6IF-yVY+ hash: v1.k794b7964.63649dd285864639be3334f1450409dd32ffb381f643a5399e16c7b48f794d68.4xKhrVrw_gEjmbdN5mWEDTj9gTuStyD0Cqne2ezG_Hwscenes-code-review--narrow--light:- hash: v1.k794b7964.546bd878a0869e18a235c9653ca3cd245dc4219e1f0d97b04cdb8dd10e109130.W3x_iacIB7oY0C-rAolmf2UZegpJAotIzO-oQ1tzKDg+ hash: v1.k794b7964.7e0bbeeffb4b8d8372dbdfe90686b2becc1991df2b78af2a0a2b6a0b3a41aadf.7Z4Aht9zbaWjsS8W-Yd9wCOuUjU5-A9Xb6Xpg__bgMsscenes-code-review--narrow-settings--dark:- hash: v1.k794b7964.cdf782bbb06ad94833e6b370163fc38086adae3e0a7262204fb245f484db4c0a.x2g0bLhG1lXqXuQ1WOLFYG8jt0ZbG7ZPyzn8y_vQGRo+ hash: v1.k794b7964.d546f76af0f025813013429c23d52b6212104cb379ec1fcf08943e4934ee2c5d.wFyM2Rme9y3HDcRPKWiOe_g6In4h_cHL9l9kce-8I0Iscenes-code-review--narrow-settings--light:- hash: v1.k794b7964.3d58a1e7d291237164789d4283eecb8b6d9bd48a72dd6cd60c81210b09cb4793.I8lBN5q2lRsu4FICyoVZlxcfrdouG5hwNATxfEjgum0+ hash: v1.k794b7964.73b9ba4a69a74077c0dc233c54662e71d63b0d9ecb492274fa9982ce756dde54.gT_BISy-ePJrir7xQgDwEUM9DCL3bIFFybJyCEtUmL8scenes-code-review--saved-inbox-opt-ins--dark:- hash: v1.k794b7964.f2d5c819a2e808c16ea634d50e27386af5e2418a47d37950b56bf20070b50a7c.wJyEO2-rtSg4H8z15MqXn2qNBlPKRmWiHTN-miC6P9E+ hash: v1.k794b7964.dad9c200176e5b9be56e1e80a1dfe3d5c1ce3a499b53be7a73c8052d585ed251.4nSbexxZBEqqRqKVwgvSaQ3k53FcZXF5-8txH9FaFQ0scenes-code-review--saved-inbox-opt-ins--light:- hash: v1.k794b7964.4e398ebc4687896fe093730c3df7538acb3dc6188c7afc737651422ab83bd677.49hCSJzvrkG78fsVgvZjOx2ReOUKjatfD-hEHJ55ZZk+ hash: v1.k794b7964.56e64569af5c37d2e61a530c2d39f74568b504dcef7cc76eff2be1433ecf2c8f.RoS4azTih4OIrutFdCk4sWUGns6WrvpPJDuPRXgJBkEscenes-code-review--settings--dark:- hash: v1.k794b7964.99c0bd08641752ff41107c904dd346706928328f357d5cee6c8d67b946349bd1.CIS_WydEc4kgzx25Z5qaNfYp8vyTjSFsA9YGkQfvuAs+ hash: v1.k794b7964.a617092a7232b08019189f2125a635fb8576ee687acecf7492dd0495d4da1118.zgtFXbxvPvpaz0TGxgPhDHLhRAdoFCnfLbx7AJlIJscscenes-code-review--settings--light:- hash: v1.k794b7964.430953687f20772b29338454be7c40ca64b1fe5ace6e550db2d0abadbe4652cd.pz_T7gTs8y0XkZkRpHI_S4sh65K2UENhgIbkdu1vjD4+ hash: v1.k794b7964.5579f34ea08fdda6357fad8a11970196becdf6597de575c2fbc774c322be689a.zzn-hRm8xYwsGUe9nHYgi0ziJQBIoC0k-oMWu_0XGG8+ scenes-code-review--settings-for-member--dark:+ hash: v1.k794b7964.f14c3a0e51ba2baebb5e0407d368b50bb340139aaec1d7eef8797140af1d7ad3.1p59Ps3G9efZlooqggBe7sC-sVF1dxVMjH2VdrkNimA+ scenes-code-review--settings-for-member--light:+ hash: v1.k794b7964.760cbd371646375a6adcbf652d575316664bb52dc81c48abfac1c0856e5c6921.LRpauwESRD6qBXB5MVNF1cKFwvFi54AXbjcPyBa0_ggscenes-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/pnpm-lock.yaml b/pnpm-lock.yamlindex e27b0088f3e8..fff383fa8bbb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -4740,6 +4740,9 @@ importers:kea-router:specifier: 'catalog:'version: 3.4.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ posthog-js:+ specifier: 'catalog:'+ version: 1.438.4(@types/[email protected])([email protected])react:specifier: 18.3.1version: 18.3.1diff --git a/products/review_hog/backend/api/project_settings.py b/products/review_hog/backend/api/project_settings.pyindex 5403d47a8e4c..abbbbb7d94d9 100644--- a/products/review_hog/backend/api/project_settings.py+++ b/products/review_hog/backend/api/project_settings.py@@ -141,6 +141,10 @@ class ReviewRepositoryOverviewEntrySerializer(serializers.Serializer):my_result = AutomaticReviewDecisionSerializer(help_text="What the requesting user's own pull requests get here, and the rule that decided it.")+ inherited_result = AutomaticReviewDecisionSerializer(+ help_text="What the requesting user's own pull requests would get here without their choice for this "+ "repository. Equals my_result when there is no choice."+ )class ReviewRepositoryOverviewSerializer(serializers.Serializer):@@ -176,6 +180,7 @@ def _entry_data(entry: OverviewEntry) -> dict[str, Any]:"my_choice": entry.my_choice.mode if entry.my_choice is not None else None,"my_choice_id": entry.my_choice.id if entry.my_choice is not None else None,"my_result": decision_data(entry.my_result),+ "inherited_result": decision_data(entry.inherited_result),}diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.pyindex 4a7ec7eed404..d4f80f4a3bb4 100644--- a/products/review_hog/backend/api/reviews.py+++ b/products/review_hog/backend/api/reviews.py@@ -36,7 +36,7 @@ from products.review_hog.backend.reviewer.artefact_content import (ReviewIssueFinding,ValidationVerdict,)-from products.review_hog.backend.reviewer.constants import effective_priority+from products.review_hog.backend.reviewer.constants import REVIEW_MODE_FULL, effective_priorityfrom products.review_hog.backend.reviewer.models.issues_review import IssuePriorityfrom products.review_hog.backend.reviewer.models.split_pr_into_chunks import ChunksListfrom products.review_hog.backend.reviewer.persistence import load_chunk_set, load_findings_bundle, load_turn_findings@@ -184,6 +184,9 @@ class ReviewRecentReviewSerializer(serializers.Serializer):allow_null=True, help_text="When the latest review turn completed; null while the first is in flight.")published = serializers.BooleanField(help_text="Whether a review has been published back to GitHub.")+ full_review_published = serializers.BooleanField(+ help_text="Whether a Full review of this pull request has been published. No Flash review runs after one."+ )in_progress = serializers.BooleanField(help_text="Whether a run is on this report right now: a review turn or a resolution run ""(activity within the last 30 minutes)."@@ -501,6 +504,8 @@ def _review_payload("run_count": report.run_count,"last_run_at": report.last_run_at,"published": report.published_head_sha is not None,+ # Reads only the per-mode marker, so the list never loads findings to tell older reports apart.+ "full_review_published": REVIEW_MODE_FULL in (report.published_heads_by_mode or {}),"in_progress": progress is not None or (resolution is not None and resolution.status == RESOLUTION_RESOLVING),"progress": progress,"resolution": {diff --git a/products/review_hog/backend/repository_settings.py b/products/review_hog/backend/repository_settings.pyindex 16ca2cb36f54..1e9d2de5e6b1 100644--- a/products/review_hog/backend/repository_settings.py+++ b/products/review_hog/backend/repository_settings.py@@ -318,6 +318,7 @@ class OverviewEntry:exception_people: Sequence[ReviewRepositoryPerson]my_choice: ReviewUserRepositoryChoice | Nonemy_result: AutomaticReviewDecision+ inherited_result: AutomaticReviewDecisionclass RepositoryOverview:@@ -355,9 +356,13 @@ class RepositoryOverview:in_project = owner is not None and owner.team_id == self.team.idchoice = self.viewer.choice_for(ref)if in_project:- result = self.rules.rule_for(own_row).resolve(self.viewer.for_repository(ref))+ rule = self.rules.rule_for(own_row)+ author = self.viewer.for_repository(ref)+ result = rule.resolve(author)+ inherited = rule.resolve(replace(author, repository_choice=None))else:result = AutomaticReviewDecision(flash=False, reason=AutomaticReviewReason.NOT_IN_PROJECT)+ inherited = resultif owner is None:owner_kind, owner_project = RepositoryOwnerKind.NONE, Noneelif in_project:@@ -376,6 +381,7 @@ class RepositoryOverview:exception_people=self.rules.people.get(own_row.id, []) if has_exception and own_row is not None else [],my_choice=choice,my_result=result,+ inherited_result=inherited,)def _in_view(self, entry: OverviewEntry, view: str) -> bool:diff --git a/products/review_hog/backend/tests/test_repositories_api.py b/products/review_hog/backend/tests/test_repositories_api.pyindex 6fc7d6e0b1e1..a6bc00a189b1 100644--- a/products/review_hog/backend/tests/test_repositories_api.py+++ b/products/review_hog/backend/tests/test_repositories_api.py@@ -282,6 +282,9 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):ReviewRepository.objects.for_team(self.team.id).create(team=self.team, installation_id=INSTALLATION, full_name="example-org/docs", flash_for="everyone")+ ReviewUserRepositoryChoice.objects.for_team(self.team.id).create(+ team=self.team, user=self.user, installation_id=INSTALLATION, full_name="example-org/docs", mode="off"+ )url = self._url(f"repository_overview/?installation_id={INSTALLATION}")everything = self.client.get(url)@@ -295,7 +298,8 @@ class TestReviewRepositorySettingsAPI(APIBaseTest):assert entries["example-org/api"]["owner_project"] == {"id": self.other_team.id, "name": "Other project"}assert entries["example-org/api"]["my_result"] == {"flash": False, "reason": "not_in_project"}assert entries["example-org/docs"]["exception"]["flash_for"] == "everyone"- assert entries["example-org/docs"]["my_result"] == {"flash": True, "reason": "repository_everyone"}+ assert entries["example-org/docs"]["my_result"] == {"flash": False, "reason": "own_repository_choice"}+ assert entries["example-org/docs"]["inherited_result"] == {"flash": True, "reason": "repository_everyone"}exceptions = self.client.get(f"{url}&view=exceptions").json()assert [entry["full_name"] for entry in exceptions["results"]] == ["example-org/docs"]diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.pyindex 067e3e57d57e..9d06d313c6e0 100644--- a/products/review_hog/backend/tests/test_reviews_api.py+++ b/products/review_hog/backend/tests/test_reviews_api.py@@ -166,6 +166,15 @@ class TestRecentReviewsAPI(APIBaseTest):assert rows[0]["published"] is Falseassert "perspective_selection" not in rows[0] # detail-only payload — the list stays lean+ def test_full_review_published_reads_only_the_full_marker(self) -> None:+ self._report(pr_number=1, acting_user=self.user, published_head_sha="a", published_heads_by_mode={"flash": "a"})+ self._report(pr_number=2, acting_user=self.user, published_head_sha="b", published_heads_by_mode={"full": "b"})++ rows = {row["pr_number"]: row for row in self.client.get(self.url).json()["results"]}++ assert rows[1]["full_review_published"] is False+ assert rows[2]["full_review_published"] is True+def test_mine_scope_includes_reviews_of_prs_i_authored(self) -> None:# The incident this guards: a review a teammate triggers on your PR lands under THEIR# acting_user, so without the author_login match it never reaches your "For you" tab — thediff --git a/products/review_hog/frontend/CodeReviewScene.stories.tsx b/products/review_hog/frontend/CodeReviewScene.stories.tsxindex d2ef751df11f..83fa989d4f4f 100644--- a/products/review_hog/frontend/CodeReviewScene.stories.tsx+++ b/products/review_hog/frontend/CodeReviewScene.stories.tsx@@ -1,4 +1,9 @@-import { MOCK_DEFAULT_USER } from 'lib/api.mock'+import {+ MOCK_DEFAULT_BASIC_USER,+ MOCK_DEFAULT_ORGANIZATION_MEMBER,+ MOCK_DEFAULT_USER,+ MOCK_SECOND_BASIC_USER,+} from 'lib/api.mock'import { Decorator, Meta, StoryObj } from '@storybook/react'import { waitFor, within } from '@testing-library/dom'@@ -10,12 +15,25 @@ import { urls } from 'scenes/urls'import { userLogic } from 'scenes/userLogic'import { mswDecorator } from '~/mocks/browser'+import { OrganizationMemberType, UserBasicType } from '~/types'import type {+ AutomaticFlashForEnumApi,+ AutomaticReviewDecisionApi,+ AutomaticReviewReasonEnumApi,+ PatchedReviewProjectSettingsApi,PatchedReviewUserSettingsApi,+ ReviewInstallationClaimScopeEnumApi,ReviewPerspectiveStatsApi,+ ReviewProjectSettingsApi,ReviewRecentReviewApi,+ ReviewRepositoryChoiceWriteApi,+ ReviewRepositoryOverviewEntryApi,+ ReviewRepositoryPersonApi,+ ReviewRepositoryPersonRequestApi,+ ReviewRepositoryWriteApi,ReviewUserSettingsApi,+ UserBasicApi,} from 'products/review_hog/frontend/generated/api.schemas'import { expect } from 'storybook/test'@@ -57,6 +75,7 @@ function completedReview(overrides: Partial<ReviewRecentReviewApi>): ReviewRecenrun_count: 1,last_run_at: '2026-09-30T10:00:00Z',published: true,+ full_review_published: true,in_progress: false,progress: null,resolution: null,@@ -88,6 +107,20 @@ const recentReviews: ReviewRecentReviewApi[] = [consider_count: 0,dismissed_count: 1,}),+ // Started by the viewer on a teammate's pull request, so "Mine" shows its author.+ completedReview({+ id: 'review-3',+ pr_number: 95,+ pr_title: 'Cache the billing summary',+ pr_author: 'example-teammate',+ github_url: 'https://github.com/example-org/example-repo/pull/95',+ head_branch: 'feat/billing-cache',+ last_run_at: '2026-09-28T09:00:00Z',+ must_fix_count: 0,+ should_fix_count: 0,+ consider_count: 1,+ dismissed_count: 2,+ }),]const perspectiveStats: ReviewPerspectiveStatsApi = {@@ -99,6 +132,201 @@ const perspectiveStats: ReviewPerspectiveStatsApi = {],}+const ADA: UserBasicType = {+ id: 301,+ uuid: '0b3f6a52-6a0e-4b8e-9d2f-4a1c7e9e0301',+ distinct_id: 'mock-user-301-distinct-id',+ first_name: 'Ada',+ last_name: 'Example',+ email: '[email protected]',+}++const members: OrganizationMemberType[] = [+ MOCK_DEFAULT_ORGANIZATION_MEMBER,+ { ...MOCK_DEFAULT_ORGANIZATION_MEMBER, id: 'member-rose', user: MOCK_SECOND_BASIC_USER },+ { ...MOCK_DEFAULT_ORGANIZATION_MEMBER, id: 'member-ada', user: ADA },+]++function toApiUser(user: UserBasicType): UserBasicApi {+ return {+ id: user.id,+ uuid: user.uuid,+ distinct_id: user.distinct_id,+ first_name: user.first_name,+ last_name: user.last_name,+ email: user.email,+ hedgehog_config: null,+ }+}++const INSTALLATION_ID = '4100'++const NAMED_REPOSITORIES = [+ 'web',+ 'api',+ 'docs',+ 'billing',+ 'mobile-app',+ 'infra',+ 'sdk-js',+ 'sdk-python',+ 'design-system',+ 'data-pipeline',+]++// Enough repositories for a second page, like a GitHub organization with many services.+const REPOSITORY_NAMES = [+ ...NAMED_REPOSITORIES.map((name) => `example-org/${name}`),+ ...Array.from({ length: 32 }, (_, i) => `example-org/service-${String(i + 1).padStart(3, '0')}`),+]++const BILLING_PROJECT = { id: 2, name: 'Billing' }++interface StoryRepositoryRow {+ id: string+ selected: boolean+ flash_for: AutomaticFlashForEnumApi | null+ people: ReviewRepositoryPersonApi[]+}++/** Mutable API state, reset before each story, so clicks in the panes behave like a real backend. */+const storyState: {+ settings: ReviewUserSettingsApi+ project: ReviewProjectSettingsApi+ rows: Record<string, StoryRepositoryRow>+ choices: Record<string, { id: string; mode: 'flash' | 'off' }>+ nextId: number+} = {+ settings: defaultSettings,+ project: projectSettings('all', true),+ rows: {},+ choices: {},+ nextId: 1,+}++function person(user: UserBasicType, kind: ReviewRepositoryPersonApi['kind']): ReviewRepositoryPersonApi {+ return { id: `person-${user.id}-${kind}`, user: toApiUser(user), kind }+}++function projectSettings(scope: ReviewInstallationClaimScopeEnumApi, canEdit: boolean): ReviewProjectSettingsApi {+ return {+ flash_for: 'everyone',+ bot_prs: 'skip',+ urgency_threshold: 'consider',+ celebrate_clean_reviews: true,+ people: [person(MOCK_SECOND_BASIC_USER, 'excepted')],+ installations: [+ {+ installation_id: INSTALLATION_ID,+ account_name: 'example-org',+ connected_by: toApiUser(ADA),+ claim_id: 'claim-1',+ scope,+ all_taken_by_project: null,+ },+ ],+ can_edit: canEdit,+ }+}++function initialRows(): Record<string, StoryRepositoryRow> {+ return {+ 'example-org/web': {+ id: 'repo-web',+ selected: true,+ flash_for: 'everyone',+ people: [person(MOCK_SECOND_BASIC_USER, 'excepted'), person(MOCK_DEFAULT_BASIC_USER, 'excepted')],+ },+ 'example-org/api': {+ id: 'repo-api',+ selected: true,+ flash_for: 'listed',+ people: [person(MOCK_SECOND_BASIC_USER, 'listed'), person(ADA, 'listed')],+ },+ 'example-org/docs': { id: 'repo-docs', selected: true, flash_for: null, people: [] },+ }+}++function inProject(name: string): boolean {+ if (name === 'example-org/billing') {+ return false+ }+ return storyState.project.installations[0].scope === 'all' || !!storyState.rows[name]?.selected+}++/** A story-sized copy of the backend resolver, so the panes answer like the real API after each change. */+function inherited(name: string): AutomaticReviewDecisionApi {+ if (!inProject(name)) {+ return { flash: false, reason: 'not_in_project' }+ }+ const defaultMode = storyState.settings.default_review_mode ?? 'follow'+ if (defaultMode !== 'follow') {+ return { flash: defaultMode === 'flash', reason: 'own_default' }+ }+ const row = storyState.rows[name]+ const exception = row?.flash_for ?? null+ const flashFor = exception ?? storyState.project.flash_for ?? 'off'+ const people = exception ? row.people : storyState.project.people+ const scope = exception ? 'repository' : 'project'+ const listed = (kind: string): boolean =>+ people.some((entry) => entry.kind === kind && entry.user.id === MOCK_DEFAULT_BASIC_USER.id)+ const decision = (flash: boolean, rule: string): AutomaticReviewDecisionApi => ({+ flash,+ reason: `${scope}_${rule}` as AutomaticReviewReasonEnumApi,+ })+ if (flashFor === 'everyone') {+ return listed('excepted') ? decision(false, 'excepted') : decision(true, 'everyone')+ }+ if (flashFor === 'listed') {+ return listed('listed') ? decision(true, 'listed') : decision(false, 'not_listed')+ }+ return decision(false, 'opt_in')+}++function overviewEntry(name: string): ReviewRepositoryOverviewEntryApi {+ const row = storyState.rows[name]+ const choice = storyState.choices[name] ?? null+ const own = inProject(name)+ const base = inherited(name)+ return {+ full_name: name,+ github_repo_id: REPOSITORY_NAMES.indexOf(name) + 1000,+ owner: name === 'example-org/billing' ? 'other_project' : own ? 'this_project' : 'none',+ owner_project: name === 'example-org/billing' ? BILLING_PROJECT : null,+ in_project: own,+ selected: row?.selected ?? false,+ repository_id: row?.id ?? null,+ exception: own && row?.flash_for ? { flash_for: row.flash_for, people: row.people } : null,+ my_choice: own ? (choice?.mode ?? null) : null,+ my_choice_id: own ? (choice?.id ?? null) : null,+ my_result: own && choice ? { flash: choice.mode === 'flash', reason: 'own_repository_choice' } : base,+ inherited_result: base,+ }+}++function saveRepository(write: ReviewRepositoryWriteApi): void {+ const current = storyState.rows[write.full_name] ?? {+ id: `repo-new-${storyState.nextId++}`,+ selected: false,+ flash_for: null,+ people: [],+ }+ const next = {+ ...current,+ selected: write.selected ?? current.selected,+ flash_for: write.flash_for !== undefined ? write.flash_for : current.flash_for,+ }+ if (!next.selected && next.flash_for === null) {+ delete storyState.rows[write.full_name]+ return+ }+ storyState.rows[write.full_name] = next+}++function rowById(id: string): [string, StoryRepositoryRow] | undefined {+ return Object.entries(storyState.rows).find(([, row]) => row.id === id)+}+function OpenTab({ tab, children }: { tab: CodeReviewTab; children: JSX.Element }): JSX.Element {useEffect(() => {router.actions.replace(urls.codeReview(), tab === 'settings' ? { tab } : {})@@ -114,6 +342,17 @@ const meta: Meta<typeof CodeReviewScene> = {featureFlags: [FEATURE_FLAGS.REVIEW_HOG],mockDate: '2026-10-01T12:00:00Z',},+ beforeEach: ({ parameters }) => {+ storyState.settings = {+ ...defaultSettings,+ stamphog_connected: parameters.showInternalFeatures ?? false,+ ...parameters.savedSettings,+ }+ storyState.project = projectSettings(parameters.claimScope ?? 'all', parameters.canEdit ?? true)+ storyState.rows = initialRows()+ storyState.choices = { 'example-org/docs': { id: 'choice-docs', mode: 'off' } }+ storyState.nextId = 1+ },decorators: [(Story, context): JSX.Element => (<OpenTab tab={context.parameters.tab ?? 'activity'}>@@ -123,17 +362,60 @@ const meta: Meta<typeof CodeReviewScene> = {</OpenTab>),(Story, context): JSX.Element => {- let settings: ReviewUserSettingsApi = {- ...defaultSettings,- ...context.parameters.savedSettings,- }return mswDecorator({get: {'/api/users/@me/': () => [200,{ ...MOCK_DEFAULT_USER, is_staff: context.parameters.isStaff ?? false },],- '/api/projects/:team_id/review_hog/settings/': () => [200, settings],+ '/api/users/@me/github_login/': { github_login: 'example-dev' },+ '/api/projects/:team_id/review_hog/settings/': () => [200, storyState.settings],+ '/api/projects/:team_id/review_hog/project_settings/': () => [200, storyState.project],+ '/api/projects/:team_id/review_hog/repositories/': () => [+ 200,+ Object.entries(storyState.rows).map(([full_name, row]) => ({+ ...row,+ installation_id: INSTALLATION_ID,+ github_repo_id: null,+ full_name,+ created_by: toApiUser(MOCK_DEFAULT_BASIC_USER),+ created_at: '2026-09-20T10:00:00Z',+ })),+ ],+ '/api/projects/:team_id/review_hog/repository_overview/': ({ request }) => {+ const params = new URL(request.url).searchParams+ const search = params.get('search')?.toLowerCase() ?? ''+ 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 page = entries.slice(offset, offset + limit)+ return [+ 200,+ {+ installation_id: INSTALLATION_ID,+ claim_scope: storyState.project.installations[0].scope,+ results: page,+ total: entries.length,+ has_more: offset + limit < entries.length,+ next_offset: offset + limit < entries.length ? offset + limit : null,+ },+ ]+ },+ '/api/organizations/:organization_id/members/': {+ results: members,+ next: null,+ previous: null,+ count: members.length,+ },'/api/projects/:team_id/review_hog/reviews/': { results: recentReviews, has_more: false },'/api/projects/:team_id/review_hog/reviews/perspective_stats/': perspectiveStats,'/api/projects/:team_id/review_hog/perspectives/': [],@@ -141,11 +423,103 @@ const meta: Meta<typeof CodeReviewScene> = {'/api/projects/:team_id/review_hog/validators/': [],'/api/projects/:team_id/review_hog/resolution/': [],},+ post: {+ '/api/projects/:team_id/review_hog/repositories/': async ({ request }) => {+ const write = (await request.json()) as ReviewRepositoryWriteApi+ saveRepository(write)+ const row = storyState.rows[write.full_name]+ return [+ 200,+ {+ repository: row+ ? {+ ...row,+ installation_id: INSTALLATION_ID,+ github_repo_id: null,+ full_name: write.full_name,+ created_by: null,+ created_at: '2026-10-01T12:00:00Z',+ }+ : null,+ taken_from_project: null,+ },+ ]+ },+ '/api/projects/:team_id/review_hog/repositories/:id/people/': async ({ request, params }) => {+ const { user_id, kind } = (await request.json()) as ReviewRepositoryPersonRequestApi+ const member = members.find((m) => m.user.id === user_id)+ const found = rowById(String(params.id))+ if (!member || !found) {+ return [400, { error: 'This user is not an active member of the organization.' }]+ }+ found[1].people = [...found[1].people, person(member.user, kind)]+ return [201, {}]+ },+ '/api/projects/:team_id/review_hog/project_settings/people/': async ({ request }) => {+ const { user_id, kind } = (await request.json()) as ReviewRepositoryPersonRequestApi+ const member = members.find((m) => m.user.id === user_id)+ if (member) {+ storyState.project = {+ ...storyState.project,+ people: [...storyState.project.people, person(member.user, kind)],+ }+ }+ return [201, storyState.project]+ },+ '/api/projects/:team_id/review_hog/repository_choices/': async ({ request }) => {+ const write = (await request.json()) as ReviewRepositoryChoiceWriteApi+ if ((write.mode === 'flash') === inherited(write.full_name).flash) {+ delete storyState.choices[write.full_name]+ } else {+ storyState.choices[write.full_name] = {+ id: `choice-${storyState.nextId++}`,+ mode: write.mode,+ }+ }+ return [200, { choice: null, my_result: overviewEntry(write.full_name).my_result }]+ },+ },patch: {'/api/projects/:team_id/review_hog/settings/': async ({ request }) => {const update = (await request.json()) as PatchedReviewUserSettingsApi- settings = { ...settings, ...update }- return [200, settings]+ storyState.settings = { ...storyState.settings, ...update }+ return [200, storyState.settings]+ },+ '/api/projects/:team_id/review_hog/project_settings/': async ({ request }) => {+ const update = (await request.json()) as PatchedReviewProjectSettingsApi+ storyState.project = { ...storyState.project, ...update }+ return [200, storyState.project]+ },+ '/api/projects/:team_id/review_hog/installation_claims/:id/': async ({ request }) => {+ const { scope } = (await request.json()) as { scope: ReviewInstallationClaimScopeEnumApi }+ const [installation] = storyState.project.installations+ storyState.project = { ...storyState.project, installations: [{ ...installation, scope }] }+ return [200, {}]+ },+ },+ delete: {+ '/api/projects/:team_id/review_hog/repository_choices/:id/': ({ params }) => {+ const name = Object.keys(storyState.choices).find(+ (key) => storyState.choices[key].id === params.id+ )+ if (name) {+ delete storyState.choices[name]+ }+ return [204]+ },+ '/api/projects/:team_id/review_hog/repositories/:id/people/:personId/': ({ params }) => {+ const found = rowById(String(params.id))+ if (found) {+ found[1].people = found[1].people.filter((entry) => entry.id !== params.personId)+ }+ return [200, {}]+ },+ '/api/projects/:team_id/review_hog/project_settings/people/:personId/': ({ params }) => {+ storyState.project = {+ ...storyState.project,+ people: storyState.project.people.filter((entry) => entry.id !== params.personId),+ }+ return [200, storyState.project]},},})(Story, context)@@ -162,7 +536,7 @@ export const Default: Story = {await expect(await canvas.findByText('Review a pull request')).toBeVisible()await expect(await canvas.findByText('Add retry to the export job')).toBeVisible()await expect(canvas.getByText('Mine')).toBeVisible()- await expect(canvas.queryByLabelText('Celebrate clean reviews')).not.toBeInTheDocument()+ await expect(canvas.queryByText('Full review settings')).not.toBeInTheDocument()},}@@ -172,13 +546,27 @@ export const Settings: Story = {userLogic.actions.loadUser()await waitFor(() => expect(userLogic.values.user?.is_staff).toBe(false))const canvas = within(canvasElement)- await expect(await canvas.findByText('What gets reviewed')).toBeVisible()+ await expect(await canvas.findByText('This project reviews example-org:')).toBeVisible()+ await expect(await canvas.findByText('example-org/web')).toBeVisible()+ await expect(canvas.getByText('Reviewed in the Billing project')).toBeVisible()+ await expect(canvas.getByText('You can edit: project admin')).toBeVisible()+ await expect(canvas.getByText('Full review settings')).toBeVisible()await expect(canvas.queryByText('Review a pull request')).not.toBeInTheDocument()- await expect(canvas.queryByLabelText('Review all your Inbox PRs')).not.toBeInTheDocument()- await expect(canvas.queryByLabelText('Let Stamphog review your Inbox PRs')).not.toBeInTheDocument()- await expect(canvas.queryByLabelText('Review all your PRs in Flash mode')).not.toBeInTheDocument()- await expect(canvas.getByLabelText('Resolve comments on your PRs')).toBeVisible()- await expect(canvas.getByLabelText('Celebrate clean reviews')).toBeVisible()+ await expect(+ canvas.queryByLabelText('Review PRs the agent opens for Inbox reports assigned to me')+ ).not.toBeInTheDocument()+ await expect(canvas.getByLabelText('Resolve comments on my pull requests')).toBeVisible()+ },+}++export const SettingsForMember: Story = {+ parameters: { tab: 'settings', canEdit: false, claimScope: 'selected' },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await expect(await canvas.findByText('Project admins edit')).toBeVisible()+ await expect(await canvas.findByText('example-org/web')).toBeVisible()+ await expect(canvas.queryByText('Include in project')).not.toBeInTheDocument()+ await expect(canvas.queryByLabelText('Add exception for example-org/docs')).not.toBeInTheDocument()},}@@ -190,9 +578,10 @@ export const InternalFeatures: Story = {},play: async ({ canvasElement }) => {const canvas = within(canvasElement)- await expect(await canvas.findByLabelText('Review all your Inbox PRs')).toBeVisible()- await expect(canvas.getByLabelText('Let Stamphog review your Inbox PRs')).toBeVisible()- await expect(canvas.getByLabelText('Review all your PRs in Flash mode')).toBeVisible()+ await expect(+ await canvas.findByLabelText('Review PRs the agent opens for Inbox reports assigned to me')+ ).toBeVisible()+ await expect(canvas.getByLabelText('Let Stamphog review my Inbox PRs')).toBeVisible()},}@@ -200,13 +589,12 @@ export const SavedInboxOptIns: Story = {parameters: { savedSettings: { review_inbox_prs: true, stamphog_review_inbox_prs: true }, tab: 'settings' },play: async ({ canvasElement }) => {const canvas = within(canvasElement)- const inboxSwitch = await canvas.findByLabelText('Review all your Inbox PRs')- const stamphogSwitch = canvas.getByLabelText('Let Stamphog review your Inbox PRs')+ const inboxSwitch = await canvas.findByLabelText('Review PRs the agent opens for Inbox reports assigned to me')+ const stamphogSwitch = canvas.getByLabelText('Let Stamphog review my Inbox PRs')await expect(inboxSwitch).toBeChecked()await expect(inboxSwitch).toBeEnabled()await expect(stamphogSwitch).toBeChecked()await expect(stamphogSwitch).toBeEnabled()- await expect(canvas.queryByLabelText('Review all your PRs in Flash mode')).not.toBeInTheDocument()},}diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsxindex b75512c2da63..4f377d7fc386 100644--- a/products/review_hog/frontend/CodeReviewScene.tsx+++ b/products/review_hog/frontend/CodeReviewScene.tsx@@ -1,14 +1,9 @@import { useActions, useValues } from 'kea'import {- IconBalance,- IconBolt,- IconChat,IconChevronDown,- IconConfetti,IconDirectedGraph,IconExternal,- IconFilter,IconGithub,IconPlus,IconPullRequest,@@ -23,7 +18,6 @@ import {LemonInput,LemonSegmentedButton,LemonSkeleton,- LemonSlider,LemonSwitch,LemonTabs,LemonTag,@@ -32,11 +26,9 @@ import {Tooltip,} from '@posthog/lemon-ui'-import { Logomark } from 'lib/brand'import { NotFound } from 'lib/components/NotFound'import { TZLabel } from 'lib/components/TZLabel'import { FEATURE_FLAGS } from 'lib/constants'-import { IconStamphog } from 'lib/lemon-ui/icons'import { LemonCard } from 'lib/lemon-ui/LemonCard'import { LemonCollapse } from 'lib/lemon-ui/LemonCollapse'import { LemonDrawer } from 'lib/lemon-ui/LemonDrawer'@@ -54,7 +46,6 @@ import type {ReviewPerspectiveStatItemApi,ReviewRecentReviewApi,ReviewResolutionStatusApi,- UrgencyThresholdEnumApi,} from 'products/review_hog/frontend/generated/api.schemas'import {ReviewHogReviewsListScope,@@ -63,6 +54,8 @@ import {import { AdoptSkillModal } from './AdoptSkillModal'import { PipelineDetailModal } from './PipelineDetailModal'+import { InstallationClaims } from './repositories/InstallationClaims'+import { RepositoriesPanes } from './repositories/RepositoriesPanes'import {CodeReviewTab,REVIEWS_PAGE_SIZE,@@ -70,6 +63,9 @@ import {ReviewSkillKind,reviewHogSettingsLogic,} from './reviewHogSettingsLogic'+import { SectionHeader } from './SectionHeader'+import { FullReviewSettingsSection } from './settings/FullReviewSettingsSection'+import { InboxSection } from './settings/InboxSection'/** "review-hog-perspective-logic-correctness" → "Logic correctness" */function prettifySkillName(skillName: string): string {@@ -138,54 +134,6 @@ const PIPELINE_PHASES: { name: string; hint: string; steps: { number: string; ti},]-const URGENCY_STOPS: { key: UrgencyThresholdEnumApi; label: string; description: string }[] = [- {- key: 'consider',- label: 'All issues',- description:- 'Every validated finding is published, including the minor consider-level ones. This is the default.',- },- {- key: 'should_fix',- label: 'Should fix',- description: 'Recommended fixes and anything more serious. Minor consider-level findings are dropped.',- },- {- key: 'must_fix',- label: 'Must fix',- description: 'Only blocking issues, the highest-priority findings. Everything else is dropped.',- },-]--function SectionHeader({- icon,- title,- pill,- action,- children,-}: {- icon: JSX.Element- title: string- pill?: JSX.Element- action?: JSX.Element- children: string-}): JSX.Element {- return (- <div className="flex flex-col gap-1.5">- <div className="flex items-center gap-2">- <span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-primary bg-surface-primary text-secondary *:size-4">- {icon}- </span>- <h3 className="m-0 text-base font-semibold">{title}</h3>- {pill}- {action && <div className="ml-auto">{action}</div>}- </div>- {/* Indented so the copy aligns under the title, not the icon tile */}- <p className="m-0 ml-9 max-w-160 text-xs text-secondary">{children}</p>- </div>- )-}-// The Mine tooltip states what the backend's `mine` scope matches: the PR author OR the user who started the run.const REVIEWS_SCOPE_OPTIONS: {value: ReviewHogReviewsListScope@@ -446,9 +394,8 @@ function resolutionLabel(resolution: ReviewResolutionStatusApi): string {/** A first review still running: no findings to expand into yet, just the live stage. */function RunningReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.Element {- const { reviewsScope } = useValues(reviewHogSettingsLogic)- // On Everyone, whose PR it is matters at a glance; on Mine it is mostly yours.- const showAuthor = reviewsScope === ReviewHogReviewsListScope.Everyone && !!review.pr_author+ const { showReviewAuthor } = useValues(reviewHogSettingsLogic)+ const showAuthor = showReviewAuthor(review)return (<div className="flex items-center gap-3 px-4 py-3"><span className="flex w-6 shrink-0 justify-center">@@ -483,12 +430,11 @@ function RunningReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.El/** One expandable review row: essentials collapsed; PR facts + funnel + findings entry when open. */function RecentReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.Element {- const { expandedReviewIds, reviewsScope } = useValues(reviewHogSettingsLogic)+ const { expandedReviewIds, showReviewAuthor } = useValues(reviewHogSettingsLogic)const { toggleReviewRowExpanded, openReviewDetail } = useActions(reviewHogSettingsLogic)const expanded = expandedReviewIds.includes(review.id)const validated = review.must_fix_count + review.should_fix_count + review.consider_count- // On Everyone, whose PR it is matters at a glance; on Mine it is mostly yours.- const showAuthor = reviewsScope === ReviewHogReviewsListScope.Everyone && !!review.pr_author+ const showAuthor = showReviewAuthor(review)// A first review has no completed turn to expand into — it renders as a live progress row.if (review.in_progress && review.run_count === 0) {@@ -713,7 +659,8 @@ function RecentReviewsSection(): JSX.Element | null {* actions are the per-run variants (review without resolving / resolve only / flash).*/function TriggerReviewSection(): JSX.Element {- const { triggerPrUrl, triggeringReview, triggerUrlResolving } = useValues(reviewHogSettingsLogic)+ const { triggerPrUrl, triggeringReview, triggerUrlResolving, triggerUrlHasFullReview } =+ useValues(reviewHogSettingsLogic)const { featureFlags } = useValues(featureFlagLogic)const showInternalFeatures = !!featureFlags[FEATURE_FLAGS.REVIEW_HOG_INTERNAL]const { setTriggerPrUrl, submitTriggerReview } = useActions(reviewHogSettingsLogic)@@ -723,11 +670,15 @@ function TriggerReviewSection(): JSX.Element {// get the same refusal from the trigger endpoint.const resolvingReason = triggerUrlResolving ? 'Still resolving comments from the last review' : undefinedconst inFlightReason = triggeringReview ? 'A run is already starting…' : undefined+ const flashAfterFullReason = triggerUrlHasFullReview+ ? 'This pull request already has a Full review. Flash does not run after one.'+ : undefinedreturn (<section className="flex flex-col gap-4"><SectionHeader icon={<IconGithub />} title="Review a pull request">- Start a review of any pull request the GitHub App can access. The review is posted back to the pull- request, runs with your perspectives, and shows up under recent reviews.+ Start a Full review of any pull request the GitHub App can access. The review is posted back to the pull+ request and shows up under recent reviews. Your perspectives and other review skills apply to Full+ reviews only.</SectionHeader><formclassName="ml-9 flex flex-wrap items-center gap-2"@@ -763,22 +714,25 @@ function TriggerReviewSection(): JSX.Element {>Review without resolving comments</LemonButton>- <LemonButton- fullWidth- onClick={() =>- submitTriggerReview(ReviewTriggerRequestRunModeEnumApi.ResolveOnly)- }- tooltip="Skip the review and only work through the pull request's existing unresolved comment threads."- >- Only resolve existing comments- </LemonButton>+ {showInternalFeatures && (+ <LemonButton+ fullWidth+ onClick={() =>+ submitTriggerReview(ReviewTriggerRequestRunModeEnumApi.ResolveOnly)+ }+ tooltip="Skip the review and only work through the pull request's existing unresolved comment threads."+ >+ Only resolve existing comments+ </LemonButton>+ )}{showInternalFeatures && (<LemonButtonfullWidthonClick={() =>submitTriggerReview(ReviewTriggerRequestRunModeEnumApi.Flash)}- tooltip="A faster, cheaper review that never resolves comments. Its status comment is marked as flash."+ tooltip="A faster, cheaper review that never resolves comments and uses none of your review skills. Its status comment is marked as flash."+ disabledReason={flashAfterFullReason}>Review in Flash mode</LemonButton>@@ -1172,203 +1126,6 @@ function ReviewDetailDrawer(): JSX.Element {)}-function TriggersSection(): JSX.Element {- const { settings, settingsLoading } = useValues(reviewHogSettingsLogic)- const { featureFlags } = useValues(featureFlagLogic)- const showInternalFeatures = !!featureFlags[FEATURE_FLAGS.REVIEW_HOG_INTERNAL]- const { updateSettings } = useActions(reviewHogSettingsLogic)-- const switchDisabledReason = settings === null ? 'Loading…' : settingsLoading ? 'Saving…' : undefined-- return (- <section className="flex flex-col gap-4 border-t border-primary pt-8">- <SectionHeader icon={<IconFilter />} title="What gets reviewed">- {showInternalFeatures- ? 'Choose which pull requests PostHog Review picks up automatically, and whether reviews also resolve the comment threads on them.'- : 'Choose whether reviews also resolve comment threads and how clean reviews appear on your pull requests.'}- </SectionHeader>- <LemonCard hoverEffect={false} className="divide-y divide-primary p-0">- {/* A switch that is on stays visible, so the user can clear a saved opt-in. */}- {(showInternalFeatures || settings?.review_inbox_prs) && (- <div className="flex items-center gap-4 p-4">- <div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary *:h-auto *:w-5">- <Logomark />- </div>- <div className="min-w-0 flex-1">- <div className="text-sm font-semibold">Review all your Inbox PRs</div>- <div className="text-xs text-secondary">- When a self-driving implementation from your Inbox opens a pull request, PostHog Review- reviews it and posts the review to the pull request automatically.- </div>- </div>- <LemonSwitch- aria-label="Review all your Inbox PRs"- checked={settings?.review_inbox_prs ?? false}- onChange={(checked) => updateSettings({ review_inbox_prs: checked })}- disabledReason={switchDisabledReason}- />- </div>- )}- {(showInternalFeatures || settings?.stamphog_review_inbox_prs) && (- <div className="flex items-center gap-4 p-4">- <div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">- <IconStamphog className="size-5" />- </div>- <div className="min-w-0 flex-1">- <div className="text-sm font-semibold">Let Stamphog review your Inbox PRs</div>- <div className="text-xs text-secondary">- When a self-driving implementation from your Inbox opens a pull request, Stamphog- reviews it and approves it if it passes.- </div>- </div>- <LemonSwitch- aria-label="Let Stamphog review your Inbox PRs"- checked={settings?.stamphog_review_inbox_prs ?? false}- onChange={(checked) => updateSettings({ stamphog_review_inbox_prs: checked })}- disabledReason={- // A switch that is already on stays usable while disconnected, so- // turning it off never requires connecting Stamphog first.- settings && !settings.stamphog_connected && !settings.stamphog_review_inbox_prs- ? 'Connect a repository to Stamphog first. Stamphog is not set up for this project yet.'- : switchDisabledReason- }- />- </div>- )}- <div className="flex items-center gap-4 p-4">- <div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">- <IconChat className="size-5" />- </div>- <div className="min-w-0 flex-1">- <div className="text-sm font-semibold">Resolve comments on your PRs</div>- <div className="text-xs text-secondary">- After a review of your pull request is published, PostHog Review works through its- unresolved comment threads: safe fixes land on the branch, and every thread gets a reply.- </div>- </div>- <LemonSwitch- aria-label="Resolve comments on your PRs"- checked={settings?.resolve_comments ?? false}- onChange={(checked) => updateSettings({ resolve_comments: checked })}- disabledReason={switchDisabledReason}- />- </div>- <div className="flex items-center gap-4 p-4">- <div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">- <IconConfetti className="size-5" />- </div>- <div className="min-w-0 flex-1">- <div className="text-sm font-semibold">Celebrate clean reviews</div>- <div className="text-xs text-secondary">- When a review of your pull request finds nothing to raise, the review comment shows a fun- image. Turn this off to end clean reviews with the text summary only.- </div>- </div>- <LemonSwitch- aria-label="Celebrate clean reviews"- data-attr="review-hog-celebrate-clean-reviews"- checked={settings?.celebrate_clean_reviews ?? true}- onChange={(checked) => updateSettings({ celebrate_clean_reviews: checked })}- disabledReason={switchDisabledReason}- />- </div>- </LemonCard>- {showInternalFeatures && (- <>- <div className="mt-2">- <h4 className="mb-1 text-sm font-semibold">ReviewHog Flash - Experimental</h4>- <p className="m-0 text-xs text-secondary">This setting applies only to Flash reviews.</p>- </div>- <LemonCard hoverEffect={false} className="divide-y divide-primary p-0">- <div className="flex items-center gap-4 p-4">- <div className="flex size-9 shrink-0 items-center justify-center rounded border border-primary bg-primary">- <IconBolt className="size-5" />- </div>- <div className="min-w-0 flex-1">- <div className="text-sm font-semibold">Review all your PRs in Flash mode</div>- <div className="text-xs text-secondary">- Automatically review PRs you author in the repositories this project reviews,- including drafts and new commits. Starts with future PR activity.- </div>- </div>- <LemonSwitch- aria-label="Review all your PRs in Flash mode"- checked={settings?.default_review_mode === 'flash'}- onChange={(checked) =>- updateSettings({ default_review_mode: checked ? 'flash' : 'off' })- }- disabledReason={switchDisabledReason}- loading={settingsLoading}- />- </div>- </LemonCard>- </>- )}- </section>- )-}--function UrgencySection(): JSX.Element {- const { settings } = useValues(reviewHogSettingsLogic)- const { updateSettings } = useActions(reviewHogSettingsLogic)-- const activeIndex = Math.max(- 0,- URGENCY_STOPS.findIndex((stop) => stop.key === (settings?.urgency_threshold ?? 'consider'))- )-- return (- <section className="flex flex-col gap-4 border-t border-primary pt-8">- <SectionHeader icon={<IconBalance />} title="Urgency threshold">- Set how strict PostHog Review is. The further right, the fewer findings reach the pull request, but the- higher their priority.- </SectionHeader>- <LemonCard hoverEffect={false} className="flex flex-col p-5">- <LemonSlider- min={0}- max={2}- step={1}- value={activeIndex}- onChange={(value) => {- // LemonSlider fires per mousemove while dragging — only PATCH on a stop change.- if (value !== activeIndex) {- updateSettings({ urgency_threshold: URGENCY_STOPS[value].key })- }- }}- disabledReason={settings === null ? 'Loading…' : undefined}- />- <div className="mt-3 flex justify-between">- {URGENCY_STOPS.map((stop, i) => (- <button- key={stop.key}- type="button"- disabled={settings === null}- aria-pressed={i === activeIndex}- className={`cursor-pointer border-0 bg-transparent p-0 text-xs font-semibold ${- i === activeIndex ? 'text-default' : 'text-tertiary'- }`}- onClick={() => {- if (i !== activeIndex) {- updateSettings({ urgency_threshold: stop.key })- }- }}- >- {stop.label}- </button>- ))}- </div>- <div className="mt-2 flex justify-between text-xxs text-tertiary">- <span>← every finding</span>- <span>only the most urgent →</span>- </div>- <div className="mt-3 border-t border-primary pt-3 text-xs text-secondary">- {URGENCY_STOPS[activeIndex].description}- </div>- </LemonCard>- </section>- )-}-interface SkillCardData {skill_name: stringdescription: string@@ -1783,17 +1540,35 @@ function ActivityTab(): JSX.Element {)}+const REVIEW_SKILLS_ANCHOR = 'review-hog-skills'+function SettingsTab(): JSX.Element {const { blindSpots, validators, resolutionSkills } = useValues(reviewHogSettingsLogic)const { selectBlindSpots, selectValidator, selectResolutionSkill } = useActions(reviewHogSettingsLogic)return (<>- <PipelineSection />- <TriggersSection />+ <section className="flex flex-col gap-3">+ <p className="m-0 text-sm text-secondary">+ Flash runs automatically on every push, following the rules below. Full runs only when someone asks+ for it: the Review button, the reviewhog label, or the Inbox. No Flash runs on a pull request after+ it had a Full review.+ </p>+ <InstallationClaims />+ <RepositoriesPanes />+ </section>+ <FullReviewSettingsSection+ onEditSkills={() =>+ document+ .getElementById(REVIEW_SKILLS_ANCHOR)+ ?.scrollIntoView({ behavior: 'smooth', block: 'start' })+ }+ />+ <InboxSection /><section className="flex flex-col gap-8 border-t border-primary pt-8">- <div className="flex flex-col gap-1.5">- <h2 className="m-0 text-xl font-bold">Review skills</h2>+ <PipelineSection />+ <div id={REVIEW_SKILLS_ANCHOR} className="flex flex-col gap-1.5 border-t border-primary pt-8">+ <h3 className="m-0 text-lg font-bold">Review skills</h3><p className="m-0 max-w-160 text-sm text-secondary">Everything below is a regular skill, stored in your PostHog skills store like anything elseyou've added. Review skills read your changed code, a blind-spot sweep catches what they missed,@@ -1827,7 +1602,7 @@ function SettingsTab(): JSX.Element {<SingleActiveSectionicon={<IconWrench />}title="Resolution criteria"- intro="After a review is published, PostHog Review works through the pull request's unresolved comment threads: asks that are worth it and safe get implemented on the branch, and every thread gets a reply. These criteria set that bar. Keep several on hand, but only one is applied."+ intro="After a review is published, PostHog Review works through the pull request's unresolved comment threads: asks that are worth it and safe get implemented on the branch, and every thread gets a reply. These criteria set that bar and how fixes work: default, big gaps only, or small fixes only. Keep several on hand, but only one is applied."kind="resolution"kindLabel="resolution criteria"createLabel="Create your own resolution criteria"@@ -1835,14 +1610,14 @@ function SettingsTab(): JSX.Element {onSelect={selectResolutionSkill}/></section>- <UrgencySection /></>)}/*** The "Code review" scene: ReviewHog's activity and settings page, split into an Activity tab- * (trigger a review, recent reviews) and a Settings tab (what gets reviewed, skills, threshold).+ * (trigger a review, recent reviews) and a Settings tab (repositories and who gets automatic Flash,+ * Full review settings, Inbox, review skills).* Every control is live from load, no save step. See `reviewHogSettingsLogic` for the data flow.* Access is gated on FEATURE_FLAGS.REVIEW_HOG, the same flag that shows the menu entry, so whoever* discovers the entry can open the page.diff --git a/products/review_hog/frontend/SectionHeader.tsx b/products/review_hog/frontend/SectionHeader.tsxnew file mode 100644index 000000000000..f3a44d274387--- /dev/null+++ b/products/review_hog/frontend/SectionHeader.tsx@@ -0,0 +1,28 @@+export function SectionHeader({+ icon,+ title,+ pill,+ action,+ children,+}: {+ icon: JSX.Element+ title: string+ pill?: JSX.Element+ action?: JSX.Element+ children: string+}): JSX.Element {+ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center gap-2">+ <span className="flex size-7 shrink-0 items-center justify-center rounded-md border border-primary bg-surface-primary text-secondary *:size-4">+ {icon}+ </span>+ <h3 className="m-0 text-base font-semibold">{title}</h3>+ {pill}+ {action && <div className="ml-auto">{action}</div>}+ </div>+ {/* Indented so the copy aligns under the title, not the icon tile */}+ <p className="m-0 ml-9 max-w-160 text-xs text-secondary">{children}</p>+ </div>+ )+}diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.tsindex e981378c1fdc..ab6f0bcf695d 100644--- a/products/review_hog/frontend/generated/api.schemas.ts+++ b/products/review_hog/frontend/generated/api.schemas.ts@@ -562,6 +562,8 @@ export interface ReviewRepositoryOverviewEntryApi {my_choice_id: string | null/** What the requesting user's own pull requests get here, and the rule that decided it. */my_result: AutomaticReviewDecisionApi+ /** What the requesting user's own pull requests would get here without their choice for this repository. Equals my_result when there is no choice. */+ inherited_result: AutomaticReviewDecisionApi}export interface ReviewRepositoryOverviewApi {@@ -729,6 +731,8 @@ export interface ReviewRecentReviewApi {last_run_at: string | null/** Whether a review has been published back to GitHub. */published: boolean+ /** Whether a Full review of this pull request has been published. No Flash review runs after one. */+ full_review_published: boolean/** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */in_progress: boolean/** The in-flight review turn's stage and counters; null unless a review turn is running (a resolving report carries `resolution` instead). */@@ -944,6 +948,8 @@ export interface ReviewDetailApi {last_run_at: string | null/** Whether a review has been published back to GitHub. */published: boolean+ /** Whether a Full review of this pull request has been published. No Flash review runs after one. */+ full_review_published: boolean/** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */in_progress: boolean/** The in-flight review turn's stage and counters; null unless a review turn is running (a resolving report carries `resolution` instead). */diff --git a/products/review_hog/frontend/repositories/InstallationClaims.tsx b/products/review_hog/frontend/repositories/InstallationClaims.tsxnew file mode 100644index 000000000000..837aa5a9b170--- /dev/null+++ b/products/review_hog/frontend/repositories/InstallationClaims.tsx@@ -0,0 +1,101 @@+import { useActions, useValues } from 'kea'++import { IconGithub } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonSelect, LemonSkeleton } from '@posthog/lemon-ui'++import type { ReviewInstallationApi } from 'products/review_hog/frontend/generated/api.schemas'++import { projectName } from './repositoryChoices'+import { ClaimScopeChoice, reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'+import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'++function claimHint(installation: ReviewInstallationApi): string {+ if (installation.scope === 'all') {+ return 'Every repository, including ones created later, except the ones another project selected. Only one project can take all repositories of a GitHub account.'+ }+ if (installation.scope === 'selected') {+ return 'Only the repositories included below. New repositories are not reviewed until you include them. Each repository belongs to one project.'+ }+ return 'This project reviews no repository here yet. Pick all repositories, or only selected ones and include them below.'+}++function InstallationClaim({ installation }: { installation: ReviewInstallationApi }): JSX.Element {+ const { editDisabledReason, claimSaving } = useValues(reviewHogProjectSettingsLogic)+ const { changeClaimScope } = useActions(reviewHogProjectSettingsLogic)+ const takenBy = installation.all_taken_by_project+ const scope: ClaimScopeChoice = installation.scope ?? 'none'++ return (+ <div className="flex flex-wrap items-center gap-3 rounded border border-primary bg-surface-primary px-4 py-2.5">+ <IconGithub className="size-6 shrink-0" />+ <div className="flex min-w-0 flex-1 basis-72 flex-col gap-0.5">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-sm font-semibold">This project reviews {installation.account_name}:</span>+ <LemonSelect<ClaimScopeChoice>+ size="small"+ aria-label={`Repositories of ${installation.account_name} this project reviews`}+ value={scope}+ options={[+ {+ value: 'all',+ label: 'All repositories',+ disabledReason: takenBy+ ? `${projectName(takenBy)} already reviews all repositories here`+ : undefined,+ },+ { value: 'selected', label: 'Only selected repositories' },+ { value: 'none', label: 'No repositories' },+ ]}+ onChange={(value) => changeClaimScope(installation, value)}+ disabledReason={claimSaving ? 'Saving…' : editDisabledReason}+ data-attr="review-hog-installation-claim"+ />+ </div>+ <span className="text-xs text-secondary">{claimHint(installation)}</span>+ </div>+ </div>+ )+}++/** One claim per connected GitHub installation: which of its repositories this project reviews. */+export function InstallationClaims(): JSX.Element {+ const { projectSettings, projectSettingsLoadFailed, installations } = useValues(reviewHogProjectSettingsLogic)+ const { loadProjectSettings } = useActions(reviewHogProjectSettingsLogic)+ const { connectGitHubUrl } = useValues(reviewHogRepositoriesLogic)++ if (projectSettings === null) {+ return projectSettingsLoadFailed ? (+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => loadProjectSettings() }}>+ Could not load the project settings.+ </LemonBanner>+ ) : (+ <LemonSkeleton className="h-14 w-full" />+ )+ }+ if (installations.length === 0) {+ return (+ <div className="flex flex-wrap items-center justify-between gap-3 rounded border border-primary bg-surface-primary px-4 py-3">+ <span className="text-sm text-secondary">+ Connect GitHub to choose which repositories this project reviews.+ </span>+ <LemonButton+ type="primary"+ size="small"+ icon={<IconGithub />}+ to={connectGitHubUrl}+ disableClientSideRouting+ data-attr="review-hog-connect-github"+ >+ Connect GitHub+ </LemonButton>+ </div>+ )+ }+ return (+ <div className="flex flex-col gap-2">+ {installations.map((installation) => (+ <InstallationClaim key={installation.installation_id} installation={installation} />+ ))}+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/MyDefaultCell.tsx b/products/review_hog/frontend/repositories/MyDefaultCell.tsxnew file mode 100644index 000000000000..29bd95826306--- /dev/null+++ b/products/review_hog/frontend/repositories/MyDefaultCell.tsx@@ -0,0 +1,37 @@+import { useActions, useValues } from 'kea'++import { LemonSelect } from '@posthog/lemon-ui'++import type { DefaultReviewModeEnumApi } from 'products/review_hog/frontend/generated/api.schemas'+import { reviewHogSettingsLogic } from 'products/review_hog/frontend/reviewHogSettingsLogic'++import { DEFAULT_REVIEW_MODE_OPTIONS } from './repositoryChoices'+import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'+import { YouMark } from './YouMark'++export function MyDefaultCell({ className }: { className?: string }): JSX.Element {+ const { settings, settingsLoading } = useValues(reviewHogSettingsLogic)+ const { setMyDefault } = useActions(reviewHogRepositoriesLogic)+ const value = settings?.default_review_mode ?? 'follow'++ return (+ <div className={`flex min-w-0 flex-col gap-2 px-4 py-3 ${className ?? ''}`}>+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-semibold">My default</span>+ <span className="text-xs text-secondary">Every repository without your own choice follows this.</span>+ </div>+ <div className="flex items-center gap-1">+ <YouMark shown={value !== 'follow'} />+ <LemonSelect<DefaultReviewModeEnumApi>+ size="small"+ aria-label="My default"+ value={value}+ options={DEFAULT_REVIEW_MODE_OPTIONS}+ onChange={(mode) => mode !== value && setMyDefault(mode)}+ disabledReason={settings === null ? 'Loading…' : settingsLoading ? 'Saving…' : undefined}+ data-attr="review-hog-default-review-mode"+ />+ </div>+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/PeopleList.tsx b/products/review_hog/frontend/repositories/PeopleList.tsxnew file mode 100644index 000000000000..25edea45a0f9--- /dev/null+++ b/products/review_hog/frontend/repositories/PeopleList.tsx@@ -0,0 +1,70 @@+import { useValues } from 'kea'++import { IconPlus } from '@posthog/icons'+import { LemonButton, LemonSnack } from '@posthog/lemon-ui'++import { MemberSelect } from 'lib/components/MemberSelect'+import { fullNameOrEmail } from 'lib/utils/strings'+import { userLogic } from 'scenes/userLogic'++import type {+ ReviewRepositoryPersonApi,+ ReviewRepositoryPersonKindEnumApi,+} from 'products/review_hog/frontend/generated/api.schemas'++export function PeopleList({+ kind,+ people,+ canEdit,+ disabledReason,+ onAdd,+ onRemove,+}: {+ kind: ReviewRepositoryPersonKindEnumApi+ people: readonly ReviewRepositoryPersonApi[]+ canEdit: boolean+ disabledReason?: string+ onAdd: (userId: number) => void+ onRemove: (person: ReviewRepositoryPersonApi) => void+}): JSX.Element {+ const { user } = useValues(userLogic)+ const listed = people.filter((person) => person.kind === kind)++ return (+ <div className="flex flex-wrap items-center gap-1.5 text-xs">+ <span className="text-secondary">{kind === 'excepted' ? 'Except:' : 'People:'}</span>+ {listed.map((person) => (+ <LemonSnack+ key={person.id}+ title={person.user.email}+ onClose={canEdit && !disabledReason ? () => onRemove(person) : undefined}+ data-attr="review-hog-rule-person"+ >+ {fullNameOrEmail(person.user)}+ {person.user.id === user?.id ? ' (you)' : ''}+ </LemonSnack>+ ))}+ {listed.length === 0 && <span className="text-tertiary">nobody yet</span>}+ {canEdit && (+ <MemberSelect+ value={null}+ allowNone={false}+ excludedMembers={listed.map((person) => person.user.id)}+ onChange={(member) => member && onAdd(member.id)}+ >+ {() => (+ <LemonButton+ size="xsmall"+ type="tertiary"+ icon={<IconPlus />}+ disabledReason={disabledReason}+ data-attr="review-hog-rule-add-person"+ >+ Person+ </LemonButton>+ )}+ </MemberSelect>+ )}+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/ProjectRuleCell.tsx b/products/review_hog/frontend/repositories/ProjectRuleCell.tsxnew file mode 100644index 000000000000..def73e7d4264--- /dev/null+++ b/products/review_hog/frontend/repositories/ProjectRuleCell.tsx@@ -0,0 +1,71 @@+import { useActions, useValues } from 'kea'++import { LemonSelect } from '@posthog/lemon-ui'++import { fullNameOrEmail } from 'lib/utils/strings'++import type {+ ReviewInstallationApi,+ ReviewProjectSettingsBotPullRequestsEnumApi,+} from 'products/review_hog/frontend/generated/api.schemas'++import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'+import { RuleControls } from './RuleControls'++/** Bot pull requests run as the person who connected GitHub, so the label names them when there is one. */+function botRunLabel(installations: readonly ReviewInstallationApi[]): string {+ const connectors = new Set(+ installations.flatMap((installation) =>+ installation.connected_by ? [fullNameOrEmail(installation.connected_by)] : []+ )+ )+ if (connectors.size === 1) {+ return `Automatic Flash, billed to ${[...connectors][0]} (connected GitHub)`+ }+ return 'Automatic Flash, billed to the person who connected GitHub'+}++export function ProjectRuleCell({ className }: { className?: string }): JSX.Element {+ const { projectSettings, canEdit, editDisabledReason, installations } = useValues(reviewHogProjectSettingsLogic)+ const { updateProjectSettings, addProjectPerson, removeProjectPerson } = useActions(reviewHogProjectSettingsLogic)+ const botPrs = projectSettings?.bot_prs ?? 'skip'++ return (+ <div className={`flex min-w-0 flex-col gap-2 px-4 py-3 ${className ?? ''}`}>+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-semibold">Project settings</span>+ <span className="text-xs text-secondary">+ Every repository without an exception starts here. Starts at opt-in only, so connecting GitHub never+ starts reviews everywhere.+ </span>+ </div>+ <RuleControls+ label="Project settings"+ flashFor={projectSettings?.flash_for ?? 'off'}+ people={projectSettings?.people ?? []}+ canEdit={canEdit}+ disabledReason={editDisabledReason}+ onChangeFlashFor={(flashFor) => updateProjectSettings({ flash_for: flashFor })}+ onAddPerson={(userId, kind) => addProjectPerson({ userId, kind })}+ onRemovePerson={removeProjectPerson}+ dataAttr="review-hog-project-flash-for"+ />+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-xs text-secondary">Bot PRs, all repositories:</span>+ <LemonSelect<ReviewProjectSettingsBotPullRequestsEnumApi>+ size="small"+ aria-label="Bot pull requests"+ value={botPrs}+ options={[+ { value: 'skip', label: 'Not reviewed' },+ { value: 'run', label: botRunLabel(installations) },+ ]}+ onChange={(value) => value !== botPrs && updateProjectSettings({ bot_prs: value })}+ disabledReason={editDisabledReason}+ className="max-w-full"+ data-attr="review-hog-project-bot-prs"+ />+ </div>+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/RepositoriesPanes.tsx b/products/review_hog/frontend/repositories/RepositoriesPanes.tsxnew file mode 100644index 000000000000..38d9b4d465d4--- /dev/null+++ b/products/review_hog/frontend/repositories/RepositoriesPanes.tsx@@ -0,0 +1,111 @@+import { useActions, useValues } from 'kea'+import { Fragment } from 'react'++import { LemonBanner, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'++import { MyDefaultCell } from './MyDefaultCell'+import { PANE_LEFT, PANE_RIGHT, PANE_ROW } from './paneClasses'+import { ProjectRuleCell } from './ProjectRuleCell'+import { RepositoryListPager } from './RepositoryListPager'+import { RepositoryListToolbar } from './RepositoryListToolbar'+import { RepositoryMyCell } from './RepositoryMyCell'+import { RepositoryProjectCell } from './RepositoryProjectCell'+import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'+import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'++function RepositoryRows(): JSX.Element {+ const { overview, overviewLoading, overviewLoadFailed } = useValues(reviewHogRepositoriesLogic)+ const { loadOverview } = useActions(reviewHogRepositoriesLogic)++ if (overview === null) {+ if (overviewLoadFailed) {+ return (+ <div className={`col-span-full px-4 py-3 ${PANE_ROW}`}>+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => loadOverview() }}>+ Could not load the repositories.+ </LemonBanner>+ </div>+ )+ }+ return (+ <div className={`col-span-full flex flex-col gap-2 px-4 py-3 ${PANE_ROW}`}>+ {overviewLoading ? (+ <>+ <LemonSkeleton className="h-8 w-full" />+ <LemonSkeleton className="h-8 w-full" />+ <LemonSkeleton className="h-8 w-full" />+ </>+ ) : (+ <span className="text-xs text-secondary">Pick which repositories this project reviews above.</span>+ )}+ </div>+ )+ }+ if (overview.results.length === 0) {+ return (+ <div className={`col-span-full px-4 py-3 text-xs text-secondary ${PANE_LEFT} ${PANE_ROW}`}>+ No repositories match.+ </div>+ )+ }+ return (+ <>+ {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>+ ))}+ </>+ )+}++/**+ * Two panes that share their rows: "This project" holds the rules everyone starts from, "My pull+ * requests" holds the viewer's own choices. Cells go left, right, left, right in one grid, so a row+ * in one pane always matches the height of the same repository's row in the other. On a narrow+ * container the grid falls back to one column, which gives one block per repository.+ */+export function RepositoriesPanes(): JSX.Element {+ const { canEdit } = useValues(reviewHogProjectSettingsLogic)++ return (+ <div className="@container">+ <div className="grid grid-cols-1 overflow-hidden rounded border border-primary @min-[48rem]:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]">+ <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">+ {canEdit ? 'You can edit: project admin' : 'Project admins edit'}+ </LemonTag>+ </span>+ <span className="text-xs text-secondary">+ Where everyone starts. Each person can still choose for their own PRs. Changes go to the+ activity log.+ </span>+ </div>+ <div className={`flex flex-col gap-0.5 px-4 py-3 ${PANE_RIGHT} ${PANE_ROW} @min-[48rem]:border-t-0`}>+ <span className="flex flex-wrap items-center gap-2 text-sm font-semibold">+ My pull requests+ <LemonTag type="highlight" size="small">+ Only you+ </LemonTag>+ </span>+ <span className="text-xs text-secondary">+ Highest wins: your repository choice, your default, the repository's exception, the project. A+ "you" mark shows where you set your own value.+ </span>+ </div>+ <ProjectRuleCell className={`${PANE_LEFT} ${PANE_ROW}`} />+ <MyDefaultCell className={`${PANE_RIGHT} ${PANE_ROW}`} />+ <RepositoryListToolbar />+ <RepositoryRows />+ <RepositoryListPager />+ </div>+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/RepositoryListPager.tsx b/products/review_hog/frontend/repositories/RepositoryListPager.tsxnew file mode 100644index 000000000000..00a35b32a5de--- /dev/null+++ b/products/review_hog/frontend/repositories/RepositoryListPager.tsx@@ -0,0 +1,49 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++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 { setPage } = useActions(reviewHogRepositoriesLogic)+ if (!overview || overview.total === 0) {+ return null+ }+ const first = page * REPOSITORIES_PAGE_SIZE + 1+ const last = Math.min(overview.total, first + overview.results.length - 1)+ return (+ <div+ className={`col-span-full flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 text-xs text-secondary ${PANE_LEFT} ${PANE_ROW}`}+ >+ <span>+ <span translate="no">+ {first}-{last} of {overview.total}+ </span>{' '}+ repositories. Nothing is saved for a repository unless it is selected, has an exception, or has a+ personal choice.+ </span>+ <span className="flex gap-1">+ <LemonButton+ size="small"+ type="secondary"+ onClick={() => setPage(page - 1)}+ disabledReason={page === 0 ? 'This is the first page' : overviewLoading ? 'Loading…' : undefined}+ >+ Previous+ </LemonButton>+ <LemonButton+ size="small"+ type="secondary"+ onClick={() => setPage(page + 1)}+ disabledReason={+ page >= pageCount - 1 ? 'This is the last page' : overviewLoading ? 'Loading…' : undefined+ }+ >+ Next+ </LemonButton>+ </span>+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/RepositoryListToolbar.tsx b/products/review_hog/frontend/repositories/RepositoryListToolbar.tsxnew file mode 100644index 000000000000..913f0db79ac8--- /dev/null+++ b/products/review_hog/frontend/repositories/RepositoryListToolbar.tsx@@ -0,0 +1,47 @@+import { useActions, useValues } from 'kea'++import { LemonInput, LemonSegmentedButton, LemonSelect } from '@posthog/lemon-ui'++import { ReviewHogRepositoryOverviewRetrieveView } from 'products/review_hog/frontend/generated/api.schemas'++import { PANE_LEFT, PANE_ROW } from './paneClasses'+import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'+import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'++const VIEW_OPTIONS: { value: ReviewHogRepositoryOverviewRetrieveView; label: string }[] = [+ { value: 'all', label: 'All' },+ { value: 'in_project', label: 'In this project' },+ { value: 'exceptions', label: 'With exceptions' },+ { value: 'mine', label: 'My choices' },+]++export function RepositoryListToolbar(): JSX.Element {+ const { installations } = useValues(reviewHogProjectSettingsLogic)+ const { installation, search, view } = useValues(reviewHogRepositoriesLogic)+ const { selectInstallation, setSearch, setView } = useActions(reviewHogRepositoriesLogic)++ return (+ <div className={`col-span-full flex flex-wrap items-center gap-2 px-4 py-2.5 ${PANE_LEFT} ${PANE_ROW}`}>+ <LemonInput+ type="search"+ size="small"+ className="min-w-48 flex-1"+ placeholder="Filter repositories"+ aria-label="Filter repositories"+ value={search}+ onChange={setSearch}+ data-attr="review-hog-repository-filter"+ />+ {installations.length > 1 && installation && (+ <LemonSelect+ size="small"+ aria-label="GitHub account"+ value={installation.installation_id}+ options={installations.map((item) => ({ value: item.installation_id, label: item.account_name }))}+ onChange={selectInstallation}+ />+ )}+ <LemonSegmentedButton size="small" value={view} options={VIEW_OPTIONS} onChange={setView} />+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/RepositoryMyCell.tsx b/products/review_hog/frontend/repositories/RepositoryMyCell.tsxnew file mode 100644index 000000000000..ab6e41b26e9a--- /dev/null+++ b/products/review_hog/frontend/repositories/RepositoryMyCell.tsx@@ -0,0 +1,98 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonSelect, Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'++import { MyChoiceValue, describeReason, myChoiceOptions, myChoiceValue, projectName } from './repositoryChoices'+import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'+import { YouMark } from './YouMark'++/** The viewer's side of one repository: what their own pull requests get there, and their choice. */+export function RepositoryMyCell({+ entry,+ className,+}: {+ entry: ReviewRepositoryOverviewEntryApi+ className?: string+}): JSX.Element {+ const { busyRepositories } = useValues(reviewHogRepositoriesLogic)+ const { setMyChoice } = useActions(reviewHogRepositoriesLogic)+ const name = entry.full_name+ const value = myChoiceValue(entry)+ const hasChoice = entry.my_choice !== null+ const busyReason = busyRepositories.includes(name) ? 'Saving…' : undefined+ const otherProjectId = entry.owner === 'other_project' ? entry.owner_project?.id : null++ let content: JSX.Element+ if (entry.owner === 'other_project') {+ content = (+ <span className="text-xs">+ {otherProjectId ? (+ <Link to={urls.project(otherProjectId, urls.codeReview())} disableClientSideRouting>+ Open {projectName(entry.owner_project)}+ </Link>+ ) : (+ <span className="text-secondary">Reviewed in {projectName(entry.owner_project)}</span>+ )}+ <span className="text-secondary"> · its rules decide your reviews here</span>+ </span>+ )+ } else if (!entry.in_project) {+ content = <span className="text-xs text-secondary">No automatic Flash. Not part of this project.</span>+ } else {+ const withoutChoice = entry.inherited_result.flash ? 'automatic Flash' : 'no automatic Flash'+ const choiceMatchesInherited = (entry.my_choice === 'flash') === entry.inherited_result.flash+ content = (+ <div className="flex min-w-0 flex-col items-start gap-1">+ <LemonSelect<MyChoiceValue>+ size="small"+ aria-label={`My choice for ${name}`}+ value={value}+ options={myChoiceOptions(entry)}+ onChange={(picked) => setMyChoice(entry, picked)}+ disabledReason={busyReason}+ data-attr="review-hog-my-choice"+ />+ <span className="text-xs text-secondary">+ {!hasChoice+ ? describeReason(entry.inherited_result)+ : choiceMatchesInherited+ ? `Your choice. Without it you also get ${withoutChoice}.`+ : `Your choice. Without it: ${withoutChoice}`}+ </span>+ </div>+ )+ }++ return (+ <div className={`flex min-w-0 flex-col justify-center gap-1 px-4 py-2.5 ${className ?? ''}`}>+ <span className="text-xxs font-semibold uppercase tracking-wide text-secondary @min-[48rem]:hidden">+ My choice+ </span>+ <div className="flex items-start gap-1">+ {/* Lines the mark up with the select, not with the reason text under it. */}+ <span className="pt-1.5">+ <YouMark shown={hasChoice} />+ </span>+ {content}+ </div>+ {hasChoice && !entry.in_project && (+ <div className="flex flex-wrap items-center gap-1 pl-10 text-xs text-secondary">+ Your saved choice applies if this repository joins this project.+ <LemonButton+ size="xsmall"+ type="tertiary"+ onClick={() => setMyChoice(entry, 'follow')}+ disabledReason={busyReason}+ data-attr="review-hog-clear-my-choice"+ >+ Clear my choice+ </LemonButton>+ </div>+ )}+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx b/products/review_hog/frontend/repositories/RepositoryProjectCell.tsxnew file mode 100644index 000000000000..0f4a07b1ad24--- /dev/null+++ b/products/review_hog/frontend/repositories/RepositoryProjectCell.tsx@@ -0,0 +1,161 @@+import { useActions, useValues } from 'kea'++import { IconPlus, IconX } from '@posthog/icons'+import { LemonButton, LemonDialog, LemonTag } from '@posthog/lemon-ui'++import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'++import { canTakeFromOtherProject, flashForLabel, projectName } from './repositoryChoices'+import { reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'+import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'+import { RuleControls } from './RuleControls'++/** The project side of one repository: whether this project reviews it, and its exception if any. */+export function RepositoryProjectCell({+ entry,+ className,+}: {+ entry: ReviewRepositoryOverviewEntryApi+ className?: string+}): JSX.Element {+ const { projectSettings, canEdit } = useValues(reviewHogProjectSettingsLogic)+ const { installation, busyRepositories } = useValues(reviewHogRepositoriesLogic)+ const {+ includeRepository,+ removeFromProject,+ addException,+ clearException,+ setExceptionFlashFor,+ addExceptionPerson,+ removeExceptionPerson,+ } = useActions(reviewHogRepositoriesLogic)++ 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 canRemove = canEdit && entry.in_project && entry.selected && installation?.scope !== 'all'++ const include = (): void => {+ if (!takeable) {+ includeRepository(entry)+ return+ }+ LemonDialog.open({+ title: `Include ${name} in this project?`,+ description: `This takes ${name} from ${projectName(entry.owner_project)}, which reviews all repositories of ${installation?.account_name ?? 'this GitHub account'}. Both projects get an activity log entry.`,+ primaryButton: {+ children: 'Include in project',+ onClick: () => includeRepository(entry),+ 'data-attr': 'review-hog-repository-take-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ })+ }++ let status: JSX.Element+ if (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) {+ status = (+ <>+ <span className="text-xs text-secondary">+ Follows project · {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>+ )}+ </>+ )+ } 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>+ )}+ </>+ )+ }++ 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>+ {entry.in_project && entry.exception !== null && (+ <RuleControls+ label={`Exception for ${name}`}+ flashFor={entry.exception.flash_for}+ people={entry.exception.people}+ canEdit={canEdit}+ disabledReason={canEdit ? savingReason : 'Only project admins can change this'}+ onChangeFlashFor={(flashFor) => setExceptionFlashFor(entry, flashFor)}+ onAddPerson={(userId, kind) => addExceptionPerson(entry, userId, kind)}+ onRemovePerson={(person) => removeExceptionPerson(entry, person)}+ dataAttr="review-hog-repository-flash-for"+ />+ )}+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/RuleControls.tsx b/products/review_hog/frontend/repositories/RuleControls.tsxnew file mode 100644index 000000000000..43ef1caa1356--- /dev/null+++ b/products/review_hog/frontend/repositories/RuleControls.tsx@@ -0,0 +1,59 @@+import { LemonSelect } from '@posthog/lemon-ui'++import type {+ AutomaticFlashForEnumApi,+ ReviewRepositoryPersonApi,+ ReviewRepositoryPersonKindEnumApi,+} from 'products/review_hog/frontend/generated/api.schemas'++import { PeopleList } from './PeopleList'+import { FLASH_FOR_OPTIONS, peopleKindFor } from './repositoryChoices'++/** Who gets automatic Flash, for the project settings and for a repository exception alike. */+export function RuleControls({+ label,+ flashFor,+ people,+ canEdit,+ disabledReason,+ onChangeFlashFor,+ onAddPerson,+ onRemovePerson,+ dataAttr,+}: {+ label: string+ flashFor: AutomaticFlashForEnumApi+ people: readonly ReviewRepositoryPersonApi[]+ canEdit: boolean+ disabledReason?: string+ onChangeFlashFor: (flashFor: AutomaticFlashForEnumApi) => void+ onAddPerson: (userId: number, kind: ReviewRepositoryPersonKindEnumApi) => void+ onRemovePerson: (person: ReviewRepositoryPersonApi) => void+ dataAttr: string+}): JSX.Element {+ const kind = peopleKindFor(flashFor)+ return (+ <div className="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"+ />+ {kind && (+ <PeopleList+ kind={kind}+ people={people}+ canEdit={canEdit}+ disabledReason={disabledReason}+ onAdd={(userId) => onAddPerson(userId, kind)}+ onRemove={onRemovePerson}+ />+ )}+ </div>+ )+}diff --git a/products/review_hog/frontend/repositories/YouMark.tsx b/products/review_hog/frontend/repositories/YouMark.tsxnew file mode 100644index 000000000000..5c0d19abd8c5--- /dev/null+++ b/products/review_hog/frontend/repositories/YouMark.tsx@@ -0,0 +1,17 @@+import { LemonTag } from '@posthog/lemon-ui'++/**+ * Marks a value the viewer set themselves. The slot keeps its width when empty, so selects in a+ * column stay aligned whether or not a row has the mark.+ */+export function YouMark({ shown }: { shown: boolean }): JSX.Element {+ return (+ <span className="flex w-9 shrink-0 justify-center">+ {shown && (+ <LemonTag type="highlight" size="small" title="Your own choice">+ you+ </LemonTag>+ )}+ </span>+ )+}diff --git a/products/review_hog/frontend/repositories/paneClasses.ts b/products/review_hog/frontend/repositories/paneClasses.tsnew file mode 100644index 000000000000..267ebbef6602--- /dev/null+++ b/products/review_hog/frontend/repositories/paneClasses.ts@@ -0,0 +1,4 @@+// Shared by every cell of the repository panes, so the two panes keep one look and one row rhythm.+export const PANE_LEFT = 'bg-surface-primary'+export const PANE_RIGHT = 'bg-surface-secondary @min-[48rem]:border-l @min-[48rem]:border-primary'+export const PANE_ROW = 'border-t border-primary'diff --git a/products/review_hog/frontend/repositories/repositoryChoices.test.ts b/products/review_hog/frontend/repositories/repositoryChoices.test.tsnew file mode 100644index 000000000000..2156056baa87--- /dev/null+++ b/products/review_hog/frontend/repositories/repositoryChoices.test.ts@@ -0,0 +1,47 @@+import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'++import { myChoiceOptions, myChoiceValue } from './repositoryChoices'++function entry(overrides: Partial<ReviewRepositoryOverviewEntryApi>): ReviewRepositoryOverviewEntryApi {+ return {+ full_name: 'example-org/web',+ github_repo_id: 1001,+ owner: 'this_project',+ owner_project: null,+ in_project: true,+ selected: false,+ repository_id: null,+ exception: null,+ my_choice: null,+ my_choice_id: null,+ my_result: { flash: false, reason: 'project_opt_in' },+ inherited_result: { flash: false, reason: 'project_opt_in' },+ ...overrides,+ }+}++describe('repositoryChoices', () => {+ it.each([+ {+ name: 'no stored choice follows',+ entry: entry({}),+ value: 'follow',+ options: ['follow', 'flash'],+ },+ {+ name: 'a choice that differs from the inherited value is selected',+ entry: entry({ my_choice: 'flash', my_choice_id: 'choice-1' }),+ value: 'flash',+ options: ['follow', 'flash'],+ },+ {+ name: 'a choice equal to the inherited value stays selected and listed',+ entry: entry({ my_choice: 'off', my_choice_id: 'choice-1' }),+ value: 'off',+ options: ['follow', 'flash', 'off'],+ },+ ])('my choice: $name', ({ entry: picked, value, options }) => {+ expect(myChoiceValue(picked)).toEqual(value)+ expect(myChoiceOptions(picked).map((option) => option.value)).toEqual(options)+ })+})diff --git a/products/review_hog/frontend/repositories/repositoryChoices.ts b/products/review_hog/frontend/repositories/repositoryChoices.tsnew file mode 100644index 000000000000..9293df27c9d9--- /dev/null+++ b/products/review_hog/frontend/repositories/repositoryChoices.ts@@ -0,0 +1,119 @@+import type {+ AutomaticFlashForEnumApi,+ AutomaticReviewDecisionApi,+ AutomaticReviewReasonEnumApi,+ DefaultReviewModeEnumApi,+ ReviewInstallationApi,+ ReviewProjectRefApi,+ ReviewRepositoryOverviewEntryApi,+ ReviewRepositoryPersonKindEnumApi,+ ReviewUserRepositoryChoiceModeEnumApi,+} from 'products/review_hog/frontend/generated/api.schemas'++export interface ChoiceOption<T extends string> {+ value: T+ label: string+}++export const FLASH_FOR_OPTIONS: ChoiceOption<AutomaticFlashForEnumApi>[] = [+ { value: 'everyone', label: 'Automatic Flash for everyone' },+ { value: 'listed', label: 'Automatic Flash for these people' },+ { value: 'off', label: 'Automatic Flash: opt-in only' },+]++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: 'Follow each repository' },+ { value: 'flash', label: 'Flash everywhere' },+ { value: 'off', label: 'Off everywhere' },+]++/** The people list a rule reads: the except list for "everyone", the people list for "listed", none for "off". */+export function peopleKindFor(flashFor: AutomaticFlashForEnumApi): ReviewRepositoryPersonKindEnumApi | null {+ if (flashFor === 'everyone') {+ return 'excepted'+ }+ return flashFor === 'listed' ? 'listed' : null+}++const REASONS: Record<AutomaticReviewReasonEnumApi, string> = {+ own_repository_choice: 'Your choice for this repository',+ own_default: 'Your default',+ repository_everyone: "This repository's exception: everyone",+ repository_excepted: "This repository's exception: you are on the except list",+ repository_listed: "This repository's exception: you are on the list",+ repository_not_listed: "This repository's exception: you are not on the list",+ repository_opt_in: "This repository's exception: opt-in only",+ project_everyone: 'Project settings: everyone',+ project_excepted: 'Project settings: you are on the except list',+ project_listed: 'Project settings: you are on the list',+ project_not_listed: 'Project settings: you are not on the list',+ project_opt_in: 'Project settings: opt-in only',+ bot_reviewed: 'The project reviews bot pull requests',+ bot_skipped: 'The project does not review bot pull requests',+ not_in_project: 'Not part of this project',+}++export function describeReason(decision: AutomaticReviewDecisionApi): string {+ return REASONS[decision.reason]+}++export function describeResult(decision: AutomaticReviewDecisionApi): string {+ return decision.flash ? 'Automatic Flash' : 'No automatic Flash'+}++export type MyChoiceValue = ReviewUserRepositoryChoiceModeEnumApi | 'follow'++export function myChoiceValue(entry: ReviewRepositoryOverviewEntryApi): MyChoiceValue {+ return entry.my_choice ?? 'follow'+}++const CHOICE_LABELS: Record<ReviewUserRepositoryChoiceModeEnumApi, string> = {+ flash: 'Flash for me',+ off: 'Off for me',+}++/**+ * Offering the inherited value as its own option would look like a pin, but the API stores only what+ * differs, so the pick would vanish. A choice saved before the inherited value changed is the exception.+ */+export function myChoiceOptions(entry: ReviewRepositoryOverviewEntryApi): ChoiceOption<MyChoiceValue>[] {+ const inherited = entry.inherited_result+ const opposite: ReviewUserRepositoryChoiceModeEnumApi = inherited.flash ? 'off' : 'flash'+ const options: ChoiceOption<MyChoiceValue>[] = [+ { value: 'follow', label: `${describeResult(inherited)} (follow)` },+ { value: opposite, label: CHOICE_LABELS[opposite] },+ ]+ if (entry.my_choice !== null && entry.my_choice !== opposite) {+ options.push({ value: entry.my_choice, label: CHOICE_LABELS[entry.my_choice] })+ }+ return options+}++export function projectName(project: ReviewProjectRefApi | null): string {+ return project?.name ? `the ${project.name} project` : 'a project in another organization'+}++function sameProject(left: ReviewProjectRefApi, right: ReviewProjectRefApi): boolean {+ return left.id === right.id && left.name === right.name+}++/**+ * A repository another project reviews only through its "all repositories" claim can still be+ * included here, which takes it from that project. One that another project selected cannot.+ */+export function canTakeFromOtherProject(+ entry: ReviewRepositoryOverviewEntryApi,+ installation: ReviewInstallationApi | null+): boolean {+ const takenBy = installation?.all_taken_by_project ?? null+ return (+ entry.owner === 'other_project' &&+ takenBy !== null &&+ entry.owner_project !== null &&+ sameProject(entry.owner_project, takenBy)+ )+}diff --git a/products/review_hog/frontend/repositories/reviewHogProjectSettingsLogic.ts b/products/review_hog/frontend/repositories/reviewHogProjectSettingsLogic.tsnew file mode 100644index 000000000000..d76235396da4--- /dev/null+++ b/products/review_hog/frontend/repositories/reviewHogProjectSettingsLogic.ts@@ -0,0 +1,366 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { LemonDialog, lemonToast } from '@posthog/lemon-ui'++import { teamLogic } from 'scenes/teamLogic'++import {+ reviewHogInstallationClaimsCreate,+ reviewHogInstallationClaimsDestroy,+ reviewHogInstallationClaimsPartialUpdate,+ reviewHogProjectSettingsPartialUpdate,+ reviewHogProjectSettingsPeopleCreate,+ reviewHogProjectSettingsPeopleDestroy,+ reviewHogProjectSettingsRetrieve,+ reviewHogRepositoriesList,+ reviewHogRepositoryOverviewRetrieve,+} from 'products/review_hog/frontend/generated/api'+import type {+ PatchedReviewProjectSettingsApi,+ ReviewInstallationApi,+ ReviewInstallationClaimScopeEnumApi,+ ReviewProjectSettingsApi,+ ReviewRepositoryPersonApi,+ ReviewRepositoryPersonKindEnumApi,+} from 'products/review_hog/frontend/generated/api.schemas'+import { ReviewHogRepositoryOverviewRetrieveView } from 'products/review_hog/frontend/generated/api.schemas'+import { reviewHogSettingsLogic } from 'products/review_hog/frontend/reviewHogSettingsLogic'++export function currentProjectId(): string {+ return String(teamLogic.values.currentTeamId)+}++/** The API names the conflicting project in `error`; DRF validation errors use `detail`. */+export function errorMessage(error: unknown, fallback: string): string {+ const body = error as { error?: unknown; detail?: unknown; data?: { error?: unknown } } | null+ for (const message of [body?.error, body?.data?.error, body?.detail]) {+ if (typeof message === 'string' && message) {+ return message+ }+ }+ return fallback+}++/** Repositories that leave the project when its claim switches from all repositories to only selected ones. */+async function countRepositoriesLeaving(installationId: string): Promise<number> {+ const [inProject, rows] = await Promise.all([+ reviewHogRepositoryOverviewRetrieve(currentProjectId(), {+ installation_id: installationId,+ view: ReviewHogRepositoryOverviewRetrieveView.InProject,+ limit: 1,+ }),+ reviewHogRepositoriesList(currentProjectId()),+ ])+ const selected = rows.filter((row) => row.installation_id === installationId && row.selected).length+ return Math.max(0, inProject.total - selected)+}++/** The installation claim select also offers "none", which deletes the claim. */+export type ClaimScopeChoice = ReviewInstallationClaimScopeEnumApi | 'none'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reviewHogProjectSettingsLogicValues {+ canEdit: boolean+ claimSaving: boolean+ editDisabledReason: string | undefined+ installations: readonly ReviewInstallationApi[]+ projectSettings: ReviewProjectSettingsApi | null+ projectSettingsLoadFailed: boolean+ projectSettingsLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reviewHogProjectSettingsLogicActions {+ loadSettings: () => any // reviewHogSettingsLogic+ addProjectPerson: ({ userId, kind }: { kind: ReviewRepositoryPersonKindEnumApi; userId: number }) => {+ userId: number+ kind: ReviewRepositoryPersonKindEnumApi+ }+ addProjectPersonFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ addProjectPersonSuccess: (+ projectSettings: ReviewProjectSettingsApi,+ payload?: {+ userId: number+ kind: ReviewRepositoryPersonKindEnumApi+ }+ ) => {+ projectSettings: ReviewProjectSettingsApi+ payload?: {+ userId: number+ kind: ReviewRepositoryPersonKindEnumApi+ }+ }+ changeClaimScope: (+ installation: ReviewInstallationApi,+ scope: ClaimScopeChoice+ ) => {+ installation: ReviewInstallationApi+ scope: ClaimScopeChoice+ }+ loadProjectSettings: () => any+ loadProjectSettingsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadProjectSettingsSuccess: (+ projectSettings: ReviewProjectSettingsApi,+ payload?: any+ ) => {+ projectSettings: ReviewProjectSettingsApi+ payload?: any+ }+ removeProjectPerson: (person: ReviewRepositoryPersonApi) => ReviewRepositoryPersonApi+ removeProjectPersonFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ removeProjectPersonSuccess: (+ projectSettings: ReviewProjectSettingsApi,+ payload?: ReviewRepositoryPersonApi+ ) => {+ projectSettings: ReviewProjectSettingsApi+ payload?: ReviewRepositoryPersonApi+ }+ setClaimScope: (+ installation: ReviewInstallationApi,+ scope: ClaimScopeChoice+ ) => {+ installation: ReviewInstallationApi+ scope: ClaimScopeChoice+ }+ setClaimScopeFinished: () => {+ value: true+ }+ updateProjectSettings: (patch: PatchedReviewProjectSettingsApi) => PatchedReviewProjectSettingsApi+ updateProjectSettingsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ updateProjectSettingsSuccess: (+ projectSettings: ReviewProjectSettingsApi,+ payload?: PatchedReviewProjectSettingsApi+ ) => {+ projectSettings: ReviewProjectSettingsApi+ payload?: PatchedReviewProjectSettingsApi+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reviewHogProjectSettingsLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ canEdit: (projectSettings: ReviewProjectSettingsApi | null) => boolean+ installations: (projectSettings: ReviewProjectSettingsApi | null) => readonly ReviewInstallationApi[]+ editDisabledReason: (+ projectSettings: ReviewProjectSettingsApi | null,+ projectSettingsLoading: boolean+ ) => string | undefined+ }+}++export type reviewHogProjectSettingsLogicType = MakeLogicType<+ reviewHogProjectSettingsLogicValues,+ reviewHogProjectSettingsLogicActions,+ Record<string, any>,+ reviewHogProjectSettingsLogicMeta+>++/**+ * The project-wide ReviewHog settings: which repositories of each GitHub installation this project+ * reviews, the rule for automatic Flash with its people lists, bot pull requests, and the project+ * defaults for Full reviews. Members read them; only project admins can change them (`can_edit`).+ */+export const reviewHogProjectSettingsLogic = kea<reviewHogProjectSettingsLogicType>([+ path(['products', 'review_hog', 'frontend', 'repositories', 'reviewHogProjectSettingsLogic']),++ connect(() => ({+ actions: [reviewHogSettingsLogic, ['loadSettings']],+ })),++ actions({+ // Asks for a confirm first when the change removes repositories from this project.+ changeClaimScope: (installation: ReviewInstallationApi, scope: ClaimScopeChoice) => ({ installation, scope }),+ setClaimScope: (installation: ReviewInstallationApi, scope: ClaimScopeChoice) => ({ installation, scope }),+ setClaimScopeFinished: true,+ }),++ loaders(() => ({+ projectSettings: [+ null as ReviewProjectSettingsApi | null,+ {+ loadProjectSettings: async () => await reviewHogProjectSettingsRetrieve(currentProjectId()),+ updateProjectSettings: async (patch: PatchedReviewProjectSettingsApi) =>+ await reviewHogProjectSettingsPartialUpdate(currentProjectId(), patch),+ addProjectPerson: async ({+ userId,+ kind,+ }: {+ userId: number+ kind: ReviewRepositoryPersonKindEnumApi+ }) => await reviewHogProjectSettingsPeopleCreate(currentProjectId(), { user_id: userId, kind }),+ removeProjectPerson: async (person: ReviewRepositoryPersonApi) =>+ await reviewHogProjectSettingsPeopleDestroy(currentProjectId(), person.id),+ },+ ],+ })),++ reducers({+ claimSaving: [+ false,+ {+ setClaimScope: () => true,+ setClaimScopeFinished: () => false,+ },+ ],+ projectSettingsLoadFailed: [+ false,+ {+ loadProjectSettings: () => false,+ loadProjectSettingsSuccess: () => false,+ loadProjectSettingsFailure: () => true,+ },+ ],+ }),++ selectors({+ canEdit: [+ (s) => [s.projectSettings],+ (projectSettings: ReviewProjectSettingsApi | null): boolean => projectSettings?.can_edit ?? false,+ ],+ installations: [+ (s) => [s.projectSettings],+ (projectSettings: ReviewProjectSettingsApi | null): readonly ReviewInstallationApi[] =>+ projectSettings?.installations ?? [],+ ],+ editDisabledReason: [+ (s) => [s.projectSettings, s.projectSettingsLoading],+ (projectSettings: ReviewProjectSettingsApi | null, loading: boolean): string | undefined => {+ if (projectSettings === null) {+ return 'Loading…'+ }+ if (!projectSettings.can_edit) {+ return 'Only project admins can change this'+ }+ return loading ? 'Saving…' : undefined+ },+ ],+ }),++ listeners(({ actions }) => ({+ changeClaimScope: async ({ installation, scope }) => {+ const account = installation.account_name+ if (scope === (installation.scope ?? 'none')) {+ return+ }+ if (scope === 'none') {+ LemonDialog.open({+ title: `Stop reviewing ${account} here?`,+ description:+ 'This project stops reviewing every repository of this GitHub account. Its selected repositories and exceptions there are removed. Personal choices stay.',+ primaryButton: {+ children: 'Stop reviewing',+ status: 'danger',+ onClick: () => actions.setClaimScope(installation, scope),+ 'data-attr': 'review-hog-claim-remove-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ })+ return+ }+ if (scope === 'selected' && installation.scope === 'all') {+ let leaving: number | null = null+ try {+ leaving = await countRepositoriesLeaving(installation.installation_id)+ } catch {+ // The confirm still explains the change without the number.+ }+ const count =+ leaving === null+ ? 'Repositories that are not selected'+ : `${leaving} ${leaving === 1 ? 'repository' : 'repositories'}`+ LemonDialog.open({+ title: 'Review only selected repositories?',+ description: `${count} stop being reviewed here, and their exceptions are removed. New repositories of ${account} are not reviewed until you include them. Personal choices stay.`,+ primaryButton: {+ children: 'Only selected repositories',+ onClick: () => actions.setClaimScope(installation, scope),+ 'data-attr': 'review-hog-claim-selected-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ })+ return+ }+ actions.setClaimScope(installation, scope)+ },+ setClaimScope: async ({ installation, scope }) => {+ try {+ if (scope === 'none') {+ if (installation.claim_id) {+ await reviewHogInstallationClaimsDestroy(currentProjectId(), installation.claim_id)+ }+ } else if (installation.claim_id) {+ await reviewHogInstallationClaimsPartialUpdate(currentProjectId(), installation.claim_id, { scope })+ } else {+ await reviewHogInstallationClaimsCreate(currentProjectId(), {+ installation_id: installation.installation_id,+ scope,+ })+ }+ // pinned: analytics event names in this file feed the Code review usage dashboards+ posthog.capture('review hog installation claim changed', {+ scope,+ previous_scope: installation.scope ?? 'none',+ })+ } catch (error) {+ lemonToast.error(errorMessage(error, 'Could not save the change. Try again.'))+ }+ actions.setClaimScopeFinished()+ actions.loadProjectSettings()+ },+ updateProjectSettingsSuccess: ({ payload }) => {+ if (payload?.flash_for !== undefined) {+ posthog.capture('review hog project rule changed', { flash_for: payload.flash_for })+ }+ if (payload?.bot_prs !== undefined) {+ posthog.capture('review hog bot pull requests changed', { bot_prs: payload.bot_prs })+ }+ for (const key of ['urgency_threshold', 'celebrate_clean_reviews'] as const) {+ if (payload?.[key] !== undefined) {+ posthog.capture('review hog project default changed', { key, value: payload[key] })+ // Everyone without an own value now gets the new default.+ actions.loadSettings()+ }+ }+ },+ addProjectPersonSuccess: ({ payload }) => {+ posthog.capture('review hog project person added', { kind: payload?.kind })+ },+ removeProjectPersonSuccess: ({ payload }) => {+ posthog.capture('review hog project person removed', { kind: payload?.kind })+ },+ updateProjectSettingsFailure: () => {+ // The loaders toast already showed the error. Reload so the controls show what is saved.+ actions.loadProjectSettings()+ },+ })),++ afterMount(({ actions }) => {+ actions.loadProjectSettings()+ }),+])diff --git a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.tsnew file mode 100644index 000000000000..9a045f8f72ce--- /dev/null+++ b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.test.ts@@ -0,0 +1,172 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { ReviewRepositoryOverviewEntryApi } from 'products/review_hog/frontend/generated/api.schemas'++import { reviewHogRepositoriesLogic } from './reviewHogRepositoriesLogic'++const ROSE = { id: 202, uuid: 'user-202', email: '[email protected]', hedgehog_config: null }++function entry(overrides: Partial<ReviewRepositoryOverviewEntryApi>): ReviewRepositoryOverviewEntryApi {+ return {+ full_name: 'example-org/web',+ github_repo_id: 1001,+ owner: 'this_project',+ owner_project: null,+ in_project: true,+ selected: false,+ repository_id: null,+ exception: null,+ my_choice: null,+ my_choice_id: null,+ my_result: { flash: true, reason: 'project_everyone' },+ inherited_result: { flash: true, reason: 'project_everyone' },+ ...overrides,+ }+}++describe('reviewHogRepositoriesLogic', () => {+ let logic: ReturnType<typeof reviewHogRepositoriesLogic.build>+ let requests: string[]+ let overviewCalls: number+ let overviewTotal: number++ beforeEach(() => {+ requests = []+ overviewCalls = 0+ overviewTotal = 0+ useMocks({+ get: {+ '/api/projects/:team_id/review_hog/project_settings/': () => [+ 200,+ {+ flash_for: 'everyone',+ bot_prs: 'skip',+ people: [{ id: 'person-rose', user: ROSE, kind: 'excepted' }],+ installations: [+ {+ installation_id: '41',+ account_name: 'example-org',+ connected_by: null,+ claim_id: 'claim-1',+ scope: 'all',+ all_taken_by_project: null,+ },+ ],+ can_edit: true,+ },+ ],+ '/api/projects/:team_id/review_hog/repository_overview/': () => {+ overviewCalls += 1+ return [+ 200,+ {+ installation_id: '41',+ claim_scope: 'all',+ results: [],+ total: overviewTotal,+ has_more: false,+ next_offset: null,+ },+ ]+ },+ '/api/projects/:team_id/review_hog/settings/': () => [200, { default_review_mode: 'follow' }],+ },+ post: {+ '/api/projects/:team_id/review_hog/repository_choices/': async ({ request }) => {+ requests.push(`POST choice ${JSON.stringify(await request.json())}`)+ return [200, { choice: null, my_result: { flash: false, reason: 'own_repository_choice' } }]+ },+ '/api/projects/:team_id/review_hog/repositories/': async ({ request }) => {+ requests.push(`POST repository ${JSON.stringify(await request.json())}`)+ return [200, { repository: { id: 'repo-web' }, taken_from_project: null }]+ },+ '/api/projects/:team_id/review_hog/repositories/:id/people/': async ({ request, params }) => {+ requests.push(`POST person ${params.id} ${JSON.stringify(await request.json())}`)+ return [201, {}]+ },+ },+ patch: {+ '/api/projects/:team_id/review_hog/settings/': async ({ request }) => [200, await request.json()],+ },+ delete: {+ '/api/projects/:team_id/review_hog/repository_choices/:id/': ({ params }) => {+ requests.push(`DELETE choice ${params.id}`)+ return [204]+ },+ },+ })+ initKeaTests()+ logic = reviewHogRepositoriesLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it.each([+ {+ name: 'follow clears a stored choice',+ entry: entry({ my_choice: 'off', my_choice_id: 'choice-1' }),+ value: 'follow' as const,+ expected: ['DELETE choice choice-1'],+ },+ {+ name: 'follow without a stored choice writes nothing',+ entry: entry({}),+ value: 'follow' as const,+ expected: [],+ },+ {+ name: 'the opposite of the inherited value is stored',+ entry: entry({}),+ value: 'off' as const,+ expected: [+ 'POST choice {"installation_id":"41","full_name":"example-org/web","github_repo_id":1001,"mode":"off"}',+ ],+ },+ ])('my choice: $name', async ({ entry: picked, value, expected }) => {+ await expectLogic(logic).toDispatchActions(['loadOverviewSuccess'])++ await expectLogic(logic, () => logic.actions.setMyChoice(picked, value)).toFinishAllListeners()++ expect(requests).toEqual(expected)+ })++ it('a new exception starts as a copy of the project rule and its list', async () => {+ await expectLogic(logic).toDispatchActions(['loadOverviewSuccess'])++ 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"}',+ ])+ })++ it('changing my default reloads the list, because the default decides every inherited result', async () => {+ await expectLogic(logic).toDispatchActions(['loadOverviewSuccess'])+ const callsBefore = overviewCalls++ await expectLogic(logic, () => logic.actions.setMyDefault('off')).toDispatchActions([+ 'updateSettingsSuccess',+ 'loadOverview',+ 'loadOverviewSuccess',+ ])+ expect(overviewCalls).toBe(callsBefore + 1)+ })++ it('goes back to the last page with rows when a write empties the current one', async () => {+ overviewTotal = 21+ await expectLogic(logic, () => logic.actions.setPage(1)).toDispatchActions(['loadOverviewSuccess'])+ expect(logic.values.page).toBe(1)++ overviewTotal = 20+ await expectLogic(logic, () => logic.actions.loadOverview()).toFinishAllListeners()++ expect(logic.values.page).toBe(0)+ })+})diff --git a/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.tsnew file mode 100644index 000000000000..00656f3a0d1b--- /dev/null+++ b/products/review_hog/frontend/repositories/reviewHogRepositoriesLogic.ts@@ -0,0 +1,593 @@+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { combineUrl } from 'kea-router'+import posthog from 'posthog-js'++import { lemonToast } from '@posthog/lemon-ui'++import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { getIntegrationsAuthorizeRetrieveUrl } from 'products/integrations/frontend/generated/api'+import {+ reviewHogRepositoriesCreate,+ reviewHogRepositoriesPeopleCreate,+ reviewHogRepositoriesPeopleDestroy,+ reviewHogRepositoryChoicesCreate,+ reviewHogRepositoryChoicesDestroy,+ reviewHogRepositoryOverviewRetrieve,+} from 'products/review_hog/frontend/generated/api'+import type {+ AutomaticFlashForEnumApi,+ DefaultReviewModeEnumApi,+ ReviewInstallationApi,+ ReviewRepositoryOverviewApi,+ ReviewRepositoryOverviewEntryApi,+ ReviewRepositoryPersonApi,+ ReviewRepositoryPersonKindEnumApi,+} from 'products/review_hog/frontend/generated/api.schemas'+import { ReviewHogRepositoryOverviewRetrieveView } from 'products/review_hog/frontend/generated/api.schemas'+import { reviewHogSettingsLogic } from 'products/review_hog/frontend/reviewHogSettingsLogic'++import type { ReviewProjectSettingsApi } from '../generated/api.schemas'+import { MyChoiceValue, peopleKindFor } from './repositoryChoices'+import { currentProjectId, errorMessage, reviewHogProjectSettingsLogic } from './reviewHogProjectSettingsLogic'++export const REPOSITORIES_PAGE_SIZE = 20++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reviewHogRepositoriesLogicValues {+ canEdit: boolean // reviewHogProjectSettingsLogic+ installations: readonly ReviewInstallationApi[] // reviewHogProjectSettingsLogic+ projectSettings: ReviewProjectSettingsApi | null // reviewHogProjectSettingsLogic+ currentTeamId: number | null // teamLogic+ busyRepositories: string[]+ connectGitHubUrl: string+ installation: ReviewInstallationApi | null+ overview: ReviewRepositoryOverviewApi | null+ overviewLoadFailed: boolean+ overviewLoading: boolean+ page: number+ pageCount: number+ search: string+ selectedInstallationId: string | null+ view: ReviewHogRepositoryOverviewRetrieveView+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reviewHogRepositoriesLogicActions {+ addProjectPersonSuccess: (+ projectSettings: ReviewProjectSettingsApi,+ payload?:+ | {+ kind: ReviewRepositoryPersonKindEnumApi+ userId: number+ }+ | undefined+ ) => {+ payload?: {+ kind: ReviewRepositoryPersonKindEnumApi+ userId: number+ }+ projectSettings: ReviewProjectSettingsApi+ } // reviewHogProjectSettingsLogic+ loadProjectSettings: () => any // reviewHogProjectSettingsLogic+ loadProjectSettingsSuccess: (+ projectSettings: ReviewProjectSettingsApi,+ payload?: any+ ) => {+ payload?: any+ projectSettings: ReviewProjectSettingsApi+ } // reviewHogProjectSettingsLogic+ removeProjectPersonSuccess: (+ projectSettings: ReviewProjectSettingsApi,+ payload?: ReviewRepositoryPersonApi | undefined+ ) => {+ payload?: ReviewRepositoryPersonApi+ projectSettings: ReviewProjectSettingsApi+ } // reviewHogProjectSettingsLogic+ updateProjectSettingsSuccess: (+ projectSettings: ReviewProjectSettingsApi,+ payload?:+ | import('products/review_hog/frontend/generated/api.schemas').PatchedReviewProjectSettingsApi+ | undefined+ ) => {+ payload?: import('products/review_hog/frontend/generated/api.schemas').PatchedReviewProjectSettingsApi+ projectSettings: ReviewProjectSettingsApi+ } // reviewHogProjectSettingsLogic+ updateSettings: (+ patch: import('products/review_hog/frontend/generated/api.schemas').PatchedReviewUserSettingsApi+ ) => import('products/review_hog/frontend/generated/api.schemas').PatchedReviewUserSettingsApi // reviewHogSettingsLogic+ updateSettingsSuccess: (+ settings: import('products/review_hog/frontend/generated/api.schemas').ReviewUserSettingsApi,+ payload?: import('products/review_hog/frontend/generated/api.schemas').PatchedReviewUserSettingsApi | undefined+ ) => {+ payload?: import('products/review_hog/frontend/generated/api.schemas').PatchedReviewUserSettingsApi+ settings: import('products/review_hog/frontend/generated/api.schemas').ReviewUserSettingsApi+ } // reviewHogSettingsLogic+ addException: (entry: ReviewRepositoryOverviewEntryApi) => {+ entry: ReviewRepositoryOverviewEntryApi+ }+ addExceptionPerson: (+ entry: ReviewRepositoryOverviewEntryApi,+ userId: number,+ kind: ReviewRepositoryPersonKindEnumApi+ ) => {+ entry: ReviewRepositoryOverviewEntryApi+ kind: ReviewRepositoryPersonKindEnumApi+ userId: number+ }+ clearException: (entry: ReviewRepositoryOverviewEntryApi) => {+ entry: ReviewRepositoryOverviewEntryApi+ }+ includeRepository: (entry: ReviewRepositoryOverviewEntryApi) => {+ entry: ReviewRepositoryOverviewEntryApi+ }+ loadOverview: (_: void) => void+ loadOverviewFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadOverviewSuccess: (+ overview: ReviewRepositoryOverviewApi | null,+ payload?: void+ ) => {+ overview: ReviewRepositoryOverviewApi | null+ payload?: void+ }+ removeExceptionPerson: (+ entry: ReviewRepositoryOverviewEntryApi,+ person: ReviewRepositoryPersonApi+ ) => {+ entry: ReviewRepositoryOverviewEntryApi+ person: ReviewRepositoryPersonApi+ }+ removeFromProject: (entry: ReviewRepositoryOverviewEntryApi) => {+ entry: ReviewRepositoryOverviewEntryApi+ }+ repositorySaveFinished: (fullName: string) => {+ fullName: string+ }+ repositorySaveStarted: (fullName: string) => {+ fullName: string+ }+ selectInstallation: (installationId: string) => {+ installationId: string+ }+ setExceptionFlashFor: (+ entry: ReviewRepositoryOverviewEntryApi,+ flashFor: AutomaticFlashForEnumApi+ ) => {+ entry: ReviewRepositoryOverviewEntryApi+ flashFor: AutomaticFlashForEnumApi+ }+ setMyChoice: (+ entry: ReviewRepositoryOverviewEntryApi,+ value: MyChoiceValue+ ) => {+ entry: ReviewRepositoryOverviewEntryApi+ value: MyChoiceValue+ }+ setMyDefault: (mode: DefaultReviewModeEnumApi) => {+ mode: DefaultReviewModeEnumApi+ }+ setPage: (page: number) => {+ page: number+ }+ setSearch: (search: string) => {+ search: string+ }+ setView: (view: ReviewHogRepositoryOverviewRetrieveView) => {+ view: ReviewHogRepositoryOverviewRetrieveView+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface reviewHogRepositoriesLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ installation: (+ installations: readonly ReviewInstallationApi[],+ selectedInstallationId: string | null+ ) => ReviewInstallationApi | null+ pageCount: (overview: ReviewRepositoryOverviewApi | null) => number+ connectGitHubUrl: (currentTeamId: number | null) => string+ }+}++export type reviewHogRepositoriesLogicType = MakeLogicType<+ reviewHogRepositoriesLogicValues,+ reviewHogRepositoriesLogicActions,+ Record<string, any>,+ reviewHogRepositoriesLogicMeta+>++/**+ * The repository list of the Code review settings: every repository a connected GitHub installation+ * can see, joined with this project's settings and the viewer's own choices. The server decides+ * `my_result` and `inherited_result`, so every write reloads the page instead of computing a rule here.+ */+export const reviewHogRepositoriesLogic = kea<reviewHogRepositoriesLogicType>([+ path(['products', 'review_hog', 'frontend', 'repositories', 'reviewHogRepositoriesLogic']),++ connect(() => ({+ values: [+ reviewHogProjectSettingsLogic,+ ['projectSettings', 'installations', 'canEdit'],+ teamLogic,+ ['currentTeamId'],+ ],+ actions: [+ reviewHogProjectSettingsLogic,+ [+ 'loadProjectSettings',+ 'loadProjectSettingsSuccess',+ 'updateProjectSettingsSuccess',+ 'addProjectPersonSuccess',+ 'removeProjectPersonSuccess',+ ],+ reviewHogSettingsLogic,+ ['updateSettings', 'updateSettingsSuccess'],+ ],+ })),++ actions({+ selectInstallation: (installationId: string) => ({ installationId }),+ setSearch: (search: string) => ({ search }),+ setView: (view: ReviewHogRepositoryOverviewRetrieveView) => ({ view }),+ setPage: (page: number) => ({ page }),+ includeRepository: (entry: ReviewRepositoryOverviewEntryApi) => ({ entry }),+ removeFromProject: (entry: ReviewRepositoryOverviewEntryApi) => ({ entry }),+ addException: (entry: ReviewRepositoryOverviewEntryApi) => ({ entry }),+ clearException: (entry: ReviewRepositoryOverviewEntryApi) => ({ entry }),+ setExceptionFlashFor: (entry: ReviewRepositoryOverviewEntryApi, flashFor: AutomaticFlashForEnumApi) => ({+ entry,+ flashFor,+ }),+ addExceptionPerson: (+ entry: ReviewRepositoryOverviewEntryApi,+ userId: number,+ kind: ReviewRepositoryPersonKindEnumApi+ ) => ({ entry, userId, kind }),+ removeExceptionPerson: (entry: ReviewRepositoryOverviewEntryApi, person: ReviewRepositoryPersonApi) => ({+ entry,+ person,+ }),+ setMyChoice: (entry: ReviewRepositoryOverviewEntryApi, value: MyChoiceValue) => ({ entry, value }),+ setMyDefault: (mode: DefaultReviewModeEnumApi) => ({ mode }),+ // One write per repository at a time. The row shows it as saving until the page reloads.+ repositorySaveStarted: (fullName: string) => ({ fullName }),+ repositorySaveFinished: (fullName: string) => ({ fullName }),+ }),++ loaders(({ values }) => ({+ overview: [+ null as ReviewRepositoryOverviewApi | null,+ {+ loadOverview: async (_: void, breakpoint) => {+ const installationId = values.installation?.installation_id+ if (!installationId) {+ return null+ }+ const overview = await reviewHogRepositoryOverviewRetrieve(currentProjectId(), {+ installation_id: installationId,+ search: values.search.trim() || undefined,+ view: values.view,+ offset: values.page * REPOSITORIES_PAGE_SIZE,+ limit: REPOSITORIES_PAGE_SIZE,+ })+ breakpoint()+ return overview+ },+ },+ ],+ })),++ reducers({+ selectedInstallationId: [+ null as string | null,+ {+ selectInstallation: (_, { installationId }) => installationId,+ },+ ],+ search: [+ '',+ {+ setSearch: (_, { search }) => search,+ },+ ],+ view: [+ ReviewHogRepositoryOverviewRetrieveView.All as ReviewHogRepositoryOverviewRetrieveView,+ {+ setView: (_, { view }) => view,+ },+ ],+ page: [+ 0,+ {+ setPage: (_, { page }) => page,+ setSearch: () => 0,+ setView: () => 0,+ selectInstallation: () => 0,+ },+ ],+ overviewLoadFailed: [+ false,+ {+ loadOverview: () => false,+ loadOverviewSuccess: () => false,+ loadOverviewFailure: () => true,+ },+ ],+ busyRepositories: [+ [] as string[],+ {+ repositorySaveStarted: (state, { fullName }) => [...state, fullName],+ repositorySaveFinished: (state, { fullName }) => state.filter((name) => name !== fullName),+ },+ ],+ }),++ selectors({+ installation: [+ (s) => [s.installations, s.selectedInstallationId],+ (+ installations: readonly ReviewInstallationApi[],+ selectedInstallationId: string | null+ ): ReviewInstallationApi | null =>+ installations.find((installation) => installation.installation_id === selectedInstallationId) ??+ installations[0] ??+ null,+ ],+ pageCount: [+ (s) => [s.overview],+ (overview: ReviewRepositoryOverviewApi | null): number =>+ Math.max(1, Math.ceil((overview?.total ?? 0) / REPOSITORIES_PAGE_SIZE)),+ ],+ // Back to the Settings tab after GitHub authorizes, so the user lands on the claim picker.+ connectGitHubUrl: [+ (s) => [s.currentTeamId],+ (currentTeamId: number | null): string =>+ `${getIntegrationsAuthorizeRetrieveUrl(String(currentTeamId))}?${new URLSearchParams({+ kind: 'github',+ next: combineUrl(urls.codeReview(), { tab: 'settings' }).url,+ })}`,+ ],+ }),++ listeners(({ actions, values }) => {+ /** Runs one write for a repository, then reloads the page so every result comes from the server. */+ async function writeRepository(+ entry: ReviewRepositoryOverviewEntryApi,+ write: () => Promise<void>,+ fallbackError: string+ ): Promise<boolean> {+ if (values.busyRepositories.includes(entry.full_name)) {+ return false+ }+ actions.repositorySaveStarted(entry.full_name)+ let saved = false+ try {+ await write()+ saved = true+ } catch (error) {+ lemonToast.error(errorMessage(error, fallbackError))+ }+ actions.repositorySaveFinished(entry.full_name)+ actions.loadOverview()+ return saved+ }++ function repositoryRef(entry: ReviewRepositoryOverviewEntryApi): {+ installation_id: string+ full_name: string+ github_repo_id?: number+ } {+ return {+ installation_id: values.installation?.installation_id ?? '',+ full_name: entry.full_name,+ github_repo_id: entry.github_repo_id ?? undefined,+ }+ }++ return {+ selectInstallation: () => actions.loadOverview(),+ setSearch: async (_, breakpoint) => {+ // Typing in the filter fires one request per pause, not per key.+ await breakpoint(300)+ actions.loadOverview()+ },+ setView: () => actions.loadOverview(),+ setPage: () => 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) {+ actions.setPage(values.pageCount - 1)+ }+ },+ // A first include creates a claim, and the rule or a list change can change every result.+ loadProjectSettingsSuccess: () => actions.loadOverview(),+ updateProjectSettingsSuccess: () => actions.loadOverview(),+ addProjectPersonSuccess: () => actions.loadOverview(),+ removeProjectPersonSuccess: () => actions.loadOverview(),+ includeRepository: async ({ entry }) => {+ const saved = await writeRepository(+ entry,+ async () => {+ const response = await reviewHogRepositoriesCreate(currentProjectId(), {+ ...repositoryRef(entry),+ selected: true,+ })+ if (response.taken_from_project) {+ lemonToast.info(`${entry.full_name} is now reviewed here instead of in the other project.`)+ }+ },+ 'Could not include the repository. Try again.'+ )+ if (saved) {+ // pinned: analytics event names in this file feed the Code review usage dashboards+ posthog.capture('review hog repository included', { taken: entry.owner === 'other_project' })+ actions.loadProjectSettings()+ }+ },+ removeFromProject: async ({ entry }) => {+ const saved = await writeRepository(+ entry,+ async () => {+ await reviewHogRepositoriesCreate(currentProjectId(), {+ ...repositoryRef(entry),+ selected: false,+ })+ },+ 'Could not remove the repository. Try again.'+ )+ if (saved) {+ posthog.capture('review hog repository removed')+ }+ },+ 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) : []+ 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,+ })+ const repositoryId = response.repository?.id+ if (repositoryId && kind) {+ for (const person of people) {+ await reviewHogRepositoriesPeopleCreate(currentProjectId(), repositoryId, {+ user_id: person.user.id,+ kind,+ })+ }+ }+ },+ 'Could not add the exception. Try again.'+ )+ if (saved) {+ posthog.capture('review hog repository exception added', { flash_for: flashFor })+ }+ },+ clearException: async ({ entry }) => {+ const saved = await writeRepository(+ entry,+ async () => {+ await reviewHogRepositoriesCreate(currentProjectId(), {+ ...repositoryRef(entry),+ flash_for: null,+ })+ },+ 'Could not clear the exception. Try again.'+ )+ if (saved) {+ posthog.capture('review hog repository exception cleared')+ }+ },+ setExceptionFlashFor: async ({ entry, flashFor }) => {+ const saved = await writeRepository(+ entry,+ async () => {+ await reviewHogRepositoriesCreate(currentProjectId(), {+ ...repositoryRef(entry),+ flash_for: flashFor,+ })+ },+ 'Could not save the exception. Try again.'+ )+ if (saved) {+ posthog.capture('review hog repository exception changed', { flash_for: flashFor })+ }+ },+ addExceptionPerson: async ({ entry, userId, kind }) => {+ const repositoryId = entry.repository_id+ if (!repositoryId) {+ return+ }+ const saved = await writeRepository(+ entry,+ async () => {+ await reviewHogRepositoriesPeopleCreate(currentProjectId(), repositoryId, {+ user_id: userId,+ kind,+ })+ },+ 'Could not add the person. Try again.'+ )+ if (saved) {+ posthog.capture('review hog repository person added', { kind })+ }+ },+ removeExceptionPerson: async ({ entry, person }) => {+ const repositoryId = entry.repository_id+ if (!repositoryId) {+ return+ }+ const saved = await writeRepository(+ entry,+ async () => {+ await reviewHogRepositoriesPeopleDestroy(currentProjectId(), repositoryId, person.id)+ },+ 'Could not remove the person. Try again.'+ )+ if (saved) {+ posthog.capture('review hog repository person removed', { kind: person.kind })+ }+ },+ setMyChoice: async ({ entry, value }) => {+ const choiceId = entry.my_choice_id+ if (value === 'follow') {+ // Following means no stored choice. Without one there is nothing to write.+ if (!choiceId) {+ return+ }+ const cleared = await writeRepository(+ entry,+ () => reviewHogRepositoryChoicesDestroy(currentProjectId(), choiceId),+ 'Could not clear your choice. Try again.'+ )+ if (cleared) {+ posthog.capture('review hog repository choice cleared')+ }+ return+ }+ const saved = await writeRepository(+ entry,+ async () => {+ await reviewHogRepositoryChoicesCreate(currentProjectId(), {+ ...repositoryRef(entry),+ mode: value,+ })+ },+ 'Could not save your choice. Try again.'+ )+ if (saved) {+ posthog.capture('review hog repository choice set', { mode: value })+ }+ },+ setMyDefault: ({ mode }) => {+ actions.updateSettings({ default_review_mode: mode })+ },+ updateSettingsSuccess: ({ payload }) => {+ // The default decides the result in every repository without an own choice.+ if (payload && 'default_review_mode' in payload) {+ posthog.capture('review hog default review mode changed', { mode: payload.default_review_mode })+ actions.loadOverview()+ }+ },+ }+ }),++ afterMount(({ actions, values }) => {+ if (values.projectSettings !== null) {+ actions.loadOverview()+ }+ }),+])diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.tsindex 20d7d9589e51..82fb8f42a96f 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts@@ -105,6 +105,46 @@ describe('reviewHogSettingsLogic', () => {expect(router.values.searchParams.reviews_scope).toBeUndefined()})+ it('following the project default writes the project value, so the server drops the own value', async () => {+ const patches: Record<string, unknown>[] = []+ useMocks({+ get: {+ '/api/projects/:team_id/review_hog/settings/': () => [+ 200,+ {+ urgency_threshold: 'must_fix',+ sources: { urgency_threshold: 'user' },+ project_defaults: { urgency_threshold: 'should_fix', celebrate_clean_reviews: true },+ },+ ],+ },+ patch: {+ '/api/projects/:team_id/review_hog/settings/': async ({ request }) => {+ const body = (await request.json()) as Record<string, unknown>+ patches.push(body)+ return [+ 200,+ {+ urgency_threshold: 'should_fix',+ sources: { urgency_threshold: 'project' },+ project_defaults: { urgency_threshold: 'should_fix', celebrate_clean_reviews: true },+ },+ ]+ },+ },+ })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSettingsSuccess'])++ await expectLogic(logic, () => logic.actions.followProjectDefault('urgency_threshold')).toDispatchActions([+ 'updateSettings',+ 'updateSettingsSuccess',+ ])++ expect(patches).toEqual([{ urgency_threshold: 'should_fix' }])+ expect(logic.values.settings?.sources.urgency_threshold).toBe('project')+ })+it('a started review clears the input, reloads the list, and resets the in-flight flag', async () => {logic.mount()// Consume the mount-time auto-default so its loadRecentReviews can't satisfy the assertion below.diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.tsindex be940e6fc892..88f615dba12a 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts@@ -9,6 +9,8 @@ import type { SkillPickerGroup } from 'lib/components/SkillPicker/SkillPicker'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'+import { usersGithubLoginRetrieve } from '~/generated/core/api'+import { OriginProduct } from 'products/posthog_ai/frontend/types/taskTypes'import {reviewHogBlindSpotsList,@@ -53,6 +55,9 @@ export type ReviewDrawerTab = 'published' | 'below_threshold' | 'dismissed' | 'cexport type CodeReviewTab = 'activity' | 'settings'+/** The personal preferences that fall back to a project default when the user has no own value. */+export type ProjectDefaultKey = 'urgency_threshold' | 'celebrate_clean_reviews'+export const REVIEW_PRIORITY_RANK: Record<ReviewIssuePriorityEnumApi, number> = {consider: 0,should_fix: 1,@@ -273,13 +278,17 @@ export interface reviewHogSettingsLogicValues {savingSkillNames: string[]settings: ReviewUserSettingsApi | nullsettingsLoading: boolean+ showReviewAuthor: (review: ReviewRecentReviewApi) => booleanskillDrawerOpen: booleantriggerPrUrl: string+ triggerUrlHasFullReview: booleantriggerUrlResolving: booleantriggeringReview: booleanvalidators: ReviewValidatorConfigApi[] | nullvalidatorsLoading: booleanviewedSkill: ViewedSkill | null+ viewerGithubLogin: string | null+ viewerGithubLoginLoading: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -308,6 +317,9 @@ export interface reviewHogSettingsLogicActions {closeSkillDrawer: () => {value: true}+ followProjectDefault: (key: ProjectDefaultKey) => {+ key: ProjectDefaultKey+ }loadAdoptableSkills: (_?: any) => anyloadAdoptableSkillsFailure: (error: string,@@ -446,6 +458,21 @@ export interface reviewHogSettingsLogicActions {validators: ReviewValidatorConfigApi[]payload?: any}+ loadViewerGithubLogin: () => any+ loadViewerGithubLoginFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadViewerGithubLoginSuccess: (+ viewerGithubLogin: string | null,+ payload?: any+ ) => {+ viewerGithubLogin: string | null+ payload?: any+ }markInitialLoadFailed: () => {value: true}@@ -592,7 +619,12 @@ export interface reviewHogSettingsLogicMeta {reviewDetail: ReviewDetailApi | null,settings: ReviewUserSettingsApi | null) => ReviewFindingsSplit | null+ triggerUrlHasFullReview: (triggerPrUrl: string, recentReviews: ReviewRecentReviewApi[] | null) => booleantriggerUrlResolving: (triggerPrUrl: string, recentReviews: ReviewRecentReviewApi[] | null) => boolean+ showReviewAuthor: (+ reviewsScope: ReviewHogReviewsListScope,+ viewerGithubLogin: string | null+ ) => (review: ReviewRecentReviewApi) => booleanperspectiveScoreboard: (reviewDetail: ReviewDetailApi | null) => PerspectiveScore[] | null}}@@ -658,6 +690,9 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([// dropped before it POSTs, mirroring the trigger flow's guard.submitAdoptSkillStarted: true,submitAdoptSkillFinished: true,+ // Drops the user's own value, so the project default applies again. The API never stores a+ // value equal to the inherited one, so writing the project default clears the key.+ followProjectDefault: (key: ProjectDefaultKey) => ({ key }),setTriggerPrUrl: (prUrl: string) => ({ prUrl }),// Starts a run on the pasted PR URL: a review (which resolves comments per the user's// setting), a review without resolving, a resolve-only run, or a flash review — the split@@ -767,6 +802,21 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([},},],+ // The viewer's linked GitHub login. Under "Mine", it tells the viewer's own pull requests+ // apart from teammates' pull requests that the viewer reviewed.+ viewerGithubLogin: [+ null as string | null,+ {+ loadViewerGithubLogin: async () => {+ try {+ return (await usersGithubLoginRetrieve('@me'))?.github_login ?? null+ } catch {+ // Without a login every author shows, which is the safe fallback.+ return null+ }+ },+ },+ ],perspectiveStats: [null as ReviewPerspectiveStatsApi | null,{@@ -1164,6 +1214,20 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([}},],+ // Flash does not run on a pull request after a Full review was published there. Only PRs the+ // list shows are known here; the trigger endpoint refuses the others with the same reason.+ triggerUrlHasFullReview: [+ (s) => [s.triggerPrUrl, s.recentReviews],+ (triggerPrUrl: string, recentReviews: ReviewRecentReviewApi[] | null): boolean => {+ const target = parsePrPath(triggerPrUrl)+ return (+ !!target &&+ (recentReviews ?? []).some(+ (review) => review.full_review_published && parsePrPath(review.github_url) === target+ )+ )+ },+ ],// Mirrors the server-side busy-guard for PRs the list already shows, so the trigger button// explains the refusal up front instead of surfacing it as a submit error.triggerUrlResolving: [@@ -1180,6 +1244,16 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([)},],+ // On Everyone, whose PR it is matters at a glance. On Mine, the author shows only when it is+ // not the viewer, which happens for reviews the viewer started on a teammate's pull request.+ showReviewAuthor: [+ (s) => [s.reviewsScope, s.viewerGithubLogin],+ (scope: ReviewHogReviewsListScope, viewerGithubLogin: string | null) =>+ (review: ReviewRecentReviewApi): boolean =>+ !!review.pr_author &&+ (scope === ReviewHogReviewsListScope.Everyone ||+ review.pr_author.toLowerCase() !== viewerGithubLogin?.toLowerCase()),+ ],perspectiveScoreboard: [(s) => [s.reviewDetail],(reviewDetail: ReviewDetailApi | null): PerspectiveScore[] | null => {@@ -1281,6 +1355,7 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([showFewerReviews: () => actions.loadRecentReviews(),loadAll: () => {actions.loadSettings()+ actions.loadViewerGithubLogin()actions.loadPerspectives()actions.loadBlindSpots()actions.loadValidators()@@ -1288,6 +1363,13 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([actions.loadRecentReviews()actions.loadPerspectiveStats()},+ followProjectDefault: ({ key }) => {+ const projectDefaults = values.settings?.project_defaults+ if (!projectDefaults) {+ return+ }+ actions.updateSettings({ [key]: projectDefaults[key] })+ },updateSettingsFailure: () => {// The global loaders toast already surfaced the error; just reconcile the optimistic state.actions.loadSettings()diff --git a/products/review_hog/frontend/settings/FullReviewSettingsSection.tsx b/products/review_hog/frontend/settings/FullReviewSettingsSection.tsxnew file mode 100644index 000000000000..d27e88cdfdd4--- /dev/null+++ b/products/review_hog/frontend/settings/FullReviewSettingsSection.tsx@@ -0,0 +1,174 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonSelect, LemonSwitch } from '@posthog/lemon-ui'++import type { UrgencyThresholdEnumApi } from 'products/review_hog/frontend/generated/api.schemas'+import { reviewHogProjectSettingsLogic } from 'products/review_hog/frontend/repositories/reviewHogProjectSettingsLogic'+import { YouMark } from 'products/review_hog/frontend/repositories/YouMark'+import { reviewHogSettingsLogic } from 'products/review_hog/frontend/reviewHogSettingsLogic'++import { SettingRow } from './SettingRow'+import { SettingsTable } from './SettingsTable'++const THRESHOLD_OPTIONS: { value: UrgencyThresholdEnumApi; label: string }[] = [+ { value: 'consider', label: 'Consider (all)' },+ { value: 'should_fix', label: 'Should fix' },+ { value: 'must_fix', label: 'Must fix' },+]++type OnOff = 'on' | 'off'++function toOnOff(value: boolean): OnOff {+ return value ? 'on' : 'off'+}++const ON_OFF_OPTIONS: { value: OnOff; label: string }[] = [+ { value: 'on', label: 'On' },+ { value: 'off', label: 'Off' },+]++/**+ * "Mine" offers the project value as a follow option plus every other value. The project value+ * shows twice only while an own value equals it: one saved before the project value changed.+ * Picking "(project)" then clears it.+ */+function mineOptions<T extends string>(+ options: { value: T; label: string }[],+ projectValue: T,+ ownValue: T | undefined+): { value: T | 'project'; label: string }[] {+ const projectLabel = options.find((option) => option.value === projectValue)?.label ?? projectValue+ return [+ { value: 'project', label: `${projectLabel} (project)` },+ ...options.filter((option) => option.value !== projectValue || option.value === ownValue),+ ]+}++export function FullReviewSettingsSection({ onEditSkills }: { onEditSkills: () => void }): JSX.Element {+ const { settings, settingsLoading } = useValues(reviewHogSettingsLogic)+ const { updateSettings, followProjectDefault } = useActions(reviewHogSettingsLogic)+ const { projectSettings, editDisabledReason } = useValues(reviewHogProjectSettingsLogic)+ const { updateProjectSettings } = useActions(reviewHogProjectSettingsLogic)++ const mineDisabledReason = settings === null ? 'Loading…' : settingsLoading ? 'Saving…' : undefined+ // The project settings answer first after an admin edit; the personal settings reload after it.+ const projectThreshold =+ projectSettings?.urgency_threshold ?? settings?.project_defaults.urgency_threshold ?? 'consider'+ const projectCelebrate = toOnOff(+ projectSettings?.celebrate_clean_reviews ?? settings?.project_defaults.celebrate_clean_reviews ?? true+ )+ const ownThreshold = settings?.sources.urgency_threshold === 'user' ? settings.urgency_threshold : undefined+ const ownCelebrate =+ settings?.sources.celebrate_clean_reviews === 'user'+ ? toOnOff(settings.celebrate_clean_reviews ?? false)+ : undefined++ return (+ <SettingsTable+ title="Full review settings"+ description="Full reviews use these. Flash reads none of them. A review someone else starts on your PR uses their settings, but only your own Resolve choice can push to your branch."+ >+ <SettingRow+ title="Resolve comments on my pull requests"+ description="Applies on your PRs. After a Full review, ReviewHog pushes fix commits to your branch. Only your own opt-in counts, whoever starts the review. Never commits while the pull request is in the merge queue or has another pull request stacked on it. Without a PostHog account behind a PR, nothing is pushed."+ project={<span className="text-xs text-secondary">Personal only. Default: off</span>}+ mine={+ <>+ <YouMark shown={settings?.resolve_comments ?? false} />+ <LemonSwitch+ aria-label="Resolve comments on my pull requests"+ checked={settings?.resolve_comments ?? false}+ onChange={(checked) => updateSettings({ resolve_comments: checked })}+ disabledReason={mineDisabledReason}+ data-attr="review-hog-resolve-comments"+ />+ </>+ }+ />+ <SettingRow+ title="Post findings at or above"+ description="Applies to Full reviews you start. Lower findings stay in the report on the PostHog side."+ project={+ <LemonSelect<UrgencyThresholdEnumApi>+ size="small"+ aria-label="Project: Post findings at or above"+ value={projectThreshold}+ options={THRESHOLD_OPTIONS}+ onChange={(value) => updateProjectSettings({ urgency_threshold: value })}+ disabledReason={editDisabledReason}+ data-attr="review-hog-project-urgency-threshold"+ />+ }+ mine={+ <>+ <YouMark shown={ownThreshold !== undefined} />+ <LemonSelect<UrgencyThresholdEnumApi | 'project'>+ size="small"+ aria-label="Mine: Post findings at or above"+ value={ownThreshold ?? 'project'}+ options={mineOptions(THRESHOLD_OPTIONS, projectThreshold, ownThreshold)}+ onChange={(value) =>+ value === 'project'+ ? followProjectDefault('urgency_threshold')+ : updateSettings({ urgency_threshold: value })+ }+ disabledReason={mineDisabledReason}+ data-attr="review-hog-urgency-threshold"+ />+ </>+ }+ />+ <SettingRow+ title="Celebrate clean reviews"+ description="Applies to Full reviews you start. A clean Full review gets a small celebration in the status comment."+ project={+ <LemonSelect<OnOff>+ size="small"+ aria-label="Project: Celebrate clean reviews"+ value={projectCelebrate}+ options={ON_OFF_OPTIONS}+ onChange={(value) => updateProjectSettings({ celebrate_clean_reviews: value === 'on' })}+ disabledReason={editDisabledReason}+ data-attr="review-hog-project-celebrate-clean-reviews"+ />+ }+ mine={+ <>+ <YouMark shown={ownCelebrate !== undefined} />+ <LemonSelect<OnOff | 'project'>+ size="small"+ aria-label="Mine: Celebrate clean reviews"+ value={ownCelebrate ?? 'project'}+ options={mineOptions(ON_OFF_OPTIONS, projectCelebrate, ownCelebrate)}+ onChange={(value) =>+ value === 'project'+ ? followProjectDefault('celebrate_clean_reviews')+ : updateSettings({ celebrate_clean_reviews: value === 'on' })+ }+ disabledReason={mineDisabledReason}+ data-attr="review-hog-celebrate-clean-reviews"+ />+ </>+ }+ />+ <SettingRow+ title="Perspectives, blind spots, validation and resolution criteria"+ description="Applies to Full reviews you start. Resolution criteria also pick how fixes work: default, big gaps only, or small fixes only."+ project={<span className="text-xs text-secondary">Skills shared in this project</span>}+ mine={+ <>+ <YouMark shown={false} />+ <LemonButton+ size="small"+ type="secondary"+ onClick={onEditSkills}+ data-attr="review-hog-edit-skills"+ >+ Edit my skills+ </LemonButton>+ </>+ }+ />+ </SettingsTable>+ )+}diff --git a/products/review_hog/frontend/settings/InboxSection.tsx b/products/review_hog/frontend/settings/InboxSection.tsxnew file mode 100644index 000000000000..5256a5d7dd0a--- /dev/null+++ b/products/review_hog/frontend/settings/InboxSection.tsx@@ -0,0 +1,82 @@+import { useActions, useValues } from 'kea'++import { LemonSwitch } from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { YouMark } from 'products/review_hog/frontend/repositories/YouMark'+import { reviewHogSettingsLogic } from 'products/review_hog/frontend/reviewHogSettingsLogic'++import { SettingRow } from './SettingRow'+import { SettingsTable } from './SettingsTable'++/**+ * Inbox reviews are internal for now. A switch that is on stays visible anywhere, so the user can+ * still turn it off.+ */+export function InboxSection(): JSX.Element | null {+ const { settings, settingsLoading } = useValues(reviewHogSettingsLogic)+ const { updateSettings } = useActions(reviewHogSettingsLogic)++ const { featureFlags } = useValues(featureFlagLogic)+ const internal = !!featureFlags[FEATURE_FLAGS.REVIEW_HOG_INTERNAL]+ const showInbox = internal || (settings?.review_inbox_prs ?? false)+ const showStamphog = internal || (settings?.stamphog_review_inbox_prs ?? false)+ if (!showInbox && !showStamphog) {+ return null+ }+ const disabledReason = settings === null ? 'Loading…' : settingsLoading ? 'Saving…' : undefined++ return (+ <SettingsTable+ title="Inbox"+ description="Pull requests the PostHog agent opens for Inbox reports. The PostHog app authors them, so the report's assigned reviewer counts as their owner."+ >+ {showInbox && (+ <SettingRow+ title="Review PRs the agent opens for Inbox reports assigned to me"+ description="Full review today. Moves to Flash once Flash is stable."+ project={<span className="text-xs text-secondary">Default: off</span>}+ mine={+ <>+ <YouMark shown={settings?.review_inbox_prs ?? false} />+ <LemonSwitch+ aria-label="Review PRs the agent opens for Inbox reports assigned to me"+ checked={settings?.review_inbox_prs ?? false}+ onChange={(checked) => updateSettings({ review_inbox_prs: checked })}+ disabledReason={disabledReason}+ data-attr="review-hog-review-inbox-prs"+ />+ </>+ }+ />+ )}+ {showStamphog && (+ <SettingRow+ title="Let Stamphog review my Inbox PRs"+ description="Stamphog reviews the same pull requests and approves them when they pass."+ project={<span className="text-xs text-secondary">Default: off</span>}+ mine={+ <>+ <YouMark shown={settings?.stamphog_review_inbox_prs ?? false} />+ <LemonSwitch+ aria-label="Let Stamphog review my Inbox PRs"+ checked={settings?.stamphog_review_inbox_prs ?? false}+ onChange={(checked) => updateSettings({ stamphog_review_inbox_prs: checked })}+ disabledReason={+ // A switch that is already on stays usable while disconnected, so+ // turning it off never requires connecting Stamphog first.+ settings && !settings.stamphog_connected && !settings.stamphog_review_inbox_prs+ ? 'Connect a repository to Stamphog first. Stamphog is not set up for this project yet.'+ : disabledReason+ }+ data-attr="review-hog-stamphog-review-inbox-prs"+ />+ </>+ }+ />+ )}+ </SettingsTable>+ )+}diff --git a/products/review_hog/frontend/settings/SettingRow.tsx b/products/review_hog/frontend/settings/SettingRow.tsxnew file mode 100644index 000000000000..9b258c0f295a--- /dev/null+++ b/products/review_hog/frontend/settings/SettingRow.tsx@@ -0,0 +1,32 @@+/**+ * One row of a settings table: the setting, the project column, and the viewer's own column. On a+ * narrow container the columns stack and each one gets its label back.+ */+export function SettingRow({+ title,+ description,+ project,+ mine,+}: {+ title: string+ description: string+ project: JSX.Element+ mine: JSX.Element+}): JSX.Element {+ return (+ <div className="grid grid-cols-1 items-center gap-2 border-t border-primary px-4 py-3 @min-[48rem]:grid-cols-[minmax(0,1fr)_minmax(0,14rem)_minmax(0,16rem)] @min-[48rem]:gap-3">+ <div className="flex min-w-0 flex-col gap-0.5">+ <span className="text-sm font-semibold">{title}</span>+ <span className="text-xs text-secondary">{description}</span>+ </div>+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <span className="text-xs text-secondary @min-[48rem]:hidden">Project:</span>+ {project}+ </div>+ <div className="flex min-w-0 flex-wrap items-center gap-1">+ <span className="text-xs text-secondary @min-[48rem]:hidden">Mine:</span>+ {mine}+ </div>+ </div>+ )+}diff --git a/products/review_hog/frontend/settings/SettingsTable.tsx b/products/review_hog/frontend/settings/SettingsTable.tsxnew file mode 100644index 000000000000..19ac1895248b--- /dev/null+++ b/products/review_hog/frontend/settings/SettingsTable.tsx@@ -0,0 +1,25 @@+/** A titled table of settings rows with the Setting / Project / Mine column header. */+export function SettingsTable({+ title,+ description,+ children,+}: {+ title: string+ description: string+ children: React.ReactNode+}): JSX.Element {+ return (+ <section className="@container overflow-hidden rounded border border-primary bg-surface-primary">+ <header className="flex flex-col gap-0.5 px-4 py-3">+ <h3 className="m-0 text-base font-semibold">{title}</h3>+ <p className="m-0 text-xs text-secondary">{description}</p>+ </header>+ <div className="hidden grid-cols-[minmax(0,1fr)_minmax(0,14rem)_minmax(0,16rem)] gap-3 border-t border-primary px-4 py-1.5 text-xxs font-semibold uppercase tracking-wide text-secondary @min-[48rem]:grid">+ <span>Setting</span>+ <span>Project</span>+ <span>Mine</span>+ </div>+ {children}+ </section>+ )+}diff --git a/products/review_hog/package.json b/products/review_hog/package.jsonindex d5bd9abaa07c..2ef012192f39 100644--- a/products/review_hog/package.json+++ b/products/review_hog/package.json@@ -6,7 +6,8 @@"dependencies": {"kea": "catalog:","kea-loaders": "catalog:",- "kea-router": "catalog:"+ "kea-router": "catalog:",+ "posthog-js": "catalog:"},"devDependencies": {"kea-test-utils": "catalog:"diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5a6f4410d3bf..888f58e2d666 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -95147,6 +95147,8 @@ export namespace Schemas {last_run_at: string | null;/** Whether a review has been published back to GitHub. */published: boolean;+ /** Whether a Full review of this pull request has been published. No Flash review runs after one. */+ full_review_published: boolean;/** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */in_progress: boolean;/** The in-flight review turn's stage and counters; null unless a review turn is running (a resolving report carries `resolution` instead). */@@ -95370,6 +95372,8 @@ export namespace Schemas {last_run_at: string | null;/** Whether a review has been published back to GitHub. */published: boolean;+ /** Whether a Full review of this pull request has been published. No Flash review runs after one. */+ full_review_published: boolean;/** Whether a run is on this report right now: a review turn or a resolution run (activity within the last 30 minutes). */in_progress: boolean;/** The in-flight review turn's stage and counters; null unless a review turn is running (a resolving report carries `resolution` instead). */@@ -95559,6 +95563,8 @@ export namespace Schemas {my_choice_id: string | null;/** What the requesting user's own pull requests get here, and the rule that decided it. */my_result: AutomaticReviewDecision;+ /** What the requesting user's own pull requests would get here without their choice for this repository. Equals my_result when there is no choice. */+ inherited_result: AutomaticReviewDecision;}export interface ReviewRepositoryOverview {