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): embed before/after snapshots in approval comment (#62635)

Paul D'Ambrae659ce8f0353
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f75ff278ec6c..029f9d6d391d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6250,6 +6250,10 @@ snapshots:
hash: v1.k794b7964.d69d7670abb2a83ae34f5fd1d5207f21e5b1ef14e0116997b55b6854f77564a5.BuxfmZGhUt3c9qQw3T27cYFr9cnafBjOJXLbAke8Sx4
scenes-app-user-research-topics--topics-list--light:
hash: v1.k794b7964.c4ee7785c554f517bcaf7013daa0277ccb038faf2883d1ddb3ccb6f3ac7c7e00.apAT1Kl9oDw_AAmV8akOA9zvcF0mOUCUjtrEwJ1wA54
+ scenes-app-visual-review-run--ready-to-finalize--dark:
+ hash: v1.k794b7964.0963628627d2de9b968394dac5513b1749b3a9c90f1ca07f51c4497036a9262b.CSDgJl9gZqu0yrd7a0p8-WSSKR2zVFP-t47fKNoGOGI
+ scenes-app-visual-review-run--ready-to-finalize--light:
+ hash: v1.k794b7964.cbad9f0954e55a8a37053d4824897f00e6ce6cdfec8bcf16afcaaef887ea53b4.BtH21G_RiNOuXE6qtG9BjC0OEcbzdO5SfkUft7rL56Y
scenes-app-web-analytics--web-analytics-dashboard--dark:
hash: v1.k794b7964.918e3e893e634a2ea697e21bc8a47b433261d2cd70f262bdf9f89a4cfbc8c89f.UVILZaS1DVrMHZKjXeu9IdpDmNRizwe9RpXAWfYaWq0
scenes-app-web-analytics--web-analytics-dashboard--light:
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f0348b518a79..1af91f65b7e5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3729,6 +3729,9 @@ importers:
'@posthog/react':
specifier: '*'
+ '@storybook/react':
+ specifier: 'catalog:'
'@types/react':
specifier: 18.3.27
version: 18.3.27
@@ -3741,9 +3744,16 @@ importers:
kea-router:
specifier: 'catalog:'
+ posthog-js:
+ specifier: 'catalog:'
+ version: 1.386.6
react:
specifier: 18.3.1
version: 18.3.1
+ devDependencies:
+ kea-test-utils:
+ specifier: 'catalog:'
products/warehouse_sources: {}
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index d7c5c8efa235..9dfca32de0a5 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -522,6 +522,7 @@ def finalize_run(
team_id: int | None = None,
approve_all: bool = False,
commit_to_github: bool = True,
+ add_images_to_comment_on_pr: bool = False,
) -> contracts.FinalizeResult:
"""Finalize a fully-reviewed run: commit the approved baseline and green the gate.
@@ -534,7 +535,12 @@ def finalize_run(
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
+ run_id=run_id,
+ user_id=user_id,
+ team_id=team_id,
+ approve_all=approve_all,
+ commit_to_github=commit_to_github,
+ add_images_to_comment_on_pr=add_images_to_comment_on_pr,
)
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)
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index 0e2c144bf2b1..e5000d3acea6 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -93,6 +93,7 @@ class FinalizeRunRequestInput:
approve_all: bool = False
commit_to_github: bool = True
+ add_images_to_comment_on_pr: bool = False
# --- Output DTOs ---
diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.py
index 7829479fed4b..adf32f12ee87 100644
--- a/products/visual_review/backend/logic.py
+++ b/products/visual_review/backend/logic.py
@@ -7,6 +7,8 @@ Called by api/api.py facade. Do not call from outside this module.
from __future__ import annotations
+import re
+import html
from collections import Counter
from collections.abc import Iterable
from dataclasses import dataclass
@@ -14,6 +16,7 @@ from datetime import datetime
from typing import TYPE_CHECKING
from uuid import UUID
+from django.conf import settings
from django.db import (
connections,
models as db_models,
@@ -1435,8 +1438,6 @@ def _build_snapshots_yaml(
*updates* is a list of ``{identifier, new_hash}`` where ``new_hash``
is a plain content hash — it gets signed here.
"""
- from django.conf import settings
-
import yaml
kid, secret_hex = repo.get_active_signing_key()
@@ -1481,8 +1482,6 @@ def _post_commit_status(
if not repo.repo_full_name:
return
- from django.conf import settings
-
from .github import github_request
try:
@@ -1494,7 +1493,7 @@ def _post_commit_status(
return
access_token = github.get_access_token()
- target_url = f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/runs/{run.id}"
+ target_url = _run_url(run, repo)
try:
response = github_request(
@@ -1654,9 +1653,7 @@ def _post_review_prompt_comment(run: Run, repo: Repo) -> None:
if run.metadata.get("github_comment_id"):
return
- from django.conf import settings
-
- run_url = f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/runs/{run.id}"
+ run_url = _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"
@@ -1723,21 +1720,153 @@ class _Approver:
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 reviewer should be able to eyeball the approved snapshots straight from the PR.
+# GitHub can't render base64 data URIs (its markdown sanitizer strips them) and the
+# user-attachments upload path needs a browser session we don't have, so we embed
+# presigned object-storage URLs and let GitHub's image proxy (camo) fetch + cache
+# them. That proxy fetch can happen well after the comment is posted, so the URL
+# must outlive the default hour — use the S3 SigV4 maximum.
+_COMMENT_IMAGE_URL_EXPIRATION = 60 * 60 * 24 * 7 # 7 days
+_COMMENT_IMAGE_WIDTH = 320
+# Keep the comment readable: show the first N snapshots and link out for the rest.
+_MAX_COMMENT_IMAGES = 8
+
+
+def _comment_image_url(repo: Repo, artifact: Artifact | None) -> str | None:
+ """Presigned URL for embedding a snapshot image in a PR comment.
+
+ Prefers the thumbnail to keep the comment lightweight. Returns None when the
+ artifact is missing or object storage is disabled — the caller renders an
+ empty cell in that case.
+ """
+ if artifact is None:
+ return None
+ display = artifact.thumbnail or artifact
+ storage = ArtifactStorage(str(repo.id))
+ return storage.get_presigned_download_url(display.content_hash, expiration=_COMMENT_IMAGE_URL_EXPIRATION)
+
+
+_TABLE_BREAKING_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")
+
+
+def _run_url(run: Run, repo: Repo) -> str:
+ """Link to the run page in PostHog."""
+ return f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/runs/{run.id}"
+
+
+def _snapshot_url(run: Run, repo: Repo, snapshot: RunSnapshot) -> str:
+ """Deep link straight to a single snapshot on the run page."""
+ return f"{_run_url(run, repo)}?snapshot={snapshot.id}"
+
+
+def _snapshot_name_cell(identifier: str, suffix: str = "") -> str:
+ """Render a snapshot identifier as a single-line table cell (code span, pipe-safe).
+
+ Identifiers come from the run manifest without newline validation, so collapse
+ control characters (newlines, tabs, etc.) to spaces first — otherwise a
+ malformed or user-controlled story name could break out of the table row and
+ inject markdown/HTML into the comment. Then strip backticks and escape pipes so
+ it stays inside the code span and the cell.
+ """
+ safe = _TABLE_BREAKING_CHARS_RE.sub(" ", identifier).replace("`", "").replace("|", "\\|")
+ return f"`{safe}`{suffix}"
+
+
+def _snapshot_link_cell(run: Run, repo: Repo, snapshot: RunSnapshot, suffix: str = "") -> str:
+ """Snapshot identifier linked to its deep link on the run page, so a reviewer can jump
+ straight to that snapshot rather than the run as a whole."""
+ return f"[{_snapshot_name_cell(snapshot.identifier)}]({_snapshot_url(run, repo, snapshot)}){suffix}"
+
+
+def _image_cell(url: str | None, alt: str) -> str:
+ """Render an image (or an empty placeholder) for a before/after table cell."""
+ if not url:
+ return "_(none)_"
+ # Escape both attributes — a URL containing a quote would otherwise break out of src.
+ src = html.escape(url, quote=True)
+ return f'<img src="{src}" width="{_COMMENT_IMAGE_WIDTH}" alt="{html.escape(alt, quote=True)}">'
+
- A short textual summary of what changed — reviewers go to PostHog to see
- the actual snapshots.
+_IMAGE_TABLE_HEADER = "| Snapshot | Before | After |\n| --- | --- | --- |"
+
+
+def _build_snapshot_image_tables(run: Run, repo: Repo) -> str:
+ """Before/after image tables for the approved snapshots.
+
+ Changed and removed snapshots share one table (removed ones leave the *after*
+ cell empty); new snapshots get their own table (empty *before* cell). Capped
+ at ``_MAX_COMMENT_IMAGES`` rows total, prioritizing changed/removed diffs;
+ anything beyond links back to PostHog. Returns "" when no image could be
+ resolved (e.g. object storage disabled) so the comment stays text-only.
"""
- from django.conf import settings
+ snapshots = list(
+ run.snapshots.using(READER_DB)
+ .filter(result__in=(SnapshotResult.CHANGED, SnapshotResult.NEW, SnapshotResult.REMOVED))
+ .select_related(
+ "current_artifact",
+ "current_artifact__thumbnail",
+ "baseline_artifact",
+ "baseline_artifact__thumbnail",
+ )
+ .order_by("identifier")
+ )
+ if not snapshots:
+ return ""
+
+ # Changed/removed first — they carry a baseline diff a reviewer most needs to
+ # see — then new snapshots fill whatever's left of the image budget.
+ changed = [s for s in snapshots if s.result in (SnapshotResult.CHANGED, SnapshotResult.REMOVED)]
+ new = [s for s in snapshots if s.result == SnapshotResult.NEW]
+
+ total = len(changed) + len(new)
+ shown_changed = changed[:_MAX_COMMENT_IMAGES]
+ shown_new = new[: max(0, _MAX_COMMENT_IMAGES - len(shown_changed))]
+ shown = len(shown_changed) + len(shown_new)
+
+ any_image = False
+
+ def cell(artifact: Artifact | None, alt: str) -> str:
+ nonlocal any_image
+ url = _comment_image_url(repo, artifact)
+ if url:
+ any_image = True
+ return _image_cell(url, alt)
+
+ def row(s: RunSnapshot, before: Artifact | None) -> str:
+ suffix = " _(removed)_" if s.result == SnapshotResult.REMOVED else ""
+ name = _snapshot_link_cell(run, repo, s, suffix)
+ return f"| {name} | {cell(before, 'before')} | {cell(s.current_artifact, 'after')} |"
+
+ changed_rows = [row(s, s.baseline_artifact) for s in shown_changed]
+ new_rows = [row(s, None) for s in shown_new]
+
+ if not any_image:
+ return ""
+ def table(heading: str, rows: list[str]) -> str:
+ return "\n".join((f"**{heading}**", "", _IMAGE_TABLE_HEADER, *rows))
+
+ sections = [table(heading, rows) for heading, rows in (("Changed", changed_rows), ("New", new_rows)) if rows]
+ if shown < total:
+ sections.append(f"…and {total - shown} more — [view all in PostHog]({_run_url(run, repo)}).")
+
+ return "\n\n".join(sections)
+
+
+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.
+
+ Always a textual summary of what changed. When ``add_images`` is set, a
+ before/after table of the approved snapshot images is appended so another
+ reviewer can eyeball them without leaving the PR (omitted when no image can
+ be resolved).
+ """
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:
@@ -1747,21 +1876,28 @@ def _build_approval_comment_body(run: Run, repo: Repo, approver: _Approver | Non
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}")
+ summary = ", ".join(
+ f"{counts[result]} {label}"
+ for result, label in (
+ (SnapshotResult.CHANGED, "changed"),
+ (SnapshotResult.NEW, "new"),
+ (SnapshotResult.REMOVED, "removed"),
+ )
+ if counts.get(result)
+ )
- if not parts:
- return header
+ sections = [
+ f"✅ **Visual changes approved** by {approver_text}{sha_text}.",
+ f"[View this run in PostHog]({_run_url(run, repo)})",
+ ]
+ if summary:
+ sections.append(f"{summary}.")
+ if add_images:
+ tables = _build_snapshot_image_tables(run, repo)
+ if tables:
+ sections.append(tables)
- return header + f"\n{', '.join(parts)}.\n"
+ return "\n\n".join(sections) + "\n"
def _resolve_approver(user_id: int | None) -> _Approver | None:
@@ -1797,12 +1933,13 @@ def _resolve_approver(user_id: int | None) -> _Approver | None:
return None
-def _post_approval_comment(run: Run, repo: Repo) -> None:
+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.
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.
+ 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.
"""
if not repo.enable_pr_comments:
return
@@ -1822,7 +1959,7 @@ def _post_approval_comment(run: Run, repo: Repo) -> None:
return
approver = _resolve_approver(run.approved_by_id)
- body = _build_approval_comment_body(run, repo, approver)
+ body = _build_approval_comment_body(run, repo, approver, add_images=add_images)
try:
response = _github_api_request(
@@ -1878,7 +2015,7 @@ def _post_approval_comment(run: Run, repo: Repo) -> None:
)
-def post_approval_comment_for_run(run_id: UUID, team_id: int | None = None) -> None:
+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."""
run = (
Run.objects.select_related("repo")
@@ -1888,7 +2025,7 @@ def post_approval_comment_for_run(run_id: UUID, team_id: int | None = None) -> N
)
if run is None:
return
- _post_approval_comment(run, run.repo)
+ _post_approval_comment(run, run.repo, add_images=add_images)
@transaction.atomic(using=WRITER_DB)
@@ -1899,6 +2036,7 @@ def finalize_run(
approve_all: bool = False,
review_decision: ReviewDecision = ReviewDecision.HUMAN_APPROVED,
commit_to_github: bool = True,
+ add_images_to_comment_on_pr: bool = False,
) -> Run:
"""Finalize a fully-reviewed run: commit the approved baseline and green the gate.
@@ -1915,6 +2053,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.
"""
run = _get_run_for_update(run_id, team_id=team_id)
repo = run.repo
@@ -1994,8 +2137,9 @@ def finalize_run(
run_id_str = str(run.id)
run_team_id = run.team_id
+ add_images = add_images_to_comment_on_pr
transaction.on_commit(
- lambda: post_approval_comment.delay(run_team_id, run_id_str),
+ lambda: post_approval_comment.delay(run_team_id, run_id_str, add_images),
using=WRITER_DB,
)
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index 4e2f1ad99bf6..734fc6808af7 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -197,6 +197,16 @@ class FinalizeRunInputSerializer(DataclassSerializer):
"greened and `metadata.baseline_commit_sha` is absent."
),
)
+ add_images_to_comment_on_pr = serializers.BooleanField(
+ required=False,
+ 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."
+ ),
+ )
class Meta:
dataclass = FinalizeRunRequestInput
diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.py
index 965c467f7f62..dd0df9208a41 100644
--- a/products/visual_review/backend/presentation/views.py
+++ b/products/visual_review/backend/presentation/views.py
@@ -622,6 +622,7 @@ class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
team_id=self.team_id,
approve_all=body.approve_all,
commit_to_github=body.commit_to_github,
+ add_images_to_comment_on_pr=body.add_images_to_comment_on_pr,
)
return Response(FinalizeResultSerializer(instance=result).data)
except api.RunNotFoundError:
diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.py
index 05d49c9094b5..43d8dd25f289 100644
--- a/products/visual_review/backend/tasks/tasks.py
+++ b/products/visual_review/backend/tasks/tasks.py
@@ -80,11 +80,12 @@ def process_run_diffs(self, team_id: int, run_id: str) -> None:
max_retries=3,
)
@with_team_scope()
-def post_approval_comment(self, team_id: int, run_id: str) -> None:
+def post_approval_comment(self, team_id: int, run_id: str, add_images: bool = False) -> 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.
+ rate-limit errors only. ``add_images`` embeds the before/after snapshot
+ images when the reviewer opted in at finalize time.
"""
from posthog.models.integration import GitHubRateLimitError
@@ -93,7 +94,7 @@ def post_approval_comment(self, team_id: int, run_id: str) -> None:
run_uuid = UUID(run_id)
try:
- logic.post_approval_comment_for_run(run_uuid, team_id=team_id)
+ logic.post_approval_comment_for_run(run_uuid, team_id=team_id, add_images=add_images)
except GitHubRateLimitError as e:
logger.warning(
"visual_review.approval_comment_rate_limited",
diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.py
index 218a3a220460..4d5114ec18d9 100644
--- a/products/visual_review/backend/tests/test_logic.py
+++ b/products/visual_review/backend/tests/test_logic.py
@@ -7,7 +7,7 @@ import pytest
from django.utils import timezone
from products.visual_review.backend import logic
-from products.visual_review.backend.facade.enums import ReviewState, RunStatus, RunType, SnapshotResult
+from products.visual_review.backend.facade.enums import ReviewDecision, ReviewState, RunStatus, RunType, SnapshotResult
from products.visual_review.backend.models import Repo, Run, RunSnapshot
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -632,6 +632,26 @@ class TestApproveRun:
assert again.approved is True
assert again.approved_at == approved_at # unchanged — the second call did no work
+ @pytest.mark.parametrize("add_images", [True, False])
+ def test_finalize_always_comments_and_forwards_add_images(self, repo, user, mocker, add_images):
+ # The PR comment is always dispatched on finalize; add_images_to_comment_on_pr only
+ # controls whether the snapshot images are embedded — forwarded to the task.
+ run = self._completed_two_change_run(repo, mocker)
+ mocker.patch.object(logic, "_post_commit_status")
+ mocker.patch.object(logic.transaction, "on_commit", side_effect=lambda fn, *args, **kwargs: fn())
+ delay = mocker.patch("products.visual_review.backend.tasks.tasks.post_approval_comment.delay")
+
+ logic.finalize_run(
+ run_id=run.id,
+ user_id=user.id,
+ approve_all=True,
+ commit_to_github=True,
+ add_images_to_comment_on_pr=add_images,
+ )
+
+ assert delay.called is True
+ assert delay.call_args.args[2] is add_images
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
class TestApproveSnapshots:
@@ -2489,3 +2509,205 @@ class TestApprovalComment:
mocker.patch.object(logic, "_github_api_request", side_effect=RuntimeError("boom"))
# Must not raise
logic._post_approval_comment(run_with_snapshots, repo)
+
+ @staticmethod
+ def _mk_artifact(repo, content_hash, *, with_thumbnail=None):
+ from products.visual_review.backend.models import Artifact
+
+ artifact = Artifact.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ content_hash=content_hash,
+ storage_path=f"path/{content_hash}",
+ width=320,
+ height=200,
+ )
+ if with_thumbnail:
+ thumb = Artifact.objects.create(
+ repo=repo,
+ team_id=repo.team_id,
+ content_hash=with_thumbnail,
+ storage_path=f"thumb/{with_thumbnail}",
+ )
+ artifact.thumbnail = thumb
+ artifact.save(update_fields=["thumbnail"])
+ return artifact
+
+ @staticmethod
+ def _fake_storage(returns_url=True):
+ class _FakeStorage:
+ def __init__(self, repo_id):
+ self.repo_id = repo_id
+
+ def get_presigned_download_url(self, content_hash, expiration=3600):
+ return f"https://cdn.example/{content_hash}?exp={expiration}" if returns_url else None
+
+ return _FakeStorage
+
+ @pytest.fixture
+ def run_with_artifacts(self, repo):
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="cafef00d",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ metadata={"github_comment_id": 9001},
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Login/Form",
+ result=SnapshotResult.CHANGED,
+ baseline_artifact=self._mk_artifact(repo, "base_a", with_thumbnail="thumb_a"),
+ current_artifact=self._mk_artifact(repo, "curr_a"),
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Settings/Tab",
+ result=SnapshotResult.NEW,
+ current_artifact=self._mk_artifact(repo, "curr_b"),
+ )
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier="Old/Component",
+ result=SnapshotResult.REMOVED,
+ baseline_artifact=self._mk_artifact(repo, "base_c"),
+ )
+ return run
+
+ def test_build_approval_comment_body_includes_before_after_tables(self, repo, run_with_artifacts, mocker):
+ mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
+
+ body = logic._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
+
+ # Changed table: baseline (thumbnail) before, current after
+ assert "**Changed**" in body
+ assert "| Snapshot | Before | After |" in body
+ assert "https://cdn.example/thumb_a" in body # prefers the thumbnail
+ assert "https://cdn.example/curr_a" in body
+ # Removed snapshot lives in the changed table with an empty after cell
+ assert "_(removed)_" in body
+ assert "https://cdn.example/base_c" in body
+ # New table: empty before cell, current after
+ assert "**New**" in body
+ assert "https://cdn.example/curr_b" in body
+ assert "_(none)_" in body
+ # Long-lived URL so GitHub's image proxy can still fetch it later
+ assert f"exp={logic._COMMENT_IMAGE_URL_EXPIRATION}" in body
+
+ def test_build_approval_comment_body_deep_links_each_snapshot(self, repo, run_with_artifacts, mocker):
+ mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
+
+ body = logic._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
+
+ # Each snapshot name links straight to its deep link on the run page
+ changed = run_with_artifacts.snapshots.get(identifier="Login/Form")
+ assert f"[`Login/Form`]({logic._run_url(run_with_artifacts, repo)}?snapshot={changed.id})" in body
+
+ def test_build_approval_comment_body_caps_at_eight_and_links_out(self, repo, mocker):
+ mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
+
+ run = Run.objects.create(
+ team_id=repo.team_id,
+ repo=repo,
+ commit_sha="manysnaps",
+ branch="feature",
+ pr_number=42,
+ review_decision=ReviewDecision.HUMAN_APPROVED,
+ )
+ for i in range(11):
+ RunSnapshot.objects.create(
+ team_id=repo.team_id,
+ run=run,
+ identifier=f"Story/{i:02d}",
+ result=SnapshotResult.CHANGED,
+ baseline_artifact=self._mk_artifact(repo, f"base_{i}"),
+ current_artifact=self._mk_artifact(repo, f"curr_{i}"),
+ )
+
+ body = logic._build_approval_comment_body(run, repo, None, add_images=True)
+
+ # 8 of 11 rows rendered, the rest linked out
+ assert body.count("<img") == 8 * 2 # before + after per shown row
+ assert "…and 3 more" in body
+ assert f"/visual_review/runs/{run.id})" in body
+
+ def test_build_approval_comment_body_falls_back_to_text_without_storage(self, repo, run_with_artifacts, mocker):
+ # Images requested, but storage yields no URL — fall back to the text summary.
+ mocker.patch.object(logic, "ArtifactStorage", self._fake_storage(returns_url=False))
+
+ body = logic._build_approval_comment_body(run_with_artifacts, repo, None, add_images=True)
+
+ assert "<img" not in body
+ assert "**Changed**" not in body
+ # Still carries the textual summary
+ assert "1 changed, 1 new, 1 removed." in body
+
+ def test_build_approval_comment_body_omits_images_unless_opted_in(self, repo, run_with_artifacts, mocker):
+ # add_images defaults false: the comment is always posted but stays a text summary.
+ mocker.patch.object(logic, "ArtifactStorage", self._fake_storage())
+
+ body = logic._build_approval_comment_body(run_with_artifacts, repo, None)
+
+ assert "<img" not in body
+ assert "**Changed**" not in body
+ # The comment still summarizes what changed and links to the run
+ assert "1 changed, 1 new, 1 removed." in body
+ assert f"/visual_review/runs/{run_with_artifacts.id}" in body
+
+ def test_image_cell_escapes_alt_and_src(self):
+ # Both attributes are escaped so a quote in either can't break out of the tag
+ cell = logic._image_cell('https://cdn.example/x?a="b', 'a"b')
+ assert 'alt="a&quot;b"' in cell
+ assert 'src="https://cdn.example/x?a=&quot;b"' in cell
+
+ @pytest.mark.parametrize(
+ "identifier,expected",
+ [
+ ("a|b", "`a\\|b`"), # pipes escaped so the cell stays intact
+ ("a`b", "`ab`"), # backticks stripped so the code span isn't closed early
+ ],
+ )
+ def test_snapshot_name_cell_escapes_markdown(self, identifier, expected):
+ assert logic._snapshot_name_cell(identifier) == expected
+
+ def test_snapshot_name_cell_collapses_control_characters(self):
+ # Newlines/tabs/carriage returns would otherwise break out of the table row
+ cell = logic._snapshot_name_cell("a\nb\tc\rd")
+ assert "\n" not in cell
+ assert "\r" not in cell
+ assert "\t" not in cell
+ assert cell == "`a b c d`"
+
+ def test_snapshot_name_cell_newline_cannot_inject_table_rows(self):
+ # A pipe-laden payload across a newline stays a single escaped cell
+ cell = logic._snapshot_name_cell("x\n| --- |")
+ assert "\n" not in cell
+ assert cell == "`x \\| --- \\|`"
+
+ def test_comment_image_url_requests_seven_day_expiry(self, repo, mocker):
+ # The 7-day expiry is load-bearing: GitHub's image proxy may fetch the URL
+ # long after the comment is posted, so lock the behaviour with a test.
+ captured = {}
+
+ class _RecordingStorage:
+ def __init__(self, repo_id):
+ pass
+
+ def get_presigned_download_url(self, content_hash, expiration=3600):
+ captured["content_hash"] = content_hash
+ captured["expiration"] = expiration
+ return "https://cdn.example/x"
+
+ mocker.patch.object(logic, "ArtifactStorage", _RecordingStorage)
+
+ artifact = self._mk_artifact(repo, "h1")
+ url = logic._comment_image_url(repo, artifact)
+
+ assert url == "https://cdn.example/x"
+ assert captured["content_hash"] == "h1"
+ assert captured["expiration"] == 60 * 60 * 24 * 7 == 604800
diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.py
index b6043ff15f23..442654484f90 100644
--- a/products/visual_review/backend/tests/test_presentation.py
+++ b/products/visual_review/backend/tests/test_presentation.py
@@ -270,6 +270,58 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue(response.json()["run"]["approved"])
+ @parameterized.expand(
+ [
+ ("add_images_true", {"approve_all": True, "add_images_to_comment_on_pr": True}, True),
+ ("add_images_false", {"approve_all": True, "add_images_to_comment_on_pr": False}, False),
+ ("add_images_default", {"approve_all": True}, False),
+ ]
+ )
+ def test_finalize_run_always_comments_and_forwards_add_images(
+ self, _name: str, body: dict, expect_add_images: bool
+ ):
+ 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)
+
+ with (
+ patch("products.visual_review.backend.logic._post_commit_status"),
+ patch("products.visual_review.backend.logic.transaction.on_commit", side_effect=lambda fn, *a, **k: fn()),
+ patch("products.visual_review.backend.tasks.tasks.post_approval_comment.delay") as delay,
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/visual_review/runs/{create_result.run_id}/finalize/",
+ body,
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ # The comment is always dispatched; the flag only forwards whether to embed images.
+ self.assertTrue(delay.called)
+ self.assertEqual(delay.call_args.args[2], expect_add_images)
+
def _changed_snapshot_for_tolerate(self) -> tuple[str, str]:
logic.get_or_create_artifact(
repo_id=self.vr_project.id,
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index 84bf0c2cf4f0..b69e5c5f331b 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -318,6 +318,8 @@ export interface FinalizeRunRequestInputApi {
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
+ /** 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. */
+ add_images_to_comment_on_pr?: boolean
}
export interface FinalizeResultApi {
diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.ts
index 93130ef290c0..c7c7ed31635b 100644
--- a/products/visual_review/frontend/generated/api.zod.ts
+++ b/products/visual_review/frontend/generated/api.zod.ts
@@ -149,6 +149,7 @@ export const VisualReviewRunsApproveCreateBody = /* @__PURE__ */ zod.object({
*/
export const visualReviewRunsFinalizeCreateBodyApproveAllDefault = false
export const visualReviewRunsFinalizeCreateBodyCommitToGithubDefault = true
+export const visualReviewRunsFinalizeCreateBodyAddImagesToCommentOnPrDefault = false
export const VisualReviewRunsFinalizeCreateBody = /* @__PURE__ */ zod.object({
approve_all: zod
@@ -163,6 +164,12 @@ export const VisualReviewRunsFinalizeCreateBody = /* @__PURE__ */ zod.object({
.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.'
),
+ 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.'
+ ),
})
/**
diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx
new file mode 100644
index 000000000000..e2cc2db53e32
--- /dev/null
+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx
@@ -0,0 +1,117 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { App } from 'scenes/App'
+
+import { mswDecorator } from '~/mocks/browser'
+
+import type { ArtifactApi, RepoApi, RunApi, SnapshotApi } from '../generated/api.schemas'
+
+const RUN_ID = '00000000-0000-0000-0000-0000000000aa'
+const REPO_ID = '00000000-0000-0000-0000-0000000000bb'
+
+// A deterministic 1x1 PNG so the diff viewer renders without hitting the network.
+const PIXEL =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
+
+const artifact = (contentHash: string): ArtifactApi => ({
+ id: `artifact-${contentHash}`,
+ content_hash: contentHash,
+ width: 320,
+ height: 200,
+ download_url: PIXEL,
+})
+
+const repo: RepoApi = {
+ id: REPO_ID,
+ team_id: 1,
+ repo_external_id: 99999,
+ repo_full_name: 'PostHog/posthog',
+ baseline_file_paths: {},
+ enable_pr_comments: true,
+ created_at: '2026-06-10T00:00:00Z',
+}
+
+const run: RunApi = {
+ id: RUN_ID,
+ repo_id: REPO_ID,
+ status: 'completed',
+ run_type: 'storybook',
+ commit_sha: 'cafef00dcafef00d',
+ branch: 'feature/new-button',
+ pr_number: 42,
+ approved: false,
+ approved_at: null,
+ summary: { total: 7, changed: 1, new: 1, removed: 0, unchanged: 5 },
+ error_message: null,
+ created_at: '2026-06-10T00:00:00Z',
+ completed_at: '2026-06-10T00:01:00Z',
+ is_stale: false,
+ metadata: {},
+}
+
+const snapshot = (overrides: Partial<SnapshotApi>): SnapshotApi => ({
+ id: 'snapshot-default',
+ run_id: RUN_ID,
+ identifier: 'Components/Button--primary',
+ result: 'changed',
+ classification_reason: '',
+ diff_percentage: 2.4,
+ diff_pixel_count: 1536,
+ review_state: 'pending',
+ reviewed_at: null,
+ approved_hash: '',
+ ...overrides,
+})
+
+const snapshots = {
+ count: 2,
+ next: null,
+ previous: null,
+ quarantined_count: 0,
+ results: [
+ snapshot({
+ id: 'snapshot-changed',
+ identifier: 'Components/Button--primary',
+ result: 'changed',
+ baseline_artifact: artifact('base_changed'),
+ current_artifact: artifact('curr_changed'),
+ }),
+ snapshot({
+ id: 'snapshot-new',
+ identifier: 'Components/Banner--info',
+ result: 'new',
+ diff_percentage: null,
+ diff_pixel_count: null,
+ current_artifact: artifact('curr_new'),
+ }),
+ ],
+}
+
+const emptyList = { count: 0, next: null, previous: null, results: [] }
+
+const meta: Meta = {
+ component: App,
+ title: 'Scenes-App/Visual review/Run',
+ parameters: {
+ layout: 'fullscreen',
+ viewMode: 'story',
+ mockDate: '2026-06-10',
+ pageUrl: `/visual_review/runs/${RUN_ID}`,
+ testOptions: { waitForSelector: '[data-attr="visual-review-add-images-to-comment"]' },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ [`/api/projects/:team_id/visual_review/runs/${RUN_ID}/`]: run,
+ [`/api/projects/:team_id/visual_review/runs/${RUN_ID}/snapshots/`]: snapshots,
+ [`/api/projects/:team_id/visual_review/runs/${RUN_ID}/tolerated-hashes/`]: emptyList,
+ [`/api/projects/:team_id/visual_review/repos/${REPO_ID}/`]: repo,
+ [`/api/projects/:team_id/visual_review/repos/${REPO_ID}/quarantine/`]: emptyList,
+ },
+ }),
+ ],
+}
+export default meta
+
+// The finalize action carries an opt-in "Also comment on the PR" checkbox beside it.
+export const ReadyToFinalize: StoryObj = {}
diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
index ff0f033d3d56..f8d010cfbc1d 100644
--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import React from 'react'
import { IconChevronLeft, IconChevronRight } from '@posthog/icons'
-import { LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
+import { LemonButton, LemonCheckbox, LemonSkeleton, Link } from '@posthog/lemon-ui'
import { PostHogCaptureOnViewed } from '@posthog/react'
import { DetectiveHog } from 'lib/components/hedgehogs'
@@ -229,6 +229,7 @@ export function VisualReviewRunScene(): JSX.Element {
isRunProcessing,
failedThumbnails,
thumbnailBasePath,
+ addImagesToComment,
} = useValues(visualReviewRunSceneLogic)
const {
setSelectedSnapshotId,
@@ -240,6 +241,7 @@ export function VisualReviewRunScene(): JSX.Element {
recomputeRun,
markThumbnailFailed,
toggleQuarantinedThumbnails,
+ setAddImagesToComment,
} = useActions(visualReviewRunSceneLogic)
// Navigation — use changed snapshots when there are changes, otherwise all snapshots
@@ -386,14 +388,24 @@ export function VisualReviewRunScene(): JSX.Element {
resourceType={{ type: 'visual_review' }}
actions={
!run.approved && !run.is_stale && (reviewPending > 0 || reviewApproved > 0) ? (
- <LemonButton
- type="primary"
- onClick={finalizeRun}
- loading={isFinalizing}
- data-attr="visual-review-finalize-run"
- >
- {reviewPending > 0 ? `Approve ${reviewPending} and finalize` : 'Finalize run'}
- </LemonButton>
+ <div className="flex items-center gap-2">
+ <LemonCheckbox
+ checked={addImagesToComment}
+ onChange={setAddImagesToComment}
+ disabledReason={isFinalizing ? 'Finalizing…' : undefined}
+ label="Add snapshots to the PR comment"
+ info="The PR comment is always posted; tick this to attach the before/after snapshot images to it. Remembered for next time."
+ data-attr="visual-review-add-images-to-comment"
+ />
+ <LemonButton
+ type="primary"
+ onClick={finalizeRun}
+ loading={isFinalizing}
+ data-attr="visual-review-finalize-run"
+ >
+ {reviewPending > 0 ? `Approve ${reviewPending} and finalize` : 'Finalize run'}
+ </LemonButton>
+ </div>
) : undefined
}
/>
diff --git a/products/visual_review/frontend/scenes/visualReviewPreferencesLogic.test.ts b/products/visual_review/frontend/scenes/visualReviewPreferencesLogic.test.ts
new file mode 100644
index 000000000000..a2178226a57e
--- /dev/null
+++ b/products/visual_review/frontend/scenes/visualReviewPreferencesLogic.test.ts
@@ -0,0 +1,29 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { visualReviewPreferencesLogic } from './visualReviewPreferencesLogic'
+
+describe('visualReviewPreferencesLogic', () => {
+ let logic: ReturnType<typeof visualReviewPreferencesLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = visualReviewPreferencesLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('defaults adding snapshot images to the comment to off so it is opt-in', async () => {
+ await expectLogic(logic).toMatchValues({ addImagesToComment: false })
+ })
+
+ it.each([true, false])('remembers the addImagesToComment choice (%s)', async (enabled) => {
+ await expectLogic(logic, () => {
+ logic.actions.setAddImagesToComment(enabled)
+ }).toMatchValues({ addImagesToComment: enabled })
+ })
+})
diff --git a/products/visual_review/frontend/scenes/visualReviewPreferencesLogic.ts b/products/visual_review/frontend/scenes/visualReviewPreferencesLogic.ts
index 7d707d9f912a..f23bf6af6d03 100644
--- a/products/visual_review/frontend/scenes/visualReviewPreferencesLogic.ts
+++ b/products/visual_review/frontend/scenes/visualReviewPreferencesLogic.ts
@@ -8,6 +8,7 @@ export const visualReviewPreferencesLogic = kea<visualReviewPreferencesLogicType
path(['products', 'visual_review', 'frontend', 'scenes', 'visualReviewPreferencesLogic']),
actions({
setComparisonMode: (mode: ComparisonMode) => ({ mode }),
+ setAddImagesToComment: (enabled: boolean) => ({ enabled }),
}),
reducers({
comparisonMode: [
@@ -17,5 +18,12 @@ export const visualReviewPreferencesLogic = kea<visualReviewPreferencesLogicType
setComparisonMode: (_, { mode }) => mode,
},
],
+ addImagesToComment: [
+ false,
+ { persist: true, prefix: 'visual_review_' },
+ {
+ setAddImagesToComment: (_, { enabled }) => enabled,
+ },
+ ],
}),
])
diff --git a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts
index 7051f57116ba..8098394b6019 100644
--- a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts
+++ b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts
@@ -1,6 +1,7 @@
import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, urlToAction } from 'kea-router'
+import posthog from 'posthog-js'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
@@ -27,6 +28,7 @@ import type {
SnapshotApi,
ToleratedHashEntryApi,
} from '../generated/api.schemas'
+import { visualReviewPreferencesLogic } from './visualReviewPreferencesLogic'
import type { visualReviewRunSceneLogicType } from './visualReviewRunSceneLogicType'
export interface VisualReviewRunSceneLogicProps {
@@ -38,7 +40,8 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([
props({} as VisualReviewRunSceneLogicProps),
key((props) => props.runId),
connect(() => ({
- values: [teamLogic, ['currentProjectId']],
+ values: [teamLogic, ['currentProjectId'], visualReviewPreferencesLogic, ['addImagesToComment']],
+ actions: [visualReviewPreferencesLogic, ['setAddImagesToComment']],
})),
actions({
setSelectedSnapshotId: (snapshotId: string | null) => ({ snapshotId }),
@@ -312,13 +315,20 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([
}
try {
+ const addImages = values.addImagesToComment
// 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,
+ add_images_to_comment_on_pr: addImages,
})
actions.finalizeRunSuccess()
- lemonToast.success('Run finalized — baseline committed')
+ posthog.capture('visual_review_run_finalized', { added_images_to_comment: addImages })
+ lemonToast.success(
+ addImages
+ ? 'Run finalized — baseline committed, PR commented with snapshots'
+ : 'Run finalized — baseline committed, PR commented'
+ )
actions.loadRun()
// 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;
diff --git a/products/visual_review/package.json b/products/visual_review/package.json
index 786865996a30..b09ed3aa510a 100644
--- a/products/visual_review/package.json
+++ b/products/visual_review/package.json
@@ -10,11 +10,16 @@
"dependencies": {
"kea": "catalog:",
"kea-loaders": "catalog:",
- "kea-router": "catalog:"
+ "kea-router": "catalog:",
+ "posthog-js": "catalog:"
+ },
+ "devDependencies": {
+ "kea-test-utils": "catalog:"
},
"peerDependencies": {
"@posthog/icons": "*",
"@posthog/react": "*",
+ "@storybook/react": "catalog:",
"@types/react": "*",
"react": "*"
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 99ab582fc14d..50527be0c969 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19289,6 +19289,8 @@ export namespace Schemas {
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;
+ /** 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. */
+ add_images_to_comment_on_pr?: boolean;
}
export interface FlagValueItem {
diff --git a/services/mcp/src/generated/visual_review/api.ts b/services/mcp/src/generated/visual_review/api.ts
index 1ecc4671e04c..b2823115b541 100644
--- a/services/mcp/src/generated/visual_review/api.ts
+++ b/services/mcp/src/generated/visual_review/api.ts
@@ -119,6 +119,7 @@ export const VisualReviewRunsFinalizeCreateParams = /* @__PURE__ */ zod.object({
export const visualReviewRunsFinalizeCreateBodyApproveAllDefault = false
export const visualReviewRunsFinalizeCreateBodyCommitToGithubDefault = true
+export const visualReviewRunsFinalizeCreateBodyAddImagesToCommentOnPrDefault = false
export const VisualReviewRunsFinalizeCreateBody = /* @__PURE__ */ zod.object({
approve_all: zod
@@ -133,6 +134,12 @@ export const VisualReviewRunsFinalizeCreateBody = /* @__PURE__ */ zod.object({
.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.'
),
+ 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.'
+ ),
})
/**
diff --git a/services/mcp/src/tools/generated/visual_review.ts b/services/mcp/src/tools/generated/visual_review.ts
index 504c9eef5c8a..dabcb1c8bb63 100644
--- a/services/mcp/src/tools/generated/visual_review.ts
+++ b/services/mcp/src/tools/generated/visual_review.ts
@@ -121,6 +121,9 @@ const visualReviewRunsFinalizeCreate = (): ToolBase<
if (params.commit_to_github !== undefined) {
body['commit_to_github'] = params.commit_to_github
}
+ if (params.add_images_to_comment_on_pr !== undefined) {
+ body['add_images_to_comment_on_pr'] = params.add_images_to_comment_on_pr
+ }
const result = await context.api.request<Schemas.FinalizeResult>({
method: 'POST',
path: `/api/projects/${encodeURIComponent(String(projectId))}/visual_review/runs/${encodeURIComponent(String(params.id))}/finalize/`,