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): report observe-run snapshot drift from run complete (#77815)

Georges-Antoine Assi7555c34b2fdb
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index da214265a2fd..25c91845c72e 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -113,8 +113,9 @@ The CLI uploads directly to S3 via presigned POST URLs — the backend never pro
**`vr run complete`** — triggers completion (classification, removal detection, diffs).
Exits 1 if unapproved changes are detected, 0 if clean or `--auto-approve` is set, and 2 if the command itself failed (auth, network, timeout, backend processing).
-The exit code does not depend on `--purpose`: an `observe` run still exits 1 on unapproved changes, so a caller that wants tracking-only behavior has to tolerate exit 1 itself.
-`ci-storybook.yml` does exactly that on master pushes and merge-queue branches, and treats exit 2 as a failure everywhere.
+Pass the same `--purpose` the run was created with.
+On `--purpose observe` the command names the drifted identifiers, emits a `::warning::` annotation, and exits 0, because a tracking-only run has nothing to approve and must not gate.
+Without the flag it reports nothing on such a run: the backend reports zero unresolved for an observe run whatever drifted, so a clean run and a drifting one look identical.
### Run purposes
diff --git a/products/visual_review/cli/src/client.test.ts b/products/visual_review/cli/src/client.test.ts
index 6b732dae4ac3..edf7b4aabe71 100644
--- a/products/visual_review/cli/src/client.test.ts
+++ b/products/visual_review/cli/src/client.test.ts
@@ -15,7 +15,7 @@ function jsonResponse(body: unknown, status = 200, headers: Record<string, strin
} as unknown as Response
}
-describe('VisualReviewClient retry logic', () => {
+describe('VisualReviewClient', () => {
let client: VisualReviewClient
beforeEach(() => {
@@ -41,6 +41,16 @@ describe('VisualReviewClient retry logic', () => {
expect(mockFetch).toHaveBeenCalledTimes(1)
})
+ it('unwraps the paginated envelope when listing run snapshots', async () => {
+ const snapshot = { id: 's1', identifier: 'story--light', result: 'changed' }
+ mockFetch.mockResolvedValueOnce(jsonResponse({ count: 4107, next: null, results: [snapshot] }))
+
+ const result = await client.getRunSnapshots('run-1')
+
+ expect(result).toEqual([snapshot])
+ expect(mockFetch.mock.calls[0][0]).toContain('limit=100')
+ })
+
it('throws immediately on 4xx errors without retrying', async () => {
mockFetch.mockResolvedValueOnce(jsonResponse({ error: 'unauthorized' }, 401))
diff --git a/products/visual_review/cli/src/client.ts b/products/visual_review/cli/src/client.ts
index 52e54ed60569..a9e7f9ea1333 100644
--- a/products/visual_review/cli/src/client.ts
+++ b/products/visual_review/cli/src/client.ts
@@ -10,6 +10,7 @@ import type {
CreateRunInputApi,
CreateRunResultApi,
FinalizeResultApi,
+ PaginatedSnapshotListApi,
RunApi,
SnapshotApi,
SnapshotManifestItemApi,
@@ -200,10 +201,15 @@ export class VisualReviewClient {
}
/**
- * Get snapshots for a run.
+ * Get snapshots for a run. The endpoint is paginated and orders actionable results
+ * (changed / new / removed) ahead of unchanged ones, so the first page names
+ * everything that needs review unless a run has more than `limit` of them.
*/
- async getRunSnapshots(runId: string): Promise<SnapshotApi[]> {
- return this.request<SnapshotApi[]>(`/visual_review/runs/${runId}/snapshots/`)
+ async getRunSnapshots(runId: string, limit = 100): Promise<SnapshotApi[]> {
+ const page = await this.request<PaginatedSnapshotListApi>(
+ `/visual_review/runs/${runId}/snapshots/?limit=${limit}`
+ )
+ return page.results
}
/**
diff --git a/products/visual_review/cli/src/index.ts b/products/visual_review/cli/src/index.ts
index 37bf9eaea6eb..30b674f523d8 100644
--- a/products/visual_review/cli/src/index.ts
+++ b/products/visual_review/cli/src/index.ts
@@ -14,6 +14,7 @@ import { resolve } from 'node:path'
import { VisualReviewClient, type Run } from './client.js'
import { hashImageWithDimensions } from './hasher.js'
+import { log, reportRunOutcome } from './outcome.js'
import { scanDirectory } from './scanner.js'
import { readBaselineHashes, readSnapshotsFile } from './snapshots.js'
@@ -131,6 +132,7 @@ run.command('complete')
.option('--team <id>', 'Team ID (overrides snapshots.yml config)')
.option('--token <value>', 'Personal API token')
.option('--cookie <value>', 'Session cookie')
+ .option('--purpose <purpose>', 'Run purpose: review or observe. Must match `run create`.', 'review')
.option('--auto-approve', 'Auto-approve all changes and write signed baseline')
.action(async (options: RunCompleteOptions) => {
if (!baselineExists(options.baseline)) {
@@ -142,8 +144,7 @@ run.command('complete')
} catch (error) {
console.error('Error:', error)
// 2, not 1, so callers can tell a failed CLI apart from the exit 1 that
- // runComplete returns for unresolved visual changes. CI tolerates the latter
- // on tracking-only runs and must never tolerate this.
+ // runComplete returns for unresolved visual changes on a review run.
process.exit(2)
}
})
@@ -205,16 +206,12 @@ interface RunCompleteOptions {
team?: string
token?: string
cookie?: string
+ purpose?: string
autoApprove?: boolean
}
// --- Helpers ---
-// Log to stderr so stdout stays clean for machine-readable output (e.g. run IDs)
-function log(message: string): void {
- process.stderr.write(message + '\n')
-}
-
function baselineExists(baselinePath: string): boolean {
const p = resolve(baselinePath)
if (!existsSync(p)) {
@@ -432,15 +429,12 @@ async function runComplete(options: RunCompleteOptions): Promise<number> {
return 0
}
- const hasUnresolved = (s.unresolved ?? s.changed + s.new + s.removed) > 0
- if (hasUnresolved) {
- const reviewUrl = `${api}/project/${team}/visual_review/runs/${runId}`
- log(`[run:${runId}] Visual changes detected — review at: ${reviewUrl}`)
- return 1
- }
-
- log(`[run:${runId}] No visual changes`)
- return 0
+ return reportRunOutcome(
+ client,
+ run,
+ `${api}/project/${team}/visual_review/runs/${runId}`,
+ options.purpose ?? 'review'
+ )
}
// --- Legacy command implementations ---
@@ -662,13 +656,5 @@ async function runSubmit(options: SubmitOptions): Promise<number> {
return 0
}
- const hasUnresolved = (s.unresolved ?? s.changed + s.new + s.removed) > 0
- if (hasUnresolved) {
- const reviewUrl = `${api}/project/${team}/visual_review/runs/${runId}`
- log(`[run:${runId}] Visual changes detected — review at: ${reviewUrl}`)
- return 1
- }
-
- log(`[run:${runId}] No visual changes`)
- return 0
+ return reportRunOutcome(client, run, `${api}/project/${team}/visual_review/runs/${runId}`, purpose)
}
diff --git a/products/visual_review/cli/src/outcome.test.ts b/products/visual_review/cli/src/outcome.test.ts
new file mode 100644
index 000000000000..c650a464edbb
--- /dev/null
+++ b/products/visual_review/cli/src/outcome.test.ts
@@ -0,0 +1,101 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { VisualReviewClient, type Run } from './client.js'
+import { reportRunOutcome } from './outcome.js'
+
+function run(summary: Partial<Run['summary']> = {}): Run {
+ return {
+ id: 'run-1',
+ branch: 'master',
+ summary: { total: 10, unchanged: 10, changed: 0, new: 0, removed: 0, unresolved: 0, ...summary },
+ } as Run
+}
+
+describe('reportRunOutcome', () => {
+ let client: VisualReviewClient
+ let output: string
+
+ beforeEach(() => {
+ output = ''
+ const capture = (chunk: unknown): boolean => {
+ output += String(chunk)
+ return true
+ }
+ vi.spyOn(process.stderr, 'write').mockImplementation(capture)
+ vi.spyOn(process.stdout, 'write').mockImplementation(capture)
+ client = new VisualReviewClient({ apiUrl: 'https://vr.example.com', teamId: '1' })
+ vi.spyOn(client, 'getRunSnapshots').mockResolvedValue([
+ { identifier: 'story--light', result: 'changed', diff_percentage: 12.07 },
+ { identifier: 'story--dark', result: 'unchanged', diff_percentage: null },
+ ] as never)
+ })
+
+ // A tolerated hash is reclassified `unchanged` server-side, so a clean master run really
+ // does report changed=0 alongside a non-zero tolerated_matched (14 of them, in this repo).
+ // Netting the two produced a negative count that read as drift and warned on every push.
+ it('stays quiet on a clean observe run that has tolerated matches', async () => {
+ const exitCode = await reportRunOutcome(
+ client,
+ run({ unchanged: 4115, total: 4115, tolerated_matched: 14 }),
+ 'https://vr.example.com/run-1',
+ 'observe'
+ )
+
+ expect(exitCode).toBe(0)
+ expect(output).toContain('No visual changes')
+ expect(output).not.toContain('::warning::')
+ })
+
+ // The mirror image: netting tolerated matches off real drift hid it entirely.
+ it('warns about drift on an observe run even when tolerated matches exist', async () => {
+ const exitCode = await reportRunOutcome(
+ client,
+ run({ unchanged: 4113, total: 4115, changed: 2, tolerated_matched: 14 }),
+ 'https://vr.example.com/run-1',
+ 'observe'
+ )
+
+ expect(exitCode).toBe(0)
+ expect(output).toContain('Unapproved snapshot drift on master')
+ expect(output).toContain('changed: story--light (12.07% diff)')
+ })
+
+ it('gates a review run with unresolved changes', async () => {
+ const exitCode = await reportRunOutcome(
+ client,
+ run({ unchanged: 8, changed: 2, unresolved: 2 }),
+ 'https://vr.example.com/run-1',
+ 'review'
+ )
+
+ expect(exitCode).toBe(1)
+ expect(output).toContain('Visual changes detected')
+ })
+
+ it('passes a review run whose changes are all resolved', async () => {
+ const exitCode = await reportRunOutcome(
+ client,
+ run({ unchanged: 8, changed: 2, unresolved: 0 }),
+ 'https://vr.example.com/run-1',
+ 'review'
+ )
+
+ expect(exitCode).toBe(0)
+ expect(output).toContain('No visual changes')
+ })
+
+ it('still reports when the snapshot listing fails', async () => {
+ vi.spyOn(client, 'getRunSnapshots').mockRejectedValue(new Error('boom'))
+
+ const exitCode = await reportRunOutcome(
+ client,
+ run({ unchanged: 8, changed: 2, unresolved: 2 }),
+ 'https://vr.example.com/run-1',
+ 'review'
+ )
+
+ expect(exitCode).toBe(1)
+ expect(output).toContain('Could not list changed snapshots: boom')
+ expect(output).toContain('Visual changes detected')
+ })
+})
diff --git a/products/visual_review/cli/src/outcome.ts b/products/visual_review/cli/src/outcome.ts
new file mode 100644
index 000000000000..0190ef4fe17a
--- /dev/null
+++ b/products/visual_review/cli/src/outcome.ts
@@ -0,0 +1,105 @@
+/**
+ * How a finished run is reported, and whether it gates.
+ *
+ * Lives outside index.ts so it can be tested directly: index.ts calls `program.parse()` at
+ * import time, so importing it from a test would run the CLI.
+ */
+import { VisualReviewClient, type Run, type Snapshot } from './client.js'
+
+// Log to stderr so stdout stays clean for machine-readable output (e.g. run IDs)
+export function log(message: string): void {
+ process.stderr.write(message + '\n')
+}
+
+// Enough to see the shape of a failure without burying the CI log when a global
+// style change moves hundreds of stories at once.
+const ACTIONABLE_SNAPSHOT_LOG_LIMIT = 25
+
+/**
+ * Name the snapshots that need review. The summary line above only carries counts, so
+ * without this, reading a CI failure means opening the run in the UI, which does not work
+ * for a run on a branch that no longer exists by the time anyone looks.
+ *
+ * `total` comes from the run summary rather than the fetched page, so the remainder stays
+ * honest when a run has more actionable snapshots than one page holds.
+ */
+async function logActionableSnapshots(client: VisualReviewClient, runId: string, total: number): Promise<void> {
+ let snapshots: Snapshot[]
+ try {
+ snapshots = await client.getRunSnapshots(runId)
+ } catch (error) {
+ log(`[run:${runId}] Could not list changed snapshots: ${error instanceof Error ? error.message : error}`)
+ return
+ }
+
+ const actionable = snapshots.filter((snapshot) => snapshot.result !== 'unchanged')
+ for (const snapshot of actionable.slice(0, ACTIONABLE_SNAPSHOT_LOG_LIMIT)) {
+ const diff = snapshot.diff_percentage === null ? '' : ` (${snapshot.diff_percentage.toFixed(2)}% diff)`
+ log(`[run:${runId}] ${snapshot.result}: ${snapshot.identifier}${diff}`)
+ }
+ const remaining = total - Math.min(actionable.length, ACTIONABLE_SNAPSHOT_LOG_LIMIT)
+ if (remaining > 0) {
+ log(`[run:${runId}] ...and ${remaining} more`)
+ }
+}
+
+/**
+ * Surface a warning where whoever is running the CLI will see it. `::warning::` goes to
+ * stdout because that is the stream GitHub Actions parses for workflow commands; only
+ * `run create` uses stdout for machine-readable output, so nothing here can corrupt it.
+ */
+function warn(message: string): void {
+ if (process.env.GITHUB_ACTIONS === 'true') {
+ process.stdout.write(`::warning::${message}\n`)
+ return
+ }
+ log(`Warning: ${message}`)
+}
+
+/**
+ * Report what the run found and return the exit code.
+ *
+ * Observe (tracking-only) runs have nothing to approve, so the backend reports zero unresolved
+ * however many snapshots drifted, and they must not fail the job. They still have to leave a
+ * trace: an identifier that drifts on the default branch without being approved or quarantined
+ * fails the next PR that renders it.
+ *
+ * The change counts are already the drift count on an observe run. A snapshot matching a
+ * tolerated hash is reclassified `unchanged` by the server, so it never reaches `changed`, and
+ * an observe run cannot approve or tolerate anything of its own (the API rejects both). So do
+ * not net `tolerated_matched` off: it double-counts, and since it also spans quarantined
+ * snapshots it goes negative on a clean run, which reads as drift. Quarantined snapshots are
+ * excluded from the counts server-side.
+ */
+export async function reportRunOutcome(
+ client: VisualReviewClient,
+ run: Run,
+ reviewUrl: string,
+ purpose: string
+): Promise<number> {
+ const runId = run.id
+ const s = run.summary
+ const changes = s.changed + s.new + s.removed
+
+ if (purpose === 'observe') {
+ if (changes === 0) {
+ log(`[run:${runId}] No visual changes`)
+ return 0
+ }
+ await logActionableSnapshots(client, runId, changes)
+ warn(
+ `Unapproved snapshot drift on ${run.branch}: approve the new baseline, or quarantine the identifier if it flips between runs, before it fails an unrelated PR. Review at: ${reviewUrl}`
+ )
+ return 0
+ }
+
+ const unresolved = s.unresolved ?? changes
+ if (unresolved > 0) {
+ await logActionableSnapshots(client, runId, unresolved)
+ log(`[run:${runId}] Visual changes detected — review at: ${reviewUrl}`)
+ return 1
+ }
+
+ log(`[run:${runId}] No visual changes`)
+ return 0
+}