Skip to content

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

feat(visual-review): Update visual review GH comments on approval (#58240)

Rafael Audibert308af9603c52
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index 182962e13b3b..3940b41ef7e9 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -26,6 +26,24 @@ from .enums import ReviewDecision
User = get_user_model()
+# Server-owned run.metadata keys — never accept these from client input.
+# Allowing clients to set these would let them target arbitrary GitHub
+# comments for PATCH, or spoof baseline commit SHAs in the audit trail.
+_RESERVED_RUN_METADATA_KEYS = frozenset(
+ {
+ "github_comment_id",
+ "baseline_commit_sha",
+ "baseline_healed_from_merge_base",
+ }
+)
+
+
+def _sanitize_run_metadata(metadata: dict | None) -> dict:
+ if not metadata:
+ return {}
+ return {k: v for k, v in metadata.items() if k not in _RESERVED_RUN_METADATA_KEYS}
+
+
# Re-export exceptions for callers
RepoNotFoundError = logic.RepoNotFoundError
RunNotFoundError = logic.RunNotFoundError
@@ -320,7 +338,7 @@ def create_run(input: contracts.CreateRunInput, team_id: int) -> contracts.Creat
unchanged_count=input.unchanged_count,
removed_identifiers=list(input.removed_identifiers),
purpose=input.purpose,
- metadata=dict(input.metadata) if input.metadata else {},
+ metadata=_sanitize_run_metadata(input.metadata),
)
upload_targets = [
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
index 2939202b6773..3ff3aef2cbc4 100644
--- a/products/visual_review/backend/logic.py
+++ b/products/visual_review/backend/logic.py
@@ -7,6 +7,7 @@ Called by api/api.py facade. Do not call from outside this module.
from __future__ import annotations
+from collections import Counter
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING
@@ -1597,6 +1598,188 @@ def _post_review_prompt_comment(run: Run, repo: Repo) -> None:
logger.warning("visual_review.pr_comment_error", run_id=str(run.id), pr_number=run.pr_number, exc_info=True)
+_MARKDOWN_ESCAPE_CHARS = r"\`*_{}[]()#+-.!|<>~"
+
+
+def _escape_markdown(value: str) -> str:
+ """Escape GitHub-flavored markdown control characters in user-supplied text."""
+ return "".join(f"\\{c}" if c in _MARKDOWN_ESCAPE_CHARS else c for c in value)
+
+
+@dataclass(frozen=True)
+class _Approver:
+ label: str
+ is_github_login: bool
+
+
+def _build_approval_comment_body(run: Run, repo: Repo, approver: _Approver | None) -> str:
+ """Build the markdown body of the post-approval PR comment.
+
+ A short textual summary of what changed — reviewers go to PostHog to see
+ the actual snapshots.
+ """
+ from django.conf import settings
+
+ counts = Counter(
+ run.snapshots.filter(
+ result__in=(SnapshotResult.CHANGED, SnapshotResult.NEW, SnapshotResult.REMOVED)
+ ).values_list("result", flat=True)
+ )
+
+ run_url = f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/runs/{run.id}"
+ if approver is None:
+ approver_text = "a reviewer"
+ elif approver.is_github_login:
+ approver_text = f"@{approver.label}"
+ else:
+ approver_text = _escape_markdown(approver.label)
+ baseline_sha = run.metadata.get("baseline_commit_sha")
+ sha_text = f" — baseline updated in `{baseline_sha[:7]}`" if isinstance(baseline_sha, str) and baseline_sha else ""
+
+ header = f"✅ **Visual changes approved** by {approver_text}{sha_text}.\n\n[View this run in PostHog]({run_url})\n"
+
+ parts = []
+ for result, label in (
+ (SnapshotResult.CHANGED, "changed"),
+ (SnapshotResult.NEW, "new"),
+ (SnapshotResult.REMOVED, "removed"),
+ ):
+ if counts.get(result):
+ parts.append(f"{counts[result]} {label}")
+
+ if not parts:
+ return header
+
+ return header + f"\n{', '.join(parts)}.\n"
+
+
+def _resolve_approver(user_id: int | None) -> _Approver | None:
+ """Resolve the approver's identity for the PR comment.
+
+ Prefers a verified GitHub login (safe to mention with `@`); otherwise
+ falls back to email local-part or first name, which the caller must
+ treat as untrusted markdown.
+ """
+ if user_id is None:
+ return None
+
+ from posthog.models.user import User
+ from posthog.models.user_integration import UserGitHubIntegration, UserIntegration
+
+ gh = (
+ UserIntegration.objects.filter(user_id=user_id, kind=UserIntegration.IntegrationKind.GITHUB)
+ .order_by("-created_at")
+ .first()
+ )
+ if gh is not None:
+ github_login = UserGitHubIntegration(gh).github_login
+ if github_login:
+ return _Approver(label=github_login, is_github_login=True)
+
+ user = User.objects.filter(id=user_id).only("email", "first_name").first()
+ if user is None:
+ return None
+ if user.email and "@" in user.email:
+ return _Approver(label=user.email.split("@", 1)[0], is_github_login=False)
+ if user.first_name:
+ return _Approver(label=user.first_name, is_github_login=False)
+ return None
+
+
+def _post_approval_comment(run: Run, repo: Repo) -> None:
+ """Update the existing PR comment in place with the approved-changes summary.
+
+ 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.
+ """
+ if not repo.enable_pr_comments:
+ return
+
+ if not repo.repo_full_name or run.pr_number is None:
+ return
+
+ 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 = _resolve_approver(run.approved_by_id)
+ body = _build_approval_comment_body(run, repo, approver)
+
+ try:
+ response = _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_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_create_failed",
+ run_id=str(run.id),
+ pr_number=run.pr_number,
+ status_code=create_response.status_code,
+ response=create_response.text[:200],
+ )
+ return
+
+ 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],
+ )
+ except GitHubRateLimitError:
+ # Bubble up so the Celery task can retry with the suggested countdown.
+ raise
+ except Exception:
+ logger.warning(
+ "visual_review.approval_comment_error",
+ run_id=str(run.id),
+ pr_number=run.pr_number,
+ exc_info=True,
+ )
+
+
+def post_approval_comment_for_run(run_id: UUID, team_id: int | None = None) -> None:
+ """Public entrypoint for the Celery task to update a PR comment after approval."""
+ run = (
+ Run.objects.select_related("repo")
+ .using(READER_DB)
+ .filter(id=run_id, **({"team_id": team_id} if team_id is not None else {}))
+ .first()
+ )
+ if run is None:
+ return
+ _post_approval_comment(run, run.repo)
+
+
@transaction.atomic(using=WRITER_DB)
def approve_all(
run_id: UUID,
@@ -1767,6 +1950,16 @@ def approve_run(
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 run
@@ -1932,7 +2125,6 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:
- 2 queries for the recent-drift average (resolve last-N runs, aggregate)
- 3 cheap aggregate queries for totals
"""
- from collections import Counter
from datetime import timedelta
from .facade.contracts import BASELINE_DRIFT_RECENT_RUN_COUNT, BASELINE_OVERVIEW_MAX_ENTRIES
diff --git a/products/visual_review/backend/tasks/__init__.py b/products/visual_review/backend/tasks/__init__.py
index ad0c04d8802c..3dc68f7d1cab 100644
--- a/products/visual_review/backend/tasks/__init__.py
+++ b/products/visual_review/backend/tasks/__init__.py
@@ -1,4 +1,4 @@
# Re-export tasks for Celery autodiscover
-from products.visual_review.backend.tasks.tasks import process_run_diffs
+from products.visual_review.backend.tasks.tasks import post_approval_comment, process_run_diffs
-__all__ = ["process_run_diffs"]
+__all__ = ["post_approval_comment", "process_run_diffs"]
diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.py
index 8157e59b068e..05d49c9094b5 100644
--- a/products/visual_review/backend/tasks/tasks.py
+++ b/products/visual_review/backend/tasks/tasks.py
@@ -69,3 +69,42 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:
logger.exception("visual_review.diff_processing_failed", run_id=run_id, team_id=team_id, error=str(e))
logic.finish_processing(run_uuid, error_message=str(e))
raise
+
+
+@shared_task(
+ name="products.visual_review.backend.tasks.post_approval_comment",
+ bind=True,
+ ignore_result=True,
+ acks_late=True,
+ reject_on_worker_lost=True,
+ max_retries=3,
+)
+@with_team_scope()
+def post_approval_comment(self, team_id: int, run_id: str) -> None:
+ """Update the PR comment in place with the approved-changes summary.
+
+ Best-effort: failures don't block the approval flow. Retries on GitHub
+ rate-limit errors only.
+ """
+ from posthog.models.integration import GitHubRateLimitError
+
+ from .. import logic
+
+ run_uuid = UUID(run_id)
+
+ try:
+ logic.post_approval_comment_for_run(run_uuid, team_id=team_id)
+ except GitHubRateLimitError as e:
+ logger.warning(
+ "visual_review.approval_comment_rate_limited",
+ run_id=run_id,
+ retry=self.request.retries,
+ max_retries=self.max_retries,
+ )
+ try:
+ countdown = e.retry_after or 60
+ self.retry(countdown=min(countdown, 600), exc=e)
+ except self.MaxRetriesExceededError:
+ logger.warning("visual_review.approval_comment_giving_up", run_id=run_id)
+ except Exception:
+ logger.exception("visual_review.approval_comment_task_failed", run_id=run_id, team_id=team_id)
diff --git a/products/visual_review/backend/tests/test_api.py b/products/visual_review/backend/tests/test_api.py
index b8db321634f9..1f720258f7a8 100644
--- a/products/visual_review/backend/tests/test_api.py
+++ b/products/visual_review/backend/tests/test_api.py
@@ -105,6 +105,33 @@ class TestRunAPI:
assert upload.url == "https://s3.example.com/upload"
assert upload.fields == {"key": "value"}
+ @patch("products.visual_review.backend.storage.ArtifactStorage.get_presigned_upload_url")
+ def test_create_run_strips_reserved_metadata_keys(self, mock_presigned, repo):
+ # Clients must not be able to seed server-owned metadata keys —
+ # otherwise they could target arbitrary GitHub comments for PATCH
+ # or spoof baseline commit SHAs in the audit trail.
+ mock_presigned.return_value = {"url": "https://s3.example.com/upload", "fields": {}}
+
+ result = api.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ snapshots=[],
+ metadata={
+ "pr_title": "kept",
+ "github_comment_id": 99999,
+ "baseline_commit_sha": "deadbeef",
+ "baseline_healed_from_merge_base": 1,
+ },
+ ),
+ team_id=repo.team_id,
+ )
+
+ run = Run.objects.get(id=result.run_id)
+ assert run.metadata == {"pr_title": "kept"}
+
def test_get_run_returns_dto(self, repo):
create_result = api.create_run(
CreateRunInput(
diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.py
index 192167710fa1..5d418ddd36c9 100644
--- a/products/visual_review/backend/tests/test_logic.py
+++ b/products/visual_review/backend/tests/test_logic.py
@@ -2031,3 +2031,186 @@ class TestVerifyBaselineHashes:
result = logic._verify_baseline_hashes(repo, {"snap-a": "v1.k1.deadbeef.fake"})
assert result == {}
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestApprovalComment:
+ """Tests for the post-approval PR comment summary."""
+
+ @pytest.fixture
+ def repo(self, team):
+ return Repo.objects.create(
+ team_id=team.id,
+ repo_external_id=66666,
+ repo_full_name="test-org/approval-repo",
+ enable_pr_comments=True,
+ )
+
+ @pytest.fixture
+ def run_with_snapshots(self, repo):
+ from products.visual_review.backend.facade.enums import ReviewDecision
+
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="deadbeef",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ metadata={"github_comment_id": 9001, "baseline_commit_sha": "abc1234567"},
+ )
+
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Login/Form",
+ current_hash="curr_a",
+ baseline_hash="base_a",
+ result=SnapshotResult.CHANGED,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Settings/Tab",
+ current_hash="curr_b",
+ baseline_hash="",
+ result=SnapshotResult.NEW,
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Old/Component",
+ current_hash="",
+ baseline_hash="base_c",
+ result=SnapshotResult.REMOVED,
+ )
+
+ return run
+
+ def test_build_approval_comment_body_summarizes_changes(self, repo, run_with_snapshots):
+ approver = logic._Approver(label="alice", is_github_login=True)
+ body = logic._build_approval_comment_body(run_with_snapshots, repo, approver)
+
+ assert "✅ **Visual changes approved** by @alice" in body
+ assert "abc1234" in body # baseline SHA prefix
+ assert f"/visual_review/runs/{run_with_snapshots.id}" in body
+ assert "1 changed, 1 new, 1 removed." in body
+ assert "<img" not in body
+ assert "<table" not in body
+ assert "/api/visual_review/public/" not in body
+
+ def test_build_approval_comment_body_falls_back_to_a_reviewer(self, repo, run_with_snapshots):
+ body = logic._build_approval_comment_body(run_with_snapshots, repo, None)
+
+ assert "by a reviewer" in body
+
+ def test_build_approval_comment_body_escapes_non_github_approver(self, repo, run_with_snapshots):
+ # email local-part / first_name fallbacks are user-controlled — must be escaped
+ approver = logic._Approver(label="alice[evil](http://attacker)", is_github_login=False)
+ body = logic._build_approval_comment_body(run_with_snapshots, repo, approver)
+
+ # No raw `@` mention (which would render as a GitHub user link)
+ assert "by @alice" not in body
+ # Markdown control chars in the label must be backslash-escaped
+ assert "\\[evil\\]" in body
+ assert "\\(http://attacker\\)" in body
+
+ def test_build_approval_comment_body_no_actionable_snapshots(self, repo):
+ from products.visual_review.backend.facade.enums import ReviewDecision
+
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="empty",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ )
+ approver = logic._Approver(label="bob", is_github_login=True)
+ body = logic._build_approval_comment_body(run, repo, approver)
+ assert "✅ **Visual changes approved**" in body
+ # No counts line when there's nothing to summarize
+ assert "changed" not in body
+ assert "new" not in body
+ assert "removed" not in body
+
+ def test_post_approval_comment_skips_when_pr_comments_disabled(self, repo, run_with_snapshots, mocker):
+ repo.enable_pr_comments = False
+ repo.save(update_fields=["enable_pr_comments"])
+
+ spy = mocker.patch.object(logic, "_github_api_request")
+ logic._post_approval_comment(run_with_snapshots, repo)
+ spy.assert_not_called()
+
+ def test_post_approval_comment_skips_when_no_pr_number(self, repo, run_with_snapshots, mocker):
+ run_with_snapshots.pr_number = None
+ run_with_snapshots.save(update_fields=["pr_number"])
+
+ spy = mocker.patch.object(logic, "_github_api_request")
+ logic._post_approval_comment(run_with_snapshots, repo)
+ spy.assert_not_called()
+
+ def test_post_approval_comment_skips_for_non_human_decision(self, repo, run_with_snapshots, mocker):
+ from products.visual_review.backend.facade.enums import ReviewDecision
+
+ run_with_snapshots.review_decision = ReviewDecision.AUTO_APPROVED
+ run_with_snapshots.save(update_fields=["review_decision"])
+
+ spy = mocker.patch.object(logic, "_github_api_request")
+ logic._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):
+ run_with_snapshots.metadata = {}
+ run_with_snapshots.save(update_fields=["metadata"])
+
+ spy = mocker.patch.object(logic, "_github_api_request")
+ logic._post_approval_comment(run_with_snapshots, repo)
+ spy.assert_not_called()
+
+ def test_post_approval_comment_patches_existing_comment(self, repo, run_with_snapshots, mocker):
+ class FakeResp:
+ status_code = 200
+ text = ""
+
+ spy = mocker.patch.object(logic, "_github_api_request", return_value=FakeResp())
+
+ logic._post_approval_comment(run_with_snapshots, repo)
+
+ spy.assert_called_once()
+ kwargs = spy.call_args.kwargs
+ assert kwargs["method"] == "PATCH"
+ assert kwargs["path"] == "issues/comments/9001"
+ assert "✅ **Visual changes approved**" in kwargs["json"]["body"]
+
+ def test_post_approval_comment_falls_back_to_post_on_404(self, repo, run_with_snapshots, mocker):
+ class PatchResp:
+ status_code = 404
+ text = "Not Found"
+
+ class PostResp:
+ status_code = 201
+ text = ""
+
+ @staticmethod
+ def json():
+ return {"id": 9999}
+
+ spy = mocker.patch.object(logic, "_github_api_request", side_effect=[PatchResp(), PostResp()])
+
+ logic._post_approval_comment(run_with_snapshots, repo)
+
+ assert spy.call_count == 2
+ first_call = spy.call_args_list[0].kwargs
+ second_call = spy.call_args_list[1].kwargs
+ assert first_call["method"] == "PATCH"
+ assert second_call["method"] == "POST"
+ assert second_call["path"] == "issues/42/comments"
+
+ run_with_snapshots.refresh_from_db()
+ assert run_with_snapshots.metadata["github_comment_id"] == 9999
+
+ def test_post_approval_comment_swallows_exceptions(self, repo, run_with_snapshots, mocker):
+ mocker.patch.object(logic, "_github_api_request", side_effect=RuntimeError("boom"))
+ # Must not raise
+ logic._post_approval_comment(run_with_snapshots, repo)
diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.py
index 0278cdfdcd41..2888f3247be3 100644
--- a/products/visual_review/backend/tests/test_tasks.py
+++ b/products/visual_review/backend/tests/test_tasks.py
@@ -8,7 +8,7 @@ from products.visual_review.backend.diffing import process_diffs
from products.visual_review.backend.facade import api
from products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItem
from products.visual_review.backend.facade.enums import RunStatus, RunType, SnapshotResult
-from products.visual_review.backend.tasks.tasks import process_run_diffs
+from products.visual_review.backend.tasks.tasks import post_approval_comment, process_run_diffs
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -161,3 +161,42 @@ class TestProcessRunDiffs:
mock_logger.warning.assert_called()
call_args = [call[0][0] for call in mock_logger.warning.call_args_list]
assert any("diff_skipped_missing_artifact" in arg for arg in call_args)
+
+
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestPostApprovalCommentTask:
+ @pytest.fixture
+ def repo(self, team):
+ return api.create_repo(team_id=team.id, repo_external_id=88888, repo_full_name="org/approval")
+
+ def test_calls_logic_helper(self, repo):
+ with patch("products.visual_review.backend.logic.post_approval_comment_for_run") as helper:
+ post_approval_comment(repo.team_id, "00000000-0000-0000-0000-000000000001")
+ helper.assert_called_once()
+ args, kwargs = helper.call_args
+ assert str(args[0]) == "00000000-0000-0000-0000-000000000001"
+ assert kwargs["team_id"] == repo.team_id
+
+ def test_swallows_unexpected_errors(self, repo):
+ with patch(
+ "products.visual_review.backend.logic.post_approval_comment_for_run",
+ side_effect=RuntimeError("boom"),
+ ):
+ # Must not raise — failure to comment must never block other work.
+ post_approval_comment(repo.team_id, "00000000-0000-0000-0000-000000000002")
+
+ def test_retries_on_rate_limit(self, repo):
+ from posthog.models.integration import GitHubRateLimitError
+
+ with (
+ patch(
+ "products.visual_review.backend.logic.post_approval_comment_for_run",
+ side_effect=GitHubRateLimitError("rate limited", retry_after=42),
+ ),
+ patch.object(post_approval_comment, "retry", side_effect=RuntimeError("retry called")) as retry_mock,
+ ):
+ with pytest.raises(RuntimeError, match="retry called"):
+ post_approval_comment(repo.team_id, "00000000-0000-0000-0000-000000000003")
+
+ retry_mock.assert_called_once()
+ assert retry_mock.call_args.kwargs["countdown"] == 42