: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): review any accessible PR from the Code review scene (#71508)
Alex Lebedev9cfbf7ca5a6d
diff --git a/products/review_hog/ARCHITECTURE.md b/products/review_hog/ARCHITECTURE.mdindex 2a273608793d..779c42c5228a 100644--- a/products/review_hog/ARCHITECTURE.md+++ b/products/review_hog/ARCHITECTURE.md@@ -2419,6 +2419,111 @@ first so the latest fixes are loaded.---+### ✅ Stage 5c — UI trigger: review any installation-accessible PR from the Code review scene (BUILT 2026-07-16)++> **Status: BUILT 2026-07-16** (same-day decision round with the maintainer, then implemented — see+> "As built" at the end of this section). Not yet e2e'd against a live non-`posthog/posthog` PR.++**Motivation.** The label trigger needs `.github/workflows/review-hog.yml` in every repo it serves — only+`PostHog/posthog` has it, so every other `posthog/*` repo is out of reach unless we replicate the workflow+file across the org. Instead: a **"Review this PR"** field in the Code review scene that starts the same+server-side review for any PR the team's GitHub App installation can access — no per-repo CI configuration+at all. Everything below the trigger already supports this: `_build_inputs` takes any `owner/repo`, the+fetch activity resolves the installation token per repository (`first_for_team_repository`), fork rejection+is authoritative server-side, and the deterministic per-PR workflow id + `USE_EXISTING` absorbs re-triggers.++**Decisions locked (maintainer, 2026-07-16):**++- **Always publish — no per-run toggle.** The UI trigger is label-path parity for repos the label can't+ reach; `publish=True` is fixed. Results are additionally viewable in the findings drawer as usual.+- **Team gate = `settings.REVIEWHOG_TEAM_ID` only** (prod team 2; local team 1). The endpoint rejects any+ other team. No server-side feature-flag check — the scene's `REVIEW_HOG` flag gates discoverability only,+ and the hard team check bounds the cost surface for now. Widening beyond the dogfood team is a later,+ deliberate decision.+- **Requester wins.** The acting user is the requesting PostHog user via the existing `acting_user_id`+ override (`resolved_from="override"`): their perspectives / blind-spots / validator / urgency threshold+ drive the run, and the report lands in their "For you" recent-reviews scope. The PR author's+ `review_labeled_prs` opt-out stays label-only (its copy is label-specific; an explicit human ask is like+ a manual CLI run). The GitHub author can be anyone, including a bot — no author→user mapping is needed.+- **Repo scope = installation access, not a hardcoded org list.**+ `GitHubIntegration.first_for_team_repository(team_id, repository)` is the boundary — for team 2 that IS+ the `posthog` org — checked **synchronously at trigger time** so an inaccessible repo 400s immediately+ with a clear message. The label endpoint's "no GitHub I/O" principle deliberately does not apply here:+ that endpoint has the Action's upstream gates; the UI has none, and a silent async failure (the fetch+ activity fails before the report row exists) would leave the user staring at nothing.++**Design shape (v1):**++- **New team-scoped, session-authenticated trigger action** (e.g. `POST` `trigger` on the+ `review_hog/reviews` viewset), taking `pr_url`. The unscoped shared-secret `ReviewHogTriggerViewSet` and+ its `ALLOWED_REPOS` stay untouched as the CI interface — the two callers have different auth and scope+ rules, so they don't share an endpoint.+- Sync pre-checks in the action: parse the URL (`PRParser`), team gate, installation-access check (above).+ Optionally one PR-meta fetch to reject 404s/forks synchronously — authoritative fork rejection stays in+ the fetch activity either way. Drafts remain reviewable + publishable (existing posture; the UI copy+ should say the review is posted to the PR).+- `start_review_pr_workflow(pr_url=…, publish=True, acting_user_id=request.user.id,+trigger_source=TRIGGER_UI)` with `user_id = request.user.id` too (inbox precedent: the run user must be a+ real active org member — the requester is one by construction). New `TRIGGER_UI = "ui"` constant beside+ label/inbox/manual; ungated in the workflow's gate map (explicit ask); update the `trigger_source`+ comment on `ReviewReport`.+- **Frontend:** a PR-URL input + submit button in `CodeReviewScene` near "Your recent reviews"+ (`reviewHogSettingsLogic` action + generated client; button disabled/loading in flight). On 202, reload+ the recent-reviews list — the row appears once the fetch activity creates the report, and the existing+ in-progress poll takes over. Hide the field when the trigger isn't available for the team (surface a+ `can_trigger` boolean, e.g. on the settings GET, computed from the team gate).+- **Accepted / out of scope for v1:** no rate limit beyond the per-PR workflow-id dedupe (internal dogfood+ team; revisit if abused); PR URLs only (no branch targets from the UI); the label Action keeps working+ unchanged for `PostHog/posthog`.++**As built (2026-07-16):**++- `backend/api/reviews.py` — `trigger` action on `ReviewRecentReviewsViewSet`+ (`POST /api/projects/:id/review_hog/reviews/trigger/`): team gate vs `settings.REVIEWHOG_TEAM_ID`+ (403), `PRParser` URL parse (400), sync `GitHubIntegration.first_for_team_repository` access check+ (400), then `start_review_pr_workflow(publish=True, user_id=acting_user_id=request.user.id,+trigger_source=TRIGGER_UI)` → `202 {workflow_id, status}`. The URL is canonicalized (trailing+ `/files` etc. dropped) before it reaches the workflow id.+- `backend/temporal/types.py` — `TRIGGER_UI = "ui"`; ungated in the workflow's gate map (no+ workflow.py change, so no Temporal versioning concern).+- `backend/api/settings.py` — `can_trigger_reviews` (read-only method field) on the settings GET;+ the scene hides the trigger field when it's false.+- `frontend/CodeReviewScene.tsx` — `TriggerReviewSection` (PR-URL input + submit, above the+ recent-reviews block; button loading/disabled while in flight);+ `frontend/reviewHogSettingsLogic.ts` — `triggerPrUrl` / `triggeringReview` state ++ `submitTriggerReview` listener (toast on error, clear + reload recent reviews on 202; the new+ report row appears once the fetch activity creates it and the in-progress poll takes over).+- Tests: `backend/tests/test_ui_trigger_api.py` (gate, URL parse, access check, workflow kwargs,+ `can_trigger_reviews` exposure), `test_settings_api.py` defaults updated, two+ `reviewHogSettingsLogic.test.ts` cases (in-flight flag resets on both outcomes).+- **Sync PR fetch (added 2026-07-16, closing the original "v1 gap"):** the action makes one+ `GET /pulls/{n}` (`_fetch_pr_metadata`) so the answer is honest — nonexistent (404), fork, and+ closed PRs reject immediately with a message instead of dying async before the report row exists,+ and a PR whose current head equals the report's `published_head_sha` returns+ `200 {status: "already_reviewed"}` (no run, info toast, watch not armed) instead of a false+ "started". The report lookup is `repository__iexact` — triggers store differing casings. The+ fetch activity keeps the authoritative fork gate.+- **Cross-caller same-head caveat (pre-existing resume identity, now easier to reach):** the per-head+ working-state cache is roster-blind, and the UI trigger lets different acting users hit the same+ head. Three of four paths are safe: already-published head → the trigger answers+ `already_reviewed` without starting (the workflow's fetch early-exit backstops the race; the+ report is per-PR, not per-caller); run in flight → the deterministic workflow id + `USE_EXISTING`+ joins it; new head →+ nothing persisted under the new `head_sha`, full recompute under the new caller's roster. The+ unsafe window: a prior turn that persisted working state **without** stamping `published_head_sha`+ (a zero-findings turn — the watermark records only on a real post — or a crashed turn). A different+ caller's re-trigger then resumes those rows: the persisted perspective selection is reused verbatim+ (name-mapped, so the new caller's customs fall out of planned chunks), and perspective results+ resume on positional `(pass_number, chunk_id)` keys — slot = position in the acting user's sorted+ enabled set — so differing rosters silently mis-map slots. Identical rosters (canonicals only, or+ the same customs) are always safe. This is the finding-identity residual already noted in the+ blind-spot section; the fix belongs there: key results by `skill_name`(+version) instead of slot,+ and drop persisted selection/results whose recorded roster differs from the run's.+- Generated clients (`frontend/generated/*`) come from CI's OpenAPI auto-commit+ (`hogli build:openapi` was unavailable in the authoring environment).++---+### ✅ Stage 6 — Inbox trigger: auto-review self-driving implementations (BUILT 2026-07-02, trigger redesigned + dogfood e2e ✅ 2026-07-03)> **Status: BUILT + e2e'd, uncommitted.** (The implementation spec, `STAGE_6_PLAN.md`, was deleteddiff --git a/products/review_hog/backend/api/reviews.py b/products/review_hog/backend/api/reviews.pyindex d6babc40b0ef..80e4127c89b6 100644--- a/products/review_hog/backend/api/reviews.py+++ b/products/review_hog/backend/api/reviews.py@@ -1,21 +1,26 @@import uuidimport loggingfrom datetime import timedelta-from typing import Any, get_args+from typing import Any, cast, get_args+from django.conf import settingsfrom django.db.models import Max, QuerySetfrom django.utils import timezonefrom drf_spectacular.openapi import AutoSchemafrom drf_spectacular.utils import OpenApiResponse, extend_schema-from rest_framework import serializers, viewsets+from rest_framework import serializers, status, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.exceptions import NotFoundfrom rest_framework.request import Requestfrom rest_framework.response import Response+from posthog.api.integration import github_rate_limited_responsefrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.egress.github.transport import GitHubRateLimitError+from posthog.models.integration import GitHubIntegrationfrom posthog.models.scoping.manager import resolve_effective_team_id+from posthog.models.user import Userfrom products.review_hog.backend.models import ReviewReport, ReviewReportArtefactfrom products.review_hog.backend.reviewer.artefact_content import (@@ -35,6 +40,10 @@ from products.review_hog.backend.reviewer.progress import (snapshot_stats,turn_stats,)+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError, github_api_request+from products.review_hog.backend.reviewer.tools.github_meta import PRFetcher, PRMetadata, PRParser+from products.review_hog.backend.temporal.client import start_review_pr_workflow+from products.review_hog.backend.temporal.types import TRIGGER_UIlogger = logging.getLogger(__name__)@@ -193,6 +202,27 @@ class ReviewRecentReviewsPageSerializer(serializers.Serializer):)+class ReviewTriggerRequestSerializer(serializers.Serializer):+ pr_url = serializers.CharField(+ help_text="GitHub pull request URL to review, e.g. 'https://github.com/PostHog/posthog.com/pull/123'. "+ "The repository must be accessible to the project's GitHub App installation.",+ )+++class ReviewTriggerResponseSerializer(serializers.Serializer):+ workflow_id = serializers.CharField(+ allow_blank=True, help_text="Temporal workflow id for the started review run; empty when no run was started."+ )+ status = serializers.CharField(+ help_text="Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the "+ "pull request's current commit already has a published review (no new run starts)."+ )+++class ReviewTriggerErrorSerializer(serializers.Serializer):+ error = serializers.CharField(help_text="Human-readable explanation of why the trigger was rejected.")++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.")@@ -280,6 +310,22 @@ class _PageEnvelopeSchema(AutoSchema):return operation_id+def _fetch_pr_metadata(github: GitHubIntegration, owner: str, repo: str, pr_number: int) -> PRMetadata:+ """One `GET /pulls/{n}` with the installation token — enough to answer the trigger honestly.++ Raises `GitHubAPIError` (404 for a nonexistent PR); the caller maps it to a clear response.+ """+ token, installation_id = github.get_access_token(), github.github_installation_id+ pr = github_api_request(+ "GET",+ f"/repos/{owner}/{repo}/pulls/{pr_number}",+ token=token,+ installation_id=installation_id,+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",+ ).json()+ return PRFetcher(owner=owner, repo=repo, pr_number=pr_number, token=token).fetch_pr_metadata(pr)++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.@@ -531,6 +577,125 @@ class ReviewRecentReviewsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSetpayload = {"report_count": len(reports), "perspectives": items}return Response(ReviewPerspectiveStatsSerializer(payload).data)+ @extend_schema(+ request=ReviewTriggerRequestSerializer,+ responses={+ 200: OpenApiResponse(+ response=ReviewTriggerResponseSerializer,+ description="No new run needed: the PR's current commit already has a published review.",+ ),+ 202: OpenApiResponse(response=ReviewTriggerResponseSerializer, description="Review run started."),+ 400: OpenApiResponse(+ response=ReviewTriggerErrorSerializer,+ description="Invalid PR URL, inaccessible repository, or a nonexistent, closed, or fork PR.",+ ),+ 403: OpenApiResponse(+ response=ReviewTriggerErrorSerializer,+ description="The ReviewHog UI trigger is not enabled for this project.",+ ),+ 429: OpenApiResponse(description="GitHub rate-limited the App's token; retry after the Retry-After delay."),+ },+ summary="Start a review of a pull request",+ description="Start a ReviewHog review of any pull request the project's GitHub App installation can "+ "access, and publish it back to the PR. The requesting user is the review's acting user: their "+ "enabled perspectives, blind-spot check, validator, and urgency threshold drive the run, and it "+ "appears under their recent reviews. Nonexistent, closed, and fork PRs are rejected synchronously; "+ "a PR whose current commit already has a published review returns 'already_reviewed' without "+ "starting a run, and triggering a PR whose review is currently running joins the in-flight run. "+ "Otherwise non-blocking: returns the Temporal workflow id immediately while the review runs in "+ "the worker.",+ )+ @action(methods=["POST"], detail=False)+ def trigger(self, request: Request, **kwargs) -> Response:+ team_id = resolve_effective_team_id(self.team_id)+ # Dogfood gate: the UI trigger only runs on the designated ReviewHog team for now — reviews are+ # expensive, so widening beyond it is a deliberate later decision, not a default.+ if not settings.REVIEWHOG_TEAM_ID or team_id != settings.REVIEWHOG_TEAM_ID:+ return Response(+ {"error": "ReviewHog reviews can't be started from this project yet"},+ status=status.HTTP_403_FORBIDDEN,+ )+ serializer = ReviewTriggerRequestSerializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ try:+ pr_info = PRParser().parse_github_pr_url(serializer.validated_data["pr_url"])+ except ValueError:+ return Response(+ {+ "error": "That doesn't look like a GitHub pull request URL (expected https://github.com/OWNER/REPO/pull/NUMBER)"+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ repository = f"{pr_info['owner']}/{pr_info['repo']}"+ # Checked synchronously (one GitHub API call) so an inaccessible repo errors here, in the UI —+ # asynchronously the fetch activity would fail before the report row exists, showing nothing.+ try:+ github = GitHubIntegration.first_for_team_repository(team_id, repository)+ except GitHubRateLimitError as e:+ return github_rate_limited_response(e)+ if github is None:+ return Response(+ {+ "error": f"ReviewHog's GitHub App can't access {repository}. It reviews repositories covered by this project's GitHub integration."+ },+ status=status.HTTP_400_BAD_REQUEST,+ )+ pr_number = int(pr_info["pr_number"])+ # One PR fetch so the answer is honest: without it a typo'd number or fork dies async (before+ # the report row exists — nothing appears), and an already-reviewed head silently no-ops while+ # the response still claims "started". Fork/closed rejection here is UX; the fetch activity+ # keeps the authoritative fork gate.+ try:+ pr_meta = _fetch_pr_metadata(github, str(pr_info["owner"]), str(pr_info["repo"]), pr_number)+ except GitHubRateLimitError as e:+ return github_rate_limited_response(e)+ except GitHubAPIError as e:+ if e.status == 404:+ return Response(+ {"error": f"No pull request #{pr_number} found in {repository}"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ raise+ if pr_meta.is_fork:+ return Response(+ {"error": "ReviewHog doesn't review fork pull requests (a fork's head can't be trusted)"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ if pr_meta.state != "open":+ return Response(+ {"error": f"Pull request #{pr_number} is {pr_meta.state}; ReviewHog reviews open pull requests"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ # Repository casing can differ per trigger (the report stores whatever its trigger carried).+ report = (+ ReviewReport.objects.for_team(team_id).filter(repository__iexact=repository, pr_number=pr_number).first()+ )+ if report is not None and pr_meta.head_sha and report.published_head_sha == pr_meta.head_sha:+ # The workflow would early-exit before resolving the acting user anyway — say so instead+ # of answering "started" for a run that will do nothing.+ return Response(+ ReviewTriggerResponseSerializer({"workflow_id": "", "status": "already_reviewed"}).data,+ status=status.HTTP_200_OK,+ )+ # Rebuilt canonical URL: the parser accepts trailing paths (e.g. …/pull/123/files).+ pr_url = f"https://github.com/{pr_info['owner']}/{pr_info['repo']}/pull/{pr_info['pr_number']}"+ # The requester is both the run user (sandbox identity) and the acting user (whose+ # perspectives/validator/threshold apply). The route is authenticated, so never anonymous.+ requester_id = cast(User, request.user).id+ workflow_id = start_review_pr_workflow(+ pr_url=pr_url,+ team_id=team_id,+ user_id=requester_id,+ publish=True,+ acting_user_id=requester_id,+ trigger_source=TRIGGER_UI,+ )+ logger.info(f"ReviewHog UI trigger started workflow {workflow_id} for {pr_url} by user {requester_id}")+ return Response(+ ReviewTriggerResponseSerializer({"workflow_id": workflow_id, "status": "started"}).data,+ status=status.HTTP_202_ACCEPTED,+ )+@extend_schema(responses={200: OpenApiResponse(diff --git a/products/review_hog/backend/api/settings.py b/products/review_hog/backend/api/settings.pyindex e8d627ddbdf7..d0104a49932c 100644--- a/products/review_hog/backend/api/settings.py+++ b/products/review_hog/backend/api/settings.py@@ -1,6 +1,8 @@import logging-from drf_spectacular.utils import OpenApiResponse, extend_schema+from django.conf import settings++from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_fieldfrom rest_framework import serializers, viewsetsfrom rest_framework.decorators import actionfrom rest_framework.request import Request@@ -33,10 +35,18 @@ class ReviewUserSettingsSerializer(serializers.ModelSerializer):"publishes everything, 'should_fix' drops consider-level findings, 'must_fix' publishes only ""blocking issues.",)+ can_trigger_reviews = serializers.SerializerMethodField(+ help_text="Whether reviews can be started from this project's Code review page (the UI trigger "+ "is limited to the designated ReviewHog team while the product is in alpha).",+ )class Meta:model = ReviewUserSettings- fields = ["review_inbox_prs", "review_labeled_prs", "urgency_threshold"]+ fields = ["review_inbox_prs", "review_labeled_prs", "urgency_threshold", "can_trigger_reviews"]++ @extend_schema_field(serializers.BooleanField())+ def get_can_trigger_reviews(self, instance: ReviewUserSettings) -> bool:+ return bool(settings.REVIEWHOG_TEAM_ID) and instance.team_id == settings.REVIEWHOG_TEAM_IDclass ReviewUserSettingsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):diff --git a/products/review_hog/backend/models.py b/products/review_hog/backend/models.pyindex a0ceb49e9b47..23cfb57251c9 100644--- a/products/review_hog/backend/models.py+++ b/products/review_hog/backend/models.py@@ -69,7 +69,7 @@ class ReviewReport(UUIDModel, TeamScopedRootMixin):# signals side (the signals-side `code_review` artefact is API-deletable; this row is the durable# link). Filled once, never overwritten by later turns from another trigger.signal_report_id = models.UUIDField(null=True, blank=True)- # Which trigger created this report ("label" / "inbox" / "manual"); stamped on create only.+ # Which trigger created this report ("label" / "inbox" / "manual" / "ui"); stamped on create only.trigger_source = models.CharField(max_length=20, default="manual")created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/products/review_hog/backend/reviewer/tests/test_github_meta.py b/products/review_hog/backend/reviewer/tests/test_github_meta.pyindex 7b023b48a329..a32061b15377 100644--- a/products/review_hog/backend/reviewer/tests/test_github_meta.py+++ b/products/review_hog/backend/reviewer/tests/test_github_meta.py@@ -22,6 +22,9 @@ class TestParseGithubPrUrl:"repo.with-dots_and-dashes",9999,),+ ("trailing_path", "https://github.com/owner/repo/pull/123/files", "owner", "repo", 123),+ ("query_string", "https://github.com/owner/repo/pull/123?w=1", "owner", "repo", 123),+ ("fragment", "https://github.com/owner/repo/pull/123#discussion_r1", "owner", "repo", 123),])def test_parse_valid_url(self, _name: str, url: str, owner: str, repo: str, number: int) -> None:@@ -34,6 +37,8 @@ class TestParseGithubPrUrl:("missing_protocol", "github.com/owner/repo/pull/123"),("missing_repo", "https://github.com/owner/pull/123"),("non_numeric_pr", "https://github.com/owner/repo/pull/abc"),+ # A typo'd suffix must not silently parse as the numeric prefix and review PR 123.+ ("digits_then_junk", "https://github.com/owner/repo/pull/123abc"),("missing_pr_number", "https://github.com/owner/repo/pull/"),("not_a_url", "not-a-url"),]diff --git a/products/review_hog/backend/reviewer/tools/github_meta.py b/products/review_hog/backend/reviewer/tools/github_meta.pyindex 80393e13c32c..88fad2538da7 100644--- a/products/review_hog/backend/reviewer/tools/github_meta.py+++ b/products/review_hog/backend/reviewer/tools/github_meta.py@@ -108,8 +108,12 @@ class PRFilter:class PRParser:@staticmethoddef parse_github_pr_url(url: str) -> dict[str, str | int]:- """Parse GitHub PR URL and extract owner, repo, and PR number."""- pattern = r"https://github\.com/([^/]+)/([^/]+)/pull/(\d+)"+ """Parse GitHub PR URL and extract owner, repo, and PR number.++ The number must end at a path boundary (`/pull/123abc` is rejected, not read as 123 — a typo+ must not silently review a different PR); trailing paths like `/files` are accepted.+ """+ pattern = r"https://github\.com/([^/]+)/([^/]+)/pull/(\d+)(?=$|[/?#])"match = re.match(pattern, url)if not match:raise ValueError(diff --git a/products/review_hog/backend/temporal/types.py b/products/review_hog/backend/temporal/types.pyindex 3167ebe63a42..1d6d55183ce0 100644--- a/products/review_hog/backend/temporal/types.py+++ b/products/review_hog/backend/temporal/types.py@@ -7,11 +7,13 @@ input without importing the workflow code (which pulls in the heavy activity depfrom dataclasses import dataclass# How a review run was triggered. Gates are trigger-aware: label → `review_labeled_prs`,-# inbox → `review_inbox_prs`, manual (CLI/eval) → ungated. Plain strings (not an Enum) so Temporal-# payloads stay forward/backward-compatible across deploys.+# inbox → `review_inbox_prs`, manual (CLI/eval) and ui (an explicit human ask from the Code review+# scene) → ungated. Plain strings (not an Enum) so Temporal payloads stay forward/backward-compatible+# across deploys.TRIGGER_LABEL = "label"TRIGGER_INBOX = "inbox"TRIGGER_MANUAL = "manual"+TRIGGER_UI = "ui"@dataclassdiff --git a/products/review_hog/backend/tests/test_settings_api.py b/products/review_hog/backend/tests/test_settings_api.pyindex 49eea5414012..6720a514b801 100644--- a/products/review_hog/backend/tests/test_settings_api.py+++ b/products/review_hog/backend/tests/test_settings_api.py@@ -21,6 +21,7 @@ class TestReviewUserSettingsAPI(APIBaseTest):"review_inbox_prs": False,"review_labeled_prs": True,"urgency_threshold": "consider",+ "can_trigger_reviews": False, # REVIEWHOG_TEAM_ID is unset in tests}assert ReviewUserSettings.objects.for_team(self.team.id).filter(user_id=self.user.id).count() == 1diff --git a/products/review_hog/backend/tests/test_ui_trigger_api.py b/products/review_hog/backend/tests/test_ui_trigger_api.pynew file mode 100644index 000000000000..a4129bfd9691--- /dev/null+++ b/products/review_hog/backend/tests/test_ui_trigger_api.py@@ -0,0 +1,175 @@+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.test import override_settings++from parameterized import parameterized+from rest_framework import status++from posthog.egress.github.transport import GitHubRateLimitError++from products.review_hog.backend.models import ReviewReport+from products.review_hog.backend.reviewer.tools.github_client import GitHubAPIError++_START = "products.review_hog.backend.api.reviews.start_review_pr_workflow"+_ACCESS = "products.review_hog.backend.api.reviews.GitHubIntegration.first_for_team_repository"+_META = "products.review_hog.backend.api.reviews._fetch_pr_metadata"+++def _pr_meta(**overrides: object) -> MagicMock:+ meta = MagicMock()+ meta.is_fork = overrides.get("is_fork", False)+ meta.state = overrides.get("state", "open")+ meta.head_sha = overrides.get("head_sha", "abc123")+ return meta+++class TestReviewHogUiTriggerApi(APIBaseTest):+ def _trigger(self, pr_url: str):+ return self.client.post(+ f"/api/projects/{self.team.id}/review_hog/reviews/trigger/", {"pr_url": pr_url}, format="json"+ )++ @patch(_META, return_value=_pr_meta())+ @patch(_ACCESS, return_value=object())+ @patch(_START, return_value="wf-ui-1")+ def test_trigger_starts_a_publishing_workflow_acting_as_the_requester(self, mock_start, mock_access, _mock_meta):+ # The URL is canonicalized (trailing /files dropped) and the requester is both the run user+ # and the acting user — losing the override would make the review follow the PR author's+ # perspectives instead of the person who asked for it.+ with override_settings(REVIEWHOG_TEAM_ID=self.team.id):+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123/files")++ self.assertEqual(resp.status_code, status.HTTP_202_ACCEPTED, resp.content)+ self.assertEqual(resp.json(), {"workflow_id": "wf-ui-1", "status": "started"})+ mock_access.assert_called_once_with(self.team.id, "PostHog/posthog.com")+ mock_start.assert_called_once_with(+ pr_url="https://github.com/PostHog/posthog.com/pull/123",+ team_id=self.team.id,+ user_id=self.user.id,+ publish=True,+ acting_user_id=self.user.id,+ trigger_source="ui",+ )++ @parameterized.expand(+ [+ ("team_unset", None),+ ("other_team", 999_999),+ ]+ )+ @patch(_START)+ def test_rejected_unless_the_project_is_the_reviewhog_team(self, _name, team_setting, mock_start):+ with override_settings(REVIEWHOG_TEAM_ID=team_setting):+ resp = self._trigger("https://github.com/PostHog/posthog/pull/1")++ self.assertEqual(resp.status_code, status.HTTP_403_FORBIDDEN)+ mock_start.assert_not_called()++ @patch(_START)+ def test_non_pr_github_url_rejected(self, mock_start):+ with override_settings(REVIEWHOG_TEAM_ID=self.team.id):+ resp = self._trigger("https://github.com/PostHog/posthog/issues/1")++ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)+ mock_start.assert_not_called()++ @patch(_ACCESS, return_value=None)+ @patch(_START)+ def test_inaccessible_repository_rejected_without_starting_a_workflow(self, mock_start, _mock_access):+ with override_settings(REVIEWHOG_TEAM_ID=self.team.id):+ resp = self._trigger("https://github.com/other-org/private-repo/pull/5")++ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertIn("can't access other-org/private-repo", resp.json()["error"])+ mock_start.assert_not_called()++ @parameterized.expand(+ [+ ("nonexistent", GitHubAPIError("not found", status=404), "No pull request #7"),+ ("fork", _pr_meta(is_fork=True), "fork"),+ ("closed", _pr_meta(state="closed"), "closed"),+ ]+ )+ @patch(_ACCESS, return_value=object())+ @patch(_START)+ def test_unreviewable_pr_rejected_synchronously(self, _name, meta_or_error, message, mock_start, _mock_access):+ # Without the sync PR fetch these die async in the fetch activity, before the report row+ # exists — the UI shows "started" and then nothing ever appears.+ side_effect = meta_or_error if isinstance(meta_or_error, Exception) else None+ return_value = None if side_effect else meta_or_error+ with (+ override_settings(REVIEWHOG_TEAM_ID=self.team.id),+ patch(_META, side_effect=side_effect, return_value=return_value),+ ):+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/7")++ self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST, resp.content)+ self.assertIn(message, resp.json()["error"])+ mock_start.assert_not_called()++ @parameterized.expand(+ [+ # Published at the PR's current head: honesty response, no run. The row's lowercased+ # repository pins the cross-trigger casing match (__iexact) — other triggers store the+ # casing they were called with.+ ("already_reviewed_at_head", "abc123", status.HTTP_200_OK, "already_reviewed", False),+ ("head_advanced_since_publish", "older-sha", status.HTTP_202_ACCEPTED, "started", True),+ ]+ )+ @patch(_META, return_value=_pr_meta(head_sha="abc123"))+ @patch(_ACCESS, return_value=object())+ @patch(_START, return_value="wf-ui-2")+ def test_already_published_head_answers_honestly(+ self, _name, published_head_sha, expected_status, expected_marker, starts, mock_start, _mock_access, _mock_meta+ ):+ ReviewReport.objects.for_team(self.team.id).create(+ team_id=self.team.id,+ repository="posthog/posthog.com",+ pr_number=123,+ pr_url="https://github.com/PostHog/posthog.com/pull/123",+ head_branch="feat-branch",+ base_branch="master",+ published_head_sha=published_head_sha,+ )+ with override_settings(REVIEWHOG_TEAM_ID=self.team.id):+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/123")++ self.assertEqual(resp.status_code, expected_status, resp.content)+ self.assertEqual(resp.json()["status"], expected_marker)+ self.assertEqual(mock_start.called, starts)++ @parameterized.expand(+ [+ ("at_access_check", _ACCESS),+ ("at_pr_fetch", _META),+ ]+ )+ @patch(_START)+ def test_github_rate_limit_maps_to_the_shared_429(self, _name, rate_limited_call, mock_start):+ # Both GitHub calls must map through github_rate_limited_response — an unwrapped call+ # surfaces a 500 to the person clicking Review, exactly during retry-prone windows.+ with (+ override_settings(REVIEWHOG_TEAM_ID=self.team.id),+ patch(_ACCESS, return_value=object()),+ patch(rate_limited_call, side_effect=GitHubRateLimitError("rate limited", retry_after=30)),+ ):+ resp = self._trigger("https://github.com/PostHog/posthog.com/pull/9")++ self.assertEqual(resp.status_code, status.HTTP_429_TOO_MANY_REQUESTS, resp.content)+ self.assertEqual(resp.json()["code"], "rate_limited")+ self.assertEqual(resp["Retry-After"], "30")+ mock_start.assert_not_called()++ @parameterized.expand(+ [+ ("reviewhog_team", True),+ ("other_team", False),+ ]+ )+ def test_settings_expose_whether_reviews_can_be_triggered_here(self, _name, is_reviewhog_team):+ with override_settings(REVIEWHOG_TEAM_ID=self.team.id if is_reviewhog_team else self.team.id + 1):+ resp = self.client.get(f"/api/projects/{self.team.id}/review_hog/settings/")++ self.assertEqual(resp.status_code, status.HTTP_200_OK)+ self.assertEqual(resp.json()["can_trigger_reviews"], is_reviewhog_team)diff --git a/products/review_hog/frontend/CodeReviewScene.tsx b/products/review_hog/frontend/CodeReviewScene.tsxindex cb4f181c0c47..18aaa449206a 100644--- a/products/review_hog/frontend/CodeReviewScene.tsx+++ b/products/review_hog/frontend/CodeReviewScene.tsx@@ -16,6 +16,7 @@ import {import {LemonBanner,LemonButton,+ LemonInput,LemonSegmentedButton,LemonSkeleton,LemonSlider,@@ -585,6 +586,50 @@ function RecentReviewsSection(): JSX.Element | null {)}+/**+ * "Review a pull request": paste any PR URL the project's GitHub App installation can access and+ * start a publishing review, acting as the requesting user. Hidden unless the backend says this+ * project can trigger reviews (limited to the designated ReviewHog team while in alpha).+ */+function TriggerReviewSection(): JSX.Element | null {+ const { settings, triggerPrUrl, triggeringReview } = useValues(reviewHogSettingsLogic)+ const { setTriggerPrUrl, submitTriggerReview } = useActions(reviewHogSettingsLogic)++ if (!settings?.can_trigger_reviews) {+ return null+ }+ return (+ <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 your recent reviews.+ </SectionHeader>+ <form+ className="ml-9 flex flex-wrap items-center gap-2"+ onSubmit={(e) => {+ e.preventDefault()+ submitTriggerReview()+ }}+ >+ <LemonInput+ className="min-w-80 flex-1"+ placeholder="https://github.com/posthog/posthog.com/pull/1234"+ value={triggerPrUrl}+ onChange={setTriggerPrUrl}+ />+ <LemonButton+ type="primary"+ htmlType="submit"+ loading={triggeringReview}+ disabledReason={!triggerPrUrl.trim() ? 'Paste a pull request URL first' : undefined}+ >+ Review+ </LemonButton>+ </form>+ </section>+ )+}+type FindingSection = 'description' | 'suggestion' | 'validator'function FindingCard({ finding, dismissed }: { finding: ReviewFindingApi; dismissed?: boolean }): JSX.Element {@@ -1492,6 +1537,7 @@ export function CodeReviewScene(): JSX.Element {</LemonBanner>)}+ <TriggerReviewSection /><RecentReviewsSection /><PipelineSection /><TriggersSection />diff --git a/products/review_hog/frontend/generated/api.schemas.ts b/products/review_hog/frontend/generated/api.schemas.tsindex 5af61b03068d..96e1a682fae7 100644--- a/products/review_hog/frontend/generated/api.schemas.ts+++ b/products/review_hog/frontend/generated/api.schemas.ts@@ -416,6 +416,23 @@ export interface ReviewPerspectiveStatsApi {perspectives: ReviewPerspectiveStatItemApi[]}+export interface ReviewTriggerRequestApi {+ /** GitHub pull request URL to review, e.g. 'https://github.com/PostHog/posthog.com/pull/123'. The repository must be accessible to the project's GitHub App installation. */+ pr_url: string+}++export interface ReviewTriggerResponseApi {+ /** Temporal workflow id for the started review run; empty when no run was started. */+ workflow_id: string+ /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts). */+ status: string+}++export interface ReviewTriggerErrorApi {+ /** Human-readable explanation of why the trigger was rejected. */+ error: string+}+/*** * `consider` - Consider* * `should_fix` - Should Fix@@ -440,6 +457,8 @@ export interface ReviewUserSettingsApi {* * `should_fix` - Should Fix* * `must_fix` - Must Fix */urgency_threshold?: UrgencyThresholdEnumApi+ /** Whether reviews can be started from this project's Code review page (the UI trigger is limited to the designated ReviewHog team while the product is in alpha). */+ readonly can_trigger_reviews: boolean}export interface PatchedReviewUserSettingsApi {@@ -453,6 +472,8 @@ export interface PatchedReviewUserSettingsApi {* * `should_fix` - Should Fix* * `must_fix` - Must Fix */urgency_threshold?: UrgencyThresholdEnumApi+ /** Whether reviews can be started from this project's Code review page (the UI trigger is limited to the designated ReviewHog team while the product is in alpha). */+ readonly can_trigger_reviews?: boolean}export interface ReviewValidatorConfigApi {diff --git a/products/review_hog/frontend/generated/api.ts b/products/review_hog/frontend/generated/api.tsindex d9257c983153..0cd0cefea574 100644--- a/products/review_hog/frontend/generated/api.ts+++ b/products/review_hog/frontend/generated/api.ts@@ -19,10 +19,29 @@ import type {ReviewPerspectiveConfigApi,ReviewPerspectiveStatsApi,ReviewRecentReviewsPageApi,+ ReviewTriggerRequestApi,+ ReviewTriggerResponseApi,ReviewUserSettingsApi,ReviewValidatorConfigApi,} from './api.schemas'+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B++type WritableKeys<T> = {+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>+}[keyof T]++type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never++type Writable<T> = Pick<T, WritableKeys<T>>+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]+ ? {+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]+ }+ : DistributeReadOnlyOverUnions<T>+export const getReviewHogBlindSpotsListUrl = (projectId: string) => {return `/api/projects/${projectId}/review_hog/blind_spots/`}@@ -171,6 +190,27 @@ export const reviewHogReviewsPerspectiveStatsRetrieve = async (})}+export const getReviewHogReviewsTriggerCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/review_hog/reviews/trigger/`+}++/**+ * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, and urgency threshold drive the run, and it appears under their recent reviews. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run, and triggering a PR whose review is currently running joins the in-flight run. Otherwise non-blocking: returns the Temporal workflow id immediately while the review runs in the worker.+ * @summary Start a review of a pull request+ */+export const reviewHogReviewsTriggerCreate = async (+ projectId: string,+ reviewTriggerRequestApi: ReviewTriggerRequestApi,+ options?: RequestInit+): Promise<ReviewTriggerResponseApi> => {+ return apiMutator<ReviewTriggerResponseApi>(getReviewHogReviewsTriggerCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(reviewTriggerRequestApi),+ })+}+export const getReviewHogSettingsRetrieveUrl = (projectId: string) => {return `/api/projects/${projectId}/review_hog/settings/`}@@ -199,7 +239,7 @@ export const getReviewHogSettingsPartialUpdateUrl = (projectId: string) => {*/export const reviewHogSettingsPartialUpdate = async (projectId: string,- patchedReviewUserSettingsApi?: PatchedReviewUserSettingsApi,+ patchedReviewUserSettingsApi?: NonReadonly<PatchedReviewUserSettingsApi>,options?: RequestInit): Promise<ReviewUserSettingsApi> => {return apiMutator<ReviewUserSettingsApi>(getReviewHogSettingsPartialUpdateUrl(projectId), {diff --git a/products/review_hog/frontend/generated/api.zod.ts b/products/review_hog/frontend/generated/api.zod.tsindex e4649ae4538c..2e1c035f2418 100644--- a/products/review_hog/frontend/generated/api.zod.ts+++ b/products/review_hog/frontend/generated/api.zod.ts@@ -33,6 +33,18 @@ export const ReviewHogPerspectivesPartialUpdateBody = /* @__PURE__ */ zod.object.describe("Set true to run this perspective on the user's PR reviews, false to stop running it."),})+/**+ * Start a ReviewHog review of any pull request the project's GitHub App installation can access, and publish it back to the PR. The requesting user is the review's acting user: their enabled perspectives, blind-spot check, validator, and urgency threshold drive the run, and it appears under their recent reviews. Nonexistent, closed, and fork PRs are rejected synchronously; a PR whose current commit already has a published review returns 'already_reviewed' without starting a run, and triggering a PR whose review is currently running joins the in-flight run. Otherwise non-blocking: returns the Temporal workflow id immediately while the review runs in the worker.+ * @summary Start a review of a pull request+ */+export const ReviewHogReviewsTriggerCreateBody = /* @__PURE__ */ zod.object({+ pr_url: zod+ .string()+ .describe(+ "GitHub pull request URL to review, e.g. 'https:\/\/github.com\/PostHog\/posthog.com\/pull\/123'. The repository must be accessible to the project's GitHub App installation."+ ),+})+/*** Partially update the requesting user's ReviewHog settings for this project. Only the provided fields change.* @summary Update the user's ReviewHog settingsdiff --git a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts b/products/review_hog/frontend/reviewHogSettingsLogic.test.tsindex a8ccf3b8497e..9989d0308dd0 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.test.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.test.ts@@ -41,6 +41,12 @@ describe('reviewHogSettingsLogic', () => {'/api/projects/:team_id/review_hog/blind_spots/': () => [200, []],'/api/projects/:team_id/review_hog/validators/': () => [200, []],},+ post: {+ '/api/projects/:team_id/review_hog/reviews/trigger/': () => [+ 202,+ { workflow_id: 'wf-1', status: 'started' },+ ],+ },})// The scope reducers persist; without this a prior test's explicit choice leaks over.localStorage.clear()@@ -68,6 +74,107 @@ describe('reviewHogSettingsLogic', () => {expect(router.values.searchParams.reviews_scope).toBeUndefined()})+ 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.+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])+ logic.actions.setTriggerPrUrl('https://github.com/PostHog/posthog.com/pull/1')++ await expectLogic(logic, () => logic.actions.submitTriggerReview())+ .toDispatchActions([+ 'submitTriggerReview',+ 'startTriggeredReviewWatch',+ 'loadRecentReviews',+ 'submitTriggerReviewFinished',+ ])+ .toMatchValues({ triggeringReview: false, triggerPrUrl: '' })+ // The report row is created seconds after the 202; the watch keeps the list polling until+ // it appears — without it the poll only arms when another review is already running.+ expect(logic.values.awaitingTriggeredReview).toBe(true)+ })++ it('a repeat submit while a request is in flight does not start a second review', async () => {+ // The disabled button can't stop an Enter keypress in the input, so the listener must drop+ // repeats itself — without the guard each keypress POSTs another trigger.+ let triggerCalls = 0+ useMocks({+ post: {+ '/api/projects/:team_id/review_hog/reviews/trigger/': () => {+ triggerCalls+++ return [202, { workflow_id: 'wf-1', status: 'started' }]+ },+ },+ })+ logic.mount()+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])+ logic.actions.setTriggerPrUrl('https://github.com/PostHog/posthog.com/pull/1')++ logic.actions.submitTriggerReview()+ logic.actions.submitTriggerReview()+ await expectLogic(logic).toDispatchActions(['submitTriggerReviewFinished'])++ expect(triggerCalls).toBe(1)+ })++ it('an already-reviewed PR informs without arming the watch', async () => {+ useMocks({+ post: {+ '/api/projects/:team_id/review_hog/reviews/trigger/': () => [+ 200,+ { workflow_id: '', status: 'already_reviewed' },+ ],+ },+ })+ logic.mount()+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])+ logic.actions.setTriggerPrUrl('https://github.com/PostHog/posthog.com/pull/1')++ // Arming the watch here would poll for two minutes waiting for a run that never starts.+ await expectLogic(logic, () => logic.actions.submitTriggerReview())+ .toDispatchActions(['submitTriggerReview', 'loadRecentReviews', 'submitTriggerReviewFinished'])+ .toNotHaveDispatchedActions(['startTriggeredReviewWatch'])+ .toMatchValues({ triggeringReview: false, triggerPrUrl: '', awaitingTriggeredReview: false })+ })++ it('a rejected trigger resets the in-flight flag and keeps the input for correction', async () => {+ useMocks({+ post: {+ '/api/projects/:team_id/review_hog/reviews/trigger/': () => [+ 403,+ { error: "ReviewHog reviews can't be started from this project yet" },+ ],+ },+ })+ logic.mount()+ await expectLogic(logic).toDispatchActions([+ 'loadRecentReviewsSuccess',+ 'applyDefaultReviewsScope',+ 'loadRecentReviewsSuccess',+ ])+ logic.actions.setTriggerPrUrl('https://github.com/PostHog/posthog.com/pull/1')++ await expectLogic(logic, () => logic.actions.submitTriggerReview())+ .toDispatchActions(['submitTriggerReview', 'submitTriggerReviewFinished'])+ .toNotHaveDispatchedActions(['loadRecentReviews', 'startTriggeredReviewWatch'])+ .toMatchValues({+ triggeringReview: false,+ triggerPrUrl: 'https://github.com/PostHog/posthog.com/pull/1',+ awaitingTriggeredReview: false,+ })+ })+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.diff --git a/products/review_hog/frontend/reviewHogSettingsLogic.ts b/products/review_hog/frontend/reviewHogSettingsLogic.tsindex 0516461ee7be..fe8a6fdc3a7a 100644--- a/products/review_hog/frontend/reviewHogSettingsLogic.ts+++ b/products/review_hog/frontend/reviewHogSettingsLogic.ts@@ -17,6 +17,7 @@ import {reviewHogReviewsList,reviewHogReviewsPerspectiveStatsRetrieve,reviewHogReviewsRetrieve,+ reviewHogReviewsTriggerCreate,reviewHogSettingsPartialUpdate,reviewHogSettingsRetrieve,reviewHogValidatorsList,@@ -50,6 +51,11 @@ 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+// How long after triggering a review the list keeps polling for its report row to appear — the row+// is created seconds after the 202 by the workflow's fetch step, but a run that dies before creating+// it must not keep the list polling forever.+const TRIGGERED_REVIEW_WATCH_TIMEOUT_MS = 2 * 60 * 1000+/** The review list's initial depth, the step each "Show more" adds, and what "Show fewer" collapses to. */export const REVIEWS_PAGE_SIZE = 5@@ -119,6 +125,7 @@ function currentProjectId(): string {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface reviewHogSettingsLogicValues {+ awaitingTriggeredReview: booleanblindSpots: ReviewBlindSpotsConfigApi[] | nullblindSpotsLoading: booleancreatingSkillKind: ReviewSkillKind | null@@ -147,6 +154,8 @@ export interface reviewHogSettingsLogicValues {settings: ReviewUserSettingsApi | nullsettingsLoading: booleanskillDrawerOpen: boolean+ triggerPrUrl: string+ triggeringReview: booleanvalidators: ReviewValidatorConfigApi[] | nullvalidatorsLoading: booleanviewedSkill: ViewedSkill | null@@ -303,6 +312,9 @@ export interface reviewHogSettingsLogicActions {saving: booleanskillName: string}+ setTriggerPrUrl: (prUrl: string) => {+ prUrl: string+ }showFewerReviews: () => {value: true}@@ -315,6 +327,21 @@ export interface reviewHogSettingsLogicActions {startSkillAuthorTaskFinished: () => {value: true}+ startTriggeredReviewWatch: () => {+ value: true+ }+ stopTriggeredReviewWatch: () => {+ value: true+ }+ submitTriggerReview: () => {+ value: true+ }+ submitTriggerReviewFinished: () => {+ value: true+ }+ submitTriggerReviewStarted: () => {+ value: true+ }togglePerspective: (skillName: string,enabled: boolean@@ -400,6 +427,16 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([applyDefaultReviewsScope: (scope: ReviewHogReviewsListScope) => ({ scope }),startSkillAuthorTask: (kind: ReviewSkillKind) => ({ kind }),startSkillAuthorTaskFinished: true,+ setTriggerPrUrl: (prUrl: string) => ({ prUrl }),+ // Starts a review of the pasted PR URL. The listener self-guards on `triggeringReview`, so a+ // repeat dispatch mid-flight (Enter spam, double click) is a no-op regardless of the source.+ submitTriggerReview: true,+ submitTriggerReviewStarted: true,+ submitTriggerReviewFinished: true,+ // Keeps the recent-reviews poll alive until a just-triggered review's report row appears —+ // without it the poll only arms when some other review is already visibly running.+ startTriggeredReviewWatch: true,+ stopTriggeredReviewWatch: true,}),loaders(({ values }) => ({@@ -609,6 +646,28 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([startSkillAuthorTaskFinished: () => null,},],+ triggerPrUrl: [+ '',+ {+ setTriggerPrUrl: (_, { prUrl }) => prUrl,+ },+ ],+ triggeringReview: [+ false,+ {+ // Flipped by the listener (not the submit action itself) so the listener can tell a+ // first submit from an Enter-spam repeat and drop the repeat before it POSTs.+ submitTriggerReviewStarted: () => true,+ submitTriggerReviewFinished: () => false,+ },+ ],+ awaitingTriggeredReview: [+ false,+ {+ startTriggeredReviewWatch: () => true,+ stopTriggeredReviewWatch: () => false,+ },+ ],}),selectors({@@ -665,10 +724,16 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([}),listeners(({ actions, values, cache }) => ({- // Poll while any review is running so the stage row moves; the disposable auto-pauses on- // hidden tabs and is torn down on unmount.+ // Poll while any review is running so the stage row moves — or while a just-triggered+ // review's row hasn't appeared yet; the disposable auto-pauses on hidden tabs and is torn+ // down on unmount.loadRecentReviewsSuccess: () => {- if (values.recentReviews?.some((review) => review.in_progress)) {+ const anyInProgress = values.recentReviews?.some((review) => review.in_progress) ?? false+ // The watch deliberately runs its full bounded window instead of stopping when an+ // in-progress row shows up: an unrelated already-running review would satisfy that check+ // and could finish before the triggered row appears, killing the poll too early. The+ // cost is at most the watch window of idle 10s polls after a fast run completes.+ if (anyInProgress || values.awaitingTriggeredReview) {cache.disposables.add(() => {const pollTimer = window.setInterval(() => actions.loadRecentReviews(),@@ -689,6 +754,20 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([actions.applyDefaultReviewsScope(ReviewHogReviewsListScope.Everyone)}},+ startTriggeredReviewWatch: () => {+ // Bounded: a run that dies before creating its report row must not poll forever. The+ // next list load after expiry sees no in-progress rows and disposes the poll itself.+ cache.disposables.add(() => {+ const expiryTimer = window.setTimeout(+ () => actions.stopTriggeredReviewWatch(),+ TRIGGERED_REVIEW_WATCH_TIMEOUT_MS+ )+ return () => clearTimeout(expiryTimer)+ }, 'triggeredReviewWatch')+ },+ stopTriggeredReviewWatch: () => {+ cache.disposables.dispose('triggeredReviewWatch')+ },setReviewsScope: () => actions.loadRecentReviews(),applyDefaultReviewsScope: () => actions.loadRecentReviews(),showMoreReviews: () => actions.loadRecentReviews(),@@ -758,6 +837,39 @@ export const reviewHogSettingsLogic = kea<reviewHogSettingsLogicType>([openReviewDetail: ({ review }) => {actions.loadReviewDetail(review.id)},+ submitTriggerReview: async () => {+ if (values.triggeringReview) {+ // A request is already in flight — the disabled button can't stop an Enter keypress+ // in the input, so the guard lives here, covering every dispatch source.+ return+ }+ const prUrl = values.triggerPrUrl.trim()+ if (!prUrl) {+ return+ }+ actions.submitTriggerReviewStarted()+ try {+ const response = await reviewHogReviewsTriggerCreate(currentProjectId(), { pr_url: prUrl })+ actions.setTriggerPrUrl('')+ if (response.status === 'already_reviewed') {+ // No run started — the PR's current commit already has a published review.+ lemonToast.info(+ 'This pull request was already reviewed at its current commit. Find it under recent reviews.'+ )+ } else {+ lemonToast.success('Review started. It will appear under recent reviews as it runs.')+ // The review's report row is created seconds later by the workflow's fetch step,+ // so one immediate reload usually misses it — arm the watch before reloading.+ actions.startTriggeredReviewWatch()+ }+ actions.loadRecentReviews()+ } catch (error: any) {+ // The trigger endpoint's rejections come back as `{error: "..."}` bodies.+ lemonToast.error(error?.data?.error || error?.detail || error?.message || 'Failed to start the review')+ } finally {+ actions.submitTriggerReviewFinished()+ }+ },startSkillAuthorTask: async ({ kind }) => {// Task-kickoff mirroring the Inbox "Make a scout" flow: create an agent task from a// templated authoring prompt, then navigate to it. Not a live chat.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3865665043f1..eb7be06c357b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -46875,6 +46875,8 @@ export namespace Schemas {* * `should_fix` - Should Fix* * `must_fix` - Must Fix */urgency_threshold?: UrgencyThresholdEnum;+ /** Whether reviews can be started from this project's Code review page (the UI trigger is limited to the designated ReviewHog team while the product is in alpha). */+ readonly can_trigger_reviews?: boolean;}export interface PatchedReviewValidatorConfigSelect {@@ -54990,6 +54992,23 @@ export namespace Schemas {stale: number;}+ export interface ReviewTriggerError {+ /** Human-readable explanation of why the trigger was rejected. */+ error: string;+ }++ export interface ReviewTriggerRequest {+ /** GitHub pull request URL to review, e.g. 'https://github.com/PostHog/posthog.com/pull/123'. The repository must be accessible to the project's GitHub App installation. */+ pr_url: string;+ }++ export interface ReviewTriggerResponse {+ /** Temporal workflow id for the started review run; empty when no run was started. */+ workflow_id: string;+ /** Run lifecycle marker: 'started' when the review was queued, 'already_reviewed' when the pull request's current commit already has a published review (no new run starts). */+ status: string;+ }+export interface ReviewUserSettings {/** Automatically review pull requests opened by PostHog agents from the user's Inbox. Stored but not consumed yet — the Inbox auto-review trigger is not built. */review_inbox_prs?: boolean;@@ -55001,6 +55020,8 @@ export namespace Schemas {* * `should_fix` - Should Fix* * `must_fix` - Must Fix */urgency_threshold?: UrgencyThresholdEnum;+ /** Whether reviews can be started from this project's Code review page (the UI trigger is limited to the designated ReviewHog team while the product is in alpha). */+ readonly can_trigger_reviews: boolean;}export interface ReviewValidatorConfig {