: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): paginate the recent-reviews list with show more/fewer (#71436)
Alex Lebedev38db29c3b3cc
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 3c39adcc4b35..131031da21c8 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -678,6 +678,35 @@ Mirrors the Inbox scope switch: the block can now list every review on the projeretrieve contract flip (teammate's review 200, other team's 404);2 jest tests for the auto-default rule.+#### ✅ BUILT 2026-07-16 — "Show more / Show fewer" pagination on the recent-reviews list++The 5-row cap became the first page: the list grows by a page per "Show more" click and collapses back in one click, on both scopes.++- **Growing `limit`, not offset pages:** in-progress rows jump to the front and drop out between the 10s polls,+ so offset pagination would shift page boundaries under the reader.+ `GET reviews/?limit=N` (default 5, min 1, max 100 — enrichment is per-row work) caps all three merge slices;+ the response is now a **page envelope `{results, has_more}`** (`ReviewRecentReviewsPageSerializer`),+ with `has_more` computed server-side by probing `limit + 1` rows — no dead "Show more" click when the count is exactly the limit.+- **`_PageEnvelopeSchema` (AutoSchema subclass):** drf-spectacular's `_is_list_view` heuristic wraps any `list` action's response in an array,+ which generated `Promise<ReviewRecentReviewsPageApi[]>` — forced to False, and the operationId pinned back to `*_list`+ (forcing the heuristic renames the operation `*_retrieve`, colliding with the real retrieve).+ The two prior overrides in the codebase (event_filter_config, access_control property state) are singletons without a sibling retrieve, so they never hit the collision.+- **Logic:** loader holds the envelope (`recentReviewsPage`); `recentReviews` / `moreReviewsAvailable` are selectors over it.+ `reviewsLimit` reducer: +5 per `showMoreReviews`, reset to 5 on `showFewerReviews` **and on any scope change** (a different scope is a different list, user decision).+ "Show fewer" collapses **instantly from already-loaded rows** (reducer slices, `has_more` forced true when rows were hidden)+ while its listener refetches to reconcile — the refetch also breakpoint-drops any wider in-flight poll response that would resurrect the collapsed rows.+ `reviewsExpanding` drives the "Show more" button's loading state (the loader's own `loading` would flash on every 10s poll);+ `LemonButton.loading` hard-disables, so it's also the double-click guard.+ Growth clamps at `MAX_REVIEWS_LIMIT` (100, mirroring reviews.py) and `moreReviewsAvailable` goes false at the ceiling even while `has_more` —+ otherwise the 20th click sends `limit=105`, the API 400s, and the generic failure path strands the page in the settings-failed banner (PR review finding, fixed same day).+ The limit is deliberately **not** mirrored to the URL — ephemeral view state, unlike scope.+- **UI:** centered tertiary "Show more" / "Show fewer" footer row inside the card (divide-y gives the hairline);+ "Show fewer" only when more than a page is showing, "Show more" only when `has_more`.+ Copy is "Show fewer" (countable rows), per user's "whatever is grammatically correct".+- Tests: BE — envelope + limit growth + has_more boundary at exact count + out-of-range 400s (wiring guard);+ jest — grow/collapse cycle (instant collapse, has_more preserved, scope flip resets the limit).+ Full suite: 503 backend + 3 jest green; `hogli build:openapi` regenerated cleanly (list function keeps its `reviewHogReviewsList` name).+#### ✅ 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 — andiff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.pyindex baba1b90f802..d6babc40b0ef 100644--- a/products/review_hog/backend/api/reviews.py+++ b/products/review_hog/backend/api/reviews.py@@ -6,6 +6,7 @@ from typing import Any, get_argsfrom django.db.models import Max, QuerySetfrom django.utils import timezone+from drf_spectacular.openapi import AutoSchemafrom drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import serializers, viewsetsfrom rest_framework.decorators import action@@ -37,7 +38,9 @@ from products.review_hog.backend.reviewer.progress import (logger = logging.getLogger(__name__)-RECENT_REVIEWS_LIMIT = 5+DEFAULT_REVIEWS_LIMIT = 5+# Caps "Show more" growth — enrichment (jsonb stats + findings bundle) is per-row work.+MAX_REVIEWS_LIMIT = 100# Effectiveness stats aggregate deeper than the list — enough history for survival rates to mean something.PERSPECTIVE_STATS_REPORT_LIMIT = 50@@ -61,6 +64,13 @@ class ReviewsListParamsSerializer(serializers.Serializer):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.",)+ limit = serializers.IntegerField(+ default=DEFAULT_REVIEWS_LIMIT,+ min_value=1,+ max_value=MAX_REVIEWS_LIMIT,+ help_text="Maximum rows to return. The list grows this instead of paging by offset — "+ "in-progress rows reorder the list between refreshes, so offset pages would shift under the reader.",+ )class ReviewProgressSerializer(serializers.Serializer):@@ -174,6 +184,15 @@ class ReviewRecentReviewSerializer(serializers.Serializer):)+class ReviewRecentReviewsPageSerializer(serializers.Serializer):+ results = ReviewRecentReviewSerializer(+ many=True, help_text="The scoped reviews: in-progress runs first, then completed newest first."+ )+ has_more = serializers.BooleanField(+ help_text='Whether reviews exist beyond this page — drives the list\'s "Show more" button.'+ )++class ReviewFindingLineRangeSerializer(serializers.Serializer):start = serializers.IntegerField(help_text="First affected line.")end = serializers.IntegerField(allow_null=True, help_text="Last affected line; null for a single line.")@@ -242,6 +261,25 @@ class ReviewPerspectiveStatsSerializer(serializers.Serializer):)+class _PageEnvelopeSchema(AutoSchema):+ """Stops drf-spectacular's list-view heuristic from wrapping the `list` response in an array.++ `list` returns a single page envelope (`results` + `has_more`), not a bare collection. The+ default heuristic already returns False for this viewset's other operations, but forcing it+ renames the list operation to `*_retrieve` — pin the operationId back so the generated client+ keeps its `*List` name and doesn't collide with the real retrieve.+ """++ def _is_list_view(self, serializer: Any = None) -> bool:+ return False++ def get_operation_id(self) -> str:+ operation_id = super().get_operation_id()+ if getattr(self.view, "action", None) == "list" and operation_id.endswith("_retrieve"):+ return operation_id.removesuffix("_retrieve") + "_list"+ return operation_id++def _in_progress_report_ids(team_id: int, reports: list[ReviewReport]) -> set[str]:"""Which ACTIVE reports are visibly running: artefact or report activity within the staleness window.@@ -368,6 +406,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetqueryset = ReviewReport.objects.unscoped()serializer_class = ReviewRecentReviewSerializerpagination_class = None+ schema = _PageEnvelopeSchema()def _reports(self, request: Request, scope: str = SCOPE_MINE) -> tuple[int, QuerySet[ReviewReport]]:team_id = resolve_effective_team_id(self.team_id)@@ -380,24 +419,29 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetparameters=[ReviewsListParamsSerializer],responses={200: OpenApiResponse(- response=ReviewRecentReviewSerializer(many=True),- description="The scoped reviews: in-progress runs first, then completed newest first.",+ response=ReviewRecentReviewsPageSerializer,+ description="The scoped reviews: in-progress runs first, then completed newest first, "+ "with a flag for whether more exist beyond `limit`.",),},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.",+ "in-flight turn's stage), then the most recent completed ones — at most `limit` rows (default 5), "+ "plus `has_more` for whether a larger `limit` would reveal more. By default only the requesting "+ "user's reviews; `scope=everyone` lists every review on the project.",)def list(self, request: Request, **kwargs) -> Response:params = ReviewsListParamsSerializer(data=request.query_params)params.is_valid(raise_exception=True)+ limit: int = params.validated_data["limit"]+ # One row beyond the limit proves whether "Show more" has anything left to reveal.+ probe_limit = limit + 1team_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])+ completed = list(queryset.filter(last_run_at__isnull=False).order_by("-last_run_at")[:probe_limit])# First-turn runs have no completed turn yet; they only surface while visibly running.running_first_turn = list(queryset.filter(status=ReviewReport.Status.ACTIVE, last_run_at__isnull=True).order_by("-created_at")[- :RECENT_REVIEWS_LIMIT+ :probe_limit])# A re-review keeps the previous turn's last_run_at until it finalizes, so a dormant report's@@ -405,7 +449,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet# an actively reviewed PR vanishes from the list mid-run.running_re_review = list(queryset.filter(status=ReviewReport.Status.ACTIVE, last_run_at__isnull=False).order_by("-updated_at")[- :RECENT_REVIEWS_LIMIT+ :probe_limit])in_progress_ids = _in_progress_report_ids(team_id, running_first_turn + running_re_review + completed)@@ -421,7 +465,8 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetif str(report.id) not in seen:seen.add(str(report.id))reports.append(report)- reports = reports[:RECENT_REVIEWS_LIMIT]+ has_more = len(reports) > limit+ reports = reports[:limit]# Row stats anchor to each report's COMPLETED turn (matching the findings' run_count); the# in-flight progress payload alone reads the live head. Pre-column rows fall back to the live@@ -451,7 +496,7 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetcurrent_pairs,)items.append(_review_payload(report, snapshot, turn, pairs, progress))- return Response(ReviewRecentReviewSerializer(items, many=True).data)+ return Response(ReviewRecentReviewsPageSerializer({"results": items, "has_more": has_more}).data)@extend_schema(responses={diff --git a/products/review_hog/backend/tests/test_reviews_api.py b/products/review_hog/backend/tests/test_reviews_api.pyindex f7dcfcd4cbc3..e0093e963566 100644--- a/products/review_hog/backend/tests/test_reviews_api.py+++ b/products/review_hog/backend/tests/test_reviews_api.py@@ -141,7 +141,8 @@ class TestRecentReviewsAPI(APIBaseTest):res = self.client.get(self.url)assert res.status_code == 200- rows = res.json()+ assert res.json()["has_more"] is False+ rows = res.json()["results"]assert [r["pr_number"] for r in rows] == [1]assert rows[0]["github_url"] == mine.pr_urlassert rows[0]["published"] is False@@ -160,9 +161,27 @@ class TestRecentReviewsAPI(APIBaseTest):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 {r["pr_number"] for r in res.json()["results"]} == {1, 2}assert self.client.get(self.url, {"scope": "nonsense"}).status_code == 400+ def test_list_limit_grows_the_page_and_has_more_flags_the_rest(self) -> None:+ # "Show more" grows `limit` instead of offset-paging. has_more must flip false exactly when+ # the page covers everything (off-by-one here strands or dead-ends the button), and+ # out-of-range limits must 400 — proving the field is wired into the params serializer.+ for pr_number in range(1, 8):+ self._report(pr_number=pr_number, acting_user=self.user)++ default_page = self.client.get(self.url).json()+ assert len(default_page["results"]) == 5+ assert default_page["has_more"] is True++ full_page = self.client.get(self.url, {"limit": 7}).json()+ assert len(full_page["results"]) == 7+ assert full_page["has_more"] is False++ assert self.client.get(self.url, {"limit": 0}).status_code == 400+ assert self.client.get(self.url, {"limit": 101}).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.@@ -175,7 +194,7 @@ class TestRecentReviewsAPI(APIBaseTest):res = self.client.get(self.url)assert res.status_code == 200- row = res.json()[0]+ row = res.json()["results"][0]assert row["github_url"] == "https://github.com/PostHog/posthog/tree/feat-branch"assert (row["must_fix_count"], row["should_fix_count"], row["consider_count"]) == (1, 1, 0)@@ -265,7 +284,7 @@ class TestRecentReviewsAPI(APIBaseTest):res = self.client.get(self.url)assert res.status_code == 200- row = res.json()[0]+ row = res.json()["results"][0]assert row["pr_title"] == "feat: current title"assert row["pr_author"] == "skoob13"assert (row["additions"], row["deletions"], row["changed_files"]) == (120, 8, 7)@@ -330,7 +349,7 @@ class TestRecentReviewsAPI(APIBaseTest):running = self._report(pr_number=2, acting_user=self.user, completed=False, run_count=0, head_sha="sha1")running_id = str(running.id)- rows = self.client.get(self.url).json()+ rows = self.client.get(self.url).json()["results"]assert [r["pr_number"] for r in rows] == [2, 1]assert rows[0]["in_progress"] is Trueassert rows[0]["progress"] == {"review_stage": "fetching", "done": None, "total": None}@@ -345,7 +364,7 @@ class TestRecentReviewsAPI(APIBaseTest):pr_comments=[],pr_files=[],)- assert self.client.get(self.url).json()[0]["progress"]["review_stage"] == "chunking"+ assert self.client.get(self.url).json()["results"][0]["progress"]["review_stage"] == "chunking"persist_chunk_set(team_id=self.team.id,@@ -354,7 +373,7 @@ class TestRecentReviewsAPI(APIBaseTest):chunks=ChunksList(chunks=[Chunk(chunk_id=i, files=[FileInfo(filename="a.py")]) for i in range(2)]),)# A chunked turn with no reads and no plan yet is the selector's window.- assert self.client.get(self.url).json()[0]["progress"] == {+ assert self.client.get(self.url).json()["results"][0]["progress"] == {"review_stage": "selecting","done": None,"total": None,@@ -368,7 +387,11 @@ class TestRecentReviewsAPI(APIBaseTest):)# No persisted plan (a fallback run): the dense estimate — 2 chunks × (3 canonical# perspectives + the blind-spot sweep) = 8 expected reads.- assert self.client.get(self.url).json()[0]["progress"] == {"review_stage": "reviewing", "done": 2, "total": 8}+ assert self.client.get(self.url).json()["results"][0]["progress"] == {+ "review_stage": "reviewing",+ "done": 2,+ "total": 8,+ }# Once the selector's plan lands, the total is exact: planned wave units + one blind spot per# chunk — without this, a pruned run's bar stalls below 100% against the dense estimate.@@ -384,7 +407,11 @@ class TestRecentReviewsAPI(APIBaseTest):]),)- assert self.client.get(self.url).json()[0]["progress"] == {"review_stage": "reviewing", "done": 2, "total": 3}+ assert self.client.get(self.url).json()["results"][0]["progress"] == {+ "review_stage": "reviewing",+ "done": 2,+ "total": 3,+ }# All planned reads in (1 selected wave unit + 2 blind spots = 3) → the dedup window.persist_perspective_results(@@ -393,7 +420,7 @@ class TestRecentReviewsAPI(APIBaseTest):head_sha="sha1",results={(1000, 0): _issues_review(0)},)- assert self.client.get(self.url).json()[0]["progress"] == {+ assert self.client.get(self.url).json()["results"][0]["progress"] == {"review_stage": "deduplicating","done": 3,"total": 3,@@ -401,7 +428,7 @@ class TestRecentReviewsAPI(APIBaseTest):self._finding(running, "1-a", priority=IssuePriority.MUST_FIX)self._finding(running, "1-b", priority=IssuePriority.CONSIDER, judged=False)- assert self.client.get(self.url).json()[0]["progress"] == {+ assert self.client.get(self.url).json()["results"][0]["progress"] == {"review_stage": "validating","done": 1,"total": 2,@@ -409,7 +436,7 @@ class TestRecentReviewsAPI(APIBaseTest):# Every finding judged → the turn is building + publishing, the moments before it completes.self._finding(running, "1-b", priority=IssuePriority.CONSIDER, is_valid=False)- assert self.client.get(self.url).json()[0]["progress"] == {+ assert self.client.get(self.url).json()["results"][0]["progress"] == {"review_stage": "finalizing","done": 2,"total": 2,@@ -453,7 +480,7 @@ class TestRecentReviewsAPI(APIBaseTest):pr_files=[],)- row = self.client.get(self.url).json()[0]+ row = self.client.get(self.url).json()["results"][0]assert (row["pr_title"], row["chunk_count"], row["must_fix_count"]) == ("completed title", 3, 1)assert row["in_progress"] is Trueassert row["progress"]["review_stage"] == "chunking" # live head: snapshot yes, chunks not yet@@ -474,7 +501,7 @@ class TestRecentReviewsAPI(APIBaseTest):last_run_at=datetime(2026, 6, 1, tzinfo=UTC))- rows = self.client.get(self.url).json()+ rows = self.client.get(self.url).json()["results"]assert len(rows) == 5assert rows[0]["pr_number"] == 99diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsxindex 8f5ac57fb859..18de06541bee 100644--- a/products/review_hog/frontend/CodeReviewScene.tsx+++ b/products/review_hog/frontend/CodeReviewScene.tsx@@ -51,7 +51,7 @@ import type {} from 'products/review_hog/frontend/generated/api.schemas'import { ReviewHogReviewsListScope } from 'products/review_hog/frontend/generated/api.schemas'-import { ReviewDrawerTab, ReviewSkillKind, reviewHogSettingsLogic } from './reviewHogSettingsLogic'+import { REVIEWS_PAGE_SIZE, ReviewDrawerTab, ReviewSkillKind, reviewHogSettingsLogic } from './reviewHogSettingsLogic'/** "review-hog-perspective-logic-correctness" → "Logic correctness" */function prettifySkillName(skillName: string): string {@@ -484,9 +484,15 @@ function RecentReviewRow({ review }: { review: ReviewRecentReviewApi }): JSX.Ele/** Compact proof-of-life block under the hero — hidden entirely until the project has reviews. */function RecentReviewsSection(): JSX.Element | null {- const { recentReviews, recentReviewsLoading, reviewsScope, hasUserChosenReviewsScope } =- useValues(reviewHogSettingsLogic)- const { setReviewsScope } = useActions(reviewHogSettingsLogic)+ const {+ recentReviews,+ recentReviewsPageLoading,+ moreReviewsAvailable,+ reviewsExpanding,+ reviewsScope,+ hasUserChosenReviewsScope,+ } = useValues(reviewHogSettingsLogic)+ const { setReviewsScope, showMoreReviews, showFewerReviews } = useActions(reviewHogSettingsLogic)const everyone = reviewsScope === ReviewHogReviewsListScope.Everyoneconst loadedEmpty = recentReviews !== null && recentReviews.length === 0@@ -494,13 +500,13 @@ function RecentReviewsSection(): JSX.Element | null {// 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) {+ if (loadedEmpty && everyone && !recentReviewsPageLoading) {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)+ const emptyAwaitingReload = loadedEmpty && (recentReviewsPageLoading || !hasUserChosenReviewsScope)return (// The one section without a top hairline — it reads as a continuation of the hero.@@ -544,7 +550,30 @@ function RecentReviewsSection(): JSX.Element | null {</div>))) : recentReviews.length ? (- recentReviews.map((review) => <RecentReviewRow key={review.id} review={review} />)+ <>+ {recentReviews.map((review) => (+ <RecentReviewRow key={review.id} review={review} />+ ))}+ {(moreReviewsAvailable || recentReviews.length > REVIEWS_PAGE_SIZE) && (+ <div className="flex justify-center gap-2 px-4 py-1.5">+ {moreReviewsAvailable && (+ <LemonButton+ size="small"+ type="tertiary"+ onClick={showMoreReviews}+ loading={reviewsExpanding}+ >+ Show more+ </LemonButton>+ )}+ {recentReviews.length > REVIEWS_PAGE_SIZE && (+ <LemonButton size="small" type="tertiary" onClick={showFewerReviews}>+ Show fewer+ </LemonButton>+ )}+ </div>+ )}+ </>) : (<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.diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.tsindex ba1abbc52d3e..fa633df78b95 100644--- a/products/review_hog/frontend/generated/api.schemas.ts+++ b/products/review_hog/frontend/generated/api.schemas.ts@@ -172,6 +172,13 @@ export interface ReviewRecentReviewApi {blind_spot_issue_count: number | null}+export interface ReviewRecentReviewsPageApi {+ /** The scoped reviews: in-progress runs first, then completed newest first. */+ results: ReviewRecentReviewApi[]+ /** Whether reviews exist beyond this page — drives the list's "Show more" button. */+ has_more: boolean+}+export interface ReviewSelectionChunkApi {/** The chunk this row describes, as numbered by the chunker. */chunk_id: number@@ -465,6 +472,12 @@ export interface PatchedReviewValidatorConfigSelectApi {}export type ReviewHogReviewsListParams = {+ /**+ * Maximum rows to return. The list grows this instead of paging by offset — in-progress rows reorder the list between refreshes, so offset pages would shift under the reader.+ * @minimum 1+ * @maximum 100+ */+ limit?: number/*** Whose reviews to list: `mine` for reviews of the requesting user's pull requests (the default), `everyone` for every review on this project.*diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.tsindex 454c9f32a983..75739fc24458 100644--- a/products/review_hog/frontend/generated/api.ts+++ b/products/review_hog/frontend/generated/api.ts@@ -18,7 +18,7 @@ import type {ReviewHogReviewsListParams,ReviewPerspectiveConfigApi,ReviewPerspectiveStatsApi,- ReviewRecentReviewApi,+ ReviewRecentReviewsPageApi,ReviewUserSettingsApi,ReviewValidatorConfigApi,} from './api.schemas'@@ -120,15 +120,15 @@ export const getReviewHogReviewsListUrl = (projectId: string, params?: ReviewHog}/**- * 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.+ * 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 `limit` rows (default 5), plus `has_more` for whether a larger `limit` would reveal more. 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, params), {+): Promise<ReviewRecentReviewsPageApi> => {+ return apiMutator<ReviewRecentReviewsPageApi>(getReviewHogReviewsListUrl(projectId, params), {...options,method: 'GET',})diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.tsindex 41bad3bbd83d..a8ccf3b8497e 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts@@ -6,7 +6,14 @@ import { initKeaTests } from '~/test/init'import { ReviewHogReviewsListScope } from 'products/review_hog/frontend/generated/api.schemas'-import { reviewHogSettingsLogic } from './reviewHogSettingsLogic'+import { MAX_REVIEWS_LIMIT, REVIEWS_PAGE_SIZE, reviewHogSettingsLogic } from './reviewHogSettingsLogic'++// More project-wide reviews than the API's maximum limit, so both "Show more" growth and its+// ceiling are reachable.+const everyoneReviews = Array.from({ length: MAX_REVIEWS_LIMIT + REVIEWS_PAGE_SIZE }, (_, i) => ({+ id: `r${i}`,+ in_progress: false,+}))describe('reviewHogSettingsLogic', () => {let logic: ReturnType<typeof reviewHogSettingsLogic.build>@@ -14,13 +21,14 @@ describe('reviewHogSettingsLogic', () => {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 }]- : [],- ],+ // The user has no reviews of their own; the project has a dozen.+ '/api/projects/:team_id/review_hog/reviews/': ({ request }) => {+ const url = new URL(request.url)+ const limit = Number(url.searchParams.get('limit') ?? REVIEWS_PAGE_SIZE)+ const pool =+ url.searchParams.get('scope') === ReviewHogReviewsListScope.Everyone ? everyoneReviews : []+ return [200, { results: pool.slice(0, limit), has_more: pool.length > limit }]+ },'/api/projects/:team_id/review_hog/reviews/perspective_stats/': () => [200,{ report_count: 0, perspectives: [] },@@ -54,7 +62,7 @@ describe('reviewHogSettingsLogic', () => {// The auto-default is not an explicit choice — a later real one must still win.hasUserChosenReviewsScope: false,})- expect(logic.values.recentReviews).toHaveLength(1)+ expect(logic.values.recentReviews).toHaveLength(REVIEWS_PAGE_SIZE)// 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()@@ -78,4 +86,56 @@ describe('reviewHogSettingsLogic', () => {recentReviews: [],})})++ it('grows the list by a page per "Show more" and collapses instantly on "Show fewer"', async () => {+ logic.mount()+ // Land on the everyone scope (auto-default) with the first page loaded.+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])+ expect(logic.values.moreReviewsAvailable).toBe(true)++ await expectLogic(logic, () => logic.actions.showMoreReviews())+ .toDispatchActions(['loadRecentReviewsSuccess'])+ .toMatchValues({ reviewsLimit: REVIEWS_PAGE_SIZE * 2 })+ expect(logic.values.recentReviews).toHaveLength(REVIEWS_PAGE_SIZE * 2)++ // The collapse must not wait for the reconciling refetch, and hiding loaded rows means+ // "Show more" must stay on offer regardless of the last response's flag.+ logic.actions.showFewerReviews()+ expect(logic.values.recentReviews).toHaveLength(REVIEWS_PAGE_SIZE)+ expect(logic.values.moreReviewsAvailable).toBe(true)+ await expectLogic(logic).toDispatchActions(['loadRecentReviewsSuccess']).toMatchValues({+ reviewsLimit: REVIEWS_PAGE_SIZE,+ })++ // A scope flip is a different list — it starts compact again.+ logic.actions.showMoreReviews()+ logic.actions.setReviewsScope(ReviewHogReviewsListScope.Mine)+ await expectLogic(logic).toMatchValues({ reviewsLimit: REVIEWS_PAGE_SIZE })+ })++ it('stops "Show more" at the API\'s maximum limit', async () => {+ logic.mount()+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])++ // Enough clicks to push an unclamped limit past the API's max, where the request would 400+ // and strand the user on a dead button.+ for (let i = 0; i < MAX_REVIEWS_LIMIT / REVIEWS_PAGE_SIZE; i++) {+ logic.actions.showMoreReviews()+ }+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.reviewsLimit).toBe(MAX_REVIEWS_LIMIT)+ expect(logic.values.recentReviews).toHaveLength(MAX_REVIEWS_LIMIT)+ // More rows exist server-side, but the ceiling is reached — the button goes away rather+ // than offering a request the server rejects.+ expect(logic.values.moreReviewsAvailable).toBe(false)+ })})diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.tsindex 4c6086033511..b0b00bdccbec 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts@@ -31,6 +31,7 @@ import type {ReviewPerspectiveConfigApi,ReviewPerspectiveStatsApi,ReviewRecentReviewApi,+ ReviewRecentReviewsPageApi,ReviewUserSettingsApi,ReviewValidatorConfigApi,} from 'products/review_hog/frontend/generated/api.schemas'@@ -51,6 +52,12 @@ export const REVIEW_PRIORITY_RANK: Record<ReviewIssuePriorityEnumApi, number> =// While a review is running, the list refreshes on this cadence so the stage/progress row is live.const IN_PROGRESS_POLL_INTERVAL_MS = 10_000+/** The review list's initial depth, the step each "Show more" adds, and what "Show fewer" collapses to. */+export const REVIEWS_PAGE_SIZE = 5++/** Mirrors MAX_REVIEWS_LIMIT in reviews.py — the API 400s above this, so growth must stop here. */+export const MAX_REVIEWS_LIMIT = 100+/** The detail's valid findings split by the user's urgency threshold: on the PR vs. kept back. */export interface ReviewFindingsSplit {published: ReviewFindingApi[]@@ -140,6 +147,8 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([setReviewDrawerTab: (tab: ReviewDrawerTab) => ({ tab }),toggleReviewRowExpanded: (reviewId: string) => ({ reviewId }),setReviewsScope: (scope: ReviewHogReviewsListScope) => ({ scope }),+ showMoreReviews: true,+ showFewerReviews: true,// 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 }),@@ -178,14 +187,14 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([loadValidators: async () => await reviewHogValidatorsList(currentProjectId()),},],- recentReviews: [- null as ReviewRecentReviewApi[] | null,+ recentReviewsPage: [+ null as ReviewRecentReviewsPageApi | null,{// 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.+ const { reviewsScope: scope, reviewsLimit: limit } = values+ const response = await reviewHogReviewsList(currentProjectId(), { scope, limit })+ // A scope or limit change mid-flight dispatched a newer load — drop this stale response.breakpoint()return response},@@ -278,6 +287,40 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([state.includes(reviewId) ? state.filter((id) => id !== reviewId) : [...state, reviewId],},],+ recentReviewsPage: {+ // "Show fewer" collapses instantly from data already loaded; the listener's refetch+ // reconciles silently and breakpoint-drops any wider in-flight response (e.g. a poll).+ showFewerReviews: (state: ReviewRecentReviewsPageApi | null) =>+ state+ ? {+ ...state,+ results: state.results.slice(0, REVIEWS_PAGE_SIZE),+ has_more: state.has_more || state.results.length > REVIEWS_PAGE_SIZE,+ }+ : state,+ },+ // How many rows the review list asks for — grows by a page per "Show more".+ reviewsLimit: [+ REVIEWS_PAGE_SIZE as number,+ {+ showMoreReviews: (state) => Math.min(state + REVIEWS_PAGE_SIZE, MAX_REVIEWS_LIMIT),+ showFewerReviews: () => REVIEWS_PAGE_SIZE,+ // A different scope is a different list — start it compact again.+ setReviewsScope: () => REVIEWS_PAGE_SIZE,+ applyDefaultReviewsScope: () => REVIEWS_PAGE_SIZE,+ },+ ],+ // Drives the "Show more" button's loading state — the loader's own `loading` would also+ // flash on every 10s in-progress poll.+ reviewsExpanding: [+ false,+ {+ showMoreReviews: () => true,+ showFewerReviews: () => false,+ loadRecentReviewsSuccess: () => false,+ loadRecentReviewsFailure: () => false,+ },+ ],// Whose reviews the "recent reviews" block lists — mirrors the inbox's// "For you / Entire project" switch.reviewsScope: [@@ -323,6 +366,17 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([}),selectors({+ recentReviews: [+ (s) => [s.recentReviewsPage],+ (recentReviewsPage): ReviewRecentReviewApi[] | null => recentReviewsPage?.results ?? null,+ ],+ moreReviewsAvailable: [+ (s) => [s.recentReviewsPage, s.reviewsLimit],+ (recentReviewsPage, reviewsLimit): boolean =>+ // At the API's ceiling the button must go away even though more rows exist —+ // offering it would send a limit the server rejects.+ (recentReviewsPage?.has_more ?? false) && reviewsLimit < MAX_REVIEWS_LIMIT,+ ],// Splits the detail's valid findings by the CURRENT threshold — a close-enough proxy for// what the run published (the run's own threshold snapshot isn't stored).reviewFindingsSplit: [@@ -387,6 +441,8 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([},setReviewsScope: () => actions.loadRecentReviews(),applyDefaultReviewsScope: () => actions.loadRecentReviews(),+ showMoreReviews: () => actions.loadRecentReviews(),+ showFewerReviews: () => actions.loadRecentReviews(),loadAll: () => {actions.loadSettings()actions.loadPerspectives()diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 4043033bbd73..8a2910a5458c 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54213,6 +54213,13 @@ export namespace Schemas {blind_spot_issue_count: number | null;}+ export interface ReviewRecentReviewsPage {+ /** The scoped reviews: in-progress runs first, then completed newest first. */+ results: ReviewRecentReview[];+ /** Whether reviews exist beyond this page — drives the list's "Show more" button. */+ has_more: boolean;+ }+export interface ReviewStateCounts {needs_review: number;clean: number;@@ -75672,6 +75679,12 @@ export namespace Schemas {};export type ReviewHogReviewsListParams = {+ /**+ * Maximum rows to return. The list grows this instead of paging by offset — in-progress rows reorder the list between refreshes, so offset pages would shift under the reader.+ * @minimum 1+ * @maximum 100+ */+ limit?: number;/*** Whose reviews to list: `mine` for reviews of the requesting user's pull requests (the default), `everyone` for every review on this project.*