Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(review_hog): add for-you/entire-project scope to recent reviews (#71059)

Alex Lebedevb66cdf239722
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 45ef2d2612de..d3ee7c8584d8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -507,7 +507,7 @@ importers:
version: 5.3.0
jest-image-snapshot:
specifier: ^6.4.0
mockdate:
specifier: ^3.0.5
version: 3.0.5
@@ -1943,7 +1943,7 @@ importers:
version: 3.6.0
jest-image-snapshot:
specifier: ^6.4.0
storybook:
specifier: 'catalog:'
@@ -4185,6 +4185,10 @@ importers:
react:
specifier: 18.3.1
version: 18.3.1
+ devDependencies:
+ kea-test-utils:
+ specifier: 'catalog:'
products/session_replay:
dependencies:
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.md
index 0a41693c369a..2e85ed9a760f 100644
--- a/products/review_hog/ARCHITECTURE.md
+++ b/products/review_hog/ARCHITECTURE.md
@@ -654,6 +654,30 @@ payload into Python) from the turn's working-state artefacts, preferring the sna
must not masquerade as another skill card. Hidden until data exists. In-progress row label format:
"Step k/4 · <stage> · NN%" (stages fetching/chunking/reviewing/validating numbered 1-4).
+#### ✅ BUILT 2026-07-15 — "For you / Entire project" scope on the recent-reviews block
+
+Mirrors the Inbox scope switch: the block can now list every review on the project, not just the requesting user's.
+
+- **`GET review_hog/reviews/?scope=mine|everyone`** (`ReviewsListParamsSerializer`, default `mine`):
+ `everyone` drops the `acting_user` filter; everything else (running-first ordering, 5-row cap, DB-side enrichment) is unchanged.
+ Bad values 400 via `is_valid(raise_exception=True)`.
+ The `scope` ChoiceField's enum stays inline in the OpenAPI query parameter, so no `ScopeEnum` component collision (verified with `--fail-on-warn`).
+- **`retrieve` is now project-wide** (queries with `SCOPE_EVERYONE` internally) so any listed review opens;
+ another team's report id still 404s (`for_team`), garbage ids still 404.
+ `perspective_stats` stays personal — it describes _your_ reviewers' effectiveness.
+- **Index:** `(team, -last_run_at)` `reviewhog_rpt_team_recent_idx` (migration 0016, `SafeAddIndexConcurrently`) serves the everyone-scope completed slice;
+ the mine slice keeps the 0011 `(team, acting_user, -last_run_at)` index.
+- **UI/logic:** `LemonSegmentedButton` "For you / Entire project" on the section header;
+ `reviewsScope` + `hasUserChosenReviewsScope` persisted reducers in `reviewHogSettingsLogic`;
+ **auto-default** — an empty first mine-scope load flips to Entire project via `applyDefaultReviewsScope`, which is _not_ marked as a user choice so a later explicit pick wins (both directions jest-tested);
+ an explicit pick is mirrored to `?reviews_scope=` — the auto-default never writes the URL, since hydrating from a link counts as an explicit choice and would make the fallback permanent;
+ the loader takes a `breakpoint()` after the fetch so a scope flip mid-flight drops the stale response;
+ rows show `by <pr_author>` in everyone scope only;
+ an empty mine-scope shows an empty state instead of hiding the section (the toggle must stay reachable) — loaded-and-empty hides the section only in everyone scope.
+- Tests: everyone-scope list (teammate rows in, cross-team rows out, bad scope 400s as the params-serializer wiring guard);
+ retrieve contract flip (teammate's review 200, other team's 404);
+ 2 jest tests for the auto-default rule.
+
#### ✅ BUILT 2026-07-02 — authoring guide moved to a canonical skill (`review-hog-authoring`)
The "Create your own …" frontend prompts were fat, self-describing instruction sets — an
diff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.py
index c777db5d812a..baba1b90f802 100644
--- a/products/review_hog/backend/api/reviews.py
+++ b/products/review_hog/backend/api/reviews.py
@@ -50,6 +50,18 @@ _PRIORITY_CHOICES = [priority.value for priority in IssuePriority]
# Display order for the detail view: most urgent first.
_PRIORITY_DISPLAY_RANK = {IssuePriority.MUST_FIX: 0, IssuePriority.SHOULD_FIX: 1, IssuePriority.CONSIDER: 2}
+SCOPE_MINE = "mine"
+SCOPE_EVERYONE = "everyone"
+
+
+class ReviewsListParamsSerializer(serializers.Serializer):
+ scope = serializers.ChoiceField(
+ choices=[SCOPE_MINE, SCOPE_EVERYONE],
+ default=SCOPE_MINE,
+ help_text="Whose reviews to list: `mine` for reviews of the requesting user's pull requests "
+ "(the default), `everyone` for every review on this project.",
+ )
+
class ReviewProgressSerializer(serializers.Serializer):
review_stage = serializers.ChoiceField(
@@ -341,12 +353,14 @@ def _review_payload(
class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
- """The requesting user's most recent ReviewHog reviews (reports where they are the acting user).
+ """Recent ReviewHog reviews on this project.
Read-only meta for the Code review tab's "recent reviews" block: what was reviewed, how many
valid findings at each effective priority, the reviewed PR's facts, and the pipeline shape of
- the latest turn. `retrieve` adds the findings themselves (valid + dismissed) and the published
- review body.
+ the latest turn. `list` covers the requesting user's reviews (reports where they are the acting
+ user) by default, or the whole project's via `scope=everyone` — mirroring the inbox's
+ "For you / Entire project" switch. `retrieve` adds the findings themselves (valid + dismissed)
+ and the published review body; it is project-wide so any listed review can be opened.
"""
scope_object = "INTERNAL"
@@ -355,23 +369,30 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
serializer_class = ReviewRecentReviewSerializer
pagination_class = None
- def _reports(self, request: Request) -> tuple[int, QuerySet[ReviewReport]]:
+ def _reports(self, request: Request, scope: str = SCOPE_MINE) -> tuple[int, QuerySet[ReviewReport]]:
team_id = resolve_effective_team_id(self.team_id)
- return team_id, ReviewReport.objects.for_team(team_id, canonical=True).filter(acting_user_id=request.user.id)
+ queryset = ReviewReport.objects.for_team(team_id, canonical=True)
+ if scope == SCOPE_MINE:
+ queryset = queryset.filter(acting_user_id=request.user.id)
+ return team_id, queryset
@extend_schema(
+ parameters=[ReviewsListParamsSerializer],
responses={
200: OpenApiResponse(
response=ReviewRecentReviewSerializer(many=True),
- description="The user's reviews: in-progress runs first, then completed newest first.",
+ description="The scoped reviews: in-progress runs first, then completed newest first.",
),
},
- summary="List the user's recent reviews",
- description="The requesting user's ReviewHog reviews on this project: actively running reviews "
- "first (with the in-flight turn's stage), then the most recent completed ones (at most 5 rows).",
+ summary="List recent reviews",
+ description="Recent ReviewHog reviews on this project: actively running reviews first (with the "
+ "in-flight turn's stage), then the most recent completed ones (at most 5 rows). By default only "
+ "the requesting user's reviews; `scope=everyone` lists every review on the project.",
)
def list(self, request: Request, **kwargs) -> Response:
- team_id, queryset = self._reports(request)
+ params = ReviewsListParamsSerializer(data=request.query_params)
+ params.is_valid(raise_exception=True)
+ team_id, queryset = self._reports(request, scope=params.validated_data["scope"])
completed = list(queryset.filter(last_run_at__isnull=False).order_by("-last_run_at")[:RECENT_REVIEWS_LIMIT])
# First-turn runs have no completed turn yet; they only surface while visibly running.
running_first_turn = list(
@@ -471,19 +492,20 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet
response=ReviewDetailSerializer,
description="The review's detail: findings (valid and dismissed) and the published body.",
),
- 404: OpenApiResponse(description="No such review of the requesting user's pull requests."),
+ 404: OpenApiResponse(description="No such review on this project."),
},
summary="Retrieve one review's detail",
- description="One completed ReviewHog review of the requesting user's pull requests, with the latest "
- "turn's validated findings, the findings the validator dismissed (and why), and the review body "
- "published to GitHub.",
+ description="One completed ReviewHog review on this project, with the latest turn's validated "
+ "findings, the findings the validator dismissed (and why), and the review body published to "
+ "GitHub. Project-wide, so reviews listed under `scope=everyone` can be opened too.",
)
def retrieve(self, request: Request, pk: str | None = None, **kwargs) -> Response:
try:
report_uuid = uuid.UUID(str(pk))
except ValueError:
raise NotFound("Review not found.")
- team_id, queryset = self._reports(request)
+ # Project-wide on purpose: the detail must open for any review the everyone-scope list shows.
+ team_id, queryset = self._reports(request, scope=SCOPE_EVERYONE)
# Detail describes a completed turn — a first run still in flight has nothing to show yet.
report = queryset.filter(id=report_uuid, last_run_at__isnull=False).first()
if report is None:
diff --git a/products/review_hog/backend/migrations/0016_reviewreport_reviewhog_rpt_team_recent_idx.py b/products/review_hog/backend/migrations/0016_reviewreport_reviewhog_rpt_team_recent_idx.py
new file mode 100644
index 000000000000..2621adb01063
--- /dev/null
+++ b/products/review_hog/backend/migrations/0016_reviewreport_reviewhog_rpt_team_recent_idx.py
@@ -0,0 +1,21 @@
+from django.db import migrations, models
+
+from posthog.migration_helpers import SafeAddIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False # Required for concurrent index creation
+
+ dependencies = [
+ ("review_hog", "0015_reviewreport_status_comment_edited_at_and_more"),
+ ]
+
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="reviewreport",
+ index=models.Index(
+ fields=["team", "-last_run_at"],
+ name="reviewhog_rpt_team_recent_idx",
+ ),
+ ),
+ ]
diff --git a/products/review_hog/backend/migrations/max_migration.txt b/products/review_hog/backend/migrations/max_migration.txt
index a4b85e7f1694..f3f94a2c44c4 100644
--- a/products/review_hog/backend/migrations/max_migration.txt
+++ b/products/review_hog/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0015_reviewreport_status_comment_edited_at_and_more
+0016_reviewreport_reviewhog_rpt_team_recent_idx
diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.py
index a0b503fcaadb..1615ac5a6e7c 100644
--- a/products/review_hog/backend/models.py
+++ b/products/review_hog/backend/models.py
@@ -92,6 +92,8 @@ class ReviewReport(UUIDModel, TeamScopedRootMixin):
models.Index(fields=["signal_report_id"], name="reviewhog_rpt_signal_rpt_idx"),
# Serves the "recent reviews" API: one user's reports, newest completed turn first.
models.Index(fields=["team", "acting_user", "-last_run_at"], name="reviewhog_rpt_recent_idx"),
+ # Same API's everyone scope: the whole project's reports, newest completed turn first.
+ models.Index(fields=["team", "-last_run_at"], name="reviewhog_rpt_team_recent_idx"),
]
diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.py
index de52ddd279cc..f7dcfcd4cbc3 100644
--- a/products/review_hog/backend/tests/test_reviews_api.py
+++ b/products/review_hog/backend/tests/test_reviews_api.py
@@ -5,7 +5,7 @@ from posthog.test.base import APIBaseTest
from django.utils import timezone
-from posthog.models import User
+from posthog.models import Team, User
from products.review_hog.backend.models import ReviewReport, ReviewReportArtefact
from products.review_hog.backend.reviewer.artefact_content import ReviewIssueFinding, ValidationVerdict
@@ -66,9 +66,18 @@ class TestRecentReviewsAPI(APIBaseTest):
super().setUp()
self.url = f"/api/projects/{self.team.id}/review_hog/reviews/"
- def _report(self, *, pr_number: int, acting_user: User | None, completed: bool = True, **kwargs) -> ReviewReport:
- return ReviewReport.objects.for_team(self.team.id).create(
- team_id=self.team.id,
+ def _report(
+ self,
+ *,
+ pr_number: int,
+ acting_user: User | None,
+ completed: bool = True,
+ team_id: int | None = None,
+ **kwargs,
+ ) -> ReviewReport:
+ team_id = team_id if team_id is not None else self.team.id
+ return ReviewReport.objects.for_team(team_id).create(
+ team_id=team_id,
repository="PostHog/posthog",
pr_number=pr_number,
pr_url=kwargs.pop("pr_url", f"https://github.com/PostHog/posthog/pull/{pr_number}"),
@@ -120,9 +129,9 @@ class TestRecentReviewsAPI(APIBaseTest):
)
def test_lists_only_my_completed_reviews(self) -> None:
- # The block is "your recent reviews": a teammate's report and an abandoned (stale, never
- # completed) run must not appear — a filter regression would leak other users' review
- # activity or show a dead run as forever in progress.
+ # The default (mine) scope is "your recent reviews": a teammate's report and an abandoned
+ # (stale, never completed) run must not appear — a filter regression would leak other users'
+ # review activity or show a dead run as forever in progress.
mine = self._report(pr_number=1, acting_user=self.user)
with freeze_time(timezone.now() - timedelta(hours=2)):
self._report(pr_number=2, acting_user=self.user, completed=False)
@@ -138,6 +147,22 @@ class TestRecentReviewsAPI(APIBaseTest):
assert rows[0]["published"] is False
assert "perspective_selection" not in rows[0] # detail-only payload — the list stays lean
+ def test_list_scope_everyone_covers_the_whole_project(self) -> None:
+ # The "Entire project" switch: everyone-scope must include teammates' reviews but never
+ # another team's (tenant isolation), and a bad scope value must 400 — proving the params
+ # serializer is actually wired into the view.
+ self._report(pr_number=1, acting_user=self.user)
+ other = User.objects.create_and_join(self.organization, "[email protected]", None)
+ self._report(pr_number=2, acting_user=other)
+ cold_team = Team.objects.create(organization=self.organization, name="cold")
+ self._report(pr_number=3, acting_user=other, team_id=cold_team.id)
+
+ res = self.client.get(self.url, {"scope": "everyone"})
+
+ assert res.status_code == 200
+ assert {r["pr_number"] for r in res.json()} == {1, 2}
+ assert self.client.get(self.url, {"scope": "nonsense"}).status_code == 400
+
def test_counts_scope_to_the_latest_run_and_fall_back_to_the_branch_url(self) -> None:
# Counts must reflect only the latest turn's VALID findings at their EFFECTIVE priority —
# stale turns, invalid findings, or ignoring the validator's override all miscount the row.
@@ -481,10 +506,14 @@ class TestRecentReviewsAPI(APIBaseTest):
{"skill_name": blind, "raised": 1, "kept": 1, "dismissed": 0},
]
- def test_retrieve_scopes_to_the_acting_user(self) -> None:
- # A teammate's report id must 404, not leak their PR's findings; garbage ids must not 500.
+ def test_retrieve_is_project_wide_but_never_cross_team(self) -> None:
+ # Opening a teammate's review from the everyone-scope list must work, but another team's
+ # report id must still 404 (tenant isolation), and garbage ids must not 500.
other = User.objects.create_and_join(self.organization, "[email protected]", None)
theirs = self._report(pr_number=9, acting_user=other)
+ cold_team = Team.objects.create(organization=self.organization, name="cold")
+ foreign = self._report(pr_number=10, acting_user=other, team_id=cold_team.id)
- assert self.client.get(f"{self.url}{theirs.id}/").status_code == 404
+ assert self.client.get(f"{self.url}{theirs.id}/").status_code == 200
+ assert self.client.get(f"{self.url}{foreign.id}/").status_code == 404
assert self.client.get(f"{self.url}not-a-uuid/").status_code == 404
diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsx
index e030b42cee93..8f5ac57fb859 100644
--- a/products/review_hog/frontend/CodeReviewScene.tsx
+++ b/products/review_hog/frontend/CodeReviewScene.tsx
@@ -16,6 +16,7 @@ import {
import {
LemonBanner,
LemonButton,
+ LemonSegmentedButton,
LemonSkeleton,
LemonSlider,
LemonSwitch,
@@ -48,6 +49,7 @@ import type {
ReviewRecentReviewApi,
UrgencyThresholdEnumApi,
} from 'products/review_hog/frontend/generated/api.schemas'
+import { ReviewHogReviewsListScope } from 'products/review_hog/frontend/generated/api.schemas'
import { ReviewDrawerTab, ReviewSkillKind, reviewHogSettingsLogic } from './reviewHogSettingsLogic'
@@ -316,6 +318,9 @@ function progressLabel(review: ReviewRecentReviewApi): 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 the Entire project scope, whose PR it is matters at a glance; on For you it's always yours.
+ const showAuthor = reviewsScope === ReviewHogReviewsListScope.Everyone && !!review.pr_author
return (
<div className="flex items-center gap-3 px-4 py-3">
<span className="flex w-6 shrink-0 justify-center">
@@ -327,6 +332,12 @@ function RunningReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.El
<span className="whitespace-nowrap font-mono text-tertiary">
{review.repository}#{review.pr_number ?? review.head_branch}
</span>
+ {showAuthor && (
+ <>
+ <span className="text-tertiary">·</span>
+ <span className="whitespace-nowrap">by {review.pr_author}</span>
+ </>
+ )}
<span className="text-tertiary">·</span>
<span className="whitespace-nowrap font-medium text-warning">{progressLabel(review)}</span>
</div>
@@ -340,10 +351,12 @@ 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 } = useValues(reviewHogSettingsLogic)
+ const { expandedReviewIds, reviewsScope } = 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 the Entire project scope, whose PR it is matters at a glance; on For you it's always yours.
+ const showAuthor = reviewsScope === ReviewHogReviewsListScope.Everyone && !!review.pr_author
// 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) {
@@ -379,6 +392,12 @@ function RecentReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.Ele
<span className="whitespace-nowrap font-mono text-tertiary">
{review.repository}#{review.pr_number ?? review.head_branch}
</span>
+ {showAuthor && (
+ <>
+ <span className="text-tertiary">·</span>
+ <span className="whitespace-nowrap">by {review.pr_author}</span>
+ </>
+ )}
<span className="text-tertiary">·</span>
<FindingCounts review={review} />
{review.last_run_at && (
@@ -463,38 +482,74 @@ function RecentReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.Ele
)
}
-/** Compact proof-of-life block under the hero — hidden entirely until the user has reviews. */
+/** Compact proof-of-life block under the hero — hidden entirely until the project has reviews. */
function RecentReviewsSection(): JSX.Element | null {
- const { recentReviews } = useValues(reviewHogSettingsLogic)
-
- // Loaded-and-empty hides the section entirely; `null` means the first load is still in flight,
- // so a skeleton holds the space instead of the page jumping when the rows land. Poll refreshes
- // keep the previous rows, so the skeleton only ever shows once.
- if (recentReviews !== null && !recentReviews.length) {
+ const { recentReviews, recentReviewsLoading, reviewsScope, hasUserChosenReviewsScope } =
+ useValues(reviewHogSettingsLogic)
+ const { setReviewsScope } = useActions(reviewHogSettingsLogic)
+ const everyone = reviewsScope === ReviewHogReviewsListScope.Everyone
+ const loadedEmpty = recentReviews !== null && recentReviews.length === 0
+
+ // Settled-and-empty on the Entire project scope means the project has no reviews at all — hide
+ // the section entirely. The scope flips before the reload lands, so an in-flight load keeps the
+ // section mounted (skeleton below) instead of yanking the toggle away mid-click. An empty
+ // For-you scope keeps the section (with an empty state) so the scope switch stays reachable.
+ if (loadedEmpty && everyone && !recentReviewsLoading) {
return null
}
+ // A stale EMPTY list must not render an empty state while a reload (scope switch, auto-default)
+ // is in flight — but previous ROWS are kept during refreshes, so the in-progress poll never
+ // flashes skeletons.
+ const emptyAwaitingReload = loadedEmpty && (recentReviewsLoading || !hasUserChosenReviewsScope)
return (
// The one section without a top hairline — it reads as a continuation of the hero.
<section className="flex flex-col gap-4">
- <SectionHeader icon={<IconPullRequest />} title="Your recent reviews">
- The latest ReviewHog runs on pull requests you authored. Expand a review for its details and findings.
- </SectionHeader>
+ <div className="flex flex-wrap items-start justify-between gap-x-4 gap-y-2">
+ <SectionHeader icon={<IconPullRequest />} title={everyone ? 'Recent reviews' : 'Your recent reviews'}>
+ {everyone
+ ? 'The latest ReviewHog runs on pull requests across this project. Expand a review for its details and findings.'
+ : 'The latest ReviewHog runs on pull requests you authored. Expand a review for its details and findings.'}
+ </SectionHeader>
+ <LemonSegmentedButton
+ size="small"
+ value={reviewsScope}
+ onChange={(value) => setReviewsScope(value)}
+ options={[
+ {
+ value: ReviewHogReviewsListScope.Mine,
+ label: 'For you',
+ tooltip: 'Only reviews of pull requests you authored',
+ },
+ {
+ value: ReviewHogReviewsListScope.Everyone,
+ label: 'Entire project',
+ tooltip: 'Every ReviewHog review on this project',
+ },
+ ]}
+ />
+ </div>
<LemonCard hoverEffect={false} className="divide-y divide-primary p-0">
- {recentReviews === null
- ? [0, 1, 2].map((i) => (
- <div key={i} className="flex items-center gap-3 px-4 py-3">
- <span className="flex w-6 shrink-0 justify-center">
- <LemonSkeleton.Circle className="size-2" />
- </span>
- <div className="flex min-w-0 flex-1 flex-col gap-1.5">
- <LemonSkeleton className="h-4 w-80 max-w-full" />
- <LemonSkeleton className="h-3 w-56 max-w-full" />
- </div>
- <LemonSkeleton className="h-8 w-24 shrink-0" />
- </div>
- ))
- : recentReviews.map((review) => <RecentReviewRow key={review.id} review={review} />)}
+ {recentReviews === null || emptyAwaitingReload ? (
+ [0, 1, 2].map((i) => (
+ <div key={i} className="flex items-center gap-3 px-4 py-3">
+ <span className="flex w-6 shrink-0 justify-center">
+ <LemonSkeleton.Circle className="size-2" />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">
+ <LemonSkeleton className="h-4 w-80 max-w-full" />
+ <LemonSkeleton className="h-3 w-56 max-w-full" />
+ </div>
+ <LemonSkeleton className="h-8 w-24 shrink-0" />
+ </div>
+ ))
+ ) : recentReviews.length ? (
+ recentReviews.map((review) => <RecentReviewRow key={review.id} review={review} />)
+ ) : (
+ <div className="px-4 py-6 text-center text-sm text-secondary">
+ No reviews of your pull requests yet. Switch to "Entire project" to see the whole team's.
+ </div>
+ )}
</LemonCard>
</section>
)
diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.ts
index 77494c64aeee..ba1abbc52d3e 100644
--- a/products/review_hog/frontend/generated/api.schemas.ts
+++ b/products/review_hog/frontend/generated/api.schemas.ts
@@ -463,3 +463,21 @@ export interface PatchedReviewValidatorConfigSelectApi {
/** Set true to make this the single validator that runs on the user's PR reviews. Only true is accepted — validators are single-active, so you switch by selecting a different one, not by deactivating the current one. */
active?: boolean
}
+
+export type ReviewHogReviewsListParams = {
+ /**
+ * Whose reviews to list: `mine` for reviews of the requesting user's pull requests (the default), `everyone` for every review on this project.
+ *
+ * * `mine` - mine
+ * * `everyone` - everyone
+ * @minLength 1
+ */
+ scope?: ReviewHogReviewsListScope
+}
+
+export type ReviewHogReviewsListScope = (typeof ReviewHogReviewsListScope)[keyof typeof ReviewHogReviewsListScope]
+
+export const ReviewHogReviewsListScope = {
+ Mine: 'mine',
+ Everyone: 'everyone',
+} as const
diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.ts
index 2386d739e5e0..454c9f32a983 100644
--- a/products/review_hog/frontend/generated/api.ts
+++ b/products/review_hog/frontend/generated/api.ts
@@ -15,6 +15,7 @@ import type {
PatchedReviewValidatorConfigSelectApi,
ReviewBlindSpotsConfigApi,
ReviewDetailApi,
+ ReviewHogReviewsListParams,
ReviewPerspectiveConfigApi,
ReviewPerspectiveStatsApi,
ReviewRecentReviewApi,
@@ -102,19 +103,32 @@ export const reviewHogPerspectivesPartialUpdate = async (
})
}
-export const getReviewHogReviewsListUrl = (projectId: string) => {
- return `/api/projects/${projectId}/review_hog/reviews/`
+export const getReviewHogReviewsListUrl = (projectId: string, params?: ReviewHogReviewsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/review_hog/reviews/?${stringifiedParams}`
+ : `/api/projects/${projectId}/review_hog/reviews/`
}
/**
- * The requesting user's ReviewHog reviews on this project: actively running reviews first (with the in-flight turn's stage), then the most recent completed ones (at most 5 rows).
- * @summary List the user's recent reviews
+ * Recent ReviewHog reviews on this project: actively running reviews first (with the in-flight turn's stage), then the most recent completed ones (at most 5 rows). By default only the requesting user's reviews; `scope=everyone` lists every review on the project.
+ * @summary List recent reviews
*/
export const reviewHogReviewsList = async (
projectId: string,
+ params?: ReviewHogReviewsListParams,
options?: RequestInit
): Promise<ReviewRecentReviewApi[]> => {
- return apiMutator<ReviewRecentReviewApi[]>(getReviewHogReviewsListUrl(projectId), {
+ return apiMutator<ReviewRecentReviewApi[]>(getReviewHogReviewsListUrl(projectId, params), {
...options,
method: 'GET',
})
@@ -125,7 +139,7 @@ export const getReviewHogReviewsRetrieveUrl = (projectId: string, id: string) =>
}
/**
- * One completed ReviewHog review of the requesting user's pull requests, with the latest turn's validated findings, the findings the validator dismissed (and why), and the review body published to GitHub.
+ * One completed ReviewHog review on this project, with the latest turn's validated findings, the findings the validator dismissed (and why), and the review body published to GitHub. Project-wide, so reviews listed under `scope=everyone` can be opened too.
* @summary Retrieve one review's detail
*/
export const reviewHogReviewsRetrieve = async (
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
new file mode 100644
index 000000000000..41bad3bbd83d
--- /dev/null
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts
@@ -0,0 +1,81 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { ReviewHogReviewsListScope } from 'products/review_hog/frontend/generated/api.schemas'
+
+import { reviewHogSettingsLogic } from './reviewHogSettingsLogic'
+
+describe('reviewHogSettingsLogic', () => {
+ let logic: ReturnType<typeof reviewHogSettingsLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ // The user has no reviews of their own; the project has one.
+ '/api/projects/:team_id/review_hog/reviews/': ({ request }) => [
+ 200,
+ new URL(request.url).searchParams.get('scope') === ReviewHogReviewsListScope.Everyone
+ ? [{ id: 'r1', in_progress: false }]
+ : [],
+ ],
+ '/api/projects/:team_id/review_hog/reviews/perspective_stats/': () => [
+ 200,
+ { report_count: 0, perspectives: [] },
+ ],
+ '/api/projects/:team_id/review_hog/settings/': () => [
+ 200,
+ { review_inbox_prs: false, review_labeled_prs: true, urgency_threshold: 'should_fix' },
+ ],
+ '/api/projects/:team_id/review_hog/perspectives/': () => [200, []],
+ '/api/projects/:team_id/review_hog/blind_spots/': () => [200, []],
+ '/api/projects/:team_id/review_hog/validators/': () => [200, []],
+ },
+ })
+ // The scope reducers persist; without this a prior test's explicit choice leaks over.
+ localStorage.clear()
+ initKeaTests()
+ logic = reviewHogSettingsLogic()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('auto-defaults to the entire project when the user has no reviews of their own', async () => {
+ logic.mount()
+
+ await expectLogic(logic)
+ .toDispatchActions(['loadRecentReviewsSuccess', 'applyDefaultReviewsScope', 'loadRecentReviewsSuccess'])
+ .toMatchValues({
+ reviewsScope: ReviewHogReviewsListScope.Everyone,
+ // The auto-default is not an explicit choice — a later real one must still win.
+ hasUserChosenReviewsScope: false,
+ })
+ expect(logic.values.recentReviews).toHaveLength(1)
+ // The auto-default must not write the URL: hydrating `?reviews_scope=` from a link marks
+ // the scope as explicitly chosen, so mirroring the fallback would make it permanent.
+ expect(router.values.searchParams.reviews_scope).toBeUndefined()
+ })
+
+ it('respects an explicit scope choice even when that scope is empty', async () => {
+ logic.mount()
+ // Consume the mount-time auto-default, so the not-dispatched window below starts after it.
+ await expectLogic(logic).toDispatchActions([
+ 'loadRecentReviewsSuccess',
+ 'applyDefaultReviewsScope',
+ 'loadRecentReviewsSuccess',
+ ])
+
+ await expectLogic(logic, () => logic.actions.setReviewsScope(ReviewHogReviewsListScope.Mine))
+ .toDispatchActions(['loadRecentReviewsSuccess'])
+ .toNotHaveDispatchedActions(['applyDefaultReviewsScope'])
+ .toMatchValues({
+ reviewsScope: ReviewHogReviewsListScope.Mine,
+ hasUserChosenReviewsScope: true,
+ recentReviews: [],
+ })
+ })
+})
diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.ts
index 3e83938f0346..4c6086033511 100644
--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts
+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts
@@ -1,6 +1,6 @@
import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { router } from 'kea-router'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import { lemonToast } from '@posthog/lemon-ui'
@@ -34,6 +34,7 @@ import type {
ReviewUserSettingsApi,
ReviewValidatorConfigApi,
} from 'products/review_hog/frontend/generated/api.schemas'
+import { ReviewHogReviewsListScope } from 'products/review_hog/frontend/generated/api.schemas'
import type { reviewHogSettingsLogicType } from './reviewHogSettingsLogicType'
@@ -138,11 +139,15 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
closeReviewDrawer: true,
setReviewDrawerTab: (tab: ReviewDrawerTab) => ({ tab }),
toggleReviewRowExpanded: (reviewId: string) => ({ reviewId }),
+ setReviewsScope: (scope: ReviewHogReviewsListScope) => ({ scope }),
+ // Auto-select a default scope (Entire project when the user has no reviews of their own)
+ // without marking it as an explicit user choice, so a later real choice still wins.
+ applyDefaultReviewsScope: (scope: ReviewHogReviewsListScope) => ({ scope }),
startSkillAuthorTask: (kind: ReviewSkillKind) => ({ kind }),
startSkillAuthorTaskFinished: true,
}),
- loaders(() => ({
+ loaders(({ values }) => ({
settings: [
null as ReviewUserSettingsApi | null,
{
@@ -176,7 +181,14 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
recentReviews: [
null as ReviewRecentReviewApi[] | null,
{
- loadRecentReviews: async () => await reviewHogReviewsList(currentProjectId()),
+ // The default param keeps the action zero-arg in the generated logic type.
+ loadRecentReviews: async (_ = null, breakpoint) => {
+ const scope = values.reviewsScope
+ const response = await reviewHogReviewsList(currentProjectId(), { scope })
+ // A scope switch mid-flight dispatched a newer load — drop this stale response.
+ breakpoint()
+ return response
+ },
},
],
reviewDetail: [
@@ -266,6 +278,26 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
state.includes(reviewId) ? state.filter((id) => id !== reviewId) : [...state, reviewId],
},
],
+ // Whose reviews the "recent reviews" block lists — mirrors the inbox's
+ // "For you / Entire project" switch.
+ reviewsScope: [
+ ReviewHogReviewsListScope.Mine as ReviewHogReviewsListScope,
+ { persist: true },
+ {
+ setReviewsScope: (_, { scope }) => scope,
+ applyDefaultReviewsScope: (_, { scope }) => scope,
+ },
+ ],
+ // Whether the user has explicitly picked a scope. Once true, the empty-list auto-default
+ // no longer fires, so a deliberate choice of "For you" is respected even with zero reviews.
+ // A shared link is an explicit choice too, so URL hydration goes through setReviewsScope.
+ hasUserChosenReviewsScope: [
+ false,
+ { persist: true },
+ {
+ setReviewsScope: () => true,
+ },
+ ],
initialLoadFailed: [
false,
{
@@ -343,7 +375,18 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
} else {
cache.disposables.dispose('inProgressPoll')
}
+ // No reviews of the user's own PRs: default to the whole project so the block isn't
+ // empty — only until the user picks a scope themselves.
+ if (
+ !values.recentReviews?.length &&
+ values.reviewsScope === ReviewHogReviewsListScope.Mine &&
+ !values.hasUserChosenReviewsScope
+ ) {
+ actions.applyDefaultReviewsScope(ReviewHogReviewsListScope.Everyone)
+ }
},
+ setReviewsScope: () => actions.loadRecentReviews(),
+ applyDefaultReviewsScope: () => actions.loadRecentReviews(),
loadAll: () => {
actions.loadSettings()
actions.loadPerspectives()
@@ -436,6 +479,34 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([
},
})),
+ // An explicit scope pick is mirrored to the URL (`?reviews_scope=everyone`) so a specific view
+ // can be shared via a link; the default scope keeps the URL clean. The auto-default deliberately
+ // does NOT write the URL: hydrating from a link marks the scope as chosen (below), so mirroring
+ // the fallback would silently upgrade it into a permanent explicit choice on reload.
+ actionToUrl(({ values }) => ({
+ setReviewsScope: (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => [
+ router.values.location.pathname,
+ {
+ ...router.values.searchParams,
+ reviews_scope: values.reviewsScope === ReviewHogReviewsListScope.Mine ? undefined : values.reviewsScope,
+ },
+ router.values.hashParams,
+ { replace: true },
+ ],
+ })),
+
+ urlToAction(({ actions, values }) => ({
+ [urls.codeReview()]: (_, searchParams) => {
+ const parsed = searchParams.reviews_scope
+ if (
+ (parsed === ReviewHogReviewsListScope.Mine || parsed === ReviewHogReviewsListScope.Everyone) &&
+ parsed !== values.reviewsScope
+ ) {
+ actions.setReviewsScope(parsed)
+ }
+ },
+ })),
+
afterMount(({ actions }) => {
actions.loadAll()
}),
diff --git a/products/review_hog/package.json b/products/review_hog/package.json
index 0ac0646f70e5..42eae7e332f6 100644
--- a/products/review_hog/package.json
+++ b/products/review_hog/package.json
@@ -8,6 +8,9 @@
"kea-loaders": "catalog:",
"kea-router": "catalog:"
},
+ "devDependencies": {
+ "kea-test-utils": "catalog:"
+ },
"peerDependencies": {
"@posthog/icons": "catalog:",
"@types/react": "*",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b7e11611f6ff..12d0572e5c66 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -75288,6 +75288,25 @@ export namespace Schemas {
offset?: number;
};
+ export type ReviewHogReviewsListParams = {
+ /**
+ * Whose reviews to list: `mine` for reviews of the requesting user's pull requests (the default), `everyone` for every review on this project.
+ *
+ * * `mine` - mine
+ * * `everyone` - everyone
+ * @minLength 1
+ */
+ scope?: ReviewHogReviewsListScope;
+ };
+
+ export type ReviewHogReviewsListScope = typeof ReviewHogReviewsListScope[keyof typeof ReviewHogReviewsListScope];
+
+
+ export const ReviewHogReviewsListScope = {
+ Mine: 'mine',
+ Everyone: 'everyone',
+ } as const;
+
export type SandboxCustomImagesListParams = {
/**
* Number of results to return per page.