Skip to content

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

fix(visual-review): post a new PR comment for new visual changes (#100463)

posthog[bot]e39a7bb51ee7
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index 4f9b376bbeaa..6923244eb69c 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -208,6 +208,17 @@ Add `--tolerate-drift` to report the drift and still exit 0. Use it on the defau
- **`observe`** — tracking only. Backend rejects approval attempts; no PR comment; excluded from "needs review". The commit status is posted green (`success`, "Tracking only…") to a separate, non-gating `… (tracking)` context — never the gating `PostHog Visual Review / {run_type}` one. `purpose` is client-supplied, so greening the gating context would let an observe run bypass branch protection on a PR head SHA; the separate context keeps observe runs informational-only (like `(partial)` runs). The UI hides all approval affordances. Use on master pushes and merge-queue branches, where there's no PR to approve.
The commit status never gates, but the exit code of `vr run complete` still does, and that is where a caller chooses. A merge-queue branch renders the tree about to land, so it lets drift fail the job. Master passes `--tolerate-drift` instead.
+### PR comments
+
+Enabled per repo with `enable_pr_comments`.
+A run that needs review posts its own comment, so GitHub notifies the reviewers and the prompt sits at the bottom of the PR with the new changes.
+GitHub sends nothing for an edit, so a run must not rewrite an earlier comment into a new prompt — a reviewer who already approved would never learn that more changes arrived.
+After the new prompt lands, the run clears the previous comment of its own run type: an approval is kept and marked as covering an earlier revision, an unanswered prompt is deleted.
+This order keeps the existing prompt on the PR when the post fails.
+Each run type keeps its own live prompt, because each one has a separate gate and a separate approval.
+An approval updates the prompt of its own run in place, because the reviewer who approved needs no notification.
+A run that never got a prompt, because it found nothing to review or because the post failed, posts a new comment on approval instead.
+
## Current state
Working end to end: CI upload → async diff → GitHub Check → web review → approve → baseline commit → clean re-run. Multi-repo per team, snapshot change history across runs, run supersession, GitHub commit status checks on transitions.
diff --git a/products/visual_review/backend/logic/approvals.py b/products/visual_review/backend/logic/approvals.py
index ab0ee1d94e8b..56b53d56092a 100644
--- a/products/visual_review/backend/logic/approvals.py
+++ b/products/visual_review/backend/logic/approvals.py
@@ -40,10 +40,11 @@ def finalize_run(
Set ``commit_to_github=False`` for CLI auto-approve, which writes the baseline locally
instead of pushing it to the PR branch.
- The post-approval PR comment is always posted (subject to the existing conditions: repo
- PR comments enabled, run initiated from a GitHub review prompt). ``add_images_to_comment_on_pr``
- only controls whether the before/after snapshot images are embedded in that comment;
- defaults false so the comment stays a text summary unless the reviewer opts in.
+ The post-approval PR comment is posted when the repo has PR comments enabled and
+ ``commit_to_github`` is true. It updates the run's review prompt when the run has one, and
+ posts a new comment when it does not. ``add_images_to_comment_on_pr`` only controls whether
+ the before/after snapshot images are embedded in that comment; defaults false so the comment
+ stays a text summary unless the reviewer opts in.
"""
run = run_queries._get_run_for_update(run_id, team_id=team_id)
repo = run.repo
diff --git a/products/visual_review/backend/logic/comment_markdown.py b/products/visual_review/backend/logic/comment_markdown.py
index a1af63770b5e..cb71fe5f246b 100644
--- a/products/visual_review/backend/logic/comment_markdown.py
+++ b/products/visual_review/backend/logic/comment_markdown.py
@@ -194,6 +194,29 @@ def _build_snapshot_image_tables(run: Run, repo: Repo) -> str:
return "\n\n".join(sections)
+def _build_review_prompt_body(run: Run, repo: Repo) -> str:
+ """Build the markdown body of the PR comment that asks for a visual review."""
+ return (
+ "👋 **Visual changes detected** for this PR.\n\n"
+ f"[Review and approve in PostHog Visual Review]({_run_url(run, repo)})\n\n"
+ "If these changes are unexpected, they may be caused by a flaky test or a "
+ "broken snapshot on master. Don't approve — rerun the job or wait for a fix."
+ )
+
+
+def _build_superseded_approval_body(run: Run, repo: Repo, approver: _Approver | None) -> str:
+ """Rewrite an approval comment that a later run replaced.
+
+ The approval still happened, so keep the summary and say which revision it
+ covered — the new changes are prompted for in a comment of their own.
+ """
+ note = (
+ "🕓 _This approval covered an earlier revision. There are new visual changes to review "
+ "in the newer comment below._"
+ )
+ return f"{note}\n\n{_build_approval_comment_body(run, repo, approver)}"
+
+
def _build_approval_comment_body(run: Run, repo: Repo, approver: _Approver | None, add_images: bool = False) -> str:
"""Build the markdown body of the post-approval PR comment.
diff --git a/products/visual_review/backend/logic/comments.py b/products/visual_review/backend/logic/comments.py
index eb43f83beda3..e7f842b34d90 100644
--- a/products/visual_review/backend/logic/comments.py
+++ b/products/visual_review/backend/logic/comments.py
@@ -1,4 +1,4 @@
-"""Posting and updating the one visual-review comment per PR."""
+"""Posting and updating the visual-review comment on a PR."""
from __future__ import annotations
@@ -8,7 +8,7 @@ import structlog
from posthog.egress.github.transport import GitHubRateLimitError
-from ..db import READER_DB, WRITER_DB
+from ..db import WRITER_DB
from ..facade.enums import ReviewDecision, RunPurpose
from ..models import Repo, Run
from . import comment_markdown, github_api, run_queries
@@ -16,28 +16,78 @@ from . import comment_markdown, github_api, run_queries
logger = structlog.get_logger(__name__)
-def _find_existing_comment_id(repo: Repo, pr_number: int, exclude_run_id: UUID) -> int | None:
- """Find the GitHub comment ID from a previous run on the same PR."""
+def _comment_id(run: Run) -> int | None:
+ """The GitHub comment ID stored on a run, if it has one."""
+ value = run.metadata.get("github_comment_id")
+ if isinstance(value, int):
+ return value
+ if isinstance(value, str) and value.isdigit():
+ return int(value)
+ return None
+
+
+def _previous_comment(repo: Repo, pr_number: int, run_type: str, exclude_run_id: UUID) -> tuple[Run, int] | None:
+ """The run of this run type that owns its live visual-review comment, and that comment's ID.
+
+ Scoped to the run type because supersession and the commit status are: a PR can carry
+ an active run per run type, each with its own gate and its own approval, so another
+ type's prompt is still waiting for an answer and must not be retired.
+
+ Reads the writer: ``review_decision`` decides whether the comment is rewritten or
+ deleted, and a replica that still reports the pre-approval value would delete a
+ comment that records a human decision.
+ """
previous_run = (
- Run.objects.filter(repo=repo, pr_number=pr_number, metadata__has_key="github_comment_id")
+ Run.objects.using(WRITER_DB)
+ .filter(repo=repo, pr_number=pr_number, run_type=run_type, metadata__has_key="github_comment_id")
.exclude(id=exclude_run_id)
.order_by("-created_at")
.first()
)
- if previous_run:
- value = previous_run.metadata.get("github_comment_id")
- if isinstance(value, int):
- return value
- if isinstance(value, str) and value.isdigit():
- return int(value)
- return None
+ if previous_run is None:
+ return None
+ comment_id = _comment_id(previous_run)
+ return (previous_run, comment_id) if comment_id is not None else None
+
+
+def _retire_previous_comment(repo: Repo, previous_run: Run, comment_id: int) -> None:
+ """Clear the previous run's comment of this run type out of the way once a new one is posted.
+
+ An approval comment records a human decision, so it stays and says which revision
+ it covered. An unanswered review prompt holds nothing worth keeping, so it goes.
+ Best-effort: a failure here only leaves an extra comment on the PR.
+ """
+ if previous_run.review_decision == ReviewDecision.HUMAN_APPROVED:
+ approver = comment_markdown._resolve_approver(previous_run.approved_by_id)
+ response = github_api._github_api_request(
+ method="PATCH",
+ repo=repo,
+ path=f"issues/comments/{comment_id}",
+ json={"body": comment_markdown._build_superseded_approval_body(previous_run, repo, approver)},
+ )
+ retired = response.status_code == 200
+ else:
+ response = github_api._github_api_request(method="DELETE", repo=repo, path=f"issues/comments/{comment_id}")
+ retired = response.status_code in (204, 404)
+
+ if not retired:
+ logger.info(
+ "visual_review.previous_pr_comment_not_retired",
+ run_id=str(previous_run.id),
+ comment_id=comment_id,
+ status_code=response.status_code,
+ )
def _post_review_prompt_comment(run: Run, repo: Repo) -> None:
"""
- Post or update a PR comment prompting reviewers to approve visual changes.
+ Post a PR comment prompting reviewers to approve visual changes.
- One comment per PR — subsequent runs update the existing comment in place.
+ Every run that needs review posts its own comment, so GitHub notifies the
+ reviewers and the prompt sits at the bottom of the PR with the new changes.
+ The previous run's comment is retired after the new one lands, to keep one live
+ prompt per run type. Retiring first would leave the PR with no prompt at all when
+ the post then fails.
Skips non-actionable runs (observe-only, stale/superseded, already commented).
Best-effort and never raises.
"""
@@ -53,34 +103,11 @@ def _post_review_prompt_comment(run: Run, repo: Repo) -> None:
if run.metadata.get("github_comment_id"):
return
- run_url = comment_markdown._run_url(run, repo)
- comment_body = (
- f"👋 **Visual changes detected** for this PR.\n\n"
- f"[Review and approve in PostHog Visual Review]({run_url})\n\n"
- f"If these changes are unexpected, they may be caused by a flaky test or a "
- f"broken snapshot on master. Don't approve — rerun the job or wait for a fix."
- )
+ comment_body = comment_markdown._build_review_prompt_body(run, repo)
+ previous: tuple[Run, int] | None = None
try:
- existing_comment_id = _find_existing_comment_id(repo, run.pr_number, exclude_run_id=run.id)
- if existing_comment_id:
- response = github_api._github_api_request(
- method="PATCH",
- repo=repo,
- path=f"issues/comments/{existing_comment_id}",
- json={"body": comment_body},
- )
- if response.status_code == 200:
- run.metadata["github_comment_id"] = existing_comment_id
- run.save(update_fields=["metadata"])
- return
- # Comment was deleted or inaccessible — fall through to create new one
- logger.info(
- "visual_review.pr_comment_update_failed_will_create",
- run_id=str(run.id),
- comment_id=existing_comment_id,
- status_code=response.status_code,
- )
+ previous = _previous_comment(repo, run.pr_number, run.run_type, exclude_run_id=run.id)
response = github_api._github_api_request(
method="POST",
@@ -88,11 +115,7 @@ def _post_review_prompt_comment(run: Run, repo: Repo) -> None:
path=f"issues/{run.pr_number}/comments",
json={"body": comment_body},
)
- if response.status_code == 201:
- comment_id = response.json().get("id")
- run.metadata["github_comment_id"] = comment_id
- run.save(update_fields=["metadata"])
- else:
+ if response.status_code != 201:
logger.warning(
"visual_review.pr_comment_failed",
run_id=str(run.id),
@@ -100,17 +123,36 @@ def _post_review_prompt_comment(run: Run, repo: Repo) -> None:
status_code=response.status_code,
response=response.text[:200],
)
+ return
+
+ comment_id = response.json().get("id")
+ run.metadata["github_comment_id"] = comment_id
+ run.save(update_fields=["metadata"])
except Exception:
logger.warning("visual_review.pr_comment_error", run_id=str(run.id), pr_number=run.pr_number, exc_info=True)
+ return
+
+ if previous is None:
+ return
+
+ try:
+ _retire_previous_comment(repo, *previous)
+ except Exception:
+ logger.warning(
+ "visual_review.previous_pr_comment_retire_error",
+ run_id=str(previous[0].id),
+ comment_id=previous[1],
+ exc_info=True,
+ )
def _post_approval_comment(run: Run, repo: Repo, add_images: bool = False) -> None:
- """Update the existing PR comment in place with the approved-changes summary.
+ """Report an approval on the PR, as an update of this run's own review prompt.
- Best-effort and never raises. Skips silently when the original review-prompt
- comment was never posted (no `github_comment_id` in run.metadata) — i.e.,
- when the review wasn't initiated by a human. ``add_images`` embeds the
- before/after snapshot images in the comment when the reviewer opted in.
+ Falls back to a new comment when the prompt is gone or was never posted, so an
+ approval is always visible on the PR. ``add_images`` embeds the before/after
+ snapshot images in the comment when the reviewer opted in. Best-effort and
+ never raises.
"""
if not repo.enable_pr_comments:
return
@@ -121,58 +163,53 @@ def _post_approval_comment(run: Run, repo: Repo, add_images: bool = False) -> No
if run.review_decision != ReviewDecision.HUMAN_APPROVED:
return
- comment_id = run.metadata.get("github_comment_id")
- if not comment_id:
- return
- if isinstance(comment_id, str) and comment_id.isdigit():
- comment_id = int(comment_id)
- if not isinstance(comment_id, int):
- return
-
approver = comment_markdown._resolve_approver(run.approved_by_id)
body = comment_markdown._build_approval_comment_body(run, repo, approver, add_images=add_images)
+ comment_id = _comment_id(run)
try:
- response = github_api._github_api_request(
- method="PATCH",
- repo=repo,
- path=f"issues/comments/{comment_id}",
- json={"body": body},
- timeout=15,
- )
- if response.status_code == 200:
- return
-
- # Comment was deleted or inaccessible — fall back to creating a new one
- if response.status_code == 404:
- create_response = github_api._github_api_request(
- method="POST",
+ if comment_id is not None:
+ response = github_api._github_api_request(
+ method="PATCH",
repo=repo,
- path=f"issues/{run.pr_number}/comments",
+ path=f"issues/comments/{comment_id}",
json={"body": body},
timeout=15,
)
- if create_response.status_code == 201:
- new_comment_id = create_response.json().get("id")
- if isinstance(new_comment_id, int):
- run.metadata["github_comment_id"] = new_comment_id
- run.save(update_fields=["metadata"], using=WRITER_DB)
+ if response.status_code == 200:
return
- logger.warning(
- "visual_review.approval_comment_create_failed",
- run_id=str(run.id),
- pr_number=run.pr_number,
- status_code=create_response.status_code,
- response=create_response.text[:200],
- )
+
+ # Anything but a missing comment is not fixed by posting a second one.
+ if response.status_code != 404:
+ logger.warning(
+ "visual_review.approval_comment_update_failed",
+ run_id=str(run.id),
+ comment_id=comment_id,
+ status_code=response.status_code,
+ response=response.text[:200],
+ )
+ return
+
+ create_response = github_api._github_api_request(
+ method="POST",
+ repo=repo,
+ path=f"issues/{run.pr_number}/comments",
+ json={"body": body},
+ timeout=15,
+ )
+ if create_response.status_code == 201:
+ new_comment_id = create_response.json().get("id")
+ if isinstance(new_comment_id, int):
+ run.metadata["github_comment_id"] = new_comment_id
+ run.save(update_fields=["metadata"], using=WRITER_DB)
return
logger.warning(
- "visual_review.approval_comment_update_failed",
+ "visual_review.approval_comment_create_failed",
run_id=str(run.id),
- comment_id=comment_id,
- status_code=response.status_code,
- response=response.text[:200],
+ pr_number=run.pr_number,
+ status_code=create_response.status_code,
+ response=create_response.text[:200],
)
except GitHubRateLimitError:
# Bubble up so the Celery task can retry with the suggested countdown.
@@ -187,10 +224,15 @@ def _post_approval_comment(run: Run, repo: Repo, add_images: bool = False) -> No
def post_approval_comment_for_run(run_id: UUID, team_id: int | None = None, add_images: bool = False) -> None:
- """Public entrypoint for the Celery task to update a PR comment after approval."""
+ """Public entrypoint for the Celery task to update a PR comment after approval.
+
+ Reads the writer: ``finalize_run`` queues this task on commit, so a replica that
+ still reports the pre-approval ``review_decision`` makes the post silently skip,
+ and nothing retries it.
+ """
run = (
Run.objects.select_related("repo")
- .using(READER_DB)
+ .using(WRITER_DB)
.filter(id=run_id, **({"team_id": team_id} if team_id is not None else {}))
.first()
)
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index 96c2815c17fd..06f5f198ef5d 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -282,7 +282,7 @@ class FinalizeRunInputSerializer(DataclassSerializer):
"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."
+ "greened, `metadata.baseline_commit_sha` is absent, and no post-approval PR comment is posted."
),
)
add_images_to_comment_on_pr = serializers.BooleanField(
@@ -290,9 +290,10 @@ class FinalizeRunInputSerializer(DataclassSerializer):
default=False,
help_text=(
"Whether to embed the before/after snapshot images in the post-approval PR comment. The comment "
- "itself is always posted (when the run was initiated from a GitHub review prompt and the repo has "
- "PR comments enabled); this flag only controls the images. Defaults false — the comment stays a "
- "text summary unless the reviewer opts in to attach the snapshots."
+ "itself is posted when the repo has PR comments enabled and `commit_to_github` is true: it updates "
+ "the run's review prompt when the run has one, and posts a new comment when it does not. This flag "
+ "only controls the images. Defaults false — the comment stays a text summary unless the reviewer "
+ "opts in to attach the snapshots."
),
)
diff --git a/products/visual_review/backend/tests/conftest.py b/products/visual_review/backend/tests/conftest.py
index 56881dd1410f..befd4e433aef 100644
--- a/products/visual_review/backend/tests/conftest.py
+++ b/products/visual_review/backend/tests/conftest.py
@@ -316,6 +316,10 @@ def mock_github_api(local_git_repo):
issue_comments.append({**data, "action": "updated"})
return (200, {}, json.dumps({"id": 1, "body": data["body"]}))
+ def issue_comment_delete_callback(request):
+ issue_comments.append({"id": int(request.url.rsplit("/", 1)[-1]), "action": "deleted"})
+ return (204, {}, "")
+
rsps.add_callback(
responses.GET,
re.compile(r"https://api\.github\.com/repos/.+/pulls/\d+"),
@@ -346,6 +350,11 @@ def mock_github_api(local_git_repo):
re.compile(r"https://api\.github\.com/repos/.+/issues/comments/\d+"),
callback=issue_comment_update_callback,
)
+ rsps.add_callback(
+ responses.DELETE,
+ re.compile(r"https://api\.github\.com/repos/.+/issues/comments/\d+"),
+ callback=issue_comment_delete_callback,
+ )
rsps.status_checks = status_checks # type: ignore[attr-defined]
rsps.issue_comments = issue_comments # type: ignore[attr-defined]
diff --git a/products/visual_review/backend/tests/logic/test_ci_status.py b/products/visual_review/backend/tests/logic/test_ci_status.py
index cf9d1851b65b..32ac202c778b 100644
--- a/products/visual_review/backend/tests/logic/test_ci_status.py
+++ b/products/visual_review/backend/tests/logic/test_ci_status.py
@@ -143,7 +143,7 @@ class TestCommitStatusChecks:
run.refresh_from_db()
assert run.metadata["github_comment_id"] is not None
- def test_subsequent_run_updates_existing_comment(self, github_repo, mock_github_api):
+ def test_subsequent_run_posts_a_new_comment(self, github_repo, mock_github_api):
github_repo.enable_pr_comments = True
github_repo.save(update_fields=["enable_pr_comments"])
@@ -175,11 +175,13 @@ class TestCommitStatusChecks:
)
runs.finish_processing(run2.id)
+ # A silent edit of the first comment gives reviewers no cue that new changes
+ # arrived, so the second run deletes it and posts its prompt at the bottom.
created = [c for c in mock_github_api.issue_comments if c["action"] == "created"]
- updated = [c for c in mock_github_api.issue_comments if c["action"] == "updated"]
- assert len(created) == 1
- assert len(updated) == 1
- assert f"/visual_review/runs/{run2.id}" in updated[0]["body"]
+ deleted = [c for c in mock_github_api.issue_comments if c["action"] == "deleted"]
+ assert len(created) == 2
+ assert [c["id"] for c in deleted] == [created[0]["id"]]
+ assert f"/visual_review/runs/{run2.id}" in created[1]["body"]
def test_complete_run_does_not_comment_twice_on_retry(self, github_repo, mock_github_api):
github_repo.enable_pr_comments = True
diff --git a/products/visual_review/backend/tests/logic/test_comments.py b/products/visual_review/backend/tests/logic/test_comments.py
index 72ebc890cbba..2236b4017498 100644
--- a/products/visual_review/backend/tests/logic/test_comments.py
+++ b/products/visual_review/backend/tests/logic/test_comments.py
@@ -2,9 +2,12 @@
import pytest
+from django.db.models import F
+
from parameterized import parameterized
-from products.visual_review.backend.facade.enums import ReviewDecision, ReviewState, SnapshotResult
+from products.visual_review.backend.db import WRITER_DB
+from products.visual_review.backend.facade.enums import ReviewDecision, ReviewState, RunType, SnapshotResult
from products.visual_review.backend.logic import comment_markdown, comments, github_api
from products.visual_review.backend.models import Repo, Run, RunSnapshot
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -205,13 +208,28 @@ class TestApprovalComment:
comments._post_approval_comment(run_with_snapshots, repo)
spy.assert_not_called()
- def test_post_approval_comment_skips_when_no_existing_comment_id(self, repo, run_with_snapshots, mocker):
+ def test_post_approval_comment_posts_when_no_existing_comment_id(self, repo, run_with_snapshots, mocker):
+ # No review prompt was posted for this run, but the approval still belongs on the PR
run_with_snapshots.metadata = {}
run_with_snapshots.save(update_fields=["metadata"])
- spy = mocker.patch.object(github_api, "_github_api_request")
+ class PostResp:
+ status_code = 201
+ text = ""
+
+ @staticmethod
+ def json():
+ return {"id": 7777}
+
+ spy = mocker.patch.object(github_api, "_github_api_request", return_value=PostResp())
comments._post_approval_comment(run_with_snapshots, repo)
- spy.assert_not_called()
+
+ spy.assert_called_once()
+ kwargs = spy.call_args.kwargs
+ assert kwargs["method"] == "POST"
+ assert kwargs["path"] == "issues/42/comments"
+ run_with_snapshots.refresh_from_db()
+ assert run_with_snapshots.metadata["github_comment_id"] == 7777
def test_post_approval_comment_patches_existing_comment(self, repo, run_with_snapshots, mocker):
class FakeResp:
@@ -510,3 +528,214 @@ class TestApprovalComment:
assert url is not None
assert "full_h" in url
assert "thumb_h" not in url
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestReviewPromptComment:
+ """Tests for the PR comment that asks for a visual review."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return Repo.objects.create(
+ team_id=team.id,
+ repo_external_id=77777,
+ repo_full_name="test-org/prompt-repo",
+ enable_pr_comments=True,
+ )
+
+ @staticmethod
+ def _mk_run(repo, commit_sha, **kwargs):
+ """A run with one changed snapshot, self-superseded so the next run can be created.
+
+ Only the latest run per (repo, branch, run type) may be un-superseded, and
+ `create_run` supersedes the previous one before inserting the new one.
+ """
+ run_type = kwargs.get("run_type", RunType.OTHER)
+ Run.objects.filter(repo=repo, run_type=run_type, superseded_by__isnull=True).update(superseded_by=F("id"))
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha=commit_sha,
+ branch="feature",
+ pr_number=42,
+ **kwargs,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Login/Form",
+ current_hash="curr",
+ baseline_hash="base",
+ result=SnapshotResult.CHANGED,
+ )
+ return run
+
+ @staticmethod
+ def _post_response(comment_id):
+ class PostResp:
+ status_code = 201
+ text = ""
+
+ @staticmethod
+ def json():
+ return {"id": comment_id}
+
+ return PostResp()
+
+ def test_posts_a_new_comment_when_the_pr_has_none(self, repo, mocker):
+ run = self._mk_run(repo, "aaa111")
+ spy = mocker.patch.object(github_api, "_github_api_request", return_value=self._post_response(5001))
+
+ comments._post_review_prompt_comment(run, repo)
+
+ spy.assert_called_once()
+ kwargs = spy.call_args.kwargs
+ assert kwargs["method"] == "POST"
+ assert kwargs["path"] == "issues/42/comments"
+ assert "Visual changes detected" in kwargs["json"]["body"]
+ run.refresh_from_db()
+ assert run.metadata["github_comment_id"] == 5001
+
+ def test_rewrites_an_approval_comment_and_posts_a_new_one(self, repo, mocker):
+ # The reviewer already approved: rewriting that comment into a review prompt
+ # sends no notification, so the approval is kept and a new prompt is posted.
+ approved = self._mk_run(
+ repo,
+ "aaa111",
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ metadata={"github_comment_id": 5001},
+ )
+ run = self._mk_run(repo, "bbb222")
+
+ class PatchResp:
+ status_code = 200
+ text = ""
+
+ spy = mocker.patch.object(
+ github_api, "_github_api_request", side_effect=[self._post_response(5002), PatchResp()]
+ )
+
+ comments._post_review_prompt_comment(run, repo)
+
+ post_call, patch_call = (call.kwargs for call in spy.call_args_list)
+ assert patch_call["method"] == "PATCH"
+ assert patch_call["path"] == "issues/comments/5001"
+ assert "✅ **Visual changes approved**" in patch_call["json"]["body"]
+ assert "covered an earlier revision" in patch_call["json"]["body"]
+ assert f"/visual_review/runs/{approved.id}" in patch_call["json"]["body"]
+ assert post_call["method"] == "POST"
+ assert f"/visual_review/runs/{run.id}" in post_call["json"]["body"]
+ run.refresh_from_db()
+ assert run.metadata["github_comment_id"] == 5002
+
+ def test_deletes_an_unanswered_prompt_and_posts_a_new_one(self, repo, mocker):
+ self._mk_run(repo, "aaa111", metadata={"github_comment_id": 5001})
+ run = self._mk_run(repo, "bbb222")
+
+ class DeleteResp:
+ status_code = 204
+ text = ""
+
+ spy = mocker.patch.object(
+ github_api, "_github_api_request", side_effect=[self._post_response(5002), DeleteResp()]
+ )
+
+ comments._post_review_prompt_comment(run, repo)
+
+ post_call, delete_call = (call.kwargs for call in spy.call_args_list)
+ assert delete_call["method"] == "DELETE"
+ assert delete_call["path"] == "issues/comments/5001"
+ assert post_call["method"] == "POST"
+ run.refresh_from_db()
+ assert run.metadata["github_comment_id"] == 5002
+
+ @pytest.mark.parametrize("status", [403, 404], ids=["delete_failed", "comment_gone"])
+ def test_posts_a_new_comment_even_when_the_old_one_cannot_be_retired(self, status, repo, mocker):
+ self._mk_run(repo, "aaa111", metadata={"github_comment_id": 5001})
+ run = self._mk_run(repo, "bbb222")
+
+ class DeleteResp:
+ status_code = status
+ text = "nope"
+
+ mocker.patch.object(github_api, "_github_api_request", side_effect=[self._post_response(5002), DeleteResp()])
+
+ comments._post_review_prompt_comment(run, repo)
+
+ run.refresh_from_db()
+ assert run.metadata["github_comment_id"] == 5002
+
+ def test_keeps_the_prompt_of_another_run_type(self, repo, mocker):
+ # Each run type has its own gate and its own approval, so the other type's
+ # run is still waiting for a reviewer.
+ other_type = self._mk_run(repo, "aaa111", run_type=RunType.STORYBOOK, metadata={"github_comment_id": 5001})
+ run = self._mk_run(repo, "bbb222", run_type=RunType.PLAYWRIGHT)
+
+ spy = mocker.patch.object(github_api, "_github_api_request", return_value=self._post_response(5002))
+
+ comments._post_review_prompt_comment(run, repo)
+
+ spy.assert_called_once()
+ assert spy.call_args.kwargs["method"] == "POST"
+ other_type.refresh_from_db()
+ assert other_type.metadata["github_comment_id"] == 5001
+ assert other_type.superseded_by_id is None
+
+ def test_keeps_the_previous_comment_when_the_new_prompt_cannot_be_posted(self, repo, mocker):
+ # Retiring first would take the PR down to no prompt at all.
+ previous = self._mk_run(repo, "aaa111", metadata={"github_comment_id": 5001})
+ run = self._mk_run(repo, "bbb222")
+
+ class PostResp:
+ status_code = 500
+ text = "boom"
+
+ spy = mocker.patch.object(github_api, "_github_api_request", return_value=PostResp())
+
+ comments._post_review_prompt_comment(run, repo)
+
+ spy.assert_called_once()
+ assert spy.call_args.kwargs["method"] == "POST"
+ previous.refresh_from_db()
+ assert previous.metadata["github_comment_id"] == 5001
+ run.refresh_from_db()
+ assert "github_comment_id" not in run.metadata
+
+ def test_keeps_the_new_prompt_when_retirement_raises(self, repo, mocker):
+ self._mk_run(repo, "aaa111", metadata={"github_comment_id": 5001})
+ run = self._mk_run(repo, "bbb222")
+
+ mocker.patch.object(
+ github_api, "_github_api_request", side_effect=[self._post_response(5002), RuntimeError("boom")]
+ )
+
+ comments._post_review_prompt_comment(run, repo)
+
+ run.refresh_from_db()
+ assert run.metadata["github_comment_id"] == 5002
+
+ def test_reads_the_previous_run_from_the_writer(self, repo, mocker):
+ # Both aliases share one database under test, so only the call records
+ # that a replica read cannot decide between rewriting and deleting.
+ self._mk_run(repo, "aaa111", metadata={"github_comment_id": 5001})
+ run = self._mk_run(repo, "bbb222")
+ using = mocker.spy(Run.objects, "using")
+
+ previous = comments._previous_comment(repo, 42, run.run_type, exclude_run_id=run.id)
+
+ using.assert_called_once_with(WRITER_DB)
+ assert previous is not None and previous[1] == 5001
+
+ def test_skips_a_run_that_already_commented(self, repo, mocker):
+ run = self._mk_run(repo, "aaa111", metadata={"github_comment_id": 5001})
+ spy = mocker.patch.object(github_api, "_github_api_request")
+
+ comments._post_review_prompt_comment(run, repo)
+
+ spy.assert_not_called()
+
+ def test_swallows_exceptions(self, repo, mocker):
+ run = self._mk_run(repo, "aaa111")
+ mocker.patch.object(github_api, "_github_api_request", side_effect=RuntimeError("boom"))
+
+ comments._post_review_prompt_comment(run, repo)
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index 61a500f4b03c..409bd60ec389 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -520,9 +520,9 @@ export interface ApproveRunRequestInputApi {
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 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. */
+ /** 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, `metadata.baseline_commit_sha` is absent, and no post-approval PR comment is posted. */
commit_to_github?: boolean
- /** Whether to embed the before/after snapshot images in the post-approval PR comment. The comment itself is always posted (when the run was initiated from a GitHub review prompt and the repo has PR comments enabled); this flag only controls the images. Defaults false — the comment stays a text summary unless the reviewer opts in to attach the snapshots. */
+ /** Whether to embed the before/after snapshot images in the post-approval PR comment. The comment itself is posted when the repo has PR comments enabled and `commit_to_github` is true: it updates the run's review prompt when the run has one, and posts a new comment when it does not. This flag only controls the images. Defaults false — the comment stays a text summary unless the reviewer opts in to attach the snapshots. */
add_images_to_comment_on_pr?: boolean
}
diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.ts
index 9df774c5a395..8fa29dae8dcf 100644
--- a/products/visual_review/frontend/generated/api.zod.ts
+++ b/products/visual_review/frontend/generated/api.zod.ts
@@ -169,13 +169,13 @@ export const VisualReviewRunsFinalizeCreateBody = /* @__PURE__ */ zod.object({
.boolean()
.default(visualReviewRunsFinalizeCreateBodyCommitToGithubDefault)
.describe(
- '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.'
+ '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, `metadata.baseline_commit_sha` is absent, and no post-approval PR comment is posted.'
),
add_images_to_comment_on_pr: zod
.boolean()
.default(visualReviewRunsFinalizeCreateBodyAddImagesToCommentOnPrDefault)
.describe(
- 'Whether to embed the before\/after snapshot images in the post-approval PR comment. The comment itself is always posted (when the run was initiated from a GitHub review prompt and the repo has PR comments enabled); this flag only controls the images. Defaults false — the comment stays a text summary unless the reviewer opts in to attach the snapshots.'
+ "Whether to embed the before\/after snapshot images in the post-approval PR comment. The comment itself is posted when the repo has PR comments enabled and `commit_to_github` is true: it updates the run's review prompt when the run has one, and posts a new comment when it does not. This flag only controls the images. Defaults false — the comment stays a text summary unless the reviewer opts in to attach the snapshots."
),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 989f14201000..b151bc6c1901 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -42111,9 +42111,9 @@ export namespace Schemas {
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. */
+ /** 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, `metadata.baseline_commit_sha` is absent, and no post-approval PR comment is posted. */
commit_to_github?: boolean;
- /** Whether to embed the before/after snapshot images in the post-approval PR comment. The comment itself is always posted (when the run was initiated from a GitHub review prompt and the repo has PR comments enabled); this flag only controls the images. Defaults false — the comment stays a text summary unless the reviewer opts in to attach the snapshots. */
+ /** Whether to embed the before/after snapshot images in the post-approval PR comment. The comment itself is posted when the repo has PR comments enabled and `commit_to_github` is true: it updates the run's review prompt when the run has one, and posts a new comment when it does not. This flag only controls the images. Defaults false — the comment stays a text summary unless the reviewer opts in to attach the snapshots. */
add_images_to_comment_on_pr?: boolean;
}
diff --git a/services/mcp/src/generated/visual_review/api.ts b/services/mcp/src/generated/visual_review/api.ts
index 3b56956ee3f3..e5c35292de30 100644
--- a/services/mcp/src/generated/visual_review/api.ts
+++ b/services/mcp/src/generated/visual_review/api.ts
@@ -225,13 +225,13 @@ export const VisualReviewRunsFinalizeCreateBody = () => zod.object({
.boolean()
.default(visualReviewRunsFinalizeCreateBodyCommitToGithubDefault)
.describe(
- '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.'
+ '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, `metadata.baseline_commit_sha` is absent, and no post-approval PR comment is posted.'
),
add_images_to_comment_on_pr: zod
.boolean()
.default(visualReviewRunsFinalizeCreateBodyAddImagesToCommentOnPrDefault)
.describe(
- 'Whether to embed the before\/after snapshot images in the post-approval PR comment. The comment itself is always posted (when the run was initiated from a GitHub review prompt and the repo has PR comments enabled); this flag only controls the images. Defaults false — the comment stays a text summary unless the reviewer opts in to attach the snapshots.'
+ "Whether to embed the before\/after snapshot images in the post-approval PR comment. The comment itself is posted when the repo has PR comments enabled and `commit_to_github` is true: it updates the run's review prompt when the run has one, and posts a new comment when it does not. This flag only controls the images. Defaults false — the comment stays a text summary unless the reviewer opts in to attach the snapshots."
),
})