:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(visual_review): add tracking-only runs for default branch pushes (#65222)
Julian Bez0447b1afd3ea
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex cf19dd534392..4d51abe5d83d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6686,6 +6686,10 @@ snapshots:hash: v1.k794b7964.0963628627d2de9b968394dac5513b1749b3a9c90f1ca07f51c4497036a9262b.CSDgJl9gZqu0yrd7a0p8-WSSKR2zVFP-t47fKNoGOGIscenes-app-visual-review-run--ready-to-finalize--light:hash: v1.k794b7964.cbad9f0954e55a8a37053d4824897f00e6ce6cdfec8bcf16afcaaef887ea53b4.BtH21G_RiNOuXE6qtG9BjC0OEcbzdO5SfkUft7rL56Y+ scenes-app-visual-review-run--tracking-only-master-run--dark:+ hash: v1.k794b7964.bfc61bf20c0b73de80378e874bb56016fd927aef402a1f463a106bc5cb827393.cWScCSGNTqzACLtACS9rLRvrFlwHZbj0AkFjEK4U4L8+ scenes-app-visual-review-run--tracking-only-master-run--light:+ hash: v1.k794b7964.efe730f50a4753a635f651e34b2e941a9d5be1f77a93dc21af67af21b9e8592e.QTyRHMOWPIo_fX8hWHNEAauDRRiGrhyB-Ak1Hv2h3KEscenes-app-web-analytics--web-analytics-dashboard--dark:hash: v1.k794b7964.e25a818b0ffdb3f8ce23e74b145500851bec3cb1a413282b6fe8748e33bb97d4.rQ7r3LELEifqwLSEximUj5oTBpTtbFwJLFYx0DynTwMscenes-app-web-analytics--web-analytics-dashboard--light:diff --git a/products/visual_review/README.md b/products/visual_review/README.mdindex 819f9f7aff3b..284d2ee08582 100644--- a/products/visual_review/README.md+++ b/products/visual_review/README.md@@ -116,7 +116,7 @@ The CLI uploads directly to S3 via presigned POST URLs — the backend never pro### Run purposes- **`review`** (default) — approvable. Backend posts PR comment prompts; UI surfaces it under "needs review"; CLI gates on unapproved changes.-- **`observe`** — tracking only. Backend rejects approval attempts; no PR comment; excluded from "needs review". Use on master pushes where there's no PR to approve.+- **`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 where there's no PR to approve.## Current statediff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex d275ea63802f..c3e77f68c824 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -24,6 +24,7 @@ from posthog.helpers.trigram_search import search_match_type_from_instancefrom .. import logicfrom ..diff_metadata import DiffMetadatafrom . import contracts+from .enums import RunPurposeUser = get_user_model()@@ -155,7 +156,15 @@ def _to_snapshot(def _compute_unresolved(run) -> int:- """Compute unresolved count from prefetched snapshots, or fall back to DB."""+ """Count snapshots still awaiting human resolution.++ Observe (tracking-only) runs are never approvable, so nothing is ever+ "unresolved" — return 0. This keeps the CLI (which exits non-zero when+ unresolved > 0) and the UI from treating a default-branch run as gating,+ matching the green commit status such runs post.+ """+ if run.purpose == RunPurpose.OBSERVE:+ return 0# Use prefetched snapshots if available (detail view), skip for list viewsif "snapshots" in getattr(run, "_prefetched_objects_cache", {}):return sum(1 for s in run.snapshots.all() if logic._is_unresolved(s))diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex ee9bf331c235..dfb27003030d 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -1141,6 +1141,23 @@ def _approved_baseline_updates(snapshots: Iterable[RunSnapshot]) -> list[dict]:]+def _format_change_counts(changed: int, new: int, removed: int) -> str:+ """'N changed, M new, K removed', omitting zero counts; '' when all are zero."""+ parts = []+ if changed:+ parts.append(f"{changed} changed")+ if new:+ parts.append(f"{new} new")+ if removed:+ parts.append(f"{removed} removed")+ return ", ".join(parts)+++def _changes_summary(run: Run) -> str:+ """Change summary from the run's denormalized (quarantine-excluded) counts."""+ return _format_change_counts(run.changed_count, run.new_count, run.removed_count)++def _update_counts_and_post_status(run: Run) -> int:"""Re-stamp quarantine, recount snapshots, compute unresolved, and post commit status.@@ -1182,15 +1199,15 @@ def _update_counts_and_post_status(run: Run) -> int:repo = run.repoif run.error_message:_post_commit_status(run, repo, "error", f"Visual review failed: {run.error_message[:100]}")+ elif run.purpose == RunPurpose.OBSERVE:+ # Default-branch (tracking-only) runs never gate — there's no PR to approve.+ # Report any changes as a green, informational status instead of a blocking+ # failure; the per-snapshot detail lives in the VR UI (linked via target_url).+ summary = _changes_summary(run)+ description = f"Tracking only: {summary} recorded" if summary else "Tracking only: no visual changes"+ _post_commit_status(run, repo, "success", description)elif unresolved > 0:- parts = []- if run.changed_count:- parts.append(f"{run.changed_count} changed")- if run.new_count:- parts.append(f"{run.new_count} new")- if run.removed_count:- parts.append(f"{run.removed_count} removed")- _post_commit_status(run, repo, "failure", f"Visual changes detected: {', '.join(parts)}")+ _post_commit_status(run, repo, "failure", f"Visual changes detected: {_changes_summary(run)}")_post_review_prompt_comment(run, repo)elif pending_commit > 0:_post_commit_status(@@ -1565,7 +1582,13 @@ def _post_commit_status(from .github import github_requestcontext = f"PostHog Visual Review / {run.run_type}"- if run.is_partial:+ # Tracking-only (observe) and partial runs must never satisfy the gating context that+ # branch protection evaluates. Both purpose and is_partial are client-supplied, so an+ # observe run posted to the gating context could green a PR head SHA's required check+ # without review. Route them to a distinct, non-gating context instead.+ if run.purpose == RunPurpose.OBSERVE:+ context = f"{context} (tracking)"+ elif run.is_partial:context = f"{context} (partial)"description = f"{description} (partial run)"@@ -1973,14 +1996,8 @@ def _build_approval_comment_body(run: Run, repo: Repo, approver: _Approver | Nonbaseline_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 ""- summary = ", ".join(- f"{counts[result]} {label}"- for result, label in (- (SnapshotResult.CHANGED, "changed"),- (SnapshotResult.NEW, "new"),- (SnapshotResult.REMOVED, "removed"),- )- if counts.get(result)+ summary = _format_change_counts(+ counts[SnapshotResult.CHANGED], counts[SnapshotResult.NEW], counts[SnapshotResult.REMOVED])sections = [diff --git a/products/visual_review/backend/tests/test_gating.py b/products/visual_review/backend/tests/test_gating.pyindex 360530badb00..1fac3edcec1c 100644--- a/products/visual_review/backend/tests/test_gating.py+++ b/products/visual_review/backend/tests/test_gating.py@@ -19,6 +19,7 @@ covers the entire state space.import pytestfrom products.visual_review.backend import logic+from products.visual_review.backend.facade import apifrom products.visual_review.backend.facade.enums import ReviewState, RunStatus, RunType, SnapshotResultfrom products.visual_review.backend.models import QuarantinedIdentifier, Runfrom products.visual_review.backend.tests.conftest import PRODUCT_DATABASES@@ -61,7 +62,7 @@ class TestGatingInvariants:mocker.patch("products.visual_review.backend.logic._post_commit_status")mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")- def _build_run(self, result: str, action: str | None) -> Run:+ def _build_run(self, result: str, action: str | None, purpose: str = "review") -> Run:snapshots: list[dict] = []baseline: dict[str, str] = {}@@ -89,6 +90,7 @@ class TestGatingInvariants:branch="feat/test",pr_number=1,snapshots=snapshots,+ purpose=purpose,)logic.complete_run(run.id)run.refresh_from_db()@@ -156,3 +158,18 @@ class TestGatingInvariants:second = logic.recompute_run(run.id, team_id=self.team.id)assert second["counts_changed"] is False++ def test_observe_run_summary_never_gates(self):+ # The CLI exits non-zero on summary.unresolved > 0. Observe (tracking-only) runs are+ # non-approvable, so the summary must report 0 unresolved even with real changes —+ # otherwise `vr submit --purpose observe` would red a default-branch job.+ run = self._build_run("changed", None, purpose="observe")+ summary = api.get_run(run.id, team_id=self.team.id).summary+ assert summary.changed == 1+ assert summary.unresolved == 0++ def test_review_run_summary_still_gates(self):+ run = self._build_run("changed", None)+ summary = api.get_run(run.id, team_id=self.team.id).summary+ assert summary.changed == 1+ assert summary.unresolved == 1diff --git a/products/visual_review/backend/tests/test_logic.py b/products/visual_review/backend/tests/test_logic.pyindex 586294b457d2..68662717aefc 100644--- a/products/visual_review/backend/tests/test_logic.py+++ b/products/visual_review/backend/tests/test_logic.py@@ -1157,6 +1157,69 @@ class TestCommitStatusChecks:assert "failed" in statuses[-1]["description"].lower()assert len(mock_github_api.issue_comments) == 0+ def test_observe_run_with_changes_posts_green_tracking_status(self, github_repo, mock_github_api, mocker):+ # Default-branch (observe) runs are tracking-only: a visual change posts a green,+ # informational status — never a blocking failure — and no review-prompt comment.+ github_repo.enable_pr_comments = True+ github_repo.save(update_fields=["enable_pr_comments"])++ run, _ = logic.create_run(+ repo_id=github_repo.id,+ team_id=github_repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc123",+ branch="master",+ pr_number=None,+ snapshots=[+ {"identifier": "changed", "content_hash": "new_h"},+ {"identifier": "added", "content_hash": "brand_new"},+ ],+ baseline_hashes={"changed": "old_h"},+ purpose="observe",+ )++ mocker.patch(+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",+ return_value=({"changed": "old_h"}, 0),+ )+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")+ logic.complete_run(run.id)+ logic.finish_processing(run.id)++ statuses = mock_github_api.status_checks+ assert statuses[-1]["state"] == "success"+ assert statuses[-1]["description"] == "Tracking only: 1 changed, 1 new recorded"+ # Observe runs post to a separate, non-gating context. purpose is client-supplied,+ # so greening the gating context would let an observe run bypass branch protection+ # on a PR head SHA — the gating context must never be touched by an observe run.+ assert statuses[-1]["context"] == "PostHog Visual Review / storybook (tracking)"+ assert all(s["context"] != "PostHog Visual Review / storybook" for s in statuses)+ assert len(mock_github_api.issue_comments) == 0++ def test_observe_run_without_changes_posts_green_tracking_status(self, github_repo, mock_github_api, mocker):+ run, _ = logic.create_run(+ repo_id=github_repo.id,+ team_id=github_repo.team_id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc123",+ branch="master",+ pr_number=None,+ snapshots=[{"identifier": "snap", "content_hash": "same"}],+ baseline_hashes={"snap": "same"},+ purpose="observe",+ )++ mocker.patch(+ "products.visual_review.backend.logic._resolve_baselines_with_merge_base",+ return_value=({"snap": "same"}, 0),+ )+ logic.complete_run(run.id)++ statuses = mock_github_api.status_checks+ assert statuses[-1]["state"] == "success"+ assert statuses[-1]["description"] == "Tracking only: no visual changes"+ assert statuses[-1]["context"] == "PostHog Visual Review / storybook (tracking)"+def test_approve_run_posts_success(self, github_repo, mock_github_api, user):logic.get_or_create_artifact(repo_id=github_repo.id, content_hash="new_h", storage_path="p/new")run, _ = logic.create_run(diff --git a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx b/products/visual_review/frontend/components/SnapshotDiffViewer.tsxindex a16b6ad8a60c..cabc5ca90ecf 100644--- a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx+++ b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx@@ -56,6 +56,7 @@ interface SnapshotDiffViewerProps {repoFullName?: string | nullrunType?: stringgithubRunId?: string | null+ isReportingOnly?: booleanisRecomputing?: booleanonRecompute?: () => voidrecomputeDisabledReason?: string@@ -77,6 +78,7 @@ export function SnapshotDiffViewer({repoFullName,runType,githubRunId,+ isReportingOnly,isRecomputing,onRecompute,recomputeDisabledReason,@@ -128,7 +130,8 @@ export function SnapshotDiffViewer({const isTolerated = snapshot.review_state === 'tolerated'const isQuarantined = !!quarantineEntryconst hasChanges = snapshot.result === 'changed' || snapshot.result === 'new' || snapshot.result === 'removed'- const needsAction = hasChanges && !isApproved && !isTolerated && !isQuarantined+ // Default-branch (tracking-only) runs are never approvable — don't offer accept/reject/tolerate.+ const needsAction = hasChanges && !isApproved && !isTolerated && !isQuarantined && !isReportingOnly// Parse identifier for display (e.g., "Feature-Flags-settings--e2e-test--dark--1440x900")const parts = snapshot.identifier.split('--')diff --git a/products/visual_review/frontend/lib/runPredicates.ts b/products/visual_review/frontend/lib/runPredicates.tsnew file mode 100644index 000000000000..0bc419adcb98--- /dev/null+++ b/products/visual_review/frontend/lib/runPredicates.ts@@ -0,0 +1,9 @@+import type { RunApi } from '../generated/api.schemas'++// A run with no PR is a default-branch (master/main) push: tracking-only, never approvable.+// CI submits these with purpose "observe", and the backend rejects approve/finalize on them,+// so the UI must never offer an approval that can't apply. The run API doesn't expose `purpose`+// yet, so PR presence is the proxy — it matches the backend's needs_review filter.+export function isReportingOnlyRun(run: RunApi | null): boolean {+ return !!run && run.pr_number == null+}diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsxindex 8b0150d8ffa6..09e0905d4fc7 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx@@ -88,6 +88,13 @@ const snapshots = {],}+// A push to the default branch — no PR, tracking-only. Nothing to approve.+const masterRun: RunApi = {+ ...run,+ branch: 'master',+ pr_number: null,+}+const emptyList = { count: 0, next: null, previous: null, results: [] }const meta: Meta = {@@ -116,3 +123,18 @@ export default meta// The finalize action carries an opt-in "Also comment on the PR" checkbox beside it.export const ReadyToFinalize: StoryObj = {}++// A default-branch run is reporting-only: no finalize action, no per-snapshot accept/reject/tolerate —+// just an informational banner. Snapshots still have changes, but there's nothing to approve.+export const TrackingOnlyMasterRun: StoryObj = {+ parameters: {+ testOptions: { waitForSelector: '[data-attr="visual-review-snapshot-thumbnail"]' },+ },+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/visual_review/runs/${RUN_ID}/`]: masterRun,+ },+ }),+ ],+}diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsxindex 04b0552261c0..d30eb1612030 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx@@ -227,6 +227,7 @@ export function VisualReviewRunScene(): JSX.Element {isRecomputing,isRunInProgress,isRunProcessing,+ isReportingOnly,failedThumbnails,thumbnailBasePath,addImagesToComment,@@ -389,7 +390,7 @@ export function VisualReviewRunScene(): JSX.Element {name={run.branch}resourceType={{ type: 'visual_review' }}actions={- !run.approved && !run.is_stale && (reviewPending > 0 || reviewApproved > 0) ? (+ !isReportingOnly && !run.approved && !run.is_stale && (reviewPending > 0 || reviewApproved > 0) ? (<div className="flex items-center gap-2"><LemonCheckboxchecked={addImagesToComment}@@ -413,6 +414,13 @@ export function VisualReviewRunScene(): JSX.Element {/><VisualReviewTabs activeKey="runs" repoId={run.repo_id} />+ {isReportingOnly && (+ <LemonBanner type="info" className="mb-4">+ Tracking-only run — this is a push to the default branch, so there's nothing to approve. Visual+ changes are recorded for history and reported to GitHub as a non-blocking status.+ </LemonBanner>+ )}+{run.is_stale && (<LemonBanner type="warning" className="mb-4">This run has been superseded by a newer run.{' '}@@ -424,7 +432,7 @@ export function VisualReviewRunScene(): JSX.Element {</LemonBanner>)}- {allChangesResolved && reviewApproved === 0 && !ciRetriggerUnavailableReason && (+ {!isReportingOnly && allChangesResolved && reviewApproved === 0 && !ciRetriggerUnavailableReason && (<LemonBannertype="info"className="mb-4"@@ -605,9 +613,12 @@ export function VisualReviewRunScene(): JSX.Element {repoFullName={repoFullName}runType={run.run_type}githubRunId={(run.metadata?.github_run_id as string) || null}+ isReportingOnly={isReportingOnly}isRecomputing={isRecomputing}onRecompute={- run.status === 'completed' && !run.approved && !run.is_stale ? recomputeRun : undefined+ !isReportingOnly && run.status === 'completed' && !run.approved && !run.is_stale+ ? recomputeRun+ : undefined}recomputeDisabledReason={ciRetriggerUnavailableReason ??diff --git a/products/visual_review/frontend/scenes/VisualReviewRunsScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunsScene.tsxindex 8274b85dd725..2849b6820eeb 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunsScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunsScene.tsx@@ -23,6 +23,7 @@ import { RepoSwitcher } from '../components/RepoSwitcher'import { RunSummaryStats } from '../components/RunSummaryStats'import { VisualReviewTabs } from '../components/VisualReviewTabs'import type { RunApi } from '../generated/api.schemas'+import { isReportingOnlyRun } from '../lib/runPredicates'import { ReviewState, VisualReviewRunsSceneLogicProps, visualReviewRunsSceneLogic } from './visualReviewRunsSceneLogic'export const scene: SceneExport = {@@ -113,7 +114,8 @@ export function VisualReviewRunsScene(): JSX.Element {align: 'right',render: (_, run) => {const hasChanges = run.summary.changed > 0 || run.summary.new > 0 || run.summary.removed > 0- const needsReview = run.status === 'completed' && hasChanges && !run.approved+ const needsReview =+ run.status === 'completed' && hasChanges && !run.approved && !isReportingOnlyRun(run)return (<LemonButtondiff --git a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.tsindex 157ee9ae6ebd..e29bda004d38 100644--- a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts@@ -28,6 +28,7 @@ import type {SnapshotApi,ToleratedHashEntryApi,} from '../generated/api.schemas'+import { isReportingOnlyRun } from '../lib/runPredicates'import { visualReviewPreferencesLogic } from './visualReviewPreferencesLogic'import type { visualReviewRunSceneLogicType } from './visualReviewRunSceneLogicType'@@ -276,6 +277,7 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([],isRunInProgress: [(s) => [s.run], (run): boolean => run?.status === 'pending' || run?.status === 'processing'],isRunProcessing: [(s) => [s.run], (run): boolean => run?.status === 'processing'],+ isReportingOnly: [(s) => [s.run], (run): boolean => isReportingOnlyRun(run)],breadcrumbs: [(s) => [s.run],(run): Breadcrumb[] => [diff --git a/turbo.json b/turbo.jsonindex 392dd1af33f6..6b060c8d7099 100644--- a/turbo.json+++ b/turbo.json@@ -6,9 +6,17 @@"tasks": {"backend:test": {"inputs": [- "**/*.py",- "!**/__pycache__/**",- "!frontend/**",+ "backend/**/*.py",+ "!backend/**/__pycache__/**",+ // A few products run pytest against roots outside backend/:+ // experiments (stats/), logs (skills/), posthog_ai (scripts/).+ // These globs anchor per-package, so they only match where the+ // dir exists. Do NOT collapse to a leading "**/*.py" — that+ // resolves from the workspace root and marks every product's+ // backend:test affected on any .py change, forcing the full suite.+ "stats/**/*.py",+ "skills/**/*.py",+ "scripts/**/*.py","../../pyproject.toml","../../uv.lock","../../common/**/*.py"