: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
fix(visual-review): make finalize the single ship action (#61107)
Julian Bezb2f0d56bf4bf
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex 18147c739830..1d0f8a348045 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -22,7 +22,6 @@ from django.contrib.auth import get_user_modelfrom .. import logicfrom ..diff_metadata import DiffMetadatafrom . import contracts-from .enums import ReviewDecisionUser = get_user_model()@@ -54,6 +53,7 @@ GitHubCommitError = logic.GitHubCommitErrorGitHubRateLimitError = logic.GitHubRateLimitErrorPRSHAMismatchError = logic.PRSHAMismatchErrorStaleRunError = logic.StaleRunError+RunNotFullyResolvedError = logic.RunNotFullyResolvedErrorBaselineFilePathNotConfiguredError = logic.BaselineFilePathNotConfiguredError@@ -468,31 +468,11 @@ def recompute_run(run_id: UUID, team_id: int | None = None) -> contracts.Recompu)-def approve_all(- run_id: UUID,- user_id: int,- team_id: int | None = None,- review_decision: ReviewDecision = ReviewDecision.HUMAN_APPROVED,- commit_to_github: bool = True,-) -> contracts.AutoApproveResult:- run, baseline_content = logic.approve_all(- run_id=run_id,- user_id=user_id,- team_id=team_id,- review_decision=review_decision,- commit_to_github=commit_to_github,- )- return contracts.AutoApproveResult(- run=_to_run(run),- baseline_content=baseline_content,- )-+def approve_snapshots(input: contracts.ApproveRunInput, team_id: int | None = None) -> contracts.Run:+ """Mark specific snapshots reviewed (DB only — no baseline commit, no gate change).-def approve_run(input: contracts.ApproveRunInput, team_id: int | None = None) -> contracts.Run:- """Approve specific snapshots (DB only).-- For full run finalization with GitHub commit, use approve_all=true- which routes through auto_approve_run.+ This is the per-snapshot "Accept change" triage action. Shipping the run (committing+ the baseline and greening the gate) happens via finalize_run."""approved_snapshots = [{"identifier": s.identifier, "new_hash": s.new_hash} for s in input.snapshots]run = logic.approve_snapshots(@@ -504,6 +484,30 @@ def approve_run(input: contracts.ApproveRunInput, team_id: int | None = None) ->return _to_run(run)+def finalize_run(+ run_id: UUID,+ user_id: int,+ team_id: int | None = None,+ approve_all: bool = False,+ commit_to_github: bool = True,+) -> contracts.FinalizeResult:+ """Finalize a fully-reviewed run: commit the approved baseline and green the gate.++ The single ship action. Commits exactly the snapshots approved in the DB (tolerated+ ones are left alone) and only succeeds once every changed/new snapshot is resolved.+ With ``approve_all=True`` any still-pending snapshot is approved first. The pushed+ baseline commit SHA is surfaced on ``run.metadata["baseline_commit_sha"]``.++ With ``commit_to_github=False`` the server skips the commit and returns the signed+ baseline YAML on ``baseline_content`` instead (for tooling that commits it itself).+ """+ run = logic.finalize_run(+ run_id=run_id, user_id=user_id, team_id=team_id, approve_all=approve_all, commit_to_github=commit_to_github+ )+ baseline_content = "" if commit_to_github else logic.build_signed_baseline(run_id, team_id=team_id)+ return contracts.FinalizeResult(run=_to_run(run), baseline_content=baseline_content)++# --- Quarantine ---diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex 28c43f2bc37d..44fef74f5040 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -73,20 +73,25 @@ class ApproveSnapshotInput:@dataclass(frozen=True)class ApproveRunRequestInput:- """Request body for approving a run. run_id and user_id come from URL and auth."""+ """Request body for marking snapshots reviewed (DB only). run_id and user_id come from URL and auth."""snapshots: list[ApproveSnapshotInput] = field(default_factory=list)- approve_all: bool = False- commit_to_github: bool = True@dataclass(frozen=True)class ApproveRunInput:- """Full input for approving visual changes (internal use)."""+ """Full input for marking snapshots reviewed (internal use)."""run_id: UUIDuser_id: intsnapshots: list[ApproveSnapshotInput]+++@dataclass(frozen=True)+class FinalizeRunRequestInput:+ """Request body for finalizing a run. run_id and user_id come from URL and auth."""++ approve_all: bool = Falsecommit_to_github: bool = True@@ -252,8 +257,12 @@ class Run:@dataclass(frozen=True)-class AutoApproveResult:- """Result of auto-approving a run, including the signed baseline YAML."""+class FinalizeResult:+ """Result of finalizing a run: the run plus the signed baseline YAML.++ ``baseline_content`` is populated only when ``commit_to_github=False`` (the caller commits+ the baseline itself); it is empty when the server already committed it to the PR branch.+ """run: Runbaseline_content: strdiff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex dcb54c0665ec..8710505ad248 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -8,6 +8,7 @@ Called by api/api.py facade. Do not call from outside this module.from __future__ import annotationsfrom collections import Counter+from collections.abc import Iterablefrom dataclasses import dataclassfrom datetime import datetimefrom typing import TYPE_CHECKING@@ -89,6 +90,18 @@ class StaleRunError(Exception):pass+class RunNotFullyResolvedError(Exception):+ """Finalize blocked because some changed/new snapshots are still unreviewed.++ Visual review is all-or-nothing: the baseline is only committed once every+ changed/new snapshot is approved or tolerated. Committing a subset is pointless+ (CI re-detects the rest on the next run) and would green the gate over unreviewed+ changes.+ """++ pass++class BaselineFilePathNotConfiguredError(Exception):"""Repo does not have a baseline file path configured for this run type."""@@ -1040,6 +1053,21 @@ def _is_unresolved(s: RunSnapshot) -> bool:return True+def _approved_baseline_updates(snapshots: Iterable[RunSnapshot]) -> list[dict]:+ """The committed-baseline update set: approved changed/new snapshots, by approved hash.++ Derived from DB state so the commit always reflects every approval regardless of how+ many calls it took. Tolerated snapshots are excluded — toleration never updates the baseline.+ """+ return [+ {"identifier": s.identifier, "new_hash": s.approved_hash}+ for s in snapshots+ if s.result in (SnapshotResult.CHANGED, SnapshotResult.NEW)+ and not s.is_quarantined+ and s.review_state == ReviewState.APPROVED+ ]++def _update_counts_and_post_status(run: Run) -> int:"""Re-stamp quarantine, recount snapshots, compute unresolved, and post commit status.@@ -1073,6 +1101,11 @@ def _update_counts_and_post_status(run: Run) -> int:unresolved = sum(1 for s in snapshots if _is_unresolved(s))+ # Approved-but-uncommitted changes still block the gate: the baseline on the PR branch+ # doesn't reflect them yet, so re-running CI would re-detect them. Only finalize commits+ # the baseline (and posts success directly), so until then the gate must stay red.+ pending_commit = 0 if run.approved else len(_approved_baseline_updates(snapshots))+repo = run.repoif run.error_message:_post_commit_status(run, repo, "error", f"Visual review failed: {run.error_message[:100]}")@@ -1086,6 +1119,13 @@ def _update_counts_and_post_status(run: Run) -> int:parts.append(f"{run.removed_count} removed")_post_commit_status(run, repo, "failure", f"Visual changes detected: {', '.join(parts)}")_post_review_prompt_comment(run, repo)+ elif pending_commit > 0:+ _post_commit_status(+ run,+ repo,+ "failure",+ f"{pending_commit} approved change(s) awaiting commit — finalize the run to update the baseline",+ )else:_post_commit_status(run, repo, "success", "No visual changes")@@ -1825,131 +1865,152 @@ def post_approval_comment_for_run(run_id: UUID, team_id: int | None = None) -> N@transaction.atomic(using=WRITER_DB)-def approve_all(+def finalize_run(run_id: UUID,user_id: int,team_id: int | None = None,+ approve_all: bool = False,review_decision: ReviewDecision = ReviewDecision.HUMAN_APPROVED,commit_to_github: bool = True,-) -> tuple[Run, str]:- """Approve all actionable snapshots and return signed baseline YAML.+) -> Run:+ """Finalize a fully-reviewed run: commit the approved baseline and green the gate.- Collects all CHANGED + NEW snapshots, approves them via approve_run,- and builds a signed baseline YAML. REMOVED snapshots are handled by- approve_run (marked as approved + pruned from baseline).+ All-or-nothing by design — a run finalizes only once every changed/new snapshot is+ resolved (approved, tolerated, quarantined, or removed). The committed baseline is+ derived from DB state — exactly the snapshots with ``review_state == APPROVED``, by+ their approved hash — so a tolerated snapshot keeps its existing baseline and is+ never silently overwritten, and the commit always contains the full approved set+ regardless of how many calls it took to review them.- The caller controls review_decision:- - HUMAN_APPROVED: UI "Approve all changes" button- - AUTO_APPROVED: CLI --auto-approve during CI+ With ``approve_all=True`` every still-pending changed/new snapshot is approved first+ (tolerated ones are left untouched) — the "approve everything and ship" path. Without+ it, the run must already be fully resolved or this raises RunNotFullyResolvedError.- Set commit_to_github=False for CLI (writes baseline locally).+ Set ``commit_to_github=False`` for CLI auto-approve, which writes the baseline locally+ instead of pushing it to the PR branch."""run = _get_run_for_update(run_id, team_id=team_id)repo = run.repo+ if run.purpose == RunPurpose.OBSERVE:+ raise ValueError("Observational runs cannot be approved")++ # Idempotent: a finalized run already committed and posted status — don't redo the work+ # (a second commit, status, and approval comment) on a repeat call.+ if run.approved:+ return run+if run.status != RunStatus.COMPLETED:raise ValueError(f"Run must be completed before approval (current status: {run.status})")if is_run_stale(run):- raise StaleRunError("This run has been superseded by a newer run.")+ raise StaleRunError("This run has been superseded by a newer run. Approve the latest run instead.")- # Collect all actionable snapshots (changed + new have hashes to approve)- needs_approval = [- {"identifier": s.identifier, "new_hash": s.current_hash}- for s in run.snapshots.all()- if s.result in (SnapshotResult.CHANGED, SnapshotResult.NEW)+ # Re-evaluate quarantine so resolution accounting reflects the current policy.+ _stamp_quarantine(run)+ now = timezone.now()++ actionable = [+ s+ for s in run.snapshots.using(WRITER_DB).all()+ if s.result in (SnapshotResult.CHANGED, SnapshotResult.NEW) and not s.is_quarantined]- if not run.approved:- approve_run(- run_id=run_id,- user_id=user_id,- team_id=team_id,- approved_snapshots=needs_approval,- review_decision=review_decision,- commit_to_github=commit_to_github,+ if approve_all:+ pending = [s for s in actionable if s.review_state not in (ReviewState.APPROVED, ReviewState.TOLERATED)]+ _validate_approval(run, {s.identifier: s.current_hash for s in pending})+ for snapshot in pending:+ snapshot.review_state = ReviewState.APPROVED+ snapshot.reviewed_at = now+ snapshot.reviewed_by_id = user_id+ snapshot.approved_hash = snapshot.current_hash+ snapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "approved_hash"])++ # All-or-nothing: refuse to commit while any actionable snapshot is still unreviewed.+ unresolved = [+ s.identifier for s in actionable if s.review_state not in (ReviewState.APPROVED, ReviewState.TOLERATED)+ ]+ if unresolved:+ raise RunNotFullyResolvedError(+ f"Cannot finalize: {len(unresolved)} snapshot(s) still need review — approve or tolerate them first: "+ f"{', '.join(sorted(unresolved)[:10])}")- run = get_run_with_snapshots(run_id)- snapshots = list(run.snapshots.all().order_by("identifier"))+ # Commit set is derived from DB state, not a caller-supplied list, so it always reflects+ # the full approved set however many calls reviewed it.+ approved_updates = _approved_baseline_updates(actionable)+ has_removed = run.snapshots.using(WRITER_DB).filter(result=SnapshotResult.REMOVED).exists()- # Fetch current baseline from GitHub — the authoritative source.- # This ensures unchanged entries are preserved even in delta mode- # where unchanged snapshots have no RunSnapshot rows.- baseline_paths = repo.baseline_file_paths or {}- baseline_path = baseline_paths.get(run.run_type) or baseline_paths.get("default", ".snapshots.yml")- current_baselines: dict[str, dict] = {}+ # Commit first — before DB writes — so a GitHub failure aborts cleanly. Removed snapshots+ # also need a commit, to prune them from the baseline, even when nothing was approved.+ if commit_to_github and (approved_updates or has_removed) and run.pr_number and repo.repo_full_name:+ _commit_baseline_to_github(run, repo, approved_updates, approver_user_id=user_id)- github = get_github_integration_for_repo(repo)- if github.access_token_expired():- github.refresh_access_token()- current_baselines, _file_sha = _fetch_baseline_file(github, repo.repo_full_name, baseline_path, run.branch)+ # Removed snapshots are pruned from the baseline on commit; mark them approved for cleanup.+ run.snapshots.filter(result=SnapshotResult.REMOVED).update(+ review_state=ReviewState.APPROVED,+ reviewed_at=now,+ reviewed_by_id=user_id,+ )- # Remove entries that are now REMOVED — they should not persist in the baseline- removed_identifiers = {s.identifier for s in snapshots if s.result == SnapshotResult.REMOVED}- for identifier in removed_identifiers:- current_baselines.pop(identifier, None)+ run.approved = True+ run.review_decision = review_decision+ run.approved_at = now+ run.approved_by_id = user_id+ run.save(update_fields=["approved", "review_decision", "approved_at", "approved_by_id"])- # Apply changes from this run on top of the baseline- updates = [- {"identifier": s.identifier, "new_hash": s.current_hash}- for s in snapshots- if s.result in (SnapshotResult.CHANGED, SnapshotResult.NEW)- ]+ if commit_to_github:+ _post_commit_status(run, repo, "success", "Visual changes approved")- baseline_content = _build_snapshots_yaml(repo, current_baselines=current_baselines, updates=updates)- return run, baseline_content+ if commit_to_github and review_decision == ReviewDecision.HUMAN_APPROVED:+ from .tasks.tasks import post_approval_comment+ run_id_str = str(run.id)+ run_team_id = run.team_id+ transaction.on_commit(+ lambda: post_approval_comment.delay(run_team_id, run_id_str),+ using=WRITER_DB,+ )[email protected](using=WRITER_DB)-def approve_snapshots(run_id: UUID, user_id: int, approved_snapshots: list[dict], team_id: int | None = None) -> Run:- """Approve specific snapshots within a run (DB only, no GitHub commit).+ return run- Used for per-snapshot "Accept change" in the UI. Does not finalize- the run — that happens via approve_run.- """- run = _get_run_for_update(run_id, team_id=team_id)- if run.purpose == RunPurpose.OBSERVE:- raise ValueError("Observational runs cannot be approved")+def build_signed_baseline(run_id: UUID, team_id: int | None = None) -> str:+ """Build the signed baseline YAML for a finalized run, without committing it.- if is_run_stale(run):- raise StaleRunError("This run has been superseded by a newer run. Approve the latest run instead.")+ For callers that commit the baseline themselves (the CLI's auto-approve, which writes+ the file and commits via git rather than the GitHub App). Mirrors the committed set:+ the current baseline merged with the approved changed/new hashes, removed entries pruned.+ """+ run = get_run_with_snapshots(run_id, team_id=team_id)+ repo = run.repo- approvals = {s["identifier"]: s["new_hash"] for s in approved_snapshots}- _validate_approval(run, approvals)+ baseline_paths = repo.baseline_file_paths or {}+ baseline_path = baseline_paths.get(run.run_type) or baseline_paths.get("default", ".snapshots.yml")- now = timezone.now()- for snapshot in run.snapshots.filter(identifier__in=approvals.keys()):- new_hash = approvals[snapshot.identifier]- snapshot.review_state = ReviewState.APPROVED- snapshot.reviewed_at = now- snapshot.reviewed_by_id = user_id- snapshot.approved_hash = new_hash- snapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "approved_hash"])+ github = get_github_integration_for_repo(repo)+ if github.access_token_expired():+ github.refresh_access_token()+ current_baselines, _file_sha = _fetch_baseline_file(github, repo.repo_full_name, baseline_path, run.branch)- return run+ snapshots = list(run.snapshots.all())+ for s in snapshots:+ if s.result == SnapshotResult.REMOVED:+ current_baselines.pop(s.identifier, None)++ return _build_snapshots_yaml(+ repo, current_baselines=current_baselines, updates=_approved_baseline_updates(snapshots)+ )@transaction.atomic(using=WRITER_DB)-def approve_run(- run_id: UUID,- user_id: int,- approved_snapshots: list[dict],- team_id: int | None = None,- review_decision: ReviewDecision = ReviewDecision.HUMAN_APPROVED,- commit_to_github: bool = True,-) -> Run:- """Approve snapshots and finalize the run — commit baseline, post status.-- This is the full approval path: validate, commit to GitHub, mark- snapshots approved, mark removed as approved, mark run approved,- and post a success commit status.+def approve_snapshots(run_id: UUID, user_id: int, approved_snapshots: list[dict], team_id: int | None = None) -> Run:+ """Approve specific snapshots within a run (DB only, no GitHub commit).- Set commit_to_github=False only for CLI auto-approve (writes locally).+ Used for per-snapshot "Accept change" in the UI. Does not finalize+ the run — that happens via finalize_run."""run = _get_run_for_update(run_id, team_id=team_id)- repo = run.repoif run.purpose == RunPurpose.OBSERVE:raise ValueError("Observational runs cannot be approved")@@ -1960,11 +2021,6 @@ def approve_run(approvals = {s["identifier"]: s["new_hash"] for s in approved_snapshots}_validate_approval(run, approvals)- # Commit to GitHub first — do this before DB changes so we can fail cleanly- if commit_to_github and run.pr_number and repo.repo_full_name:- _commit_baseline_to_github(run, repo, approved_snapshots, approver_user_id=user_id)-- # Mark approved snapshotsnow = timezone.now()for snapshot in run.snapshots.filter(identifier__in=approvals.keys()):new_hash = approvals[snapshot.identifier]@@ -1974,36 +2030,6 @@ def approve_run(snapshot.approved_hash = new_hashsnapshot.save(update_fields=["review_state", "reviewed_at", "reviewed_by_id", "approved_hash"])- # Mark removed snapshots as approved (cleanup, not actionable)- run.snapshots.filter(result=SnapshotResult.REMOVED).update(- review_state=ReviewState.APPROVED,- reviewed_at=now,- reviewed_by_id=user_id,- )-- # Re-evaluate quarantine at approval time- _stamp_quarantine(run)-- # Finalize run- run.approved = True- run.review_decision = review_decision- run.approved_at = now- run.approved_by_id = user_id- run.save(update_fields=["approved", "review_decision", "approved_at", "approved_by_id"])-- if commit_to_github:- _post_commit_status(run, repo, "success", "Visual changes approved")-- if commit_to_github and review_decision == ReviewDecision.HUMAN_APPROVED:- from .tasks.tasks import post_approval_comment-- run_id_str = str(run.id)- run_team_id = run.team_id- transaction.on_commit(- lambda: post_approval_comment.delay(run_team_id, run_id_str),- using=WRITER_DB,- )-return rundiff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.pyindex a188601b0e57..4e2f1ad99bf6 100644--- a/products/visual_review/backend/presentation/serializers.py+++ b/products/visual_review/backend/presentation/serializers.py@@ -13,7 +13,6 @@ from ..facade.contracts import (ApproveRunRequestInput,ApproveSnapshotInput,Artifact,- AutoApproveResult,BaselineEntry,BaselineOverview,BaselineQuarantineSummary,@@ -23,6 +22,8 @@ from ..facade.contracts import (CreateRunInput,CreateRunResult,DiffCluster,+ FinalizeResult,+ FinalizeRunRequestInput,QuarantinedIdentifierEntry,QuarantineInput,QuarantineSourceRun,@@ -110,14 +111,14 @@ class CreateRunResultSerializer(DataclassSerializer):dataclass = CreateRunResult-class AutoApproveResultSerializer(DataclassSerializer):+class RecomputeResultSerializer(DataclassSerializer):class Meta:- dataclass = AutoApproveResult+ dataclass = RecomputeResult-class RecomputeResultSerializer(DataclassSerializer):+class FinalizeResultSerializer(DataclassSerializer):class Meta:- dataclass = RecomputeResult+ dataclass = FinalizeResult# --- Input Serializers ---@@ -163,41 +164,42 @@ class ApproveSnapshotInputSerializer(DataclassSerializer):class ApproveRunInputSerializer(DataclassSerializer):snapshots = ApproveSnapshotInputSerializer(many=True,- required=False,+ required=True,+ allow_empty=False,help_text=(- "Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true."+ "Snapshots to mark reviewed, each with `identifier` and `new_hash`. This only records the "+ 'review in the database (the per-snapshot "Accept change" action) — it does not change the '+ "baseline or the GitHub gate. Commit the baseline and green the gate with the finalize endpoint."),)++ class Meta:+ dataclass = ApproveRunRequestInput+++class FinalizeRunInputSerializer(DataclassSerializer):approve_all = serializers.BooleanField(required=False,default=False,help_text=(- "Approve every changed and new snapshot in the run. "- "Mutually exclusive with `snapshots` — pass one or the other."+ "Approve every still-pending changed and new snapshot before finalizing (tolerated snapshots are "+ "left untouched). Leave false to finalize a run you've already reviewed — finalizing fails if any "+ "changed/new snapshot is still unreviewed."),)commit_to_github = serializers.BooleanField(required=False,default=True,help_text=(- "Whether to commit the updated baseline YAML to the PR branch on GitHub. "- "Set to false to record the approval without pushing a commit."+ "Whether the server commits the approved baseline to the PR branch and greens the gate (the normal "+ "path — leave true). Set false only for tooling that commits the baseline itself: the server skips "+ "the commit and returns the signed YAML in `baseline_content` instead. With false, the gate is NOT "+ "greened and `metadata.baseline_commit_sha` is absent."),)class Meta:- dataclass = ApproveRunRequestInput-- def validate(self, attrs: ApproveRunRequestInput) -> ApproveRunRequestInput:- if attrs.approve_all and attrs.snapshots:- raise serializers.ValidationError(- {"approve_all": "`approve_all` and `snapshots` are mutually exclusive — pass one or the other."}- )- if not attrs.approve_all and not attrs.snapshots:- raise serializers.ValidationError(- {"snapshots": "Provide a non-empty `snapshots` list or set `approve_all: true`."}- )- return attrs+ dataclass = FinalizeRunRequestInputclass SnapshotHistoryEntrySerializer(DataclassSerializer):diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.pyindex a6802484a367..beaa0565c6d9 100644--- a/products/visual_review/backend/presentation/views.py+++ b/products/visual_review/backend/presentation/views.py@@ -33,20 +33,21 @@ from ..facade.contracts import (ApproveRunRequestInput,CreateRepoInput,CreateRunInput,+ FinalizeRunRequestInput,QuarantineInput,UpdateRepoInput,UpdateRepoRequestInput,)-from ..facade.enums import ReviewDecisionfrom .serializers import (AddSnapshotsInputSerializer,AddSnapshotsResultSerializer,ApproveRunInputSerializer,- AutoApproveResultSerializer,BaselineOverviewSerializer,CreateRepoInputSerializer,CreateRunInputSerializer,CreateRunResultSerializer,+ FinalizeResultSerializer,+ FinalizeRunInputSerializer,MarkToleratedInputSerializer,QuarantinedIdentifierEntrySerializer,QuarantineInputSerializer,@@ -531,37 +532,62 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):@validated_request(request_serializer=ApproveRunInputSerializer,- responses={200: OpenApiResponse(response=AutoApproveResultSerializer)},+ responses={200: OpenApiResponse(response=RunSerializer)},)@action(detail=True, methods=["post"])def approve(self, request: TypedRequest[ApproveRunRequestInput], pk: str, **kwargs) -> Response:- """Approve visual changes for snapshots in this run.+ """Mark snapshots reviewed (DB only).- With approve_all=true, approves all changed+new snapshots and returns- signed baseline YAML. With specific snapshots, approves only those.+ Records the per-snapshot "Accept change" decision. Does not commit the baseline+ or change the GitHub gate — call finalize to ship the run."""body = request.validated_datarun_id = UUID(pk)user_id = cast(int, request.user.id)try:- if body.approve_all:- result = api.approve_all(run_id=run_id, user_id=user_id, team_id=self.team_id)- return Response(AutoApproveResultSerializer(instance=result).data)+ input_dto = ApproveRunInput(run_id=run_id, user_id=user_id, snapshots=body.snapshots)+ run = api.approve_snapshots(input_dto, team_id=self.team_id)+ return Response(RunSerializer(instance=run).data)+ except api.RunNotFoundError:+ return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)+ except api.StaleRunError as e:+ return Response({"detail": str(e), "code": "stale_run"}, status=status.HTTP_409_CONFLICT)+ except api.ArtifactNotFoundError as e:+ return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)+ except ValueError as e:+ return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)- input_dto = ApproveRunInput(+ @validated_request(+ request_serializer=FinalizeRunInputSerializer,+ responses={200: OpenApiResponse(response=FinalizeResultSerializer)},+ )+ @action(detail=True, methods=["post"])+ def finalize(self, request: TypedRequest[FinalizeRunRequestInput], pk: str, **kwargs) -> Response:+ """Finalize a fully-reviewed run: commit the approved baseline and green the gate.++ Commits exactly the snapshots approved in the DB (tolerated ones keep their baseline)+ and only succeeds once every changed/new snapshot is resolved. With approve_all=true,+ any still-pending changed/new snapshot is approved first. With commit_to_github=false+ the server returns the signed baseline YAML instead of committing it.+ """+ body = request.validated_data+ run_id = UUID(pk)+ user_id = cast(int, request.user.id)++ try:+ result = api.finalize_run(run_id=run_id,user_id=user_id,- snapshots=body.snapshots,+ team_id=self.team_id,+ approve_all=body.approve_all,commit_to_github=body.commit_to_github,)- run = api.approve_run(input_dto, team_id=self.team_id)- return Response(- AutoApproveResultSerializer(instance=contracts.AutoApproveResult(run=run, baseline_content="")).data- )-+ return Response(FinalizeResultSerializer(instance=result).data)except api.RunNotFoundError:return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)+ except api.RunNotFullyResolvedError as e:+ return Response({"detail": str(e), "code": "not_fully_resolved"}, status=status.HTTP_409_CONFLICT)except api.StaleRunError as e:return Response({"detail": str(e), "code": "stale_run"}, status=status.HTTP_409_CONFLICT)except api.ArtifactNotFoundError as e:@@ -583,6 +609,8 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):return responseexcept api.GitHubCommitError:return Response({"detail": "GitHub commit failed"}, status=status.HTTP_502_BAD_GATEWAY)+ except ValueError as e:+ return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)@extend_schema(request=None,@@ -600,26 +628,3 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):{"detail": "Run must be completed and not yet approved"}, status=status.HTTP_400_BAD_REQUEST)return Response(RecomputeResultSerializer(instance=result).data)-- @extend_schema(request=None, responses={200: AutoApproveResultSerializer}, deprecated=True)- @action(detail=True, methods=["post"], url_path="auto-approve")- def auto_approve(self, request: Request, pk: str, **kwargs) -> Response:- """CLI auto-approve: approve all and return baseline YAML for local write."""- try:- result = api.approve_all(- run_id=UUID(pk),- user_id=cast(int, request.user.id),- team_id=self.team_id,- review_decision=ReviewDecision.AUTO_APPROVED,- commit_to_github=False,- )- except api.RunNotFoundError:- return Response({"detail": "Run not found"}, status=status.HTTP_404_NOT_FOUND)- except api.StaleRunError as e:- return Response({"detail": str(e), "code": "stale_run"}, status=status.HTTP_409_CONFLICT)- except api.ArtifactNotFoundError as e:- return Response({"detail": str(e)}, status=status.HTTP_400_BAD_REQUEST)- except ValueError:- return Response({"detail": "Invalid request"}, status=status.HTTP_400_BAD_REQUEST)-- return Response(AutoApproveResultSerializer(instance=result).data)diff --git a/products/visual_review/backend/tests/test_api.py b/products/visual_review/backend/tests/test_api.pyindex d5ded59b4cd9..bffbb4efae5a 100644--- a/products/visual_review/backend/tests/test_api.py+++ b/products/visual_review/backend/tests/test_api.py@@ -295,7 +295,7 @@ class TestApproveRunAPI:logic.finish_processing(create_result.run_id)# Per-snapshot approval is DB only — no run-level finalization- result = api.approve_run(+ result = api.approve_snapshots(ApproveRunInput(run_id=create_result.run_id,user_id=user.id,diff --git a/products/visual_review/backend/tests/test_github_integration.py b/products/visual_review/backend/tests/test_github_integration.pyindex 9ef2675149e7..8768bb4e5d54 100644--- a/products/visual_review/backend/tests/test_github_integration.py+++ b/products/visual_review/backend/tests/test_github_integration.py@@ -370,16 +370,10 @@ class TestGitHubCommitOnApprove:"""run = run_with_changes- # Approve the snapshots- approved = [- {"identifier": "button--primary", "new_hash": "abc123hash"},- {"identifier": "card--default", "new_hash": "def456hash"},- ]-- result = logic.approve_run(+ result = logic.finalize_run(run_id=run.id,user_id=user.id,- approved_snapshots=approved,+ approve_all=True,commit_to_github=True,)@@ -407,6 +401,104 @@ class TestGitHubCommitOnApprove:)assert "chore(visual): update storybook baselines" in log_result.stdout+ def test_finalize_commits_all_db_approved_not_just_last_reviewed(+ self,+ local_git_repo,+ mock_github_api,+ mock_github_integration,+ vr_project_with_github,+ run_with_changes,+ user,+ ):+ """Regression: the committed baseline comes from DB state, so snapshots reviewed in+ earlier (DB-only) calls are still committed — not just the finalizing call's set."""+ run = run_with_changes++ # Mark each snapshot reviewed in a separate DB-only call, then finalize with no list.+ logic.approve_snapshots(+ run_id=run.id,+ user_id=user.id,+ approved_snapshots=[{"identifier": "button--primary", "new_hash": "abc123hash"}],+ )+ logic.approve_snapshots(+ run_id=run.id,+ user_id=user.id,+ approved_snapshots=[{"identifier": "card--default", "new_hash": "def456hash"}],+ )+ logic.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=True)++ parsed = yaml.safe_load((local_git_repo / ".snapshots.yml").read_text())+ # Both land — the old explicit-list path would have dropped the one not in the final call.+ assert "abc123hash" in parsed["snapshots"]["button--primary"]["hash"]+ assert "def456hash" in parsed["snapshots"]["card--default"]["hash"]++ def test_finalize_does_not_commit_tolerated_snapshot(+ self,+ local_git_repo,+ mock_github_api,+ mock_github_integration,+ vr_project_with_github,+ run_with_changes,+ user,+ ):+ """Regression: a tolerated snapshot keeps its baseline — finalize must not bake its+ current hash into snapshots.yml (and approve_all must not flip it to approved)."""+ run = run_with_changes+ card = run.snapshots.get(identifier="card--default")+ logic.mark_snapshot_as_tolerated(run.id, card.id, user.id, run.team_id)++ logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=True)++ parsed = yaml.safe_load((local_git_repo / ".snapshots.yml").read_text())+ assert "abc123hash" in parsed["snapshots"]["button--primary"]["hash"]+ assert "card--default" not in parsed["snapshots"] # tolerated → baseline untouched+ card.refresh_from_db()+ assert card.review_state == "tolerated"++ def test_finalize_commits_to_prune_removed_only_run(+ self,+ local_git_repo,+ mock_github_api,+ mock_github_integration,+ vr_project_with_github,+ user,+ ):+ """Regression: a run whose only actionable change is a REMOVED snapshot must still commit —+ the removed entry has to be pruned from snapshots.yml, or the gate greens over a stale baseline."""+ repo = vr_project_with_github++ # Seed a baseline containing the entry finalize must prune.+ snapshots_file = local_git_repo / ".snapshots.yml"+ snapshots_file.write_text(+ yaml.dump({"version": 1, "snapshots": {"gone--snap": {"hash": "v1.kfake.gonehash.fakemac" + "1" * 40}}})+ )+ subprocess.run(["git", "add", "."], cwd=local_git_repo, check=True)+ subprocess.run(["git", "commit", "-m", "seed baseline"], cwd=local_git_repo, check=True)++ run = Run.objects.create(+ repo=repo,+ team_id=repo.team_id,+ status=RunStatus.COMPLETED,+ run_type="storybook",+ commit_sha=_get_head_sha(local_git_repo),+ branch="feature-branch",+ pr_number=42,+ total_snapshots=1,+ removed_count=1,+ )+ RunSnapshot.objects.create(+ run=run,+ team_id=repo.team_id,+ identifier="gone--snap",+ result=SnapshotResult.REMOVED,+ )++ result = logic.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=True)++ assert result.approved is True+ parsed = yaml.safe_load(snapshots_file.read_text())+ assert "gone--snap" not in parsed["snapshots"] # pruned by the finalize commit+def test_approve_merges_with_existing_baselines(self,local_git_repo,@@ -435,13 +527,10 @@ class TestGitHubCommitOnApprove:run.commit_sha = _get_head_sha(local_git_repo)run.save()- # Approve only button--primary- approved = [{"identifier": "button--primary", "new_hash": "abc123hash"}]-- logic.approve_run(+ logic.finalize_run(run_id=run.id,user_id=user.id,- approved_snapshots=approved,+ approve_all=True,commit_to_github=True,)@@ -472,13 +561,11 @@ class TestGitHubCommitOnApprove:subprocess.run(["git", "commit", "-m", "new commit"], cwd=local_git_repo, check=True)# Now the run's commit_sha doesn't match HEAD- approved = [{"identifier": "button--primary", "new_hash": "abc123hash"}]-with pytest.raises(logic.PRSHAMismatchError) as exc_info:- logic.approve_run(+ logic.finalize_run(run_id=run.id,user_id=user.id,- approved_snapshots=approved,+ approve_all=True,commit_to_github=True,)@@ -517,10 +604,10 @@ class TestGitHubCommitOnApprove:sensitive_config={"user_access_token": "ghu_fake"},)- logic.approve_run(+ logic.finalize_run(run_id=run_with_changes.id,user_id=user.id,- approved_snapshots=[{"identifier": "button--primary", "new_hash": "abc123hash"}],+ approve_all=True,commit_to_github=True,)@@ -545,13 +632,11 @@ class TestGitHubCommitOnApprove:"""Approve with commit_to_github=False should only update DB."""run = run_with_changes- approved = [{"identifier": "button--primary", "new_hash": "abc123hash"}]-# This should succeed without GitHub mocks- result = logic.approve_run(+ result = logic.finalize_run(run_id=run.id,user_id=user.id,- approved_snapshots=approved,+ approve_all=True,commit_to_github=False,)@@ -595,13 +680,11 @@ class TestGitHubCommitOnApprove:result=SnapshotResult.CHANGED,)- approved = [{"identifier": "test-snapshot", "new_hash": "newhash"}]-# Should succeed without GitHub interaction- result = logic.approve_run(+ result = logic.finalize_run(run_id=run.id,user_id=user.id,- approved_snapshots=approved,+ approve_all=True,commit_to_github=True, # True but no pr_number)@@ -629,15 +712,10 @@ class TestGitHubCommitOnApprove:assert s.reviewed_by_id is Noneassert s.approved_hash == ""- approved = [- {"identifier": "button--primary", "new_hash": "abc123hash"},- {"identifier": "card--default", "new_hash": "def456hash"},- ]-- logic.approve_run(+ logic.finalize_run(run_id=run.id,user_id=user.id,- approved_snapshots=approved,+ approve_all=True,commit_to_github=False,)@@ -693,9 +771,9 @@ class TestGitHubIntegrationErrors:)with pytest.raises(logic.GitHubIntegrationNotFoundError):- logic.approve_run(+ logic.finalize_run(run_id=run.id,user_id=user.id,- approved_snapshots=[{"identifier": "snap", "new_hash": "hash123"}],+ approve_all=True,commit_to_github=True,)diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.pyindex 7a77b46a08f5..fd13e60844da 100644--- a/products/visual_review/backend/tests/test_logic.py+++ b/products/visual_review/backend/tests/test_logic.py@@ -399,11 +399,7 @@ class TestRunOperations:logic.finish_processing(run.id)with pytest.raises(ValueError, match="Observational"):- logic.approve_run(- run_id=run.id,- user_id=1,- approved_snapshots=[{"identifier": "btn", "new_hash": "h1"}],- )+ logic.finalize_run(run_id=run.id, user_id=1, approve_all=True)def test_get_run(self, repo):run, _ = logic.create_run(@@ -558,11 +554,7 @@ class TestApproveRun:logic.complete_run(run.id)logic.finish_processing(run.id)- updated = logic.approve_run(- run_id=run.id,- user_id=user.id,- approved_snapshots=[{"identifier": "Button", "new_hash": "new_hash"}],- )+ updated = logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True)assert updated.approved is Trueassert updated.review_decision == "human_approved"@@ -577,6 +569,69 @@ class TestApproveRun:assert snapshot.reviewed_at is not Noneassert snapshot.reviewed_by_id == user.id+ def _completed_two_change_run(self, repo, mocker):+ logic.get_or_create_artifact(repo_id=repo.id, content_hash="ha", storage_path="p/a")+ logic.get_or_create_artifact(repo_id=repo.id, content_hash="hb", storage_path="p/b")+ run, _ = logic.create_run(+ repo_id=repo.id,+ team_id=repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc",+ branch="main",+ pr_number=None,+ snapshots=[{"identifier": "A", "content_hash": "ha"}, {"identifier": "B", "content_hash": "hb"}],+ baseline_hashes={"A": "olda", "B": "oldb"},+ )+ mocker.patch(+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",+ return_value=({"A": "olda", "B": "oldb"}, 0),+ )+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")+ logic.complete_run(run.id)+ logic.finish_processing(run.id)+ return run++ def test_finalize_requires_full_resolution(self, repo, user, mocker):+ # Finalize is all-or-nothing: it refuses while any changed/new snapshot is unreviewed.+ run = self._completed_two_change_run(repo, mocker)++ logic.approve_snapshots(+ run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "A", "new_hash": "ha"}]+ )+ with pytest.raises(logic.RunNotFullyResolvedError, match="B"):+ logic.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=False)++ # Resolving the rest lets it finalize.+ logic.approve_snapshots(+ run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "B", "new_hash": "hb"}]+ )+ updated = logic.finalize_run(run_id=run.id, user_id=user.id, commit_to_github=False)+ assert updated.approved is True++ def test_finalize_leaves_tolerated_snapshot_alone(self, repo, user, mocker):+ # A tolerated snapshot resolves the run without being approved or committed.+ run = self._completed_two_change_run(repo, mocker)+ snap_b = run.snapshots.get(identifier="B")+ logic.mark_snapshot_as_tolerated(run.id, snap_b.id, user.id, repo.team_id)++ updated = logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)++ assert updated.approved is True+ snapshots = {s.identifier: s for s in updated.snapshots.all()}+ assert snapshots["A"].review_state == ReviewState.APPROVED+ assert snapshots["B"].review_state == ReviewState.TOLERATED # approve_all did not clobber it++ def test_finalize_is_idempotent_on_approved_run(self, repo, user, mocker):+ # Re-finalizing an already-finalized run is a no-op — no second commit/status/comment.+ run = self._completed_two_change_run(repo, mocker)+ logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)+ approved_at = logic.get_run_with_snapshots(run.id).approved_at++ again = logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)++ assert again.approved is True+ assert again.approved_at == approved_at # unchanged — the second call did no work+@pytest.mark.django_db(databases=PRODUCT_DATABASES)class TestApproveSnapshots:@@ -1010,17 +1065,45 @@ class TestCommitStatusChecks:snapshots=[{"identifier": "snap", "content_hash": "new_h"}],baseline_hashes={"snap": "old_h"},)+ logic.finish_processing(run.id)- logic.approve_run(- run_id=run.id,- user_id=user.id,- approved_snapshots=[{"identifier": "snap", "new_hash": "new_h"}],- )+ logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True)statuses = mock_github_api.status_checksassert statuses[-1]["state"] == "success"assert "approved" in statuses[-1]["description"].lower()+ def test_recompute_does_not_green_approved_but_uncommitted(self, github_repo, mock_github_api, user, mocker):+ # Approving in the DB does not commit the baseline, so recompute must keep the gate red —+ # otherwise re-running CI would re-detect the change. Only finalize (which commits) greens it.+ logic.get_or_create_artifact(repo_id=github_repo.id, content_hash="new_h", storage_path="p/new")+ run, _ = logic.create_run(+ repo_id=github_repo.id,+ team_id=github_repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc123",+ branch="main",+ pr_number=None,+ snapshots=[{"identifier": "snap", "content_hash": "new_h"}],+ baseline_hashes={"snap": "old_h"},+ )+ mocker.patch(+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",+ return_value=({"snap": "old_h"}, 0),+ )+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")+ logic.complete_run(run.id)+ logic.finish_processing(run.id)++ logic.approve_snapshots(+ run_id=run.id, user_id=user.id, approved_snapshots=[{"identifier": "snap", "new_hash": "new_h"}]+ )+ logic.recompute_run(run.id, team_id=github_repo.team_id)++ statuses = mock_github_api.status_checks+ assert statuses[-1]["state"] == "failure"+ assert "awaiting commit" in statuses[-1]["description"].lower()+def test_no_status_without_github_integration(self, team):"""Status checks are silently skipped when no GitHub integration exists."""repo = logic.create_repo(team_id=team.id, repo_external_id=77777, repo_full_name="org/no-github")@@ -1155,36 +1238,21 @@ class TestRunSupersession:old.refresh_from_db()with pytest.raises(logic.StaleRunError):- logic.approve_run(- run_id=old.id,- user_id=user.id,- approved_snapshots=[{"identifier": "snap", "new_hash": "old"}],- commit_to_github=False,- )+ logic.finalize_run(run_id=old.id, user_id=user.id, approve_all=True, commit_to_github=False)def test_approve_latest_run_succeeds(self, repo, user):self._create_run(repo, commit_sha="old")newest = self._create_run(repo, commit_sha="new")logic.get_or_create_artifact(repo_id=repo.id, content_hash="new", storage_path="p/new")- run = logic.approve_run(- run_id=newest.id,- user_id=user.id,- approved_snapshots=[{"identifier": "snap", "new_hash": "new"}],- commit_to_github=False,- )+ run = logic.finalize_run(run_id=newest.id, user_id=user.id, approve_all=True, commit_to_github=False)assert run.approved is Truedef test_approved_run_superseded_but_stays_clean(self, repo, user, team):first = self._create_run(repo, commit_sha="1st")logic.get_or_create_artifact(repo_id=repo.id, content_hash="1st", storage_path="p/1st")- logic.approve_run(- run_id=first.id,- user_id=user.id,- approved_snapshots=[{"identifier": "snap", "new_hash": "1st"}],- commit_to_github=False,- )+ logic.finalize_run(run_id=first.id, user_id=user.id, approve_all=True, commit_to_github=False)self._create_run(repo, commit_sha="2nd")@@ -1224,12 +1292,7 @@ class TestRunSupersession:def test_approved_run_shows_in_clean_not_stale(self, repo, team, user):first = self._create_run(repo, commit_sha="1st")logic.get_or_create_artifact(repo_id=repo.id, content_hash="1st", storage_path="p/1st")- logic.approve_run(- run_id=first.id,- user_id=user.id,- approved_snapshots=[{"identifier": "snap", "new_hash": "1st"}],- commit_to_github=False,- )+ logic.finalize_run(run_id=first.id, user_id=user.id, approve_all=True, commit_to_github=False)self._create_run(repo, commit_sha="2nd")@@ -1331,13 +1394,8 @@ class TestQuarantineStamping:repo_id=repo.id, identifier="Button-primary", run_type=RunType.STORYBOOK, team_id=team.id)- # Approve the run — _stamp_quarantine re-evaluates- logic.approve_run(- run_id=run.id,- user_id=user.id,- approved_snapshots=[{"identifier": "Button-primary", "new_hash": "h1"}],- commit_to_github=False,- )+ # Finalize the run — _stamp_quarantine re-evaluates+ logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)snapshot.refresh_from_db()assert snapshot.is_quarantined is False@@ -1550,12 +1608,7 @@ class TestRecomputeRun:identifiers_and_hashes=[("Button", "h1")],baseline={"Button": "old1"},)- logic.approve_run(- run_id=run.id,- user_id=user.id,- approved_snapshots=[{"identifier": "Button", "new_hash": "h1"}],- commit_to_github=False,- )+ logic.finalize_run(run_id=run.id, user_id=user.id, approve_all=True, commit_to_github=False)with pytest.raises(ValueError, match="already approved"):logic.recompute_run(run.id, team_id=team.id)diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.pyindex 484f9ffc3f7e..4dba29ee2512 100644--- a/products/visual_review/backend/tests/test_presentation.py+++ b/products/visual_review/backend/tests/test_presentation.py@@ -193,7 +193,44 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)# Per-snapshot approval is DB only — run not finalized- self.assertFalse(response.json()["run"]["approved"])+ self.assertFalse(response.json()["approved"])++ def test_finalize_run(self):+ logic.get_or_create_artifact(+ repo_id=self.vr_project.id,+ content_hash="new_hash",+ storage_path="visual_review/new_hash",+ )+ create_result = api.create_run(+ CreateRunInput(+ repo_id=self.vr_project.id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc123",+ branch="main",+ snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],+ baseline_hashes={"Button": "old_hash"},+ ),+ team_id=self.team.id,+ )+ with (+ patch(+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",+ return_value=({"Button": "old_hash"}, 0),+ ),+ patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay"),+ ):+ logic.complete_run(create_result.run_id)+ logic.finish_processing(create_result.run_id)++ # No PR on this run, so nothing is pushed, but approve_all + finalize marks it approved.+ response = self.client.post(+ f"/api/projects/{self.team.id}/visual_review/runs/{create_result.run_id}/finalize/",+ {"approve_all": True},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertTrue(response.json()["run"]["approved"])def _changed_snapshot_for_tolerate(self) -> tuple[str, str]:logic.get_or_create_artifact(diff --git a/products/visual_review/cli/src/client.ts b/products/visual_review/cli/src/client.tsindex 8cb3ad7460c7..4da95ddf2390 100644--- a/products/visual_review/cli/src/client.ts+++ b/products/visual_review/cli/src/client.ts@@ -7,9 +7,9 @@import type {ApproveSnapshotInputApi,ArtifactApi,- AutoApproveResultApi,CreateRunInputApi,CreateRunResultApi,+ FinalizeResultApi,RunApi,SnapshotApi,SnapshotManifestItemApi,@@ -193,11 +193,15 @@ export class VisualReviewClient {}/**- * Auto-approve all changes in a run and get signed baseline YAML.+ * Approve all changes and finalize, returning the signed baseline YAML to write/commit yourself.+ *+ * Uses commit_to_github=false so the server does not push the baseline — the CLI writes it+ * locally and the CI commits it via git.*/- async autoApproveRun(runId: string): Promise<AutoApproveResultApi> {- return this.request<AutoApproveResultApi>(`/visual_review/runs/${runId}/auto-approve/`, {+ async autoApproveRun(runId: string): Promise<FinalizeResultApi> {+ return this.request<FinalizeResultApi>(`/visual_review/runs/${runId}/finalize/`, {method: 'POST',+ body: JSON.stringify({ approve_all: true, commit_to_github: false }),})}}diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.tsindex 68052c3dd55e..2e6712e43195 100644--- a/products/visual_review/frontend/generated/api.schemas.ts+++ b/products/visual_review/frontend/generated/api.schemas.ts@@ -309,15 +309,18 @@ export interface ApproveSnapshotInputApi {}export interface ApproveRunRequestInputApi {- /** Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true. */- snapshots?: ApproveSnapshotInputApi[]- /** Approve every changed and new snapshot in the run. Mutually exclusive with `snapshots` — pass one or the other. */+ /** Snapshots to mark reviewed, each with `identifier` and `new_hash`. This only records the review in the database (the per-snapshot "Accept change" action) — it does not change the baseline or the GitHub gate. Commit the baseline and green the gate with the finalize endpoint. */+ snapshots: ApproveSnapshotInputApi[]+}++export interface FinalizeRunRequestInputApi {+ /** Approve every still-pending changed and new snapshot before finalizing (tolerated snapshots are left untouched). Leave false to finalize a run you've already reviewed — finalizing fails if any changed/new snapshot is still unreviewed. */approve_all?: boolean- /** Whether to commit the updated baseline YAML to the PR branch on GitHub. Set to false to record the approval without pushing a commit. */+ /** Whether the server commits the approved baseline to the PR branch and greens the gate (the normal path — leave true). Set false only for tooling that commits the baseline itself: the server skips the commit and returns the signed YAML in `baseline_content` instead. With false, the gate is NOT greened and `metadata.baseline_commit_sha` is absent. */commit_to_github?: boolean}-export interface AutoApproveResultApi {+export interface FinalizeResultApi {run: RunApibaseline_content: string}diff --git a/products/visual_review/frontend/generated/api.ts b/products/visual_review/frontend/generated/api.tsindex b135964bc0d8..a4c103070a5f 100644--- a/products/visual_review/frontend/generated/api.ts+++ b/products/visual_review/frontend/generated/api.ts@@ -12,11 +12,12 @@ import type {AddSnapshotsInputApi,AddSnapshotsResultApi,ApproveRunRequestInputApi,- AutoApproveResultApi,BaselineOverviewApi,CreateRepoInputApi,CreateRunInputApi,CreateRunResultApi,+ FinalizeResultApi,+ FinalizeRunRequestInputApi,MarkToleratedInputApi,PaginatedQuarantinedIdentifierEntryListApi,PaginatedRepoListApi,@@ -439,18 +440,18 @@ export const getVisualReviewRunsApproveCreateUrl = (projectId: string, id: strin}/**- * Approve visual changes for snapshots in this run.+ * Mark snapshots reviewed (DB only).-With approve_all=true, approves all changed+new snapshots and returns-signed baseline YAML. With specific snapshots, approves only those.+Records the per-snapshot "Accept change" decision. Does not commit the baseline+or change the GitHub gate — call finalize to ship the run.*/export const visualReviewRunsApproveCreate = async (projectId: string,id: string,- approveRunRequestInputApi?: ApproveRunRequestInputApi,+ approveRunRequestInputApi: ApproveRunRequestInputApi,options?: RequestInit-): Promise<AutoApproveResultApi> => {- return apiMutator<AutoApproveResultApi>(getVisualReviewRunsApproveCreateUrl(projectId, id), {+): Promise<RunApi> => {+ return apiMutator<RunApi>(getVisualReviewRunsApproveCreateUrl(projectId, id), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },@@ -476,6 +477,32 @@ export const visualReviewRunsCompleteCreate = async (})}+export const getVisualReviewRunsFinalizeCreateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/visual_review/runs/${id}/finalize/`+}++/**+ * Finalize a fully-reviewed run: commit the approved baseline and green the gate.++Commits exactly the snapshots approved in the DB (tolerated ones keep their baseline)+and only succeeds once every changed/new snapshot is resolved. With approve_all=true,+any still-pending changed/new snapshot is approved first. With commit_to_github=false+the server returns the signed baseline YAML instead of committing it.+ */+export const visualReviewRunsFinalizeCreate = async (+ projectId: string,+ id: string,+ finalizeRunRequestInputApi?: FinalizeRunRequestInputApi,+ options?: RequestInit+): Promise<FinalizeResultApi> => {+ return apiMutator<FinalizeResultApi>(getVisualReviewRunsFinalizeCreateUrl(projectId, id), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(finalizeRunRequestInputApi),+ })+}+export const getVisualReviewRunsRecomputeCreateUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/visual_review/runs/${id}/recompute/`}diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.tsindex c98c2774d7e3..3b6f58d2a76b 100644--- a/products/visual_review/frontend/generated/api.zod.ts+++ b/products/visual_review/frontend/generated/api.zod.ts@@ -117,14 +117,11 @@ export const VisualReviewRunsAddSnapshotsCreateBody = /* @__PURE__ */ zod.object})/**- * Approve visual changes for snapshots in this run.+ * Mark snapshots reviewed (DB only).-With approve_all=true, approves all changed+new snapshots and returns-signed baseline YAML. With specific snapshots, approves only those.+Records the per-snapshot "Accept change" decision. Does not commit the baseline+or change the GitHub gate — call finalize to ship the run.*/-export const visualReviewRunsApproveCreateBodyApproveAllDefault = false-export const visualReviewRunsApproveCreateBodyCommitToGithubDefault = true-export const VisualReviewRunsApproveCreateBody = /* @__PURE__ */ zod.object({snapshots: zod.array(@@ -137,21 +134,34 @@ export const VisualReviewRunsApproveCreateBody = /* @__PURE__ */ zod.object({.describe('The content hash of the new baseline image to record for this identifier.'),}))- .optional().describe(- 'Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true.'+ 'Snapshots to mark reviewed, each with `identifier` and `new_hash`. This only records the review in the database (the per-snapshot \"Accept change\" action) — it does not change the baseline or the GitHub gate. Commit the baseline and green the gate with the finalize endpoint.'),+})++/**+ * Finalize a fully-reviewed run: commit the approved baseline and green the gate.++Commits exactly the snapshots approved in the DB (tolerated ones keep their baseline)+and only succeeds once every changed/new snapshot is resolved. With approve_all=true,+any still-pending changed/new snapshot is approved first. With commit_to_github=false+the server returns the signed baseline YAML instead of committing it.+ */+export const visualReviewRunsFinalizeCreateBodyApproveAllDefault = false+export const visualReviewRunsFinalizeCreateBodyCommitToGithubDefault = true++export const VisualReviewRunsFinalizeCreateBody = /* @__PURE__ */ zod.object({approve_all: zod.boolean()- .default(visualReviewRunsApproveCreateBodyApproveAllDefault)+ .default(visualReviewRunsFinalizeCreateBodyApproveAllDefault).describe(- 'Approve every changed and new snapshot in the run. Mutually exclusive with `snapshots` — pass one or the other.'+ "Approve every still-pending changed and new snapshot before finalizing (tolerated snapshots are left untouched). Leave false to finalize a run you've already reviewed — finalizing fails if any changed\/new snapshot is still unreviewed."),commit_to_github: zod.boolean()- .default(visualReviewRunsApproveCreateBodyCommitToGithubDefault)+ .default(visualReviewRunsFinalizeCreateBodyCommitToGithubDefault).describe(- 'Whether to commit the updated baseline YAML to the PR branch on GitHub. Set to false to record the approval without pushing a commit.'+ 'Whether the server commits the approved baseline to the PR branch and greens the gate (the normal path — leave true). Set false only for tooling that commits the baseline itself: the server skips the commit and returns the signed YAML in `baseline_content` instead. With false, the gate is NOT greened and `metadata.baseline_commit_sha` is absent.'),})diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsxindex 8e6c7eb3cfe1..67c184f334cd 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx@@ -195,7 +195,7 @@ export function VisualReviewRunScene(): JSX.Element {quarantinedIdentifiers,quarantinedIdentifierSet,repoFullName,- isApproving,+ isFinalizing,isApprovingSnapshot,isRecomputing,isRunInProgress,@@ -205,7 +205,7 @@ export function VisualReviewRunScene(): JSX.Element {} = useValues(visualReviewRunSceneLogic)const {setSelectedSnapshotId,- approveChanges,+ finalizeRun,approveSnapshot,markAsTolerated,quarantineSnapshot,@@ -343,16 +343,14 @@ export function VisualReviewRunScene(): JSX.Element {name={run.branch}resourceType={{ type: 'visual_review' }}actions={- !run.approved &&- !run.is_stale &&- (reviewPending > 0 || reviewApproved > 0 || reviewTolerated > 0) ? (+ !run.approved && !run.is_stale && (reviewPending > 0 || reviewApproved > 0) ? (<LemonButtontype="primary"- onClick={approveChanges}- loading={isApproving}- data-attr="visual-review-commit-baseline"+ onClick={finalizeRun}+ loading={isFinalizing}+ data-attr="visual-review-finalize-run">- {reviewPending > 0 ? `Approve ${reviewPending} pending and commit` : 'Commit to baseline'}+ {reviewPending > 0 ? `Approve ${reviewPending} and finalize` : 'Finalize run'}</LemonButton>) : undefined}@@ -370,7 +368,7 @@ export function VisualReviewRunScene(): JSX.Element {</LemonBanner>)}- {allChangesResolved && !ciRetriggerUnavailableReason && (+ {allChangesResolved && reviewApproved === 0 && !ciRetriggerUnavailableReason && (<LemonBannertype="info"className="mb-4"@@ -381,7 +379,8 @@ export function VisualReviewRunScene(): JSX.Element {'data-attr': 'visual-review-recompute-run',}}>- All changes are resolved — re-trigger to update the commit status and pass the gate.+ All changes are resolved by tolerating or quarantining — re-trigger to update the commit status and+ pass the gate. (No baseline commit needed; approved changes are shipped via Finalize run.)</LemonBanner>)}diff --git a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.tsindex b6411079898c..91a9e40fec6e 100644--- a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts@@ -13,6 +13,7 @@ import {visualReviewReposQuarantineList,visualReviewReposRetrieve,visualReviewRunsApproveCreate,+ visualReviewRunsFinalizeCreate,visualReviewRunsRecomputeCreate,visualReviewRunsTolerateCreate,visualReviewRunsRetrieve,@@ -41,9 +42,9 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([})),actions({setSelectedSnapshotId: (snapshotId: string | null) => ({ snapshotId }),- approveChanges: true,- approveChangesSuccess: true,- approveChangesFailure: true,+ finalizeRun: true,+ finalizeRunSuccess: true,+ finalizeRunFailure: true,approveSnapshot: (snapshot: SnapshotApi) => ({ snapshot }),approveSnapshotSuccess: true,approveSnapshotFailure: true,@@ -72,12 +73,12 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([setSelectedSnapshotId: (_, { snapshotId }) => snapshotId,},],- isApproving: [+ isFinalizing: [false,{- approveChanges: () => true,- approveChangesSuccess: () => false,- approveChangesFailure: () => false,+ finalizeRun: () => true,+ finalizeRunSuccess: () => false,+ finalizeRunFailure: () => false,},],isApprovingSnapshot: [@@ -294,32 +295,36 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([actions.loadToleratedHashes(snapshot.identifier)}},- approveChanges: async () => {+ finalizeRun: async () => {const { run } = valuesif (!run) {return}try {- await visualReviewRunsApproveCreate(String(values.currentProjectId), props.runId, {+ // approve_all approves any still-pending changes (tolerated ones are left alone),+ // commits the approved baseline, and greens the gate.+ await visualReviewRunsFinalizeCreate(String(values.currentProjectId), props.runId, {approve_all: true,})- actions.approveChangesSuccess()- lemonToast.success('Changes approved successfully')+ actions.finalizeRunSuccess()+ lemonToast.success('Run finalized — baseline committed')actions.loadRun()- // Patch in place — refetching all snapshots after a bulk approve made the whole- // grid flash and lost the user's selection. Server is the source of truth on- // next mount; we only need the UI to reflect the change immediately.+ // Patch in place — refetching all snapshots after finalize made the whole grid+ // flash and lost the user's selection. Server is the source of truth on next mount;+ // we only need the UI to reflect the change immediately.actions.loadSnapshotsSuccess(values.snapshots.map((s) =>- s.review_state === 'pending' && s.result !== 'unchanged'+ s.review_state === 'pending' &&+ s.result !== 'unchanged' &&+ !values.quarantinedIdentifierSet.has(s.identifier)? { ...s, review_state: 'approved' }: s))} catch (e: any) {- actions.approveChangesFailure()- lemonToast.error(e?.detail || e?.message || 'Failed to approve changes')+ actions.finalizeRunFailure()+ lemonToast.error(e?.detail || e?.message || 'Failed to finalize run')}},approveSnapshot: async ({ snapshot }) => {diff --git a/products/visual_review/mcp/tools.yaml b/products/visual_review/mcp/tools.yamlindex b8fbf47b791d..121a45d81bf3 100644--- a/products/visual_review/mcp/tools.yaml+++ b/products/visual_review/mcp/tools.yaml@@ -83,15 +83,15 @@ tools:- visual_review:writeannotations:readOnly: false- destructive: true- idempotent: false- title: Approve visual review snapshots+ destructive: false+ idempotent: true+ title: Mark visual review snapshots revieweddescription: >- Approve visual changes for snapshots in a run. With `approve_all: true`, approves every changed and new- snapshot in the run. Otherwise pass an explicit `snapshots` list, each entry being `{identifier, new_hash}`- — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. Approval updates the baseline YAML- in the repo; `commit_to_github` (default true) also pushes a commit to the PR branch. Confirm with the user- before approving — this is the action that ships the visual change.+ Mark specific snapshots as reviewed (approved) in a run. Pass a `snapshots` list, each entry being+ `{identifier, new_hash}` — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. This only+ records the review in the database (the per-snapshot "Accept change" action) — it does NOT update the+ baseline, push a commit, or change the GitHub gate, and it can be re-run safely. To actually ship the visual+ change (commit the baseline + green the gate), use `visual-review-runs-finalize-create`.feature_flag: visual-reviewvisual-review-runs-complete-create:operation: visual_review_runs_complete_create@@ -113,6 +113,28 @@ tools:visual-review-runs-create:operation: visual_review_runs_createenabled: false+ visual-review-runs-finalize-create:+ operation: visual_review_runs_finalize_create+ enabled: true+ scopes:+ - visual_review:write+ annotations:+ readOnly: false+ destructive: true+ idempotent: false+ title: Finalize a visual review run+ description: >+ Finalize a fully-reviewed run: commit the approved baseline to the PR branch and green the GitHub+ visual-review check. Commits exactly the snapshots approved in the DB (tolerated snapshots keep their+ baseline and are never overwritten) and is all-or-nothing — it only succeeds once every changed/new snapshot+ is resolved (approved, tolerated, or quarantined), otherwise it returns the unresolved list. With+ `approve_all: true` every still-pending changed/new snapshot is approved first. When a baseline commit is+ pushed its SHA comes back on the run's `metadata.baseline_commit_sha`; it's absent when nothing needed+ committing (all changes resolved by toleration/quarantine — the gate still greens) or when the commit was+ skipped (no PR, or a `409 sha_mismatch` from newer PR commits, which leaves the gate red — re-run CI and+ finalize again). STOP: never finalize on your own initiative. Require explicit, per-run human confirmation+ first — finalizing ships the visual change and rewrites the committed baseline.+ feature_flag: visual-reviewvisual-review-runs-list:operation: visual_review_runs_listenabled: truediff --git a/products/visual_review/skills/triaging-visual-review-runs/SKILL.md b/products/visual_review/skills/triaging-visual-review-runs/SKILL.mdindex 3f1c02d70047..e5aa1ac1c3e8 100644--- a/products/visual_review/skills/triaging-visual-review-runs/SKILL.md+++ b/products/visual_review/skills/triaging-visual-review-runs/SKILL.md@@ -18,8 +18,9 @@ snapshot is approved or tolerated in the [VR UI](https://us.posthog.com/project/This skill teaches an agent how to answer the questions a human reviewer would actually ask, by chainingthe VR MCP tools — instead of reaching for `gh pr view` and tab-hopping to the VR web UI. The read tools-cover status / scope / history / triage; two write tools (`approve-create`, `tolerate-create`) let the-agent act once the user confirms.+cover status / scope / history / triage. Two are reversible DB-only triage marks (`approve-create`,+`tolerate-create`); one ships the change (`finalize-create`) — it commits the baseline and greens the gate,+and only that one needs explicit per-run human confirmation.## When this skill applies@@ -49,26 +50,54 @@ Read tools (safe to call freely):| `posthog:visual-review-repos-list` | Repos (one per GitHub repo) — usually only one matters; useful for filtering. || `posthog:visual-review-repos-retrieve` | Repo metadata: baseline file paths, PR-comment configuration. |-Write tools (require explicit user confirmation — these ship the visual change):+Triage tools (reversible, DB-only — they record a review decision but do NOT change the baseline or the gate):| Tool | Purpose || -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |-| `posthog:visual-review-runs-approve-create` | Approve `changed` / `new` snapshots in a run. Updates the baseline YAML and (by default) pushes a commit to the PR. |+| `posthog:visual-review-runs-approve-create` | Mark `changed` / `new` snapshots reviewed (approved) in the DB. Does NOT commit or green the gate — ship via finalize. || `posthog:visual-review-runs-tolerate-create` | Mark a single changed snapshot as a known tolerated alternate. Does NOT change the baseline — use for benign variants. |-Approval call shape:+Ship tool (irreversible, outward-facing — requires explicit per-run human confirmation; see [the gate](#the-finalize-gate)):++| Tool | Purpose |+| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |+| `posthog:visual-review-runs-finalize-create` | Commit the approved baseline to the PR branch and green the GitHub `visual-review` check. This ships the change. |++Mark-reviewed call shape (`approve-create`):- `id` (required) — the run UUID. It's the route parameter, so the call fails without it.-- `approve_all: true` — approves every `changed` and `new` snapshot in the run. Convenient when you've verified every diff is intended.-- `snapshots: [{identifier, new_hash}]` — explicit list. `new_hash` is the `content_hash` of each snapshot's `current_artifact`. Prefer this when only some diffs are intended.-- `commit_to_github: true` (default) — pushes the baseline-YAML update straight to the PR branch. Set false to record the approval without a commit.+- `snapshots: [{identifier, new_hash}]` — `new_hash` is the `content_hash` of each snapshot's `current_artifact`. This only records the review in the DB; nothing is committed and the gate stays red until you finalize.Toleration call shape — both fields are required:- `id` (required) — the run UUID. It's the route parameter, so the call fails without it.- `snapshot_id` (required) — the UUID of the individual snapshot to tolerate (from `visual-review-runs-snapshots-list`). This identifies _which_ snapshot inside the run; it does not replace the run `id`.-If approval fails with `409 stale_run`, the run has been superseded — `visual-review-runs-list { pr_number }` and approve the newest one. A successful approval often kicks off a fresh CI run, which is normal.+Finalize call shape (`finalize-create`) — the all-or-nothing ship action:++- `id` (required) — the run UUID.+- `approve_all: true` — approve every still-pending `changed`/`new` snapshot before finalizing (tolerated ones are left alone). Use when you've verified every remaining diff is intended.+- Omit `approve_all` (default false) to finalize a run you've already reviewed snapshot-by-snapshot. Finalize is all-or-nothing: it fails with `409 not_fully_resolved` (and lists what's left) unless every changed/new snapshot is approved, tolerated, or quarantined.+- It commits exactly the snapshots approved in the DB — tolerated snapshots keep their baseline and are never overwritten. When a baseline commit is pushed, its SHA comes back on the run's `metadata.baseline_commit_sha`. It's absent when nothing needed committing (everything resolved by toleration/quarantine — the gate still greens) or when the commit was skipped: no PR, or a `409 sha_mismatch` because the PR has newer commits (that one leaves the gate red — re-run CI on the latest commit and finalize again).++If finalize fails with `409 stale_run`, the run has been superseded — `visual-review-runs-list { pr_number }` and finalize the newest one. A successful finalize often kicks off a fresh CI run, which is normal.++### The finalize gate++Finalize is the one irreversible, outward-facing action in this skill: it rewrites the baseline committed to the+PR and greens the merge gate. Treat it like pushing to someone's branch — never automatic.++Before _any_ `finalize-create` call, all of these must hold:++1. **You verified the diffs.** You pulled the current (and, for `changed`, baseline) PNGs and looked at them, ran+ the flake check on anything suspect, and reached a per-snapshot verdict. Metadata alone is never enough.+2. **You presented the verdict and waited.** Show the user, per snapshot, what changed and your recommendation, then stop.+3. **The user explicitly approved _this_ run.** A broad "get the gate green" / "fix the PR" is permission to+ investigate and recommend — NOT to finalize. When the task implies finalizing but the human hasn't said it for+ this specific run, ask.++`approve-create` and `tolerate-create` are reversible triage and don't need this gate — but they don't ship anything+either. The moment you're about to `finalize-create` and can't point to a specific human "yes" for this run, stop and ask.## Vocabulary cheat sheetdiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 9a2ad6325e69..bd6c747e1586 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -5569,15 +5569,15 @@"feature_flag": "visual-review"},"visual-review-runs-approve-create": {- "description": "Approve visual changes for snapshots in a run. With `approve_all: true`, approves every changed and new snapshot in the run. Otherwise pass an explicit `snapshots` list, each entry being `{identifier, new_hash}` — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. Approval updates the baseline YAML in the repo; `commit_to_github` (default true) also pushes a commit to the PR branch. Confirm with the user before approving — this is the action that ships the visual change.",+ "description": "Mark specific snapshots as reviewed (approved) in a run. Pass a `snapshots` list, each entry being `{identifier, new_hash}` — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. This only records the review in the database (the per-snapshot \"Accept change\" action) — it does NOT update the baseline, push a commit, or change the GitHub gate, and it can be re-run safely. To actually ship the visual change (commit the baseline + green the gate), use `visual-review-runs-finalize-create`.","category": "Visual review","feature": "visual_review",- "summary": "Approve visual review snapshots",- "title": "Approve visual review snapshots",+ "summary": "Mark visual review snapshots reviewed",+ "title": "Mark visual review snapshots reviewed","required_scopes": ["visual_review:write"],"annotations": {- "destructiveHint": true,- "idempotentHint": false,+ "destructiveHint": false,+ "idempotentHint": true,"openWorldHint": true,"readOnlyHint": false},@@ -5598,6 +5598,21 @@},"feature_flag": "visual-review"},+ "visual-review-runs-finalize-create": {+ "description": "Finalize a fully-reviewed run: commit the approved baseline to the PR branch and green the GitHub visual-review check. Commits exactly the snapshots approved in the DB (tolerated snapshots keep their baseline and are never overwritten) and is all-or-nothing — it only succeeds once every changed/new snapshot is resolved (approved, tolerated, or quarantined), otherwise it returns the unresolved list. With `approve_all: true` every still-pending changed/new snapshot is approved first. When a baseline commit is pushed its SHA comes back on the run's `metadata.baseline_commit_sha`; it's absent when nothing needed committing (all changes resolved by toleration/quarantine — the gate still greens) or when the commit was skipped (no PR, or a `409 sha_mismatch` from newer PR commits, which leaves the gate red — re-run CI and finalize again). STOP: never finalize on your own initiative. Require explicit, per-run human confirmation first — finalizing ships the visual change and rewrites the committed baseline.",+ "category": "Visual review",+ "feature": "visual_review",+ "summary": "Finalize a visual review run",+ "title": "Finalize a visual review run",+ "required_scopes": ["visual_review:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "visual-review"+ },"visual-review-runs-list": {"description": "List visual review runs for the current project. Each run represents a single CI execution that captured screenshots for a commit. Filter by `review_state` (e.g. `needs_review`, `clean`, `processing`, `stale`) to triage workload, or by `pr_number` / `commit_sha` / `branch` to find the specific run(s) blocking a PR. Returns status, review decision, commit sha, branch, pr number, and a summary of changed / new / removed / unchanged snapshots.","category": "Visual review",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 04e47c636561..8fe82f8b1304 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -5924,15 +5924,15 @@"feature_flag": "visual-review"},"visual-review-runs-approve-create": {- "description": "Approve visual changes for snapshots in a run. With `approve_all: true`, approves every changed and new snapshot in the run. Otherwise pass an explicit `snapshots` list, each entry being `{identifier, new_hash}` — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. Approval updates the baseline YAML in the repo; `commit_to_github` (default true) also pushes a commit to the PR branch. Confirm with the user before approving — this is the action that ships the visual change.",+ "description": "Mark specific snapshots as reviewed (approved) in a run. Pass a `snapshots` list, each entry being `{identifier, new_hash}` — `new_hash` is the `content_hash` of the snapshot's `current_artifact`. This only records the review in the database (the per-snapshot \"Accept change\" action) — it does NOT update the baseline, push a commit, or change the GitHub gate, and it can be re-run safely. To actually ship the visual change (commit the baseline + green the gate), use `visual-review-runs-finalize-create`.","category": "Visual review","feature": "visual_review",- "summary": "Approve visual review snapshots",- "title": "Approve visual review snapshots",+ "summary": "Mark visual review snapshots reviewed",+ "title": "Mark visual review snapshots reviewed","required_scopes": ["visual_review:write"],"annotations": {- "destructiveHint": true,- "idempotentHint": false,+ "destructiveHint": false,+ "idempotentHint": true,"openWorldHint": true,"readOnlyHint": false},@@ -5953,6 +5953,21 @@},"feature_flag": "visual-review"},+ "visual-review-runs-finalize-create": {+ "description": "Finalize a fully-reviewed run: commit the approved baseline to the PR branch and green the GitHub visual-review check. Commits exactly the snapshots approved in the DB (tolerated snapshots keep their baseline and are never overwritten) and is all-or-nothing — it only succeeds once every changed/new snapshot is resolved (approved, tolerated, or quarantined), otherwise it returns the unresolved list. With `approve_all: true` every still-pending changed/new snapshot is approved first. When a baseline commit is pushed its SHA comes back on the run's `metadata.baseline_commit_sha`; it's absent when nothing needed committing (all changes resolved by toleration/quarantine — the gate still greens) or when the commit was skipped (no PR, or a `409 sha_mismatch` from newer PR commits, which leaves the gate red — re-run CI and finalize again). STOP: never finalize on your own initiative. Require explicit, per-run human confirmation first — finalizing ships the visual change and rewrites the committed baseline.",+ "category": "Visual review",+ "feature": "visual_review",+ "summary": "Finalize a visual review run",+ "title": "Finalize a visual review run",+ "required_scopes": ["visual_review:write"],+ "annotations": {+ "destructiveHint": true,+ "idempotentHint": false,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "feature_flag": "visual-review"+ },"visual-review-runs-list": {"description": "List visual review runs for the current project. Each run represents a single CI execution that captured screenshots for a commit. Filter by `review_state` (e.g. `needs_review`, `clean`, `processing`, `stale`) to triage workload, or by `pr_number` / `commit_sha` / `branch` to find the specific run(s) blocking a PR. Returns status, review decision, commit sha, branch, pr number, and a summary of changed / new / removed / unchanged snapshots.","category": "Visual review",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 23f6ad0dbf76..935427162678 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7575,12 +7575,8 @@ export namespace Schemas {}export interface ApproveRunRequestInput {- /** Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true. */- snapshots?: ApproveSnapshotInput[];- /** Approve every changed and new snapshot in the run. Mutually exclusive with `snapshots` — pass one or the other. */- approve_all?: boolean;- /** Whether to commit the updated baseline YAML to the PR branch on GitHub. Set to false to record the approval without pushing a commit. */- commit_to_github?: boolean;+ /** Snapshots to mark reviewed, each with `identifier` and `new_hash`. This only records the review in the database (the per-snapshot "Accept change" action) — it does not change the baseline or the GitHub gate. Commit the baseline and green the gate with the finalize endpoint. */+ snapshots: ApproveSnapshotInput[];}export interface Artifact {@@ -7638,54 +7634,6 @@ export namespace Schemas {PositionBased: 'position_based',} as const;- export interface UserBasicInfo {- id: number;- first_name: string;- email: string;- }-- export interface RunSummary {- total: number;- changed: number;- new: number;- removed: number;- unchanged: number;- unresolved?: number;- tolerated_matched?: number;- }-- export type RunMetadata = { [key: string]: unknown };-- export interface Run {- approved_by?: UserBasicInfo | null;- id: string;- repo_id: string;- status: string;- run_type: string;- commit_sha: string;- branch: string;- /** @nullable */- pr_number: number | null;- approved: boolean;- /** @nullable */- approved_at: string | null;- summary: RunSummary;- /** @nullable */- error_message: string | null;- created_at: string;- /** @nullable */- completed_at: string | null;- is_stale?: boolean;- /** @nullable */- superseded_by_id?: string | null;- metadata?: RunMetadata;- }-- export interface AutoApproveResult {- run: Run;- baseline_content: string;- }-export type AutocompleteCompletionItemKind = typeof AutocompleteCompletionItemKind[keyof typeof AutocompleteCompletionItemKind];@@ -8328,6 +8276,12 @@ export namespace Schemas {Zmw: 'ZMW',} as const;+ export interface UserBasicInfo {+ id: number;+ first_name: string;+ email: string;+ }+export interface QuarantineSourceRun {id: string;branch: string;@@ -18249,6 +18203,55 @@ export namespace Schemas {ordered_ids: string[];}+ export interface RunSummary {+ total: number;+ changed: number;+ new: number;+ removed: number;+ unchanged: number;+ unresolved?: number;+ tolerated_matched?: number;+ }++ export type RunMetadata = { [key: string]: unknown };++ export interface Run {+ approved_by?: UserBasicInfo | null;+ id: string;+ repo_id: string;+ status: string;+ run_type: string;+ commit_sha: string;+ branch: string;+ /** @nullable */+ pr_number: number | null;+ approved: boolean;+ /** @nullable */+ approved_at: string | null;+ summary: RunSummary;+ /** @nullable */+ error_message: string | null;+ created_at: string;+ /** @nullable */+ completed_at: string | null;+ is_stale?: boolean;+ /** @nullable */+ superseded_by_id?: string | null;+ metadata?: RunMetadata;+ }++ export interface FinalizeResult {+ run: Run;+ baseline_content: string;+ }++ export interface FinalizeRunRequestInput {+ /** Approve every still-pending changed and new snapshot before finalizing (tolerated snapshots are left untouched). Leave false to finalize a run you've already reviewed — finalizing fails if any changed/new snapshot is still unreviewed. */+ approve_all?: boolean;+ /** Whether the server commits the approved baseline to the PR branch and greens the gate (the normal path — leave true). Set false only for tooling that commits the baseline itself: the server skips the commit and returns the signed YAML in `baseline_content` instead. With false, the gate is NOT greened and `metadata.baseline_commit_sha` is absent. */+ commit_to_github?: boolean;+ }+export interface FlagValueItem {name: unknown;}diff --git a/services/mcp/src/generated/visual_review/api.ts b/services/mcp/src/generated/visual_review/api.tsindex 2598f558a62d..4fd711b1383a 100644--- a/services/mcp/src/generated/visual_review/api.ts+++ b/services/mcp/src/generated/visual_review/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 10 enabled ops+ * PostHog API - MCP 11 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -69,10 +69,10 @@ export const VisualReviewRunsRetrieveParams = /* @__PURE__ */ zod.object({})/**- * Approve visual changes for snapshots in this run.+ * Mark snapshots reviewed (DB only).-With approve_all=true, approves all changed+new snapshots and returns-signed baseline YAML. With specific snapshots, approves only those.+Records the per-snapshot "Accept change" decision. Does not commit the baseline+or change the GitHub gate — call finalize to ship the run.*/export const VisualReviewRunsApproveCreateParams = /* @__PURE__ */ zod.object({id: zod.string(),@@ -83,9 +83,6 @@ export const VisualReviewRunsApproveCreateParams = /* @__PURE__ */ zod.object({),})-export const visualReviewRunsApproveCreateBodyApproveAllDefault = false-export const visualReviewRunsApproveCreateBodyCommitToGithubDefault = true-export const VisualReviewRunsApproveCreateBody = /* @__PURE__ */ zod.object({snapshots: zod.array(@@ -98,21 +95,43 @@ export const VisualReviewRunsApproveCreateBody = /* @__PURE__ */ zod.object({.describe('The content hash of the new baseline image to record for this identifier.'),}))- .optional().describe(- 'Specific snapshots to approve, each with `identifier` and `new_hash`. Ignored when `approve_all` is true.'+ 'Snapshots to mark reviewed, each with `identifier` and `new_hash`. This only records the review in the database (the per-snapshot "Accept change" action) — it does not change the baseline or the GitHub gate. Commit the baseline and green the gate with the finalize endpoint.'),+})++/**+ * Finalize a fully-reviewed run: commit the approved baseline and green the gate.++Commits exactly the snapshots approved in the DB (tolerated ones keep their baseline)+and only succeeds once every changed/new snapshot is resolved. With approve_all=true,+any still-pending changed/new snapshot is approved first. With commit_to_github=false+the server returns the signed baseline YAML instead of committing it.+ */+export const VisualReviewRunsFinalizeCreateParams = /* @__PURE__ */ zod.object({+ id: zod.string(),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const visualReviewRunsFinalizeCreateBodyApproveAllDefault = false+export const visualReviewRunsFinalizeCreateBodyCommitToGithubDefault = true++export const VisualReviewRunsFinalizeCreateBody = /* @__PURE__ */ zod.object({approve_all: zod.boolean()- .default(visualReviewRunsApproveCreateBodyApproveAllDefault)+ .default(visualReviewRunsFinalizeCreateBodyApproveAllDefault).describe(- 'Approve every changed and new snapshot in the run. Mutually exclusive with `snapshots` — pass one or the other.'+ "Approve every still-pending changed and new snapshot before finalizing (tolerated snapshots are left untouched). Leave false to finalize a run you've already reviewed — finalizing fails if any changed/new snapshot is still unreviewed."),commit_to_github: zod.boolean()- .default(visualReviewRunsApproveCreateBodyCommitToGithubDefault)+ .default(visualReviewRunsFinalizeCreateBodyCommitToGithubDefault).describe(- 'Whether to commit the updated baseline YAML to the PR branch on GitHub. Set to false to record the approval without pushing a commit.'+ 'Whether the server commits the approved baseline to the PR branch and greens the gate (the normal path — leave true). Set false only for tooling that commits the baseline itself: the server skips the commit and returns the signed YAML in `baseline_content` instead. With false, the gate is NOT greened and `metadata.baseline_commit_sha` is absent.'),})diff --git a/services/mcp/src/tools/generated/visual_review.ts b/services/mcp/src/tools/generated/visual_review.tsindex 29be480271e5..869783859049 100644--- a/services/mcp/src/tools/generated/visual_review.ts+++ b/services/mcp/src/tools/generated/visual_review.ts@@ -7,6 +7,8 @@ import {VisualReviewReposRetrieveParams,VisualReviewRunsApproveCreateBody,VisualReviewRunsApproveCreateParams,+ VisualReviewRunsFinalizeCreateBody,+ VisualReviewRunsFinalizeCreateParams,VisualReviewRunsListQueryParams,VisualReviewRunsRetrieveParams,VisualReviewRunsSnapshotHistoryListParams,@@ -63,10 +65,7 @@ const VisualReviewRunsApproveCreateSchema = VisualReviewRunsApproveCreateParams.VisualReviewRunsApproveCreateBody.shape)-const visualReviewRunsApproveCreate = (): ToolBase<- typeof VisualReviewRunsApproveCreateSchema,- Schemas.AutoApproveResult-> => ({+const visualReviewRunsApproveCreate = (): ToolBase<typeof VisualReviewRunsApproveCreateSchema, Schemas.Run> => ({name: 'visual-review-runs-approve-create',schema: VisualReviewRunsApproveCreateSchema,handler: async (context: Context, params: z.infer<typeof VisualReviewRunsApproveCreateSchema>) => {@@ -75,13 +74,7 @@ const visualReviewRunsApproveCreate = (): ToolBase<if (params.snapshots !== undefined) {body['snapshots'] = params.snapshots}- if (params.approve_all !== undefined) {- body['approve_all'] = params.approve_all- }- if (params.commit_to_github !== undefined) {- body['commit_to_github'] = params.commit_to_github- }- const result = await context.api.request<Schemas.AutoApproveResult>({+ const result = await context.api.request<Schemas.Run>({method: 'POST',path: `/api/projects/${encodeURIComponent(String(projectId))}/visual_review/runs/${encodeURIComponent(String(params.id))}/approve/`,body,@@ -109,6 +102,34 @@ const visualReviewRunsCountsRetrieve = (): ToolBase<},})+const VisualReviewRunsFinalizeCreateSchema = VisualReviewRunsFinalizeCreateParams.omit({ project_id: true }).extend(+ VisualReviewRunsFinalizeCreateBody.shape+)++const visualReviewRunsFinalizeCreate = (): ToolBase<+ typeof VisualReviewRunsFinalizeCreateSchema,+ Schemas.FinalizeResult+> => ({+ name: 'visual-review-runs-finalize-create',+ schema: VisualReviewRunsFinalizeCreateSchema,+ handler: async (context: Context, params: z.infer<typeof VisualReviewRunsFinalizeCreateSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const body: Record<string, unknown> = {}+ if (params.approve_all !== undefined) {+ body['approve_all'] = params.approve_all+ }+ if (params.commit_to_github !== undefined) {+ body['commit_to_github'] = params.commit_to_github+ }+ const result = await context.api.request<Schemas.FinalizeResult>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/visual_review/runs/${encodeURIComponent(String(params.id))}/finalize/`,+ body,+ })+ return result+ },+})+const VisualReviewRunsListSchema = VisualReviewRunsListQueryParamsconst visualReviewRunsList = (): ToolBase<@@ -263,6 +284,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'visual-review-repos-retrieve': visualReviewReposRetrieve,'visual-review-runs-approve-create': visualReviewRunsApproveCreate,'visual-review-runs-counts-retrieve': visualReviewRunsCountsRetrieve,+ 'visual-review-runs-finalize-create': visualReviewRunsFinalizeCreate,'visual-review-runs-list': visualReviewRunsList,'visual-review-runs-retrieve': visualReviewRunsRetrieve,'visual-review-runs-snapshot-history-list': visualReviewRunsSnapshotHistoryList,