: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): suggest quarantine when tolerating a flaky snapshot (#103833)
Julian Bez0200277e75ab
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 84fd95434b09..1c146cf9bf54 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11016,6 +11016,10 @@ snapshots:hash: v1.k794b7964.879549ba86b942a0497ef5b08bb0172ac58c62fe8da41a21584c82bea231db20.lG7LsOxr5tzXDBwFMJwt3c7IgoQuIH6h8qlUZnPNJVwscenes-app-visual-review-run--ready-to-finalize--light:hash: v1.k794b7964.197e6fe1cc9dba0da720ef1e1cfc94b3601d775aa389e49230465a2b65797d47.Tqyss84UbEfq4Gra3v9eMtLs4zfONfl5fSfff9FlmZA+ scenes-app-visual-review-run--tolerate-suggests-quarantine--dark:+ hash: v1.k794b7964.01b906bdb8448973bb5a655f0ea96dbf42ba0def73d179ce3f1c2779d603d1cd.ZVbpVkiu1tofZS8NcQ8DpGM57DqjoiC5vDWQnPKEscw+ scenes-app-visual-review-run--tolerate-suggests-quarantine--light:+ hash: v1.k794b7964.423d5d2ad0d7ef00ba976f5455835ba0c518c8d7c86a7a2a359c8af4b1eab648.V47tBu61Pg3UnMCcefNn1D4VzvUXv5-qQU8_qkyk3_kscenes-app-visual-review-run--tracking-only-master-run--dark:hash: v1.k794b7964.16fda1278ef2eb5cec07ca3903959e2701d2ff01e37c20a9b4e5cd013a765dd0.TQ9RJbHXN6hccxpL_rOIK0ylVS9s8KVzCjNgCZWqi6wscenes-app-visual-review-run--tracking-only-master-run--light:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1e47a2e5216c..4d71604058b0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -5026,6 +5026,12 @@ importers:'@storybook/react':specifier: 'catalog:'version: 10.4.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@testing-library/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])+ '@testing-library/dom':+ specifier: '*'+ version: 10.4.0+ '@testing-library/user-event':+ specifier: '*'+ version: 14.6.1(@testing-library/[email protected])'@types/react':specifier: 18.3.27version: 18.3.27diff --git a/products/visual_review/README.md b/products/visual_review/README.mdindex 9baa620f3ca6..c23a9a16dded 100644--- a/products/visual_review/README.md+++ b/products/visual_review/README.md@@ -228,6 +228,7 @@ Working end to end: CI upload → async diff → GitHub Check → web review →**Tolerated hashes** — when the diff classifies a snapshot as below-threshold noise, it caches the `(identifier, baseline_hash, alternate_hash)` tuple.Future runs skip diffing entirely for cached pairs.Developers can also manually tolerate a snapshot from the UI.+When a snapshot already has 3 manual or agent tolerations, or 10 automatic ones, in the last 30 days, the Tolerate button offers a quarantine first, because another toleration covers only that one rendering.**Row alignment** — a panel that grows by a pixel moves everything below it down, which a top-aligned pixel diff reads as a page-wide change.Before thresholding, the diff pairs the rows that exist in both images, so the classifier sees only what actually changed.diff --git a/products/visual_review/frontend/components/QuarantineAction.tsx b/products/visual_review/frontend/components/QuarantineAction.tsxindex ec8b779f885f..9c4b994c6621 100644--- a/products/visual_review/frontend/components/QuarantineAction.tsx+++ b/products/visual_review/frontend/components/QuarantineAction.tsx@@ -1,92 +1,22 @@-import { useEffect, useState } from 'react'+import { useState } from 'react'-import { LemonButton, LemonCheckbox, LemonInput, LemonModal } from '@posthog/lemon-ui'+import { LemonButton } from '@posthog/lemon-ui'-import { DatePicker } from 'lib/components/DatePicker/DatePicker'-import { dayjs } from 'lib/dayjs'+import { QuarantineModal, type OnQuarantine, type QuarantineModalMode } from './QuarantineModal'-const SUGGESTED_REASONS = [- 'Non-deterministic rendering (animations, timestamps)',- 'Font hinting varies across environments',- 'Async content loading race condition',- 'Known flaky — fix in progress',-]--const DEFAULT_EXPIRY_DAYS = 30--const COPY = {- create: {- triggerLabel: 'Quarantine this identifier',- modalTitle: 'Quarantine snapshot',- confirmLabel: 'Quarantine',- dataAttrOpen: 'visual-review-quarantine-open',- dataAttrConfirm: 'visual-review-quarantine-confirm',- expiresLabel: 'Expires',- description:- 'Quarantined identifiers appear as quarantined immediately and are excluded from gating when future runs finalize — including pending runs on other branches. Snapshots are still captured and diffed, just not gated on.',- },- extend: {- triggerLabel: 'Extend',- modalTitle: 'Extend quarantine',- confirmLabel: 'Extend',- dataAttrOpen: 'visual-review-quarantine-extend-open',- dataAttrConfirm: 'visual-review-quarantine-extend-confirm',- expiresLabel: 'New expiry',- description:- 'Extending creates a new quarantine entry that supersedes the current one — the audit trail keeps both. The reason can be edited; the expiry will be bumped to the date you pick below.',- },+const TRIGGER = {+ create: { label: 'Quarantine this identifier', dataAttr: 'visual-review-quarantine-open' },+ extend: { label: 'Extend', dataAttr: 'visual-review-quarantine-extend-open' },} as const-// Bump from the current expiry, not "now", when extending. Falls back to a-// fresh +30d window if the prior entry already expired.-function computeDefaultExpiry(initialExpiresAt: string | null | undefined): dayjs.Dayjs {- if (initialExpiresAt) {- const prior = dayjs(initialExpiresAt)- const base = prior.isAfter(dayjs()) ? prior : dayjs()- return base.add(DEFAULT_EXPIRY_DAYS, 'day')- }- return dayjs().add(DEFAULT_EXPIRY_DAYS, 'day')-}--/**- * Identifiers carry an optional `--light` / `--dark` theme suffix.- * When the user quarantines one variant, they almost always want- * the sibling quarantined too — same code path, same flake.- */-export function getThemeSibling(identifier: string): string | null {- const parts = identifier.split('--')- const themeIndex = [...parts].reverse().findIndex((part) => part === 'dark' || part === 'light')- if (themeIndex === -1) {- return null- }- const actualIndex = parts.length - 1 - themeIndex- const siblingParts = [...parts]- siblingParts[actualIndex] = siblingParts[actualIndex] === 'dark' ? 'light' : 'dark'- return siblingParts.join('--')-}-interface QuarantineActionProps {identifier: string- onQuarantine: (reason: string, identifiers: string[], expiresAt: string | null, sourceRunId: string | null) => void+ onQuarantine: OnQuarantine/** Override the trigger button label. Defaults to "Quarantine this identifier". */triggerLabel?: string- /**- * "extend" mode reuses this modal to bump an active quarantine's expiry — the- * backend create endpoint auto-supersedes the prior active row, so extending- * is just a re-create with a pre-populated reason and a future date. The- * sibling-quarantine checkbox is hidden because the sibling has its own- * quarantine row already.- */- mode?: 'create' | 'extend'- /** Pre-fill the reason field. Useful when extending. */+ mode?: QuarantineModalModeinitialReason?: string- /** Pre-fill the expiry field. Useful when extending (default: +30d from now). */initialExpiresAt?: string | null- /**- * The run whose failing snapshot prompted this quarantine. Set when extending- * (carries forward the original source) or when creating from the run scene.- * Forwarded to the parent via `onQuarantine` so the backend can store it.- */sourceRunId?: string | null/*** Set while a quarantine write for this identifier is in flight. The create@@ -98,9 +28,8 @@ interface QuarantineActionProps {}/**- * Quarantine modal + trigger button. Used from the run scene (per snapshot- * sidebar) and the snapshot history scene (per identifier banner). Local- * state for the modal — the parent owns the API call via `onQuarantine`.+ * Quarantine trigger button plus its modal. Used from the run scene (per snapshot+ * sidebar) and the snapshot history scene (per identifier banner).*/export function QuarantineAction({identifier,@@ -112,41 +41,8 @@ export function QuarantineAction({sourceRunId,pendingReason,}: QuarantineActionProps): JSX.Element {- const isExtend = mode === 'extend'- const copy = COPY[mode]-const [isOpen, setIsOpen] = useState(false)- const [reason, setReason] = useState(initialReason ?? '')- const [includeSibling, setIncludeSibling] = useState(true)- const [expiresAt, setExpiresAt] = useState<dayjs.Dayjs | null>(computeDefaultExpiry(initialExpiresAt))-- // Re-prefill if the parent swaps which entry we're acting on mid-session.- // Skip while the modal is open so a background refresh of the underlying- // entry can't silently trample the user's in-progress edits.- useEffect(() => {- if (isOpen) {- return- }- setReason(initialReason ?? '')- setExpiresAt(computeDefaultExpiry(initialExpiresAt))- }, [initialReason, initialExpiresAt, isOpen])-- const sibling = getThemeSibling(identifier)-- const handleSubmit = (): void => {- const identifiers = [identifier]- // Extending only affects the entry the user opened — siblings have- // their own quarantine and their own expiry to manage.- if (!isExtend && sibling && includeSibling) {- identifiers.push(sibling)- }- onQuarantine(reason, identifiers, expiresAt ? expiresAt.toISOString() : null, sourceRunId ?? null)- setIsOpen(false)- if (!isExtend) {- setReason('')- setExpiresAt(dayjs().add(DEFAULT_EXPIRY_DAYS, 'day'))- }- }+ const trigger = TRIGGER[mode]return (<div>@@ -154,90 +50,22 @@ export function QuarantineAction({type="secondary"size="small"onClick={() => setIsOpen(true)}- data-attr={copy.dataAttrOpen}+ data-attr={trigger.dataAttr}loading={!!pendingReason}disabledReason={pendingReason ?? undefined}>- {triggerLabel ?? copy.triggerLabel}+ {triggerLabel ?? trigger.label}</LemonButton>- <LemonModal+ <QuarantineModalisOpen={isOpen}onClose={() => setIsOpen(false)}- title={copy.modalTitle}- footer={- <>- <LemonButton- type="secondary"- onClick={() => setIsOpen(false)}- data-attr="visual-review-quarantine-cancel"- >- Cancel- </LemonButton>- <LemonButton- type="primary"- disabledReason={!reason.trim() ? 'Reason is required' : undefined}- onClick={handleSubmit}- data-attr={copy.dataAttrConfirm}- >- {copy.confirmLabel}- </LemonButton>- </>- }- >- <div className="space-y-4">- <p className="text-sm text-muted">{copy.description}</p>-- <div>- <label className="text-sm font-medium mb-1 block">Identifier</label>- <div className="font-mono text-xs text-muted bg-bg-3000 rounded px-2 py-1.5">{identifier}</div>- {!isExtend && sibling && (- <LemonCheckbox- className="mt-1.5"- label={- <span className="text-xs">- Also quarantine <span className="font-mono">{sibling}</span>- </span>- }- checked={includeSibling}- onChange={setIncludeSibling}- />- )}- </div>-- <div>- <label className="text-sm font-medium mb-1 block">Reason</label>- <LemonInput- placeholder="Why is this snapshot quarantined?"- value={reason}- onChange={setReason}- autoFocus- />- <div className="flex flex-wrap gap-1 mt-1.5">- {SUGGESTED_REASONS.map((suggestion) => (- <button- key={suggestion}- type="button"- className="text-[11px] text-muted hover:text-default bg-bg-3000 hover:bg-border rounded px-1.5 py-0.5 transition-colors"- onClick={() => setReason(suggestion)}- >- {suggestion}- </button>- ))}- </div>- </div>-- <div>- <label className="text-sm font-medium mb-1 block">{copy.expiresLabel}</label>- <DatePicker- value={expiresAt}- onChange={setExpiresAt}- placeholder="No expiry"- clearable- maxDate={dayjs().add(1, 'year')}- />- </div>- </div>- </LemonModal>+ identifier={identifier}+ onQuarantine={onQuarantine}+ mode={mode}+ initialReason={initialReason}+ initialExpiresAt={initialExpiresAt}+ sourceRunId={sourceRunId}+ /></div>)}diff --git a/products/visual_review/frontend/components/QuarantineModal.tsx b/products/visual_review/frontend/components/QuarantineModal.tsxnew file mode 100644index 000000000000..26eeacdcb3e3--- /dev/null+++ b/products/visual_review/frontend/components/QuarantineModal.tsx@@ -0,0 +1,220 @@+import { useEffect, useState } from 'react'++import { LemonButton, LemonCheckbox, LemonInput, LemonModal } from '@posthog/lemon-ui'++import { DatePicker } from 'lib/components/DatePicker/DatePicker'+import { dayjs } from 'lib/dayjs'++const SUGGESTED_REASONS = [+ 'Non-deterministic rendering (animations, timestamps)',+ 'Font hinting varies across environments',+ 'Async content loading race condition',+ 'Known flaky — fix in progress',+]++const DEFAULT_EXPIRY_DAYS = 30++const COPY = {+ create: {+ modalTitle: 'Quarantine snapshot',+ confirmLabel: 'Quarantine',+ dataAttrConfirm: 'visual-review-quarantine-confirm',+ expiresLabel: 'Expires',+ description:+ 'Quarantined identifiers appear as quarantined immediately and are excluded from gating when future runs finalize — including pending runs on other branches. Snapshots are still captured and diffed, just not gated on.',+ },+ extend: {+ modalTitle: 'Extend quarantine',+ confirmLabel: 'Extend',+ dataAttrConfirm: 'visual-review-quarantine-extend-confirm',+ expiresLabel: 'New expiry',+ description:+ 'Extending creates a new quarantine entry that supersedes the current one — the audit trail keeps both. The reason can be edited; the expiry will be bumped to the date you pick below.',+ },+} as const++// Bump from the current expiry, not "now", when extending. Falls back to a+// fresh +30d window if the prior entry already expired.+function computeDefaultExpiry(initialExpiresAt: string | null | undefined): dayjs.Dayjs {+ if (initialExpiresAt) {+ const prior = dayjs(initialExpiresAt)+ const base = prior.isAfter(dayjs()) ? prior : dayjs()+ return base.add(DEFAULT_EXPIRY_DAYS, 'day')+ }+ return dayjs().add(DEFAULT_EXPIRY_DAYS, 'day')+}++/**+ * Identifiers carry an optional `--light` / `--dark` theme suffix.+ * When the user quarantines one variant, they almost always want+ * the sibling quarantined too — same code path, same flake.+ */+function getThemeSibling(identifier: string): string | null {+ const parts = identifier.split('--')+ const themeIndex = [...parts].reverse().findIndex((part) => part === 'dark' || part === 'light')+ if (themeIndex === -1) {+ return null+ }+ const actualIndex = parts.length - 1 - themeIndex+ const siblingParts = [...parts]+ siblingParts[actualIndex] = siblingParts[actualIndex] === 'dark' ? 'light' : 'dark'+ return siblingParts.join('--')+}++export type QuarantineModalMode = 'create' | 'extend'++export type OnQuarantine = (+ reason: string,+ identifiers: string[],+ expiresAt: string | null,+ sourceRunId: string | null+) => void++interface QuarantineModalProps {+ isOpen: boolean+ onClose: () => void+ identifier: string+ onQuarantine: OnQuarantine+ /**+ * "extend" mode reuses this modal to bump an active quarantine's expiry — the+ * backend create endpoint auto-supersedes the prior active row, so extending+ * is just a re-create with a pre-populated reason and a future date. The+ * sibling-quarantine checkbox is hidden because the sibling has its own+ * quarantine row already.+ */+ mode?: QuarantineModalMode+ /** Pre-fill the reason field. Useful when extending. */+ initialReason?: string+ /** Pre-fill the expiry field. Useful when extending (default: +30d from now). */+ initialExpiresAt?: string | null+ /**+ * The run whose failing snapshot prompted this quarantine. Set when extending+ * (carries forward the original source) or when creating from the run scene.+ * Forwarded to the parent via `onQuarantine` so the backend can store it.+ */+ sourceRunId?: string | null+}++/**+ * Quarantine form in a modal. The parent owns the open state and the API call+ * via `onQuarantine`, so a trigger other than `QuarantineAction` can open it.+ */+export function QuarantineModal({+ isOpen,+ onClose,+ identifier,+ onQuarantine,+ mode = 'create',+ initialReason,+ initialExpiresAt,+ sourceRunId,+}: QuarantineModalProps): JSX.Element {+ const isExtend = mode === 'extend'+ const copy = COPY[mode]++ const [reason, setReason] = useState(initialReason ?? '')+ const [includeSibling, setIncludeSibling] = useState(true)+ const [expiresAt, setExpiresAt] = useState<dayjs.Dayjs | null>(() => computeDefaultExpiry(initialExpiresAt))++ // Re-prefill if the parent swaps which entry we're acting on mid-session.+ // Skip while the modal is open so a background refresh of the underlying+ // entry can't silently trample the user's in-progress edits.+ useEffect(() => {+ if (isOpen) {+ return+ }+ setReason(initialReason ?? '')+ setIncludeSibling(true)+ setExpiresAt(computeDefaultExpiry(initialExpiresAt))+ }, [initialReason, initialExpiresAt, isOpen])++ const sibling = getThemeSibling(identifier)++ const handleSubmit = (): void => {+ const identifiers = [identifier]+ // Extending only affects the entry the user opened — siblings have+ // their own quarantine and their own expiry to manage.+ if (!isExtend && sibling && includeSibling) {+ identifiers.push(sibling)+ }+ onQuarantine(reason, identifiers, expiresAt ? expiresAt.toISOString() : null, sourceRunId ?? null)+ onClose()+ }++ return (+ <LemonModal+ isOpen={isOpen}+ onClose={onClose}+ title={copy.modalTitle}+ footer={+ <>+ <LemonButton type="secondary" onClick={onClose} data-attr="visual-review-quarantine-cancel">+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ disabledReason={!reason.trim() ? 'Reason is required' : undefined}+ onClick={handleSubmit}+ data-attr={copy.dataAttrConfirm}+ >+ {copy.confirmLabel}+ </LemonButton>+ </>+ }+ >+ <div className="space-y-4">+ <p className="text-sm text-muted">{copy.description}</p>++ <div>+ <label className="text-sm font-medium mb-1 block">Identifier</label>+ <div className="font-mono text-xs text-muted bg-bg-3000 rounded px-2 py-1.5">{identifier}</div>+ {!isExtend && sibling && (+ <LemonCheckbox+ className="mt-1.5"+ label={+ <span className="text-xs">+ Also quarantine <span className="font-mono">{sibling}</span>+ </span>+ }+ checked={includeSibling}+ onChange={setIncludeSibling}+ />+ )}+ </div>++ <div>+ <label className="text-sm font-medium mb-1 block">Reason</label>+ <LemonInput+ placeholder="Why is this snapshot quarantined?"+ value={reason}+ onChange={setReason}+ autoFocus+ />+ <div className="flex flex-wrap gap-1 mt-1.5">+ {SUGGESTED_REASONS.map((suggestion) => (+ <button+ key={suggestion}+ type="button"+ className="text-[11px] text-muted hover:text-default bg-bg-3000 hover:bg-border rounded px-1.5 py-0.5 transition-colors"+ onClick={() => setReason(suggestion)}+ >+ {suggestion}+ </button>+ ))}+ </div>+ </div>++ <div>+ <label className="text-sm font-medium mb-1 block">{copy.expiresLabel}</label>+ <DatePicker+ value={expiresAt}+ onChange={setExpiresAt}+ placeholder="No expiry"+ clearable+ maxDate={dayjs().add(1, 'year')}+ />+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx b/products/visual_review/frontend/components/SnapshotDiffViewer.tsxindex e992bebb9bf9..dad9aaf08f5f 100644--- a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx+++ b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx@@ -7,11 +7,14 @@ import { LemonButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'import { VisualImageDiffViewer, type VisualDiffResult } from 'lib/components/VisualImageDiffViewer'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'+import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'import type { QuarantinedIdentifierEntryApi, SnapshotApi, ToleratedHashEntryApi } from '../generated/api.schemas'+import { QUARANTINE_NUDGE_WINDOW_DAYS, type RecentTolerations, shouldSuggestQuarantine } from '../lib/quarantineNudge'import { visualReviewPreferencesLogic } from '../scenes/visualReviewPreferencesLogic'import { QuarantineAction } from './QuarantineAction'+import { QuarantineModal, type OnQuarantine } from './QuarantineModal'import { SnapshotChangeBadge, hasSnapshotChangeBadge } from './SnapshotChangeBadge'import { SnapshotClusterPanel } from './SnapshotClusterPanel'import { SnapshotShiftSummary } from './SnapshotShiftSummary'@@ -25,6 +28,16 @@ const TOLERATION_REASON_LABELS: Record<string, string> = {auto_threshold: 'auto',}+function describeRecentTolerations(counts: RecentTolerations): string {+ const total = counts.manual + counts.agent + counts.auto+ const parts = [+ counts.manual > 0 && `${counts.manual} manual`,+ counts.agent > 0 && `${counts.agent} by an agent`,+ counts.auto > 0 && `${counts.auto} automatic`,+ ].filter(Boolean)+ return `Tolerated ${pluralize(total, 'time')} in the last ${QUARANTINE_NUDGE_WINDOW_DAYS} days (${parts.join(', ')}).`+}+function DiffMinimap({ url, onClick }: { url: string; onClick?: () => void }): JSX.Element {const [loaded, setLoaded] = useState(false)return (@@ -53,11 +66,12 @@ interface SnapshotDiffViewerProps {snapshot: SnapshotApitoleratedHashes?: ToleratedHashEntryApi[]toleratedHashesLoading?: boolean+ recentTolerations?: RecentTolerations | nullonApprove?: () => voidisApproving?: booleanonMarkTolerated?: () => voidquarantineEntry?: QuarantinedIdentifierEntryApi | null- onQuarantine?: (reason: string, identifiers: string[], expiresAt: string | null, sourceRunId: string | null) => void+ onQuarantine?: OnQuarantineonUnquarantine?: () => voidcommitSha?: stringprNumber?: number | null@@ -75,6 +89,7 @@ export function SnapshotDiffViewer({snapshot,toleratedHashes,toleratedHashesLoading,+ recentTolerations,onApprove,isApproving,onMarkTolerated,@@ -101,6 +116,8 @@ export function SnapshotDiffViewer({const height = snapshot.current_artifact?.height || snapshot.baseline_artifact?.heightconst [highlightedClusterIndex, setHighlightedClusterIndex] = useState<number | null>(null)+ // The identifier the nudge opened for. Hotkeys can move to another snapshot while the dialog is open.+ const [nudgedIdentifier, setNudgedIdentifier] = useState<string | null>(null)// When a single (post-merge) cluster covers most of the image, the// bbox overlay adds no information beyond the diff% tag — full@@ -143,6 +160,43 @@ export function SnapshotDiffViewer({// Default-branch (tracking-only) runs are never approvable — don't offer accept/reject/tolerate.const needsAction = hasChanges && !isApproved && !isTolerated && !isQuarantined && !isReportingOnly+ // A snapshot that keeps needing a toleration is flaky, and one more toleration+ // only covers this exact rendering. While the history loads, fall back to the+ // plain confirm so the nudge never delays the click.+ const openTolerateDialog = (): void => {+ if (recentTolerations && onQuarantine && shouldSuggestQuarantine(recentTolerations)) {+ const identifier = snapshot.identifier+ LemonDialog.open({+ title: 'This snapshot keeps changing',+ description:+ `${describeRecentTolerations(recentTolerations)} A toleration only covers this exact rendering, so the next variation blocks PRs again. ` ++ 'If this change is unrelated to your PR, quarantine the snapshot. It stops blocking PRs until someone fixes it.',+ primaryButton: {+ children: 'Quarantine…',+ onClick: () => setNudgedIdentifier(identifier),+ 'data-attr': 'visual-review-tolerate-nudge-quarantine',+ },+ secondaryButton: {+ children: 'Tolerate anyway',+ onClick: onMarkTolerated,+ 'data-attr': 'visual-review-tolerate-nudge-tolerate',+ },+ })+ return+ }+ LemonDialog.open({+ title: 'Does this snapshot really render correctly?',+ description:+ 'Only tolerate slight rendering noise above the difference threshold. Confirm there are no visible errors or missing elements. ' ++ 'Otherwise, quarantine this snapshot.',+ primaryButton: {+ children: 'Tolerate',+ onClick: onMarkTolerated,+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+// Parse identifier for display (e.g., "Feature-Flags-settings--e2e-test--dark--1440x900")const parts = snapshot.identifier.split('--')const pageName = parts[0]?.replace(/-/g, ' ') || snapshot.identifier@@ -183,19 +237,7 @@ export function SnapshotDiffViewer({<LemonButtontype="secondary"size="small"- onClick={() => {- LemonDialog.open({- title: 'Does this snapshot really render correctly?',- description:- 'Only tolerate slight rendering noise above the difference threshold. Confirm there are no visible errors or missing elements. ' +- 'Otherwise, quarantine this snapshot.',- primaryButton: {- children: 'Tolerate',- onClick: onMarkTolerated,- },- secondaryButton: { children: 'Cancel' },- })- }}+ onClick={openTolerateDialog}data-attr="visual-review-snapshot-tolerate">Tolerate@@ -519,6 +561,15 @@ export function SnapshotDiffViewer({{hasChanges && !isQuarantined && onQuarantine && (<QuarantineAction identifier={snapshot.identifier} onQuarantine={onQuarantine} />)}+ {nudgedIdentifier && onQuarantine && (+ <QuarantineModal+ isOpen+ onClose={() => setNudgedIdentifier(null)}+ identifier={nudgedIdentifier}+ onQuarantine={onQuarantine}+ initialReason="Keeps changing in unrelated PRs"+ />+ )}{isQuarantined && onUnquarantine && (<div><LemonButtondiff --git a/products/visual_review/frontend/lib/quarantineNudge.test.ts b/products/visual_review/frontend/lib/quarantineNudge.test.tsnew file mode 100644index 000000000000..c1ae71fbeb63--- /dev/null+++ b/products/visual_review/frontend/lib/quarantineNudge.test.ts@@ -0,0 +1,41 @@+import { dayjs } from 'lib/dayjs'++import type { ToleratedHashEntryApi } from '../generated/api.schemas'+import { countRecentTolerations, shouldSuggestQuarantine } from './quarantineNudge'++const NOW = dayjs('2026-06-10T12:00:00Z')++function tolerations(reason: string, count: number, daysAgo: number): ToleratedHashEntryApi[] {+ return Array.from({ length: count }, (_, index) => ({+ id: `${reason}-${daysAgo}-${index}`,+ alternate_hash: `alt-${index}`,+ baseline_hash: 'base',+ reason,+ diff_percentage: 1,+ created_at: NOW.subtract(daysAgo, 'day').toISOString(),+ source_run_id: null,+ }))+}++describe('quarantineNudge', () => {+ it.each([+ { name: 'three manual in the window', hashes: tolerations('human', 3, 2), expected: true },+ {+ name: 'manual and agent add up',+ hashes: [...tolerations('human', 2, 2), ...tolerations('agent', 1, 5)],+ expected: true,+ },+ { name: 'two manual is not enough', hashes: tolerations('human', 2, 2), expected: false },+ { name: 'manual exactly at the window edge count', hashes: tolerations('human', 3, 30), expected: true },+ { name: 'manual outside the window do not count', hashes: tolerations('human', 3, 31), expected: false },+ {+ name: 'a few auto do not reach the manual bar',+ hashes: tolerations('auto_threshold', 9, 2),+ expected: false,+ },+ { name: 'ten auto in the window', hashes: tolerations('auto_threshold', 10, 2), expected: true },+ { name: 'no history', hashes: [], expected: false },+ ])('$name', ({ hashes, expected }) => {+ expect(shouldSuggestQuarantine(countRecentTolerations(hashes, NOW))).toBe(expected)+ })+})diff --git a/products/visual_review/frontend/lib/quarantineNudge.ts b/products/visual_review/frontend/lib/quarantineNudge.tsnew file mode 100644index 000000000000..9c5c6b61e16a--- /dev/null+++ b/products/visual_review/frontend/lib/quarantineNudge.ts@@ -0,0 +1,35 @@+import { dayjs } from 'lib/dayjs'++import type { ToleratedHashEntryApi } from '../generated/api.schemas'++// Same window the baselines overview uses for `tolerate_count_30d`.+export const QUARANTINE_NUDGE_WINDOW_DAYS = 30++// Same floor as the backend `VARIANT_PILEUP_MIN`, chosen to agree with it: at+// three accepted renderings a snapshot no longer has one rendering.+const QUARANTINE_NUDGE_MIN_INTENTIONAL = 3++// Auto tolerations cost nobody a click, so it takes more of them to mean the+// same thing. Each one is a distinct rendering the diff pipeline absorbed, and+// ten in a month is a snapshot that renders differently every few days.+const QUARANTINE_NUDGE_MIN_AUTO = 10++export interface RecentTolerations {+ manual: number+ agent: number+ auto: number+}++export function countRecentTolerations(toleratedHashes: ToleratedHashEntryApi[], now: dayjs.Dayjs): RecentTolerations {+ const cutoff = now.subtract(QUARANTINE_NUDGE_WINDOW_DAYS, 'day')+ const recent = toleratedHashes.filter((entry) => !dayjs(entry.created_at).isBefore(cutoff))+ return {+ manual: recent.filter((entry) => entry.reason === 'human').length,+ agent: recent.filter((entry) => entry.reason === 'agent').length,+ auto: recent.filter((entry) => entry.reason === 'auto_threshold').length,+ }+}++export function shouldSuggestQuarantine(counts: RecentTolerations): boolean {+ return counts.manual + counts.agent >= QUARANTINE_NUDGE_MIN_INTENTIONAL || counts.auto >= QUARANTINE_NUDGE_MIN_AUTO+}diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsxindex 81279fac32f0..38a0a0f851e9 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx@@ -1,4 +1,6 @@import type { Meta, StoryObj } from '@storybook/react'+import { waitFor } from '@testing-library/dom'+import userEvent from '@testing-library/user-event'import { App } from 'scenes/App'@@ -181,3 +183,48 @@ export const TrackingOnlyMasterRun: StoryObj = {}),],}++const repeatedTolerations = {+ count: 3,+ next: null,+ previous: null,+ results: ['2026-06-02', '2026-06-05', '2026-06-08'].map((day, index) => ({+ id: `tolerated-${index}`,+ alternate_hash: `alt_${index}`,+ baseline_hash: 'base_changed',+ reason: 'human',+ diff_percentage: 2.6,+ created_at: `${day}T10:00:00Z`,+ source_run_id: null,+ })),+}++// A snapshot tolerated three times this month keeps changing. Clicking Tolerate offers a quarantine first.+export const TolerateSuggestsQuarantine: StoryObj = {+ parameters: {+ // Not `fullscreen`: the runner rejects snapshotTargetSelector for fullscreen stories.+ layout: 'padded',+ testOptions: {+ waitForSelector: '[data-attr="visual-review-tolerate-nudge-quarantine"]',+ snapshotTargetSelector: '.LemonModal',+ },+ },+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/visual_review/runs/${RUN_ID}/tolerated-hashes/`]: repeatedTolerations,+ },+ }),+ ],+ play: async () => {+ const tolerateButton = await waitFor(() => {+ const element = document.querySelector<HTMLButtonElement>('[data-attr="visual-review-snapshot-tolerate"]')+ // The nudge reads the tolerated hashes, so wait for the sidebar to list them.+ if (!element || !document.body.textContent?.includes('alt_0')) {+ throw new Error('Tolerate button or tolerated hashes not yet rendered')+ }+ return element+ })+ await userEvent.click(tolerateButton)+ },+}diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsxindex c7af33093e09..5036416121a6 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx@@ -221,6 +221,7 @@ export function VisualReviewRunScene(): JSX.Element {sortedChangedSnapshots,toleratedHashes,toleratedHashesLoading,+ recentTolerations,quarantinedIdentifiers,quarantinedIdentifierSet,showQuarantinedThumbnails,@@ -595,6 +596,7 @@ export function VisualReviewRunScene(): JSX.Element {snapshot={selectedSnapshot}toleratedHashes={toleratedHashes}toleratedHashesLoading={toleratedHashesLoading}+ recentTolerations={recentTolerations}onApprove={handleApproveSnapshot}isApproving={isApprovingSnapshot}onMarkTolerated={() => markAsTolerated(selectedSnapshot)}diff --git a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.test.ts b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.test.tsnew file mode 100644index 000000000000..f37f57ae6c1b--- /dev/null+++ b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.test.ts@@ -0,0 +1,80 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { visualReviewRunSceneLogic } from './visualReviewRunSceneLogic'++const RUN_ID = '00000000-0000-0000-0000-0000000000aa'+const TOLERATED_URL = `/api/projects/:team_id/visual_review/runs/${RUN_ID}/tolerated-hashes/`++const toleratedToday = (index: number): Record<string, unknown> => ({+ id: `tolerated-${index}`,+ alternate_hash: `alt-${index}`,+ baseline_hash: 'base',+ reason: 'human',+ diff_percentage: 2.6,+ created_at: new Date().toISOString(),+ source_run_id: null,+})++describe('visualReviewRunSceneLogic', () => {+ let logic: ReturnType<typeof visualReviewRunSceneLogic.build>+ let releaseSlow: () => void = () => {}++ beforeEach(() => {+ useMocks({+ get: {+ [`/api/projects/:team_id/visual_review/runs/${RUN_ID}/`]: [404, {}],+ [`/api/projects/:team_id/visual_review/runs/${RUN_ID}/snapshots/`]: [404, {}],+ [TOLERATED_URL]: async ({ request }) => {+ const identifier = new URL(request.url).searchParams.get('identifier')+ if (identifier === 'other') {+ return [500, {}]+ }+ if (identifier?.startsWith('slow')) {+ await new Promise<void>((resolve) => {+ releaseSlow = resolve+ })+ }+ if (identifier === 'slow-failing') {+ return [500, {}]+ }+ const results = identifier === 'quiet' ? [] : [0, 1, 2].map(toleratedToday)+ return [200, { count: results.length, next: null, previous: null, results }]+ },+ },+ })+ initKeaTests()+ logic = visualReviewRunSceneLogic({ runId: RUN_ID })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ })++ it('drops the previous snapshot tolerations when the next load fails', async () => {+ await expectLogic(logic, () => logic.actions.loadToleratedHashes('flaky'))+ .toDispatchActions(['loadToleratedHashesSuccess'])+ .toMatchValues({ recentTolerations: { manual: 3, agent: 0, auto: 0 } })++ await expectLogic(logic, () => logic.actions.loadToleratedHashes('other'))+ .toDispatchActions(['loadToleratedHashesFailure'])+ .toMatchValues({ recentTolerations: { manual: 0, agent: 0, auto: 0 } })+ })++ it.each([+ { slow: 'slow', fast: 'quiet', manual: 0 },+ { slow: 'slow-failing', fast: 'flaky', manual: 3 },+ ])('ignores a $slow response that lands after $fast', async ({ slow, fast, manual }) => {+ logic.actions.loadToleratedHashes(slow)+ await expectLogic(logic, () => logic.actions.loadToleratedHashes(fast))+ .toDispatchActions(['loadToleratedHashesSuccess'])+ .toMatchValues({ recentTolerations: { manual, agent: 0, auto: 0 } })++ releaseSlow()+ await expectLogic(logic).toFinishAllListeners()+ await expectLogic(logic).toMatchValues({ recentTolerations: { manual, agent: 0, auto: 0 } })+ })+})diff --git a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.tsindex 1bc159f94503..abc8f81674f0 100644--- a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts@@ -3,6 +3,7 @@ import { loaders } from 'kea-loaders'import { actionToUrl, urlToAction } from 'kea-router'import posthog from 'posthog-js'+import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { teamLogic } from 'scenes/teamLogic'@@ -28,6 +29,7 @@ import type {SnapshotApi,ToleratedHashEntryApi,} from '../generated/api.schemas'+import { type RecentTolerations, countRecentTolerations } from '../lib/quarantineNudge'import { isReportingOnlyRun } from '../lib/runPredicates'import { visualReviewPreferencesLogic } from './visualReviewPreferencesLogic'@@ -52,6 +54,7 @@ export interface visualReviewRunSceneLogicValues {quarantinedIdentifierSet: Set<string>quarantinedIdentifiers: QuarantinedIdentifierEntryApi[]quarantinedIdentifiersLoading: boolean+ recentTolerations: RecentTolerations | nullrepo: RepoApi | nullrepoFullName: string | nullrepoLoading: boolean@@ -213,6 +216,10 @@ export interface visualReviewRunSceneLogicMeta {selectedSnapshotId: string | null,quarantinedIdentifierSet: Set<string>) => SnapshotApi | null+ recentTolerations: (+ toleratedHashes: ToleratedHashEntryApi[],+ toleratedHashesLoading: boolean+ ) => RecentTolerations | nullchangedSnapshots: (snapshots: SnapshotApi[]) => SnapshotApi[]sortedChangedSnapshots: (changedSnapshots: SnapshotApi[]) => SnapshotApi[]hasChanges: (changedSnapshots: SnapshotApi[]) => boolean@@ -273,6 +280,15 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([toggleQuarantinedThumbnails: true,}),reducers({+ // kea-loaders keeps the last success when a load fails, which would let the+ // previous snapshot's tolerations drive the quarantine nudge. Clearing at the+ // start, not on failure, also keeps an overtaken failure from wiping newer data.+ toleratedHashes: [+ [] as ToleratedHashEntryApi[],+ {+ loadToleratedHashes: () => [],+ },+ ],selectedSnapshotId: [null as string | null,{@@ -356,12 +372,14 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([toleratedHashes: [[] as ToleratedHashEntryApi[],{- loadToleratedHashes: async (identifier: string) => {+ loadToleratedHashes: async (identifier: string, breakpoint) => {const response = await visualReviewRunsToleratedHashesList(String(values.currentProjectId),props.runId,{ identifier })+ // Drop a response that a newer selection overtook, so it can't land last.+ breakpoint()return response.results},},@@ -400,6 +418,12 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([return changedNotQuarantined[0] || changed[0] || snapshots[0] || null},],+ // Null while loading, so the list of a previous snapshot never drives the quarantine nudge.+ recentTolerations: [+ (s) => [s.toleratedHashes, s.toleratedHashesLoading],+ (toleratedHashes: ToleratedHashEntryApi[], toleratedHashesLoading: boolean): RecentTolerations | null =>+ toleratedHashesLoading ? null : countRecentTolerations(toleratedHashes, dayjs()),+ ],changedSnapshots: [(s) => [s.snapshots],(snapshots: SnapshotApi[]): SnapshotApi[] => snapshots.filter((s) => s.result !== 'unchanged'),diff --git a/products/visual_review/package.json b/products/visual_review/package.jsonindex 08e2be18b972..0622be82d0dc 100644--- a/products/visual_review/package.json+++ b/products/visual_review/package.json@@ -21,6 +21,8 @@"@posthog/icons": "catalog:","@posthog/react": "*","@storybook/react": "catalog:",+ "@testing-library/dom": "*",+ "@testing-library/user-event": "*","@types/react": "*","react": "*"}