: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
fix(visual-review): improve diff metrics UX and quarantine per theme (#57779)
Julian Bez2b326b83b61c
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex 73ef7e162288..4fcc9fd3b525 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -157,7 +157,7 @@ class ClusterSummary:"""Spatial clustering of differing pixels for a snapshot.`total` is the count before any per-snapshot cap (so the FE can show- "+N more" or pick a categorical label like 'Layout shift' for highly+ "+N more" or pick a categorical label like 'Perceptible change' for highlyscattered diffs even when only the top-N items are shipped).`truncated` is True when `len(items) < total`."""@@ -326,7 +326,7 @@ class SnapshotHistoryEntry:review_state: str = ""current_artifact: Artifact | None = None# Diff classification — see ChangeKind enum. Lets the history view- # render categorical chips ('Layout shift' / 'Size changed') instead+ # render categorical chips ('Perceptible change' / 'Size changed') instead# of conflating SSIM dissimilarity with pixel diff %. `cluster_summary`# deliberately omitted here — bbox overlays don't apply to a# list-of-history-rows view; load the full snapshot for those.diff --git a/products/visual_review/backend/facade/enums.py b/products/visual_review/backend/facade/enums.pyindex 22d9e771129d..907e8e127f49 100644--- a/products/visual_review/backend/facade/enums.py+++ b/products/visual_review/backend/facade/enums.py@@ -74,8 +74,8 @@ class ChangeKind(StrEnum):Set when a snapshot's `result` is CHANGED. The two-tier classifierdistinguishes a pixel-level diff (lots of pixels differ) from a- structural shift caught by SSIM (few pixels but a measurable layout- change). Empty for snapshots that haven't been diffed yet (legacy data).+ structural/perceptual change caught by SSIM (few pixels but a measurable+ perceptual difference). Empty for snapshots that haven't been diffed yet (legacy data).Size mismatch is *not* a kind here — a snapshot can have a differentviewport AND a content change. The flag lives in `diff_metadata`@@ -83,7 +83,7 @@ class ChangeKind(StrEnum):"""PIXEL = "pixel" # Pixel diff above threshold — a chunk of pixels visibly changed- STRUCTURAL = "structural" # SSIM caught a layout/structural shift; pixel diff was below threshold+ STRUCTURAL = "structural" # SSIM caught a perceptual change; pixel diff was below thresholdclass ActorType(StrEnum):diff --git a/products/visual_review/frontend/components/SnapshotChangeBadge.tsx b/products/visual_review/frontend/components/SnapshotChangeBadge.tsxindex 56a043538438..88a3d39ea345 100644--- a/products/visual_review/frontend/components/SnapshotChangeBadge.tsx+++ b/products/visual_review/frontend/components/SnapshotChangeBadge.tsx@@ -22,6 +22,9 @@ const PCT_DISPLAY_FLOOR = 0.05const PCT_WARNING_THRESHOLD = 5function formatPct(value: number): string {+ if (value > 0 && value < PCT_DISPLAY_FLOOR) {+ return '<0.1%'+ }if (value < 1) {return `${value.toFixed(1)}%`}@@ -73,11 +76,10 @@ type ChangeBadgeProps = {/*** Categorical chip describing the *kind* of change in a snapshot.*- * The diff pipeline classifies into one of: `pixel` (a chunk of pixels- * visibly differ), `structural` (SSIM caught a layout shift while pixel- * diff was below threshold). Size-mismatch is *not* a kind — it composes- * with whichever kind the classifier picked, so when set it renders as- * an additional chip next to the main one.+ * `pixel` shows a percentage pill. `structural` shows the pixel diff %+ * alongside a "Perceptible change" label — the % is real but low, and+ * the label explains why it's flagged. Both tiers use the same metric+ * (pixel diff %) so the overview can average across them.** Returns null when there's nothing to show (no diff, no size mismatch,* or pre-migration legacy row with no kind and no percentage).@@ -95,18 +97,17 @@ export function SnapshotChangeBadge({ snapshot, size = 'default' }: ChangeBadgePlet kindChip: JSX.Element | null = nullif (kind === 'structural') {- const ssimText =- snapshot.ssim_score != null- ? `SSIM ${snapshot.ssim_score.toFixed(3)} — structurally different despite few pixels changing.`- : 'Structural shift caught by SSIM despite few pixels changing.'+ const hasPct = pct != null+ const tooltip = hasPct+ ? `${pct.toFixed(2)}% of pixels differ, but the change is perceptually significant. Structural similarity analysis confirmed this is a real visual change.`+ : 'Few pixels differ, but the change is perceptually significant. Structural similarity analysis confirmed this is a real visual change.'kindChip = (- <Tooltip- title={`Layout shift. ${ssimText} Pixel-diff percentage isn't shown because it's below the classifier threshold and would mislead.`}- >+ <Tooltip title={tooltip}><span- className={`shrink-0 inline-flex items-center bg-primary-highlight font-medium text-primary leading-none ${radiusClass} ${sizeClass}`}+ className={`shrink-0 inline-flex items-center gap-1 bg-primary-highlight font-medium text-primary leading-none ${radiusClass} ${sizeClass}`}>- {isCompact ? 'Shift' : 'Layout shift'}+ {hasPct && <span className="font-mono tabular-nums">{formatPct(pct)}</span>}+ {isCompact ? 'Perceptible' : 'Perceptible change'}</span></Tooltip>)@@ -121,7 +122,8 @@ export function SnapshotChangeBadge({ snapshot, size = 'default' }: ChangeBadgePtooltipBits.push(`${t} ${t === 1 ? 'region' : 'regions'} affected`)}if (snapshot.ssim_score != null) {- tooltipBits.push(`SSIM ${snapshot.ssim_score.toFixed(3)}`)+ const ssimClamped = Math.max(0, Math.min(1, snapshot.ssim_score))+ tooltipBits.push(`${((1 - ssimClamped) * 100).toFixed(1)}% perceptual diff`)}const tooltip = tooltipBits.length ? `${pct.toFixed(2)}% pixel diff. ${tooltipBits.join(' · ')}.` : nullconst chip = (diff --git a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx b/products/visual_review/frontend/components/SnapshotDiffViewer.tsxindex f202f3a2e866..75a1ccc024e4 100644--- a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx+++ b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx@@ -242,7 +242,7 @@ export function SnapshotDiffViewer({</div>{/* Right sidebar */}- <div className="w-52 shrink-0 border-l pl-4 space-y-4">+ <div className="w-[250px] shrink-0 border-l pl-4 space-y-4">{/* === Diff minimap === */}{snapshot.diff_artifact?.download_url && (<DiffMinimapdiff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsxindex 8f8416621183..2b4d8cb4691e 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx@@ -93,13 +93,13 @@ function SnapshotThumbnail({</span></>)}- <div className="w-[104px] h-[72px] rounded-sm overflow-hidden bg-bg-3000 relative">+ <div className="w-[125px] h-[86px] rounded-sm overflow-hidden bg-bg-3000 relative">{imgSrc ? (<imgsrc={imgSrc}alt=""- width={104}- height={72}+ width={125}+ height={86}loading="lazy"decoding="async"className={`w-full h-full object-contain ${isQuarantined ? 'grayscale opacity-40' : ''}`}@@ -116,7 +116,7 @@ function SnapshotThumbnail({</span>)}</div>- <div className="flex items-center gap-1 max-w-[108px] w-full">+ <div className="flex items-center gap-1 max-w-[130px] w-full">{hasDiff ? (<SnapshotChangeBadge snapshot={snapshot} size="small" />) : (diff --git a/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx b/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsxindex 81928289992b..849b1e31b87f 100644--- a/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx@@ -182,12 +182,14 @@ function HistoryRow({function QuarantineSection({identifier,+ label,quarantineEntry,isQuarantined,onQuarantine,onUnquarantine,}: {identifier: string+ label?: string | nullquarantineEntry: QuarantinedIdentifierEntryApi | nullisQuarantined: booleanonQuarantine: (reason: string, identifiers: string[], expiresAt: string | null) => void@@ -197,10 +199,10 @@ function QuarantineSection({const expires = quarantineEntry.expires_at ? new Date(quarantineEntry.expires_at) : nullconst openConfirmation = (): void => {LemonDialog.open({- title: 'Unquarantine this identifier?',+ title: `Unquarantine ${label ? `(${label})` : 'this identifier'}?`,description:'This identifier will be gated on again in future runs. ' +- 'Branches that haven’t merged the fix may get blocked.',+ "Branches that haven't merged the fix may get blocked.",primaryButton: {children: 'Unquarantine',status: 'danger',@@ -220,7 +222,7 @@ function QuarantineSection({}}><div className="text-sm flex flex-wrap items-center gap-x-2 gap-y-1">- <span className="font-semibold">Quarantined</span>+ <span className="font-semibold">Quarantined{label && ` (${label})`}</span><span>— {quarantineEntry.reason || 'no reason given'}</span>{expires && (<>@@ -239,8 +241,12 @@ function QuarantineSection({)}return (- <div className="flex justify-end">- <QuarantineAction identifier={identifier} onQuarantine={onQuarantine} />+ <div className="flex items-center justify-end">+ <QuarantineAction+ identifier={identifier}+ onQuarantine={onQuarantine}+ triggerLabel={label ? `Quarantine (${label})` : undefined}+ /></div>)}@@ -262,20 +268,25 @@ export function VisualReviewSnapshotHistoryScene(): JSX.Element {historyLoading,identifier,pairedHistory,+ primaryTheme,+ siblingIdentifier,runType,repoId,quarantineEntry,quarantineEntryLoading,- } = useValues(visualReviewSnapshotHistorySceneLogic)- const { quarantineIdentifier, unquarantineIdentifier } = useActions(visualReviewSnapshotHistorySceneLogic)+ siblingQuarantineEntry,+ siblingQuarantineEntryLoading,+ } = useValues(visualReviewSnapshotHistorySceneLogic) as any+ const { quarantineIdentifier, unquarantineIdentifier, unquarantineSibling } = useActions(+ visualReviewSnapshotHistorySceneLogic+ ) as anyconst repoFullName = repo?.repo_full_name ?? null- // history is already deduped to one row per distinct baseline (newest first),- // so the tail is the first ever capture and the length is the number of- // distinct baselines this identifier has had.const firstSeen = history.length > 0 ? history[history.length - 1].created_at : nullconst baselineUpdates = Math.max(0, history.length - 1)const isQuarantined = !!quarantineEntry+ const isSiblingQuarantined = !!siblingQuarantineEntry+ const hasThemePair = primaryTheme !== null && siblingIdentifier !== nullreturn (<SceneContent>@@ -315,17 +326,39 @@ export function VisualReviewSnapshotHistoryScene(): JSX.Element {)}</div>- {/* Quarantine state for this identifier — banner when active,- * trigger button when not. Mirrors the run-scene UX so users- * can act on flake state from either surface. */}- {!quarantineEntryLoading && (- <QuarantineSection- identifier={identifier}- quarantineEntry={quarantineEntry}- isQuarantined={isQuarantined}- onQuarantine={quarantineIdentifier}- onUnquarantine={unquarantineIdentifier}- />+ {hasThemePair ? (+ <div className="grid grid-cols-2 gap-2">+ {!quarantineEntryLoading && (+ <QuarantineSection+ identifier={identifier}+ label={primaryTheme}+ quarantineEntry={quarantineEntry}+ isQuarantined={isQuarantined}+ onQuarantine={quarantineIdentifier}+ onUnquarantine={unquarantineIdentifier}+ />+ )}+ {!siblingQuarantineEntryLoading && (+ <QuarantineSection+ identifier={siblingIdentifier}+ label={primaryTheme === 'light' ? 'dark' : 'light'}+ quarantineEntry={siblingQuarantineEntry}+ isQuarantined={isSiblingQuarantined}+ onQuarantine={quarantineIdentifier}+ onUnquarantine={unquarantineSibling}+ />+ )}+ </div>+ ) : (+ !quarantineEntryLoading && (+ <QuarantineSection+ identifier={identifier}+ quarantineEntry={quarantineEntry}+ isQuarantined={isQuarantined}+ onQuarantine={quarantineIdentifier}+ onUnquarantine={unquarantineIdentifier}+ />+ ))}{historyLoading || repoLoading ? (diff --git a/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.tsindex 8eddac33490a..5a3a809138d5 100644--- a/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts@@ -58,6 +58,7 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHisexpiresAt,}),unquarantineIdentifier: true,+ unquarantineSibling: true,}),loaders(({ props, values }) => ({repo: [@@ -103,10 +104,6 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis},},],- // Active quarantine entry for this (identifier, run_type), or- // null when none. The endpoint returns full history when an- // identifier filter is applied; we pick the still-active one- // (no expiry, or expiry in the future).quarantineEntry: [null as QuarantinedIdentifierEntryApi | null,{@@ -126,6 +123,33 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis},},],+ siblingQuarantineEntry: [+ null as QuarantinedIdentifierEntryApi | null,+ {+ loadSiblingQuarantineEntry: async () => {+ const { theme } = detectTheme(props.identifier)+ if (!theme) {+ return null+ }+ const sibling = values.siblingIdentifier+ if (!sibling) {+ return null+ }+ const response = await visualReviewReposQuarantineList(+ String(values.currentProjectId),+ props.repoId,+ { identifier: sibling, run_type: props.runType }+ )+ const now = Date.now()+ return (+ response.results.find(+ (q: QuarantinedIdentifierEntryApi) =>+ !q.expires_at || new Date(q.expires_at).getTime() > now+ ) ?? null+ )+ },+ },+ ],})),selectors({identifier: [() => [(_, p) => p.identifier], (identifier: string): string => identifier],@@ -135,6 +159,16 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis() => [(_, p) => p.identifier],(identifier: string): 'light' | 'dark' | null => detectTheme(identifier).theme,],+ siblingIdentifier: [+ () => [(_, p) => p.identifier],+ (identifier: string): string | null => {+ const { stem, theme } = detectTheme(identifier)+ if (!theme) {+ return null+ }+ return `${stem}--${theme === 'light' ? 'dark' : 'light'}`+ },+ ],// Pair entries by run_id so a single timeline row shows both themes.pairedHistory: [(s) => [s.history, s.partnerHistory, s.primaryTheme],@@ -187,6 +221,7 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHisconst count = identifiers.lengthlemonToast.success(`${count} identifier${count > 1 ? 's' : ''} quarantined`)actions.loadQuarantineEntry()+ actions.loadSiblingQuarantineEntry()} catch (e: any) {lemonToast.error(e?.detail || e?.message || 'Failed to quarantine')}@@ -205,11 +240,30 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHislemonToast.error(e?.detail || e?.message || 'Failed to unquarantine')}},+ unquarantineSibling: async () => {+ const sibling = values.siblingIdentifier+ if (!sibling) {+ return+ }+ try {+ await visualReviewReposQuarantineExpireCreate(+ String(values.currentProjectId),+ props.repoId,+ props.runType,+ { identifier: sibling, reason: '' }+ )+ lemonToast.success('Sibling unquarantined — future runs will gate on it again')+ actions.loadSiblingQuarantineEntry()+ } catch (e: any) {+ lemonToast.error(e?.detail || e?.message || 'Failed to unquarantine sibling')+ }+ },})),afterMount(({ actions }) => {actions.loadRepo()actions.loadHistory()actions.loadPartnerHistory()actions.loadQuarantineEntry()+ actions.loadSiblingQuarantineEntry()}),])