: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): split pixel/structural diff, cluster panel, history-view quarantine (#57624)
Julian Bez89f2857ef562
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex cd54ea193475..f16c6c0307f1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3263,15 +3263,15 @@ snapshots:lemon-ui-visual-image-diff-viewer--changed-snapshot--dark:hash: v1.k794b7964.0f8650ee61bfe5a53ac0cafd544db33ae724e8a470707a3a9cd4848576ecfab8.I1OHmY6oDliifw_Miwe4wCAtWGmgMCmWmZjycUErVrQlemon-ui-visual-image-diff-viewer--changed-snapshot--light:- hash: v1.k794b7964.1edde6def7ddc09fae37740edfc5610b7f8fb1bc49dfccbb732de864b24ab76c.NEpNa4596dWklW6q_mksidX5Fj8oHiCExpD9Smkdn4w+ hash: v1.k794b7964.78a2dc393e6cadbff95e17265942865b9493707226331d451547293548e89e6d.kR_9KW862PEOmcPEo3sD7XuQPbStEU5xUakYPa4Laeclemon-ui-visual-image-diff-viewer--new-snapshot--dark:- hash: v1.k794b7964.d7cf0011eac7312939314dc6d9f2afc84894da71a5680ae456e5af7d663b7aa3.EuOUwGAHE_FCzySQsteEyWqkineGs1ybMeI9ODksECI+ hash: v1.k794b7964.f234d8bba15a289ddcb3f7344727caa2ec9359787701b7a4aed7e9956b2d21cd.8wKBjxsi-RYHaS6deJvY80dmc3qK40nOhl8ln1ZF-dUlemon-ui-visual-image-diff-viewer--new-snapshot--light:- hash: v1.k794b7964.539502d9c12bc218a17557e69dc7ef2960d44bc3db608b65056b2a149dceeaf2.nV3KWY5nmgN6rUg87FGNYtVm0Pyw9xvXsFxiGtU_gFU+ hash: v1.k794b7964.8eaf961359bfd2691a63ba1e0f98bad8da5d1d2f7598ce140a5cc361f656fdea.nVw_NtDUWN8hjco2koeQvjHQ6MPktn54QYMj-_6kzOAlemon-ui-visual-image-diff-viewer--small-image--dark:hash: v1.k794b7964.13781e9369ccfad5542a85edfbd547e4d6d770df8b5e5d0d8ec540e50608d453.RPeQpda22EpHoIa5b4UePdKIimFuTS9NAwcGP9ccfpMlemon-ui-visual-image-diff-viewer--small-image--light:- hash: v1.k794b7964.7b70b3e558ee6423735df0ab00f9c0d1d8ec0d4556483ae8db5edce6b3602fb3.UWi5QxvA5OPlUYmD5ERLCxVUyuFuFaAVDykiWktxv2Q+ hash: v1.k794b7964.ed31587820d0216f2281ec8e610da8cb9fe8cb45f9c13e0280f17771cf84994a.spusB2C8AKwu5Tv0KOr8pkjDxgEZw5jcOlEikYAzKWImcp-apps-actions--list--light:hash: v1.k794b7964.24244bf73bd4914893a2811f39274aaa957ad7792e52f5b2d90c662e8deeaed6.g0Ag3Rdrj7Bb1pHIE8oQsqzY8mkA7yb_vFEe-iDM-b0mcp-apps-actions--multi-step--light:diff --git a/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.tsx b/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.tsxindex c6bd8510e508..5e4517d687ef 100644--- a/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.tsx+++ b/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.tsx@@ -8,6 +8,14 @@ export type VisualDiffResult = 'changed' | 'new' | 'removed' | 'unchanged'export type ComparisonMode = 'sideBySide' | 'blend' | 'split' | 'diff'+/** Bounding box of a connected diff region, in natural image coordinates. */+export interface DiffOverlayBox {+ x: number+ y: number+ width: number+ height: number+}+export interface VisualImageDiffViewerProps {baselineUrl: string | nullcurrentUrl: string | null@@ -20,6 +28,28 @@ export interface VisualImageDiffViewerProps {imageHeight?: numbermode?: ComparisonModeonModeChange?: (mode: ComparisonMode) => void+ /**+ * Bounding boxes drawn over the diff image (and the blend overlay+ * when on `blend` mode). Coords are in the diff image's natural+ * pixel space (which is the *padded* size when baseline and current+ * differed); the overlay scales with the rendered image via SVG+ * viewBox + preserveAspectRatio="none". Empty array == no overlays.+ */+ diffOverlayBoxes?: DiffOverlayBox[]+ /**+ * Natural-pixel dimensions of the bbox coord space — the diff+ * image's dimensions, which equal current/baseline when sizes+ * match and the padded size when they don't. Defaults to+ * `imageWidth`/`imageHeight` for back-compat with callers that+ * never had a size mismatch.+ */+ diffOverlayWidth?: number+ diffOverlayHeight?: number+ /** Highlighted cluster index — emphasized in the overlay (filled, opaque). */+ highlightedOverlayIndex?: number | null+ /** Fires when a user hovers a bbox/number in the overlay. Lets the+ * parent sync a sidebar panel's row highlight to the overlay. */+ onOverlayHover?: (index: number | null) => void}const RESULT_LABELS: Record<VisualDiffResult, string> = {@@ -54,24 +84,58 @@ interface ImagePanelProps {emptyTitle: stringimgClassName?: stringimgStyle?: React.CSSProperties+ /** When set, draw bbox outlines over the image at these natural-coord positions. */+ overlayBoxes?: DiffOverlayBox[]+ overlayWidth?: number+ overlayHeight?: number+ /** Highlighted cluster index — that one box renders emphasized. */+ highlightedOverlayIndex?: number | null+ /** Fires on hover so a parent panel can sync. */+ onOverlayHover?: (index: number | null) => void}-function ImagePanel({ url, label, emptyTitle, imgClassName, imgStyle }: ImagePanelProps): JSX.Element {+function ImagePanel({+ url,+ label,+ emptyTitle,+ imgClassName,+ imgStyle,+ overlayBoxes,+ overlayWidth,+ overlayHeight,+ highlightedOverlayIndex,+ onOverlayHover,+}: ImagePanelProps): JSX.Element {+ const hasOverlay = !!url && !!overlayBoxes && overlayBoxes.length > 0 && !!overlayWidth && !!overlayHeightreturn (<div className="overflow-hidden rounded-lg border bg-bg-light inline-block max-w-full"><div className="px-2 py-1 text-[11px] font-semibold uppercase tracking-wide border-b bg-bg-3000">{label}</div>{url ? (- <img- src={url}- alt={label}- loading="lazy"- decoding="async"- className={cn('h-auto bg-black/5', imgClassName || 'max-w-full')}- // eslint-disable-next-line react/forbid-dom-props- style={imgStyle}- />+ // `block` on the inline-block wrapper kills the implicit+ // baseline-descender gap that nudges the SVG overlay a few+ // pixels below the image's actual bottom edge.+ <div className="relative inline-block max-w-full leading-none">+ <img+ src={url}+ alt={label}+ loading="lazy"+ decoding="async"+ className={cn('block h-auto bg-black/5', imgClassName || 'max-w-full')}+ // eslint-disable-next-line react/forbid-dom-props+ style={imgStyle}+ />+ {hasOverlay && (+ <BboxOverlay+ boxes={overlayBoxes!}+ width={overlayWidth!}+ height={overlayHeight!}+ highlightedIndex={highlightedOverlayIndex ?? null}+ onHover={onOverlayHover}+ />+ )}+ </div>) : (<EmptyImageState title={emptyTitle} />)}@@ -79,6 +143,97 @@ function ImagePanel({ url, label, emptyTitle, imgClassName, imgStyle }: ImagePan)}+interface BboxOverlayProps {+ boxes: DiffOverlayBox[]+ /** Natural pixel coord space the bboxes live in. */+ width: number+ height: number+ /** When non-null, that box is emphasized (filled) and the others fade. */+ highlightedIndex: number | null+ /** Fires on hover so the parent can sync sidebar highlight. */+ onHover?: (index: number | null) => void+}++// Warm orange palette to match the mockup — distinct from the+// blue-tinted "Before/After" labels and the green/red of result tags.+const OVERLAY_STROKE = 'rgb(245, 134, 52)'+const OVERLAY_FILL_DEFAULT = 'rgba(245, 134, 52, 0.10)'+const OVERLAY_FILL_HIGHLIGHT = 'rgba(245, 134, 52, 0.28)'++function BboxOverlay({ boxes, width, height, highlightedIndex, onHover }: BboxOverlayProps): JSX.Element {+ return (+ <>+ <svg+ // viewBox in the bbox coord space + preserveAspectRatio=none+ // stretches the SVG to the rendered image's box. With+ // `vector-effect: non-scaling-stroke` the stroke stays a+ // constant 2px regardless of how the image is scaled. The+ // SVG itself stays pointer-events-none so the rects don't+ // shadow underlying interactions; rects flip to auto so+ // they can fire hover callbacks for sidebar sync.+ className="absolute inset-0 w-full h-full pointer-events-none"+ viewBox={`0 0 ${width} ${height}`}+ preserveAspectRatio="none"+ >+ {boxes.map((b, i) => {+ const isHighlighted = highlightedIndex === i+ const isDimmed = highlightedIndex !== null && !isHighlighted+ return (+ <rect+ key={i}+ x={b.x}+ y={b.y}+ width={b.width}+ height={b.height}+ fill={isHighlighted ? OVERLAY_FILL_HIGHLIGHT : OVERLAY_FILL_DEFAULT}+ stroke={OVERLAY_STROKE}+ strokeWidth={isHighlighted ? 3 : 2}+ strokeDasharray={isHighlighted ? undefined : '4 3'}+ opacity={isDimmed ? 0.4 : 1}+ vectorEffect="non-scaling-stroke"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ pointerEvents: onHover ? 'auto' : 'none',+ cursor: onHover ? 'pointer' : undefined,+ }}+ onMouseEnter={onHover ? () => onHover(i) : undefined}+ onMouseLeave={onHover ? () => onHover(null) : undefined}+ />+ )+ })}+ </svg>+ {boxes.map((b, i) => {+ const leftPct = (b.x / width) * 100+ const topPct = (b.y / height) * 100+ const isHighlighted = highlightedIndex === i+ const isDimmed = highlightedIndex !== null && !isHighlighted+ return (+ <span+ key={`label-${i}`}+ className="absolute flex items-center justify-center rounded-full text-white text-[11px] font-bold tabular-nums shadow-md ring-1 ring-white/70 transition-transform"+ // eslint-disable-next-line react/forbid-dom-props+ style={{+ left: `calc(${leftPct}% - 11px)`,+ top: `calc(${topPct}% - 11px)`,+ width: 22,+ height: 22,+ background: OVERLAY_STROKE,+ opacity: isDimmed ? 0.45 : 1,+ transform: isHighlighted ? 'scale(1.15)' : undefined,+ cursor: onHover ? 'pointer' : undefined,+ pointerEvents: onHover ? 'auto' : 'none',+ }}+ onMouseEnter={onHover ? () => onHover(i) : undefined}+ onMouseLeave={onHover ? () => onHover(null) : undefined}+ >+ {i + 1}+ </span>+ )+ })}+ </>+ )+}+function EmptyImageState({ title }: { title: string }): JSX.Element {return (<div className="flex size-full items-center justify-center bg-bg-light px-4 text-center text-muted-foreground">@@ -112,9 +267,22 @@ export function VisualImageDiffViewer({className,imageWidth,imageHeight,+ diffOverlayBoxes,+ diffOverlayWidth,+ diffOverlayHeight,+ highlightedOverlayIndex,+ onOverlayHover,mode: controlledMode,onModeChange,}: VisualImageDiffViewerProps): JSX.Element {+ // Bbox coords live in the diff image's natural pixel space (= padded+ // size when sizes mismatched). Fall back to image dims for the+ // common matched-size case.+ const overlayCoordWidth = diffOverlayWidth ?? imageWidth+ const overlayCoordHeight = diffOverlayHeight ?? imageHeight+ const hasOverlayBoxes = !!diffOverlayBoxes && diffOverlayBoxes.length > 0+ const [showClusters, setShowClusters] = useState(true)+ const overlayBoxesIfShown = showClusters ? diffOverlayBoxes : undefinedconst supportsComparison = isComparisonResult(result)const hasBothImages = Boolean(baselineUrl && currentUrl)const hasDiffImage = Boolean(diffUrl)@@ -222,12 +390,27 @@ export function VisualImageDiffViewer({if (mode === 'diff') {return (<div className="p-3 flex justify-center">- <ImagePanel url={diffUrl} label="Diff" emptyTitle="No diff image available" />+ <ImagePanel+ url={diffUrl}+ label="Diff"+ emptyTitle="No diff image available"+ overlayBoxes={overlayBoxesIfShown}+ overlayWidth={overlayCoordWidth}+ overlayHeight={overlayCoordHeight}+ highlightedOverlayIndex={highlightedOverlayIndex}+ onOverlayHover={onOverlayHover}+ /></div>)}if (mode === 'sideBySide') {+ // Overlay only on the "After" panel — that's the side users+ // judge against, and bboxes were computed against current.+ // Skip when the bbox coord space doesn't match the rendered+ // image (size-mismatch case).+ const overlaySafeOnAfter =+ !!overlayBoxesIfShown && overlayCoordWidth === imageWidth && overlayCoordHeight === imageHeightreturn (<div className="flex flex-col gap-3 p-3 lg:flex-row lg:justify-center lg:items-start"><ImagePanel@@ -243,6 +426,11 @@ export function VisualImageDiffViewer({emptyTitle="After snapshot missing"imgClassName={pixelatedClass}imgStyle={pixelatedStyle}+ overlayBoxes={overlaySafeOnAfter ? overlayBoxesIfShown : undefined}+ overlayWidth={overlayCoordWidth}+ overlayHeight={overlayCoordHeight}+ highlightedOverlayIndex={highlightedOverlayIndex}+ onOverlayHover={onOverlayHover}/></div>)@@ -333,6 +521,29 @@ export function VisualImageDiffViewer({/>)}+ {/* Cluster bbox overlays — drawn on top of the+ * blend stack so users can read where the change+ * regions are without leaving blend mode. Only+ * meaningful when the bbox coord space matches+ * the underlying image (mismatch case has bboxes+ * in padded coords that don't align with either+ * baseline or current). */}+ {(mode === 'blend' || mode === 'split') &&+ !!overlayBoxesIfShown &&+ overlayBoxesIfShown.length > 0 &&+ !!overlayCoordWidth &&+ !!overlayCoordHeight &&+ overlayCoordWidth === imageWidth &&+ overlayCoordHeight === imageHeight && (+ <BboxOverlay+ boxes={overlayBoxesIfShown}+ width={overlayCoordWidth}+ height={overlayCoordHeight}+ highlightedIndex={highlightedOverlayIndex ?? null}+ onHover={onOverlayHover}+ />+ )}+{/* Split drag handle — inside image area */}{!flicker && mode === 'split' && hasBothImages && (<button@@ -364,13 +575,36 @@ export function VisualImageDiffViewer({<div className="flex items-center justify-end px-2 py-1 border-b bg-bg-3000 text-[11px] font-semibold uppercase tracking-wide"><span>After</span></div>- <img- src={activeOverlayUrl}- alt="After snapshot"- className="w-full h-auto bg-black/5 block"- // eslint-disable-next-line react/forbid-dom-props- style={isSmallImage ? { imageRendering: 'pixelated' as const } : undefined}- />+ <div className="relative">+ <img+ src={activeOverlayUrl}+ alt="After snapshot"+ className="w-full h-auto bg-black/5 block"+ // eslint-disable-next-line react/forbid-dom-props+ style={isSmallImage ? { imageRendering: 'pixelated' as const } : undefined}+ />+ {/* Second copy of the bbox overlay inside the+ * clipped After half so the boxes stay visible+ * regardless of where the user drags the split.+ * Forwards onHover so hovering a chip on the+ * After side still syncs with the sidebar+ * panel (without it the After-side bboxes were+ * silently non-interactive). */}+ {!!overlayBoxesIfShown &&+ overlayBoxesIfShown.length > 0 &&+ !!overlayCoordWidth &&+ !!overlayCoordHeight &&+ overlayCoordWidth === imageWidth &&+ overlayCoordHeight === imageHeight && (+ <BboxOverlay+ boxes={overlayBoxesIfShown}+ width={overlayCoordWidth}+ height={overlayCoordHeight}+ highlightedIndex={highlightedOverlayIndex ?? null}+ onHover={onOverlayHover}+ />+ )}+ </div></div>)}@@ -424,6 +658,15 @@ export function VisualImageDiffViewer({<div className="flex flex-wrap items-center gap-2"><LemonTag type={RESULT_TAG_TYPES[result]}>{RESULT_LABELS[result]}</LemonTag>{diffLabel && <LemonTag type="muted">{diffLabel}</LemonTag>}+ {hasOverlayBoxes && (+ <LemonSwitch+ checked={showClusters}+ onChange={setShowClusters}+ size="xsmall"+ label="Clusters"+ bordered+ />+ )}{isSmallImage && (<LemonTag type="highlight" className="font-bold">Enlarged 2x for reviewdiff --git a/products/visual_review/backend/diff.py b/products/visual_review/backend/diff.pyindex b2f970b9c703..9ce12a347d36 100644--- a/products/visual_review/backend/diff.py+++ b/products/visual_review/backend/diff.py@@ -1,29 +1,60 @@"""Image comparison using pixelhog (Rust-accelerated).-Single-pass: pixelmatch diff, SSIM, and optional thumbnail in one decode.+Single decode via pixelhog.Comparison; reuses the decoded buffers across+diff_count, ssim, diff_image, thumbnail, and clusters without paying for+re-decode."""from dataclasses import dataclassfrom blake3 import blake3-from pixelhog import compare as pixelhog_compare+from pixelhog import Comparison++from .diff_metadata import ClusterSummary, DiffCluster++# Aligned-bbox merge tunables passed through to pixelhog's clusters().+# Catches the "list shifted vertically" pattern where every row of a+# list becomes its own cluster despite being a single semantic change.+# Validated against ~20k real master snapshot diffs: 62% collapse to a+# single regional cluster, mean drops 8.33 -> 1.79 clusters.+CLUSTER_MERGE_GAP_PX = 60+CLUSTER_MERGE_OVERLAP_RATIO = 0.5THUMB_WIDTH = 200THUMB_HEIGHT = 140+# Clustering parameters tuned for screenshot diffs. See pixelhog PR6_REVIEW+# for the rationale: dilation merges glyph fragments into region-level+# clusters; min_pixels + min_side filter sub-character noise; max_clusters+# caps at the rough UI legibility ceiling for bbox overlays. `total` on the+# stored summary preserves the true count when the cap kicks in.+#+# Dilation tuning: 8 closes ~16px gaps, which is the common spacing+# between text rows in a UI list (line height ~20px + ~13px gap). At+# dilation=4 a list-shift diff exploded into one cluster per text row+# plus one per separator; bumping to 8 collapses those into a single+# regional cluster covering the list area, which is what humans+# actually mean when they say "the list shifted".+CLUSTER_MIN_PIXELS = 16+CLUSTER_MIN_SIDE = 4+CLUSTER_DILATION = 8+CLUSTER_MAX = 20+@dataclassclass CompareResult:diff_image: bytes | Nonediff_hash: str- diff_percentage: float # 0.0 to 100.0+ diff_percentage: float # 0.0 to 100.0 — fraction of pixels that differdiff_pixel_count: int- ssim_score: float+ ssim_score: float # 0.0 to 1.0 — 1.0 = identical, lower = more differentwidth: intheight: intthumbnail: bytes | Nonethumbnail_hash: str+ size_mismatch: bool # baseline and current have different dimensions+ cluster_summary: ClusterSummary | None # None when not computed (size mismatch / no thumbnail-only mode)def compare_images(@@ -31,28 +62,55 @@ def compare_images(current_bytes: bytes,threshold: float = 0.1,with_thumbnail: bool = True,+ with_clusters: bool = True,) -> CompareResult:- """- Compare two PNG images: pixelmatch diff, SSIM, and optional thumbnail.+ """Compare two PNG images: pixelmatch + SSIM + optional thumbnail + clusters.- Single Rust decode pass via pixelhog.compare().+ One decode of each PNG; subsequent ops reuse the decoded RGBA buffers.+ When sizes differ, pixelhog pads to the largest dimensions and runs+ every metric against the padded buffers — including clusters. The+ padded region surfaces as a cluster of its own, which is the right+ answer ("here's the new content area") rather than something to hide."""- diff_pixel_count, ssim_score, width, height, diff_image, thumbnail = pixelhog_compare(- baseline_bytes,- current_bytes,- threshold=threshold,- alpha=0.1,- return_diff=True,- thumbnail_width=THUMB_WIDTH if with_thumbnail else None,- thumbnail_height=THUMB_HEIGHT if with_thumbnail else None,- )+ cmp = Comparison(baseline_bytes, current_bytes)++ diff_pixel_count = cmp.diff_count(threshold=threshold)+ ssim_score = cmp.ssim()+ diff_image = cmp.diff_image(threshold=threshold, alpha=0.1)+ thumbnail = cmp.current_thumbnail(width=THUMB_WIDTH, height=THUMB_HEIGHT) if with_thumbnail else None+ width = cmp.width+ height = cmp.heighttotal_pixels = width * heightdiff_percentage = (diff_pixel_count / total_pixels * 100) if total_pixels > 0 else 0.0diff_hash = blake3(diff_image).hexdigest() if diff_image else ""thumbnail_hash = blake3(thumbnail).hexdigest() if thumbnail else ""+ cluster_summary: ClusterSummary | None = None+ if with_clusters and diff_pixel_count > 0:+ clusters_result = cmp.clusters(+ threshold=threshold,+ min_pixels=CLUSTER_MIN_PIXELS,+ min_side=CLUSTER_MIN_SIDE,+ dilation=CLUSTER_DILATION,+ max_clusters=CLUSTER_MAX,+ merge_gap=CLUSTER_MERGE_GAP_PX,+ merge_overlap=CLUSTER_MERGE_OVERLAP_RATIO,+ )+ cluster_summary = ClusterSummary(+ items=[+ DiffCluster(+ bbox=(c.bbox.x, c.bbox.y, c.bbox.width, c.bbox.height),+ px=c.pixel_count,+ centroid=c.centroid,+ )+ for c in clusters_result.clusters+ ],+ total=clusters_result.total_clusters,+ truncated=clusters_result.truncated,+ )+return CompareResult(diff_image=diff_image,diff_hash=diff_hash,@@ -63,4 +121,6 @@ def compare_images(height=height,thumbnail=thumbnail,thumbnail_hash=thumbnail_hash,+ size_mismatch=cmp.size_mismatch,+ cluster_summary=cluster_summary,)diff --git a/products/visual_review/backend/diff_metadata.py b/products/visual_review/backend/diff_metadata.pynew file mode 100644index 000000000000..3ae77af20e1f--- /dev/null+++ b/products/visual_review/backend/diff_metadata.py@@ -0,0 +1,58 @@+"""Schema for the system-computed `diff_metadata` JSON column on RunSnapshot.++This file is the single source of truth for what the diff pipeline can+write into that column. Storage is JSONB so the DB itself enforces nothing;+correctness comes from routing every write through `DiffMetadata.model_dump`+and every read through `DiffMetadata.model_validate`. Adding a new key+later means adding a field with a default — old rows still validate, new+rows populate it.++Kept separate from `facade/contracts.py` (which is dataclass-based, public+API contracts) because this is internal storage shape, not a public DTO.+"""++from __future__ import annotations++from pydantic import BaseModel, ConfigDict, Field+++class DiffCluster(BaseModel):+ """One connected region of differing pixels in a snapshot diff."""++ model_config = ConfigDict(frozen=True)++ bbox: tuple[int, int, int, int] = Field(description="(x, y, width, height) in image coordinates")+ px: int = Field(ge=0, description="Total differing pixels in this cluster")+ centroid: tuple[float, float] = Field(description="(x, y) center of mass in image coordinates")+++class ClusterSummary(BaseModel):+ """Spatial clustering of differing pixels for a single diff.++ `total` counts all clusters that passed the lib's lower-bound filters+ (pixel count + bbox dimensions + dilation merge); `items` may be a+ truncated top-N by pixel_count when `truncated` is True. Frontend uses+ `total` to label scattered diffs differently from localized ones even+ when only the top items are shipped.+ """++ model_config = ConfigDict(frozen=True)++ items: list[DiffCluster]+ total: int = Field(ge=0)+ truncated: bool+++class DiffMetadata(BaseModel):+ """Container for everything the diff pipeline writes into the+ `diff_metadata` JSONB column.++ Empty (`{}`) for snapshots that haven't been diffed yet, or for+ snapshots where the pipeline produced nothing storable here. New keys+ land as new fields with defaults so old rows still validate.+ """++ model_config = ConfigDict(extra="ignore") # forward-compat: ignore unknown keys on read++ cluster_summary: ClusterSummary | None = None+ size_mismatch: bool = False # baseline and current had different dimensions; pixelhog padded to largestdiff --git a/products/visual_review/backend/diffing.py b/products/visual_review/backend/diffing.pyindex e32c1221e4de..1fa393de40cb 100644--- a/products/visual_review/backend/diffing.py+++ b/products/visual_review/backend/diffing.py@@ -14,7 +14,8 @@ from blake3 import blake3from pixelhog import thumbnail as pixelhog_thumbnailfrom .diff import THUMB_HEIGHT, THUMB_WIDTH, CompareResult, compare_images-from .facade.enums import ClassificationReason, SnapshotResult, ToleratedReason+from .diff_metadata import DiffMetadata+from .facade.enums import ChangeKind, ClassificationReason, SnapshotResult, ToleratedReasonfrom .models import RunSnapshot, ToleratedHashlogger = structlog.get_logger(__name__)@@ -32,6 +33,25 @@ PIXEL_DIFF_THRESHOLD_PERCENT = 2.5SSIM_DISSIMILARITY_THRESHOLD = 0.01 # 1% structural difference+def classify_compare_result(result: CompareResult) -> ChangeKind | None:+ """Classify a compare result into a ChangeKind, or None for unchanged.++ Pure function — no DB, no side effects — so tests can drive every+ classification path without spinning up a snapshot row. The same logic+ drives `_diff_snapshot` below; keeping it here means the production+ branch and the tests can't drift.++ Size mismatch is *not* a kind — pixelhog pads to the largest dims and+ we still get a real pixel/SSIM answer over that padded image. The fact+ that sizes differed is recorded separately on `DiffMetadata`.+ """+ if result.diff_percentage >= PIXEL_DIFF_THRESHOLD_PERCENT:+ return ChangeKind.PIXEL+ if (1.0 - result.ssim_score) >= SSIM_DISSIMILARITY_THRESHOLD:+ return ChangeKind.STRUCTURAL+ return None++def _store_thumbnail(snapshot: RunSnapshot, result: CompareResult) -> None:"""Store the thumbnail artifact and link it to the current artifact."""from . import logic@@ -55,8 +75,12 @@ def _store_thumbnail(snapshot: RunSnapshot, result: CompareResult) -> None:artifact.save(update_fields=["thumbnail"])-def _store_diff(snapshot: RunSnapshot, result: CompareResult) -> None:- """Upload diff artifact and update snapshot metrics."""+def _store_diff(+ snapshot: RunSnapshot,+ result: CompareResult,+ change_kind: ChangeKind,+) -> None:+ """Upload diff artifact and update snapshot metrics + classification."""from . import logicif not result.diff_image:@@ -71,11 +95,19 @@ def _store_diff(snapshot: RunSnapshot, result: CompareResult) -> None:team_id=snapshot.team_id,)+ diff_metadata = DiffMetadata(+ cluster_summary=result.cluster_summary,+ size_mismatch=result.size_mismatch,+ )+logic.update_snapshot_diff(snapshot_id=snapshot.id,diff_artifact=diff_artifact,diff_percentage=result.diff_percentage,diff_pixel_count=result.diff_pixel_count,+ ssim_score=result.ssim_score,+ change_kind=change_kind,+ diff_metadata=diff_metadata,team_id=snapshot.team_id,)@@ -83,20 +115,30 @@ def _store_diff(snapshot: RunSnapshot, result: CompareResult) -> None:"visual_review.diff_computed",snapshot_id=str(snapshot.id),identifier=snapshot.identifier,+ change_kind=change_kind.value,diff_percentage=result.diff_percentage,diff_pixel_count=result.diff_pixel_count,ssim_score=result.ssim_score,+ size_mismatch=result.size_mismatch,+ cluster_count=result.cluster_summary.total if result.cluster_summary else 0,)def _diff_snapshot(snapshot: RunSnapshot) -> None:- """- Compare snapshot against baseline using single-pass pixelhog.compare().+ """Compare snapshot against baseline; classify and store diff metrics.++ Classification (in priority order):+ 1. Pixel diff above threshold -> CHANGED, kind=pixel+ 2. SSIM dissimilarity above threshold -> CHANGED, kind=structural+ (tall-page dilution safety net)+ 3. Both below -> UNCHANGED (noise), auto-populate tolerance cache.- Classification:- 1. Pixel diff above threshold -> CHANGED- 2. SSIM dissimilarity above threshold -> CHANGED (tall-page dilution)- 3. Both below -> UNCHANGED (noise), auto-populate tolerance cache+ Size mismatch is recorded as `diff_metadata.size_mismatch` and surfaced+ separately in the UI — a snapshot can have a different viewport AND a+ real content change, so we don't conflate the two.++ `diff_percentage` and `ssim_score` are recorded faithfully; the categorical+ kind is what callers use to render. No overwriting one signal with another."""from . import logic@@ -121,37 +163,26 @@ def _diff_snapshot(snapshot: RunSnapshot) -> None:_store_thumbnail(snapshot, result)- if result.diff_percentage >= PIXEL_DIFF_THRESHOLD_PERCENT:- _store_diff(snapshot, result)- return-- ssim_dissimilarity = 1.0 - result.ssim_score-- if ssim_dissimilarity >= SSIM_DISSIMILARITY_THRESHOLD:- result.diff_percentage = round(ssim_dissimilarity * 100, 4)- result.diff_pixel_count = 0- _store_diff(snapshot, result)- logger.info(- "visual_review.diff_caught_by_ssim",- snapshot_id=str(snapshot.id),- identifier=snapshot.identifier,- diff_percentage=result.diff_percentage,- ssim_dissimilarity=round(ssim_dissimilarity, 4),- )+ kind = classify_compare_result(result)+ if kind is not None:+ _store_diff(snapshot, result, kind)return- # Both below threshold — genuine noise, reclassify and cache for future runs+ # Both tiers below threshold — genuine noise, reclassify and cache for future runssnapshot.result = SnapshotResult.UNCHANGEDsnapshot.classification_reason = ClassificationReason.BELOW_THRESHOLDsnapshot.diff_percentage = result.diff_percentagesnapshot.diff_pixel_count = result.diff_pixel_count- snapshot.save(update_fields=["result", "classification_reason", "diff_percentage", "diff_pixel_count"])+ snapshot.ssim_score = result.ssim_score+ snapshot.save(+ update_fields=["result", "classification_reason", "diff_percentage", "diff_pixel_count", "ssim_score"]+ )logger.info("visual_review.diff_below_threshold",snapshot_id=str(snapshot.id),identifier=snapshot.identifier,diff_percentage=result.diff_percentage,- ssim_dissimilarity=round(ssim_dissimilarity, 4),+ ssim_score=result.ssim_score,)# Auto-populate tolerance cache so future runs skip diffing for this hashdiff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex 3bcf1ce512cf..0e9644fe2e6b 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -20,6 +20,7 @@ from uuid import UUIDfrom django.contrib.auth import get_user_modelfrom .. import logic+from ..diff_metadata import DiffMetadatafrom . import contractsfrom .enums import ReviewDecision@@ -55,10 +56,45 @@ def _to_artifact(artifact, repo_id: UUID) -> contracts.Artifact:)+def _parse_diff_metadata(+ diff_metadata_raw: dict | None,+) -> tuple[contracts.ClusterSummary | None, bool]:+ """Translate the compact storage shape into the verbose wire shape.++ Returns `(cluster_summary, size_mismatch)`. The cluster_summary side+ is None for legacy rows and identical-pair rows; size_mismatch+ defaults to False everywhere it isn't explicitly recorded.+ """+ if not diff_metadata_raw:+ return None, False+ parsed = DiffMetadata.model_validate(diff_metadata_raw)+ cluster_summary: contracts.ClusterSummary | None = None+ if parsed.cluster_summary is not None:+ cs = parsed.cluster_summary+ cluster_summary = contracts.ClusterSummary(+ items=[+ contracts.DiffCluster(+ x=c.bbox[0],+ y=c.bbox[1],+ width=c.bbox[2],+ height=c.bbox[3],+ pixel_count=c.px,+ centroid_x=c.centroid[0],+ centroid_y=c.centroid[1],+ )+ for c in cs.items+ ],+ total=cs.total,+ truncated=cs.truncated,+ )+ return cluster_summary, parsed.size_mismatch++def _to_snapshot(snapshot, repo_id: UUID, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = None) -> contracts.Snapshot:reviewed_by = (user_basic_infos or {}).get(snapshot.reviewed_by_id) if snapshot.reviewed_by_id else None+ cluster_summary, size_mismatch = _parse_diff_metadata(snapshot.diff_metadata)return contracts.Snapshot(id=snapshot.id,identifier=snapshot.identifier,@@ -76,6 +112,10 @@ def _to_snapshot(is_quarantined=snapshot.is_quarantined,reviewed_by=reviewed_by,metadata=snapshot.metadata or {},+ ssim_score=snapshot.ssim_score,+ change_kind=snapshot.change_kind or "",+ cluster_summary=cluster_summary,+ size_mismatch=size_mismatch,)@@ -342,6 +382,13 @@ def get_snapshot_history(repo_id: UUID, identifier: str, run_type: str) -> list[diff_percentage=e.diff_percentage,review_state=e.review_state,current_artifact=_to_artifact(e.current_artifact, repo_id) if e.current_artifact else None,+ ssim_score=e.ssim_score,+ change_kind=e.change_kind or "",+ # Read the flag directly instead of round-tripping through the+ # full Pydantic parse — `cluster_summary` isn't on the history+ # entry contract and we'd just be allocating cluster dataclasses+ # to throw away. The default mirrors `DiffMetadata.size_mismatch`.+ size_mismatch=bool((e.diff_metadata or {}).get("size_mismatch", False)),)for e in entries]diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex 48b7954e88c0..73ef7e162288 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -135,6 +135,38 @@ class UserBasicInfo:email: str+@dataclass(frozen=True)+class DiffCluster:+ """One connected region of differing pixels in a snapshot diff.++ Wire shape — verbose key names for frontend consumption. Storage uses+ a compact form (see `diff_metadata.DiffCluster`).+ """++ x: int+ y: int+ width: int+ height: int+ pixel_count: int+ centroid_x: float+ centroid_y: float+++@dataclass(frozen=True)+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+ scattered diffs even when only the top-N items are shipped).+ `truncated` is True when `len(items) < total`.+ """++ items: list[DiffCluster]+ total: int+ truncated: bool++@dataclass(frozen=True)class Snapshot:"""A snapshot with its comparison results."""@@ -157,6 +189,17 @@ class Snapshot:reviewed_by: UserBasicInfo | None = None# Flexible metadata (browser, viewport, is_critical, is_flaky, page_group, etc.)metadata: dict = field(default_factory=dict)+ # Diff classification details — see ChangeKind enum and the diff+ # pipeline. `change_kind` is the categorical signal the UI renders+ # ('pixel' / 'structural'); `ssim_score` and `cluster_summary` are+ # details available alongside. `size_mismatch` flags the case where+ # baseline and current had different dimensions (composes with any+ # change_kind — pixelhog padded the smaller image and ran metrics+ # against the padded buffers).+ ssim_score: float | None = None+ change_kind: str = ""+ cluster_summary: ClusterSummary | None = None+ size_mismatch: bool = False@dataclass(frozen=True)@@ -282,6 +325,14 @@ class SnapshotHistoryEntry:diff_percentage: float | None = Nonereview_state: str = ""current_artifact: Artifact | None = None+ # Diff classification — see ChangeKind enum. Lets the history view+ # render categorical chips ('Layout shift' / '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.+ ssim_score: float | None = None+ change_kind: str = ""+ size_mismatch: bool = False@dataclass(frozen=True)diff --git a/products/visual_review/backend/facade/enums.py b/products/visual_review/backend/facade/enums.pyindex 3cd93a09202c..22d9e771129d 100644--- a/products/visual_review/backend/facade/enums.py+++ b/products/visual_review/backend/facade/enums.py@@ -69,6 +69,23 @@ class ClassificationReason(StrEnum):BELOW_THRESHOLD = "below_threshold" # Diffed this run, below pixel/SSIM threshold+class ChangeKind(StrEnum):+ """What kind of change a CHANGED snapshot represents.++ Set when a snapshot's `result` is CHANGED. The two-tier classifier+ distinguishes 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).++ Size mismatch is *not* a kind here — a snapshot can have a different+ viewport AND a content change. The flag lives in `diff_metadata`+ instead so it composes with whichever kind the classifier picks.+ """++ 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++class ActorType(StrEnum):"""Who performed an action — human user, AI agent, or automated system."""diff --git a/products/visual_review/backend/logic.py b/products/visual_review/backend/logic.pyindex 75cfe792f526..92a64ff2630f 100644--- a/products/visual_review/backend/logic.py+++ b/products/visual_review/backend/logic.py@@ -29,7 +29,16 @@ from posthog.models.integration import GitHubRateLimitErrorfrom .classifier import SnapshotClassifierfrom .db import READER_DB, WRITER_DB-from .facade.enums import ReviewDecision, ReviewState, RunPurpose, RunStatus, SnapshotResult, ToleratedReason+from .diff_metadata import DiffMetadata+from .facade.enums import (+ ChangeKind,+ ReviewDecision,+ ReviewState,+ RunPurpose,+ RunStatus,+ SnapshotResult,+ ToleratedReason,+)from .models import Artifact, QuarantinedIdentifier, Repo, Run, RunSnapshot, ToleratedHashfrom .signing import sign_snapshot_hash, verify_signed_hashfrom .storage import ArtifactStorage@@ -2363,6 +2372,9 @@ def update_snapshot_diff(diff_artifact: Artifact,diff_percentage: float,diff_pixel_count: int,+ ssim_score: float,+ change_kind: ChangeKind,+ diff_metadata: DiffMetadata,team_id: int | None = None,) -> RunSnapshot:qs = RunSnapshot.objects.select_related("run")@@ -2379,7 +2391,22 @@ def update_snapshot_diff(snapshot.diff_artifact = diff_artifactsnapshot.diff_percentage = diff_percentagesnapshot.diff_pixel_count = diff_pixel_count- snapshot.save(update_fields=["diff_artifact", "diff_percentage", "diff_pixel_count"])+ snapshot.ssim_score = ssim_score+ snapshot.change_kind = change_kind.value+ # The Pydantic dump is the only legal write path into this column; reads+ # go through DiffMetadata.model_validate. Storage is JSONB; the schema+ # lives in diff_metadata.py.+ snapshot.diff_metadata = diff_metadata.model_dump(mode="json")+ snapshot.save(+ update_fields=[+ "diff_artifact",+ "diff_percentage",+ "diff_pixel_count",+ "ssim_score",+ "change_kind",+ "diff_metadata",+ ]+ )return snapshotdiff --git a/products/visual_review/backend/migrations/0009_add_ssim_score_and_change_kind.py b/products/visual_review/backend/migrations/0009_add_ssim_score_and_change_kind.pynew file mode 100644index 000000000000..450bb5ab2798--- /dev/null+++ b/products/visual_review/backend/migrations/0009_add_ssim_score_and_change_kind.py@@ -0,0 +1,27 @@+# Generated by Django 5.2.13 on 2026-05-04 14:08++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("visual_review", "0008_add_artifact_thumbnail"),+ ]++ operations = [+ migrations.AddField(+ model_name="runsnapshot",+ name="change_kind",+ field=models.CharField(blank=True, default="", max_length=24),+ ),+ migrations.AddField(+ model_name="runsnapshot",+ name="ssim_score",+ field=models.FloatField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="runsnapshot",+ name="diff_metadata",+ field=models.JSONField(blank=True, default=dict),+ ),+ ]diff --git a/products/visual_review/backend/migrations/0010_backfill_change_kind_and_ssim.py b/products/visual_review/backend/migrations/0010_backfill_change_kind_and_ssim.pynew file mode 100644index 000000000000..66c50f01418c--- /dev/null+++ b/products/visual_review/backend/migrations/0010_backfill_change_kind_and_ssim.py@@ -0,0 +1,74 @@+"""Backfill change_kind and ssim_score on existing RunSnapshot rows.++The diff pipeline previously stored two different signals in `diff_percentage`:+true pixel-diff percent for the pixel tier, and SSIM dissimilarity percent+for the SSIM tier (which also zeroed `diff_pixel_count` as a side-effect).+That zeroed-count is the discriminator we use here to repair the semantics.++After this migration:+- Pixel-tier rows: change_kind='pixel', diff_percentage unchanged.+- SSIM-tier rows: change_kind='structural', ssim_score derived from the+ original dissimilarity, diff_percentage NULLed (we don't have the true+ pixel-diff fraction for these rows).+- UNCHANGED rows are left alone — change_kind only applies when CHANGED.+"""++from django.db import migrations+from django.db.models import F, FloatField, Value+from django.db.models.functions import Cast+++def backfill_change_kind(apps, _schema_editor):+ RunSnapshot = apps.get_model("visual_review", "RunSnapshot")++ # Pixel tier: classifier saw pixel diff above the 2.5% threshold.+ RunSnapshot.objects.filter(+ result="changed",+ diff_pixel_count__gt=0,+ change_kind="",+ ).update(change_kind="pixel")++ # SSIM tier: pixel diff was below threshold but SSIM dissimilarity+ # cleared the 1% bar. The old code overwrote diff_percentage with+ # `dissimilarity * 100` and zeroed diff_pixel_count — both are how we+ # recognize these rows. Recover ssim_score from the stored dissimilarity+ # and null out the now-misleading diff_percentage. Postgres evaluates all+ # SET expressions against the OLD row, so referencing diff_percentage+ # while also nulling it in the same UPDATE is well-defined.+ RunSnapshot.objects.filter(+ result="changed",+ diff_pixel_count=0,+ diff_percentage__gt=0,+ change_kind="",+ ).update(+ ssim_score=Cast(Value(1.0) - F("diff_percentage") / Value(100.0), output_field=FloatField()),+ diff_percentage=None,+ change_kind="structural",+ )+++def reverse(apps, _schema_editor):+ RunSnapshot = apps.get_model("visual_review", "RunSnapshot")++ RunSnapshot.objects.filter(change_kind="pixel").update(change_kind="")++ # Structural rows: rebuild diff_percentage from ssim_score and clear the+ # new fields. Pure SQL again.+ RunSnapshot.objects.filter(+ change_kind="structural",+ ssim_score__isnull=False,+ ).update(+ diff_percentage=Cast((Value(1.0) - F("ssim_score")) * Value(100.0), output_field=FloatField()),+ ssim_score=None,+ change_kind="",+ )+++class Migration(migrations.Migration):+ dependencies = [+ ("visual_review", "0009_add_ssim_score_and_change_kind"),+ ]++ operations = [+ migrations.RunPython(backfill_change_kind, reverse),+ ]diff --git a/products/visual_review/backend/migrations/max_migration.txt b/products/visual_review/backend/migrations/max_migration.txtindex aaef81736eac..5e23994e0365 100644--- a/products/visual_review/backend/migrations/max_migration.txt+++ b/products/visual_review/backend/migrations/max_migration.txt@@ -1 +1 @@-0008_add_artifact_thumbnail+0010_backfill_change_kind_and_ssimdiff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.pyindex c3a318dfddbe..ec2edd465503 100644--- a/products/visual_review/backend/models.py+++ b/products/visual_review/backend/models.py@@ -237,9 +237,30 @@ class RunSnapshot(models.Model):# Frozen at run finalization — reflects quarantine policy at that point in timeis_quarantined = models.BooleanField(default=False)- # Diff metrics+ # Diff metrics. `diff_percentage` always means "fraction of pixels that+ # differ" — the previous behavior where the SSIM tier overwrote this with+ # SSIM dissimilarity is gone (split into `ssim_score` + `change_kind`+ # below). Pre-split rows have been backfilled accordingly: SSIM-tier+ # rows have `diff_percentage = NULL`, `ssim_score` derived from the+ # original dissimilarity, and `change_kind = 'structural'`.diff_percentage = models.FloatField(null=True, blank=True)diff_pixel_count = models.PositiveIntegerField(null=True, blank=True)+ # SSIM score (0.0–1.0). 1.0 = identical, lower = more structurally+ # different. Populated for every diffed snapshot regardless of which+ # tier classified it.+ ssim_score = models.FloatField(null=True, blank=True)+ # Categorical: see ChangeKind enum. Empty for snapshots that haven't+ # been diffed (NEW, REMOVED, exact-match UNCHANGED).+ change_kind = models.CharField(max_length=24, blank=True, default="")+ # System-computed metadata produced by the diff pipeline (not the+ # uploader's `metadata` field above, which is for ingestion-time+ # context like browser/viewport). Storage is JSONB but the Python+ # shape is governed by `DiffMetadata` in `diff_metadata.py` — all+ # writes go through `.model_dump()` and reads through+ # `.model_validate()`. Currently holds `cluster_summary`; future+ # additions like `engine_version` land alongside without a schema+ # migration.+ diff_metadata = models.JSONField(default=dict, blank=True)# Review state — only set on actionable snapshots (CHANGED, NEW, REMOVED).# Empty for unchanged snapshots that don't need review.diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.pyindex 70a90e5ad291..cebd559e1d83 100644--- a/products/visual_review/backend/presentation/serializers.py+++ b/products/visual_review/backend/presentation/serializers.py@@ -17,9 +17,11 @@ from ..facade.contracts import (BaselineEntry,BaselineOverview,BaselineTotals,+ ClusterSummary,CreateRepoInput,CreateRunInput,CreateRunResult,+ DiffCluster,QuarantinedIdentifierEntry,QuarantineInput,RecomputeResult,@@ -60,12 +62,25 @@ class UserBasicInfoSerializer(DataclassSerializer):dataclass = UserBasicInfo+class DiffClusterSerializer(DataclassSerializer):+ class Meta:+ dataclass = DiffCluster+++class ClusterSummarySerializer(DataclassSerializer):+ items = DiffClusterSerializer(many=True)++ class Meta:+ dataclass = ClusterSummary++class SnapshotSerializer(DataclassSerializer):# Explicitly mark artifact fields as nullable for OpenAPI schemacurrent_artifact = ArtifactSerializer(allow_null=True, required=False)baseline_artifact = ArtifactSerializer(allow_null=True, required=False)diff_artifact = ArtifactSerializer(allow_null=True, required=False)reviewed_by = UserBasicInfoSerializer(allow_null=True, required=False)+ cluster_summary = ClusterSummarySerializer(allow_null=True, required=False)class Meta:dataclass = Snapshotdiff --git a/products/visual_review/backend/ssim.py b/products/visual_review/backend/ssim.pydeleted file mode 100644index 8c5c3994b6f0..000000000000--- a/products/visual_review/backend/ssim.py+++ /dev/null@@ -1,28 +0,0 @@-"""-SSIM (Structural Similarity Index) computation for visual review.--Safety net for tall-page dilution: pixelmatch counts differing pixels as a-percentage of total image area, so a real UI change at the bottom of a long-screenshot can fall below the pixel threshold. SSIM evaluates structural-similarity in local windows, catching changes that affect few pixels but-produce a measurable perceptual shift.--Only called when the pixel-based diff classifies a snapshot as below-threshold.--Uses pixelhog (Rust) for fast 11x11 windowed SSIM with reflect padding.-"""--from pixelhog import ssim---def compute_ssim(baseline_bytes: bytes, current_bytes: bytes) -> float:- """- Compute mean SSIM between two PNG images.-- Uses 11x11 uniform windows with reflect padding, matching the standard- used by jest-image-snapshot. Smaller images are padded to the larger- dimensions internally.-- Returns a score from 0.0 (completely different) to 1.0 (identical).- """- return ssim(baseline_bytes, current_bytes)diff --git a/products/visual_review/backend/tests/test_thumbnails.py b/products/visual_review/backend/tests/test_thumbnails.pyindex 426024a8491d..6167ca1b0c50 100644--- a/products/visual_review/backend/tests/test_thumbnails.py+++ b/products/visual_review/backend/tests/test_thumbnails.py@@ -75,6 +75,8 @@ def _make_compare_result(thumbnail: bytes = b"fake-webp") -> CompareResult:height=600,thumbnail=thumbnail,thumbnail_hash="thumb_hash_auto",+ size_mismatch=False,+ cluster_summary=None,)diff --git a/products/visual_review/backend/tests/test_two_tier_diff.py b/products/visual_review/backend/tests/test_two_tier_diff.pyindex 659fbd7e54a3..c6c31bad27e8 100644--- a/products/visual_review/backend/tests/test_two_tier_diff.py+++ b/products/visual_review/backend/tests/test_two_tier_diff.py@@ -2,12 +2,18 @@import io+import pytest+import numpy as npfrom PIL import Image, ImageDrawfrom products.visual_review.backend.diff import compare_images-from products.visual_review.backend.diffing import PIXEL_DIFF_THRESHOLD_PERCENT, SSIM_DISSIMILARITY_THRESHOLD-from products.visual_review.backend.ssim import compute_ssim+from products.visual_review.backend.diffing import (+ PIXEL_DIFF_THRESHOLD_PERCENT,+ SSIM_DISSIMILARITY_THRESHOLD,+ classify_compare_result,+)+from products.visual_review.backend.facade.enums import ChangeKinddef _make_png(width: int, height: int, color: tuple[int, int, int, int]) -> bytes:@@ -49,47 +55,10 @@ def _make_tall_settings_page(width: int = 400, height: int = 3000, extra_elementreturn buf.getvalue()-def _classify(baseline_bytes: bytes, current_bytes: bytes) -> str:- """Run the same two-tier classification logic as _diff_snapshot."""+def _classify(baseline_bytes: bytes, current_bytes: bytes) -> ChangeKind | None:+ """Run the production classifier on a fresh compare result."""result = compare_images(baseline_bytes, current_bytes, with_thumbnail=False)-- if result.diff_percentage >= PIXEL_DIFF_THRESHOLD_PERCENT:- return "changed_by_pixelmatch"-- ssim_dissimilarity = 1.0 - result.ssim_score-- if ssim_dissimilarity >= SSIM_DISSIMILARITY_THRESHOLD:- return "changed_by_ssim"-- return "unchanged"---class TestComputeSSIM:- def test_identical_images_score_one(self):- img = _make_png(100, 100, (200, 100, 50, 255))- assert compute_ssim(img, img) > 0.999-- def test_completely_different_images_low_score(self):- img1 = _make_png(100, 100, (255, 0, 0, 255))- img2 = _make_png(100, 100, (0, 0, 255, 255))- assert compute_ssim(img1, img2) < 0.8-- def test_slight_difference_high_score(self):- img1 = _make_png(100, 100, (100, 100, 100, 255))- img2 = _make_png(100, 100, (105, 100, 100, 255))- assert compute_ssim(img1, img2) > 0.99-- def test_small_images_below_window_size(self):- img1 = _make_png(5, 5, (255, 0, 0, 255))- img2 = _make_png(5, 5, (255, 0, 0, 255))- assert compute_ssim(img1, img2) > 0.999-- def test_different_sizes_pads_to_larger(self):- small = _make_png(50, 50, (200, 200, 200, 255))- large = _make_png(100, 100, (200, 200, 200, 255))- score = compute_ssim(small, large)- # 75% of padded area is black vs gray — significant structural difference- assert 0.0 < score < 1.0+ return classify_compare_result(result)class TestTwoTierClassification:@@ -101,10 +70,23 @@ class TestTwoTierClassification:shift that SSIM catches."""- def test_obvious_change_caught_by_pixelmatch(self):- red = _make_png(100, 100, (255, 0, 0, 255))- blue = _make_png(100, 100, (0, 0, 255, 255))- assert _classify(red, blue) == "changed_by_pixelmatch"+ @pytest.mark.parametrize(+ "baseline_color, current_color, expected_kind",+ [+ pytest.param((255, 0, 0, 255), (0, 0, 255, 255), ChangeKind.PIXEL, id="obvious_pixel_change"),+ pytest.param((100, 100, 100, 255), (100, 100, 100, 255), None, id="identical"),+ pytest.param((100, 100, 100, 255), (105, 100, 100, 255), None, id="subtle_noise"),+ ],+ )+ def test_solid_color_classification(+ self,+ baseline_color: tuple[int, int, int, int],+ current_color: tuple[int, int, int, int],+ expected_kind: ChangeKind | None,+ ):+ baseline = _make_png(100, 100, baseline_color)+ current = _make_png(100, 100, current_color)+ assert _classify(baseline, current) == expected_kinddef test_tall_page_change_caught_by_ssim(self):baseline = _make_tall_settings_page(extra_element=False)@@ -116,13 +98,91 @@ class TestTwoTierClassification:ssim_dissimilarity = 1.0 - result.ssim_scoreassert ssim_dissimilarity > SSIM_DISSIMILARITY_THRESHOLD- assert _classify(baseline, current) == "changed_by_ssim"+ assert _classify(baseline, current) == ChangeKind.STRUCTURAL++ def test_size_mismatch_still_classifies_normally(self):+ # Pixelhog pads to the bigger size and runs metrics over the+ # padded buffers — we still get a real pixel-tier classification+ # (the new content area shows up as differing pixels). The fact+ # that sizes differed is recorded separately on diff_metadata.+ small = _make_png(100, 100, (200, 200, 200, 255))+ large = _make_png(200, 100, (200, 200, 200, 255))+ result = compare_images(small, large, with_thumbnail=False)+ assert result.size_mismatch+ assert _classify(small, large) == ChangeKind.PIXEL++ def test_compare_images_populates_ssim_score_for_every_path(self):+ # ssim_score is now the source of truth for structural similarity —+ # not derived after the fact, not overwritten by the classifier.+ # A pixel-tier diff still has a meaningful SSIM number alongside.+ red = _make_png(100, 100, (255, 0, 0, 255))+ blue = _make_png(100, 100, (0, 0, 255, 255))+ result = compare_images(red, blue, with_thumbnail=False)+ assert 0.0 <= result.ssim_score <= 1.0+ assert result.ssim_score < 0.8 # red vs blue is structurally different- def test_identical_images_classified_unchanged(self):- page = _make_tall_settings_page(extra_element=False)- assert _classify(page, page) == "unchanged"- def test_subtle_noise_classified_unchanged(self):- img1 = _make_png(100, 100, (100, 100, 100, 255))- img2 = _make_png(100, 100, (105, 100, 100, 255))- assert _classify(img1, img2) == "unchanged"+class TestClusterSummary:+ """Cluster output is meaningful for localized diffs only — not for+ full inversions, not for identical pairs.+ """++ def test_localized_change_yields_clusters(self):+ # Same baseline and current except for a small block in the middle.+ base = _make_png(200, 200, (240, 240, 240, 255))+ cur_img = Image.open(io.BytesIO(base))+ ImageDraw.Draw(cur_img).rectangle([90, 90, 110, 110], fill=(255, 0, 0, 255))+ buf = io.BytesIO()+ cur_img.save(buf, format="PNG")++ result = compare_images(base, buf.getvalue(), with_thumbnail=False)+ assert result.cluster_summary is not None+ assert result.cluster_summary.total >= 1+ assert len(result.cluster_summary.items) >= 1+ # Bbox should land near the drawn rectangle (90,90)+20×20, with+ # tolerance for the dilation that grows the bbox outward in+ # every direction.+ c = result.cluster_summary.items[0]+ x, y, w, h = c.bbox+ assert 76 <= x <= 92 and 76 <= y <= 92+ assert 18 <= w <= 40 and 18 <= h <= 40+ assert c.px > 0+ assert 0 <= c.centroid[0] <= 200 and 0 <= c.centroid[1] <= 200++ def test_size_mismatch_yields_clusters_for_new_content_area(self):+ # Pixelhog pads to the bigger size; the new content area+ # surfaces as a cluster of its own. That's the right answer+ # ("here's the new region") rather than something to hide.+ small = _make_png(100, 100, (200, 200, 200, 255))+ large = _make_png(200, 100, (200, 200, 200, 255))+ result = compare_images(small, large, with_thumbnail=False)+ assert result.size_mismatch+ assert result.cluster_summary is not None+ assert result.cluster_summary.total >= 1++ def test_identical_images_have_no_clusters(self):+ img = _make_png(100, 100, (200, 200, 200, 255))+ result = compare_images(img, img, with_thumbnail=False)+ assert result.cluster_summary is None # diff_pixel_count is 0, skipped++ def test_with_clusters_false_skips_computation(self):+ red = _make_png(100, 100, (255, 0, 0, 255))+ blue = _make_png(100, 100, (0, 0, 255, 255))+ result = compare_images(red, blue, with_thumbnail=False, with_clusters=False)+ assert result.cluster_summary is None++ def test_diff_metadata_pydantic_round_trip(self):+ # Storage round-trip: dump -> load yields the same shape.+ from products.visual_review.backend.diff_metadata import DiffMetadata++ base = _make_png(200, 200, (240, 240, 240, 255))+ cur_img = Image.open(io.BytesIO(base))+ ImageDraw.Draw(cur_img).rectangle([90, 90, 110, 110], fill=(255, 0, 0, 255))+ buf = io.BytesIO()+ cur_img.save(buf, format="PNG")++ result = compare_images(base, buf.getvalue(), with_thumbnail=False)+ original = DiffMetadata(cluster_summary=result.cluster_summary)+ dumped = original.model_dump(mode="json")+ roundtripped = DiffMetadata.model_validate(dumped)+ assert roundtripped == originaldiff --git a/products/visual_review/frontend/components/QuarantineAction.tsx b/products/visual_review/frontend/components/QuarantineAction.tsxnew file mode 100644index 000000000000..22317d8eff3c--- /dev/null+++ b/products/visual_review/frontend/components/QuarantineAction.tsx@@ -0,0 +1,158 @@+import { useState } from 'react'++import { LemonButton, LemonCheckbox, LemonInput, LemonModal } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'++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++/**+ * 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) => void+ /** Override the trigger button label. Defaults to "Quarantine this identifier". */+ triggerLabel?: string+}++/**+ * 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`.+ */+export function QuarantineAction({ identifier, onQuarantine, triggerLabel }: QuarantineActionProps): JSX.Element {+ const [isOpen, setIsOpen] = useState(false)+ const [reason, setReason] = useState('')+ const [includeSibling, setIncludeSibling] = useState(true)+ const [expiresAt, setExpiresAt] = useState<dayjs.Dayjs | null>(dayjs().add(DEFAULT_EXPIRY_DAYS, 'day'))++ const sibling = getThemeSibling(identifier)++ const handleSubmit = (): void => {+ const identifiers = [identifier]+ if (sibling && includeSibling) {+ identifiers.push(sibling)+ }+ onQuarantine(reason, identifiers, expiresAt ? expiresAt.toISOString() : null)+ setIsOpen(false)+ setReason('')+ setExpiresAt(dayjs().add(DEFAULT_EXPIRY_DAYS, 'day'))+ }++ return (+ <div>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setIsOpen(true)}+ data-attr="visual-review-quarantine-open"+ >+ {triggerLabel ?? 'Quarantine this identifier'}+ </LemonButton>+ <LemonModal+ isOpen={isOpen}+ onClose={() => setIsOpen(false)}+ title="Quarantine snapshot"+ 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="visual-review-quarantine-confirm"+ >+ Quarantine+ </LemonButton>+ </>+ }+ >+ <div className="space-y-4">+ <p className="text-sm text-muted">+ 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.+ </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>+ {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">Expires</label>+ <LemonCalendarSelectInput+ value={expiresAt}+ onChange={setExpiresAt}+ placeholder="No expiry"+ clearable+ />+ </div>+ </div>+ </LemonModal>+ </div>+ )+}diff --git a/products/visual_review/frontend/components/SnapshotChangeBadge.tsx b/products/visual_review/frontend/components/SnapshotChangeBadge.tsxnew file mode 100644index 000000000000..56a043538438--- /dev/null+++ b/products/visual_review/frontend/components/SnapshotChangeBadge.tsx@@ -0,0 +1,168 @@+import { IconWarning } from '@posthog/icons'++import { Tooltip } from 'lib/lemon-ui/Tooltip'++import type { ClusterSummaryApi } from '../generated/api.schemas'++// IconPulse is intentionally NOT used here. The "pulse" icon reads as+// "average drift / activity over time" and only makes sense in the+// snapshots overview where we surface aggregated drift. On a single+// snapshot's diff result it overstates a one-off measurement and the+// filmstrip got crowded with two icon-bearing chips per card. See+// SnapshotCard / VisualReviewSnapshotOverviewScene for the avg-drift+// usage we kept.++// Display floor mirrors `DRIFT_DISPLAY_FLOOR_PCT` on the overview card —+// values below this would round to "0.0%" via the formatter and look like+// "no change" on a card that actually has change.+const PCT_DISPLAY_FLOOR = 0.05++// Crossing this tints the chip warning. Picked for visual hierarchy, not+// derived from any backend classifier threshold.+const PCT_WARNING_THRESHOLD = 5++function formatPct(value: number): string {+ if (value < 1) {+ return `${value.toFixed(1)}%`+ }+ return `${Math.round(value)}%`+}++type ChangeBadgeSnapshot = {+ change_kind?: string | null+ diff_percentage?: number | null+ ssim_score?: number | null+ // Optional — history entries don't carry cluster info; only the full+ // snapshot DTO does. The badge renders fine without it.+ cluster_summary?: ClusterSummaryApi | null+ // Sizes differed between baseline and current. Renders an extra chip+ // alongside the kind chip; doesn't replace it (a snapshot can have a+ // different viewport AND a real content change).+ size_mismatch?: boolean | null+}++/**+ * Mirrors the render rules below — true when the badge will render+ * something. Callers should gate parent-level layout (separators,+ * "Change" rows, hasDiff badges) on this rather than rolling their+ * own predicate, otherwise sub-floor/legacy snapshots leave empty+ * UI shells when the badge ends up returning null.+ */+export function hasSnapshotChangeBadge(snapshot: ChangeBadgeSnapshot): boolean {+ if (snapshot.size_mismatch) {+ return true+ }+ const kind = snapshot.change_kind || ''+ if (kind === 'structural') {+ return true+ }+ if (kind === 'pixel' || kind === '') {+ const pct = snapshot.diff_percentage ?? null+ if (pct != null && pct >= PCT_DISPLAY_FLOOR) {+ return true+ }+ }+ return false+}++type ChangeBadgeProps = {+ snapshot: ChangeBadgeSnapshot+ size?: 'small' | 'default'+}++/**+ * 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.+ *+ * Returns null when there's nothing to show (no diff, no size mismatch,+ * or pre-migration legacy row with no kind and no percentage).+ */+export function SnapshotChangeBadge({ snapshot, size = 'default' }: ChangeBadgeProps): JSX.Element | null {+ const kind = snapshot.change_kind || ''+ const pct = snapshot.diff_percentage ?? null+ const isCompact = size === 'small'+ // Smaller padding + non-pill corners on the filmstrip; the rounded-full+ // pill plus icon pair was too visually heavy stacked next to a thumbnail.+ const sizeClass = isCompact ? 'text-[10px] px-1 py-0' : 'text-[11px] px-2 py-0.5'+ const iconClass = isCompact ? 'w-2.5 h-2.5' : 'w-3.5 h-3.5'+ const radiusClass = isCompact ? 'rounded' : 'rounded-full'++ let kindChip: JSX.Element | null = null++ if (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.'+ kindChip = (+ <Tooltip+ title={`Layout shift. ${ssimText} Pixel-diff percentage isn't shown because it's below the classifier threshold and would mislead.`}+ >+ <span+ className={`shrink-0 inline-flex items-center bg-primary-highlight font-medium text-primary leading-none ${radiusClass} ${sizeClass}`}+ >+ {isCompact ? 'Shift' : 'Layout shift'}+ </span>+ </Tooltip>+ )+ } else if ((kind === 'pixel' || kind === '') && pct != null && pct >= PCT_DISPLAY_FLOOR) {+ // `pixel` (current pipeline) and legacy rows (no `change_kind`+ // but a populated `diff_percentage`) both render as the+ // percentage pill — it's a true pixel diff number in both cases.+ const isHigh = pct > PCT_WARNING_THRESHOLD+ const tooltipBits: string[] = []+ if (snapshot.cluster_summary && snapshot.cluster_summary.total > 0) {+ const t = snapshot.cluster_summary.total+ tooltipBits.push(`${t} ${t === 1 ? 'region' : 'regions'} affected`)+ }+ if (snapshot.ssim_score != null) {+ tooltipBits.push(`SSIM ${snapshot.ssim_score.toFixed(3)}`)+ }+ const tooltip = tooltipBits.length ? `${pct.toFixed(2)}% pixel diff. ${tooltipBits.join(' · ')}.` : null+ const chip = (+ <span+ className={`shrink-0 inline-flex items-center font-mono tabular-nums leading-none ${radiusClass} ${sizeClass} ${+ isHigh+ ? 'bg-warning-highlight text-warning-dark font-semibold'+ : 'bg-warning-highlight/60 text-warning-dark'+ }`}+ >+ {formatPct(pct)}+ </span>+ )+ kindChip = tooltip ? <Tooltip title={tooltip}>{chip}</Tooltip> : chip+ }++ // Size mismatch is secondary info — render the full chip on the+ // verbose surface (sidebar) and an icon-only badge in the filmstrip+ // so two side-by-side chips don't crowd the thumbnail.+ const sizeChipTooltip =+ 'Baseline and current screenshots had different dimensions. Pixelhog padded to the larger size before computing the diff, so metrics are still meaningful — they just include the new content area as part of the change.'+ const sizeChip = snapshot.size_mismatch ? (+ <Tooltip title={sizeChipTooltip}>+ <span+ className={`shrink-0 inline-flex items-center bg-warning-highlight font-medium text-warning-dark leading-none ${radiusClass} ${+ isCompact ? 'p-0.5' : `gap-1 ${sizeClass}`+ }`}+ >+ <IconWarning className={iconClass} />+ {!isCompact && 'Size changed'}+ </span>+ </Tooltip>+ ) : null++ if (!kindChip && !sizeChip) {+ return null+ }+ return (+ <span className="inline-flex items-center gap-1">+ {kindChip}+ {sizeChip}+ </span>+ )+}diff --git a/products/visual_review/frontend/components/SnapshotClusterPanel.tsx b/products/visual_review/frontend/components/SnapshotClusterPanel.tsxnew file mode 100644index 000000000000..696d11a7f31e--- /dev/null+++ b/products/visual_review/frontend/components/SnapshotClusterPanel.tsx@@ -0,0 +1,101 @@+import type { ClusterSummaryApi } from '../generated/api.schemas'++interface SnapshotClusterPanelProps {+ clusterSummary: ClusterSummaryApi+ /** Total pixels in the diff image — used to render each cluster's % share. */+ totalPixels?: number | null+ highlightedIndex: number | null+ onHighlight: (index: number | null) => void+}++function formatNumber(n: number): string {+ return n.toLocaleString('en-US')+}++// Same warm-orange chip color as the bbox overlay so panel rows and+// image overlays read as a single visual system.+const CHIP_BG = 'rgb(245, 134, 52)'++/**+ * Sidebar overview of the diff's connected change regions. One row per+ * region — position, size, pixel count, share-of-image. Rows are+ * always visible (not collapsible) since the sidebar already gives them+ * a natural home; hovering a row highlights the matching bbox in the+ * image overlay, and overlay hover lights up the row.+ *+ * Pixelhog returns up to `CLUSTER_MAX` clusters ranked by pixel count,+ * with `total` carrying the true count when truncated. The header+ * surfaces both so users know whether they're seeing the full picture.+ */+export function SnapshotClusterPanel({+ clusterSummary,+ totalPixels,+ highlightedIndex,+ onHighlight,+}: SnapshotClusterPanelProps): JSX.Element | null {+ const { items, total, truncated } = clusterSummary+ if (items.length === 0) {+ return null+ }+ const totalShownPixels = items.reduce((sum, c) => sum + c.pixel_count, 0)+ const count = items.length+ // pixelhog 1.2 semantics: `total` is the pre-merge raw CCL count;+ // `truncated` fires only when max_clusters dropped some pre-merge.+ // When total > count without truncation, merging compressed+ // pre-merge clusters — surface as context, not as missing data.+ let regionCountLabel = `${count} ${count === 1 ? 'region' : 'regions'}`+ if (total > count) {+ regionCountLabel += ` · merged from ${total} raw`+ }+ if (truncated) {+ regionCountLabel += ' · cap reached'+ }++ return (+ <div>+ <h4 className="text-xs font-semibold text-muted mb-1">Change clusters</h4>+ <div className="text-[11px] text-muted mb-2 tabular-nums">+ {regionCountLabel} · {formatNumber(totalShownPixels)} px+ </div>+ <div+ className="flex flex-col rounded-md border bg-bg-light overflow-hidden"+ onMouseLeave={() => onHighlight(null)}+ >+ {items.map((cluster, i) => {+ const isHighlighted = highlightedIndex === i+ const pctOfImage = totalPixels && totalPixels > 0 ? (cluster.pixel_count / totalPixels) * 100 : null+ return (+ <button+ type="button"+ key={i}+ onMouseEnter={() => onHighlight(i)}+ onFocus={() => onHighlight(i)}+ onBlur={() => onHighlight(null)}+ className={`flex items-center gap-2 px-2 py-1.5 text-left border-b last:border-b-0 transition-colors ${+ isHighlighted ? 'bg-warning-highlight' : 'hover:bg-bg-3000'+ }`}+ data-attr="visual-review-cluster-row"+ >+ <span+ className="shrink-0 inline-flex items-center justify-center w-6 h-6 rounded-full text-white text-[11px] font-bold tabular-nums shadow-sm ring-1 ring-white/70"+ // eslint-disable-next-line react/forbid-dom-props+ style={{ background: CHIP_BG }}+ >+ {i + 1}+ </span>+ <div className="flex-1 min-w-0 text-[11px] font-mono tabular-nums leading-tight">+ <div className="text-default truncate">+ {cluster.x},{cluster.y} · {cluster.width}×{cluster.height}+ </div>+ <div className="text-muted">+ {formatNumber(cluster.pixel_count)} px+ {pctOfImage != null && ` · ${pctOfImage.toFixed(2)}%`}+ </div>+ </div>+ </button>+ )+ })}+ </div>+ </div>+ )+}diff --git a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx b/products/visual_review/frontend/components/SnapshotDiffViewer.tsxindex 81e19d1895d2..f202f3a2e866 100644--- a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx+++ b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx@@ -1,19 +1,19 @@import { useActions, useValues } from 'kea'-import { useState } from 'react'+import { useMemo, useState } from 'react'import { IconGithub } from '@posthog/icons'-import { LemonButton, LemonCheckbox, LemonInput, LemonModal, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'+import { LemonButton, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'import { VisualImageDiffViewer, type VisualDiffResult } from 'lib/components/VisualImageDiffViewer'-import { dayjs } from 'lib/dayjs'-import { LemonCalendarSelectInput } from 'lib/lemon-ui/LemonCalendar/LemonCalendarSelect'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { urls } from 'scenes/urls'import type { QuarantinedIdentifierEntryApi, SnapshotApi, ToleratedHashEntryApi } from '../generated/api.schemas'import { visualReviewPreferencesLogic } from '../scenes/visualReviewPreferencesLogic'-import { DiffPercentage } from './DiffPercentage'+import { QuarantineAction } from './QuarantineAction'+import { SnapshotChangeBadge, hasSnapshotChangeBadge } from './SnapshotChangeBadge'+import { SnapshotClusterPanel } from './SnapshotClusterPanel'import { SnapshotStatusIndicator } from './SnapshotStatusIndicator'function DiffMinimap({ url, onClick }: { url: string; onClick?: () => void }): JSX.Element {@@ -40,147 +40,6 @@ function DiffMinimap({ url, onClick }: { url: string; onClick?: () => void }): J)}-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('--')-}--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--function QuarantineAction({- identifier,- onQuarantine,-}: {- identifier: string- onQuarantine: (reason: string, identifiers: string[], expiresAt: string | null) => void-}): JSX.Element {- const [isOpen, setIsOpen] = useState(false)- const [reason, setReason] = useState('')- const [includeSibling, setIncludeSibling] = useState(true)- const [expiresAt, setExpiresAt] = useState<dayjs.Dayjs | null>(dayjs().add(DEFAULT_EXPIRY_DAYS, 'day'))-- const sibling = getThemeSibling(identifier)-- const handleSubmit = (): void => {- const identifiers = [identifier]- if (sibling && includeSibling) {- identifiers.push(sibling)- }- onQuarantine(reason, identifiers, expiresAt ? expiresAt.toISOString() : null)- setIsOpen(false)- setReason('')- setExpiresAt(dayjs().add(DEFAULT_EXPIRY_DAYS, 'day'))- }-- return (- <div>- <LemonButton- type="secondary"- size="small"- onClick={() => setIsOpen(true)}- data-attr="visual-review-quarantine-open"- >- Quarantine this identifier- </LemonButton>- <LemonModal- isOpen={isOpen}- onClose={() => setIsOpen(false)}- title="Quarantine snapshot"- 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="visual-review-quarantine-confirm"- >- Quarantine- </LemonButton>- </>- }- >- <div className="space-y-4">- <p className="text-sm text-muted">- 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.- </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>- {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">Expires</label>- <LemonCalendarSelectInput- value={expiresAt}- onChange={setExpiresAt}- placeholder="No expiry"- clearable- />- </div>- </div>- </LemonModal>- </div>- )-}-interface SnapshotDiffViewerProps {snapshot: SnapshotApitoleratedHashes?: ToleratedHashEntryApi[]@@ -230,6 +89,41 @@ export function SnapshotDiffViewer({const width = snapshot.current_artifact?.width || snapshot.baseline_artifact?.widthconst height = snapshot.current_artifact?.height || snapshot.baseline_artifact?.height+ const [highlightedClusterIndex, setHighlightedClusterIndex] = useState<number | null>(null)++ // When a single (post-merge) cluster covers most of the image, the+ // bbox overlay adds no information beyond the diff% tag — full+ // inversions or wholesale changes show as "1 region · 99%". Skip+ // the overlay and panel in that regime so the user sees the+ // underlying diff cleanly. Use `items.length` (post-merge count),+ // not `total` — total is the pre-merge raw count so it can be 21+ // even after pixelhog merged everything into one regional cluster.+ const DOMINANT_CLUSTER_PCT_THRESHOLD = 80+ const clusterSummary = snapshot.cluster_summary+ const isClusterDominant =+ !!clusterSummary &&+ clusterSummary.items.length === 1 &&+ snapshot.diff_percentage != null &&+ snapshot.diff_percentage >= DOMINANT_CLUSTER_PCT_THRESHOLD+ const visibleClusterSummary = useMemo(+ () => (isClusterDominant ? null : clusterSummary),+ [clusterSummary, isClusterDominant]+ )+ const overlayBoxes = useMemo(+ () =>+ visibleClusterSummary?.items.map((c) => ({+ x: c.x,+ y: c.y,+ width: c.width,+ height: c.height,+ })),+ [visibleClusterSummary]+ )+ const diffPixelTotal =+ snapshot.diff_artifact?.width && snapshot.diff_artifact?.height+ ? snapshot.diff_artifact.width * snapshot.diff_artifact.height+ : null+const isApproved = snapshot.review_state === 'approved'const isTolerated = snapshot.review_state === 'tolerated'const isQuarantined = !!quarantineEntry@@ -339,6 +233,11 @@ export function SnapshotDiffViewer({mode={comparisonMode}onModeChange={setComparisonMode}className="min-h-[200px]"+ diffOverlayBoxes={overlayBoxes}+ diffOverlayWidth={snapshot.diff_artifact?.width ?? undefined}+ diffOverlayHeight={snapshot.diff_artifact?.height ?? undefined}+ highlightedOverlayIndex={highlightedClusterIndex}+ onOverlayHover={setHighlightedClusterIndex}/></div>@@ -352,6 +251,16 @@ export function SnapshotDiffViewer({/>)}+ {/* === Change clusters === */}+ {visibleClusterSummary && visibleClusterSummary.items.length > 0 && (+ <SnapshotClusterPanel+ clusterSummary={visibleClusterSummary}+ totalPixels={diffPixelTotal}+ highlightedIndex={highlightedClusterIndex}+ onHighlight={setHighlightedClusterIndex}+ />+ )}+{/* === Run section === */}{(runType || commitSha || prNumber) && (<div>@@ -504,10 +413,10 @@ export function SnapshotDiffViewer({</span></div>)}- {snapshot.diff_percentage != null && snapshot.diff_percentage > 0 && (+ {hasSnapshotChangeBadge(snapshot) && (<div className="flex items-center justify-between text-xs">- <span className="text-muted">Diff</span>- <DiffPercentage value={snapshot.diff_percentage} suffix="" />+ <span className="text-muted">Change</span>+ <SnapshotChangeBadge snapshot={snapshot} /></div>)}{snapshot.baseline_artifact?.content_hash && (diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.tsindex 0eb43f5ecb81..a39ad1514fca 100644--- a/products/visual_review/frontend/generated/api.schemas.ts+++ b/products/visual_review/frontend/generated/api.schemas.ts@@ -196,6 +196,10 @@ export interface SnapshotHistoryEntryApi {/** @nullable */diff_percentage?: number | nullreview_state?: string+ /** @nullable */+ ssim_score?: number | null+ change_kind?: string+ size_mismatch?: boolean}export interface PaginatedSnapshotHistoryEntryListApi {@@ -288,6 +292,22 @@ export interface RecomputeResultApi {ci_rerun_error?: string | null}+export interface DiffClusterApi {+ x: number+ y: number+ width: number+ height: number+ pixel_count: number+ centroid_x: number+ centroid_y: number+}++export interface ClusterSummaryApi {+ items: DiffClusterApi[]+ total: number+ truncated: boolean+}+export type SnapshotApiMetadata = { [key: string]: unknown }export interface SnapshotApi {@@ -295,6 +315,7 @@ export interface SnapshotApi {baseline_artifact?: ArtifactApi | nulldiff_artifact?: ArtifactApi | nullreviewed_by?: UserBasicInfoApi | null+ cluster_summary?: ClusterSummaryApi | nullid: stringidentifier: stringresult: string@@ -311,6 +332,10 @@ export interface SnapshotApi {tolerated_hash_id?: string | nullis_quarantined?: booleanmetadata?: SnapshotApiMetadata+ /** @nullable */+ ssim_score?: number | null+ change_kind?: string+ size_mismatch?: boolean}export interface PaginatedSnapshotListApi {diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsxindex 35a839ff4e9f..8f8416621183 100644--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.tsx@@ -15,6 +15,7 @@ import { KeyboardShortcut } from '~/layout/navigation-3000/components/KeyboardShimport { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { SnapshotChangeBadge, hasSnapshotChangeBadge } from '../components/SnapshotChangeBadge'import { SnapshotDiffViewer } from '../components/SnapshotDiffViewer'import { SnapshotStatusIndicator } from '../components/SnapshotStatusIndicator'import { VisualReviewTabs } from '../components/VisualReviewTabs'@@ -53,7 +54,10 @@ function SnapshotThumbnail({const isReviewed = snapshot.review_state === 'approved' || snapshot.review_state === 'tolerated'const showBadge = isReviewed || isQuarantined- const hasDiff = snapshot.diff_percentage != null && snapshot.diff_percentage > 0+ // True iff the SnapshotChangeBadge will actually render. Mirrors+ // its visibility predicate so we don't show "hasDiff = true but+ // empty chip area" for sub-display-floor noise rows.+ const hasDiff = hasSnapshotChangeBadge(snapshot)const imgSrc = thumbnailSrc ?? fallbackSrc@@ -114,12 +118,7 @@ function SnapshotThumbnail({</div><div className="flex items-center gap-1 max-w-[108px] w-full">{hasDiff ? (- <span className="shrink-0 bg-warning-highlight rounded-full px-1.5 py-0.5 text-[10px] font-mono tabular-nums text-warning-dark leading-none">- {snapshot.diff_percentage! < 1- ? snapshot.diff_percentage!.toFixed(1)- : Math.round(snapshot.diff_percentage!)}- %- </span>+ <SnapshotChangeBadge snapshot={snapshot} size="small" />) : (<SnapshotStatusIndicatorresult={snapshot.result || 'unchanged'}diff --git a/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx b/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsxindex 94c13f1ef53a..81928289992b 100644--- a/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx+++ b/products/visual_review/frontend/scenes/VisualReviewSnapshotHistoryScene.tsx@@ -1,19 +1,22 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { useState } from 'react'import { LemonBanner, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'import { SceneExport } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'-import { DiffPercentage } from '../components/DiffPercentage'+import { QuarantineAction } from '../components/QuarantineAction'+import { SnapshotChangeBadge, hasSnapshotChangeBadge } from '../components/SnapshotChangeBadge'import { VisualReviewTabs } from '../components/VisualReviewTabs'-import type { SnapshotHistoryEntryApi } from '../generated/api.schemas'+import type { QuarantinedIdentifierEntryApi, SnapshotHistoryEntryApi } from '../generated/api.schemas'import {ThemePair,VisualReviewSnapshotHistorySceneLogicProps,@@ -151,10 +154,10 @@ function HistoryRow({) : (<span className="font-mono">{entry.commit_sha.slice(0, 8)}</span>)}- {entry.diff_percentage != null && entry.diff_percentage > 0 && (+ {hasSnapshotChangeBadge(entry) && (<><span>·</span>- <DiffPercentage value={entry.diff_percentage} />+ <SnapshotChangeBadge snapshot={entry} size="small" /></>)}</div>@@ -177,6 +180,71 @@ function HistoryRow({)}+function QuarantineSection({+ identifier,+ quarantineEntry,+ isQuarantined,+ onQuarantine,+ onUnquarantine,+}: {+ identifier: string+ quarantineEntry: QuarantinedIdentifierEntryApi | null+ isQuarantined: boolean+ onQuarantine: (reason: string, identifiers: string[], expiresAt: string | null) => void+ onUnquarantine: () => void+}): JSX.Element {+ if (isQuarantined && quarantineEntry) {+ const expires = quarantineEntry.expires_at ? new Date(quarantineEntry.expires_at) : null+ const openConfirmation = (): void => {+ LemonDialog.open({+ title: 'Unquarantine this identifier?',+ description:+ 'This identifier will be gated on again in future runs. ' ++ 'Branches that haven’t merged the fix may get blocked.',+ primaryButton: {+ children: 'Unquarantine',+ status: 'danger',+ onClick: onUnquarantine,+ },+ secondaryButton: { children: 'Cancel' },+ })+ }+ return (+ <LemonBanner+ type="warning"+ action={{+ children: 'Unquarantine',+ status: 'danger',+ 'data-attr': 'visual-review-history-unquarantine',+ onClick: openConfirmation,+ }}+ >+ <div className="text-sm flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="font-semibold">Quarantined</span>+ <span>— {quarantineEntry.reason || 'no reason given'}</span>+ {expires && (+ <>+ <span aria-hidden>·</span>+ <span>until {expires.toLocaleDateString()}</span>+ </>+ )}+ {quarantineEntry.created_by && (+ <>+ <span aria-hidden>·</span>+ <ProfilePicture user={quarantineEntry.created_by} size="xs" showName />+ </>+ )}+ </div>+ </LemonBanner>+ )+ }+ return (+ <div className="flex justify-end">+ <QuarantineAction identifier={identifier} onQuarantine={onQuarantine} />+ </div>+ )+}+function Stat({ value, label }: { value: React.ReactNode; label: string }): JSX.Element {return (<div className="flex flex-col gap-0.5">@@ -187,9 +255,19 @@ function Stat({ value, label }: { value: React.ReactNode; label: string }): JSX.}export function VisualReviewSnapshotHistoryScene(): JSX.Element {- const { repo, repoLoading, history, historyLoading, identifier, pairedHistory, runType, repoId } = useValues(- visualReviewSnapshotHistorySceneLogic- )+ const {+ repo,+ repoLoading,+ history,+ historyLoading,+ identifier,+ pairedHistory,+ runType,+ repoId,+ quarantineEntry,+ quarantineEntryLoading,+ } = useValues(visualReviewSnapshotHistorySceneLogic)+ const { quarantineIdentifier, unquarantineIdentifier } = useActions(visualReviewSnapshotHistorySceneLogic)const repoFullName = repo?.repo_full_name ?? null// history is already deduped to one row per distinct baseline (newest first),@@ -197,6 +275,7 @@ export function VisualReviewSnapshotHistoryScene(): JSX.Element {// 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 = !!quarantineEntryreturn (<SceneContent>@@ -236,6 +315,19 @@ 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}+ />+ )}+{historyLoading || repoLoading ? (<div className="flex flex-col gap-4"><LemonSkeleton className="h-32 w-full" />diff --git a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.tsindex 446c6c158dec..7ea068705e53 100644--- a/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewRunSceneLogic.ts@@ -200,10 +200,26 @@ export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([groups.set(base, group)}- // Sort groups by max diff% descending+ // Severity score for ordering. Pixel-tier rows have a real+ // diff_percentage; structural-tier rows had it nulled by the+ // split-diff-metrics migration (legacy diff_percentage was+ // SSIM-as-percentage and would mislead now). Fall back to+ // SSIM dissimilarity scaled to a comparable percent so+ // structural shifts surface alongside pixel diffs instead+ // of sinking to the bottom as 0.+ const severity = (s: SnapshotApi): number => {+ if (s.diff_percentage != null) {+ return s.diff_percentage+ }+ if (s.ssim_score != null) {+ return (1 - s.ssim_score) * 100+ }+ return 0+ }+const sortedGroups = [...groups.values()].sort((a, b) => {- const maxA = Math.max(...a.map((s) => s.diff_percentage ?? 0))- const maxB = Math.max(...b.map((s) => s.diff_percentage ?? 0))+ const maxA = Math.max(...a.map(severity))+ const maxB = Math.max(...b.map(severity))return maxB - maxA})diff --git a/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.tsindex 59c513e50356..8eddac33490a 100644--- a/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts+++ b/products/visual_review/frontend/scenes/visualReviewSnapshotHistorySceneLogic.ts@@ -1,13 +1,20 @@-import { afterMount, connect, kea, key, path, props, selectors } from 'kea'+import { actions, afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { Breadcrumb } from '~/types'-import { visualReviewReposRetrieve, visualReviewReposSnapshotsList } from '../generated/api'-import type { RepoApi, SnapshotHistoryEntryApi } from '../generated/api.schemas'+import {+ visualReviewReposQuarantineCreate,+ visualReviewReposQuarantineExpireCreate,+ visualReviewReposQuarantineList,+ visualReviewReposRetrieve,+ visualReviewReposSnapshotsList,+} from '../generated/api'+import type { QuarantinedIdentifierEntryApi, RepoApi, SnapshotHistoryEntryApi } from '../generated/api.schemas'import type { visualReviewSnapshotHistorySceneLogicType } from './visualReviewSnapshotHistorySceneLogicType'export interface VisualReviewSnapshotHistorySceneLogicProps {@@ -44,6 +51,14 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHisconnect(() => ({values: [teamLogic, ['currentProjectId']],})),+ actions({+ quarantineIdentifier: (reason: string, identifiers: string[], expiresAt: string | null) => ({+ reason,+ identifiers,+ expiresAt,+ }),+ unquarantineIdentifier: true,+ }),loaders(({ props, values }) => ({repo: [null as RepoApi | null,@@ -88,6 +103,29 @@ 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,+ {+ loadQuarantineEntry: async () => {+ const response = await visualReviewReposQuarantineList(+ String(values.currentProjectId),+ props.repoId,+ { identifier: props.identifier, 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],@@ -133,9 +171,45 @@ export const visualReviewSnapshotHistorySceneLogic = kea<visualReviewSnapshotHis],],}),+ listeners(({ actions, values, props }) => ({+ quarantineIdentifier: async ({ reason, identifiers, expiresAt }) => {+ try {+ await Promise.all(+ identifiers.map((identifier) =>+ visualReviewReposQuarantineCreate(+ String(values.currentProjectId),+ props.repoId,+ props.runType,+ { identifier, reason, expires_at: expiresAt }+ )+ )+ )+ const count = identifiers.length+ lemonToast.success(`${count} identifier${count > 1 ? 's' : ''} quarantined`)+ actions.loadQuarantineEntry()+ } catch (e: any) {+ lemonToast.error(e?.detail || e?.message || 'Failed to quarantine')+ }+ },+ unquarantineIdentifier: async () => {+ try {+ await visualReviewReposQuarantineExpireCreate(+ String(values.currentProjectId),+ props.repoId,+ props.runType,+ { identifier: props.identifier, reason: '' }+ )+ lemonToast.success('Identifier unquarantined — future runs will gate on it again')+ actions.loadQuarantineEntry()+ } catch (e: any) {+ lemonToast.error(e?.detail || e?.message || 'Failed to unquarantine')+ }+ },+ })),afterMount(({ actions }) => {actions.loadRepo()actions.loadHistory()actions.loadPartnerHistory()+ actions.loadQuarantineEntry()}),])diff --git a/pyproject.toml b/pyproject.tomlindex e8990efdf1df..2f532b27231f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -187,7 +187,7 @@ dependencies = ["defusedxml>=0.7.1","confluent-kafka>=2.13.0","blake3>=1.0.8",- "pixelhog~=1.1.0",+ "pixelhog~=1.2.0","google-re2>=1.1.20251105","scrubadub~=2.0.1","braintrust-core>=0.0.59",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 3e6bd0dbfc41..0efe51413cde 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -7941,6 +7941,22 @@ export namespace Schemas {readonly elements_chain: string;}+ export interface DiffCluster {+ x: number;+ y: number;+ width: number;+ height: number;+ pixel_count: number;+ centroid_x: number;+ centroid_y: number;+ }++ export interface ClusterSummary {+ items: DiffCluster[];+ total: number;+ truncated: boolean;+ }+/*** * `trace` - trace* `generation` - generation@@ -24718,6 +24734,10 @@ export namespace Schemas {/** @nullable */diff_percentage?: number | null;review_state?: string;+ /** @nullable */+ ssim_score?: number | null;+ change_kind?: string;+ size_mismatch?: boolean;}export interface PaginatedSnapshotHistoryEntryList {@@ -24736,6 +24756,7 @@ export namespace Schemas {baseline_artifact?: Artifact | null;diff_artifact?: Artifact | null;reviewed_by?: UserBasicInfo | null;+ cluster_summary?: ClusterSummary | null;id: string;identifier: string;result: string;@@ -24752,6 +24773,10 @@ export namespace Schemas {tolerated_hash_id?: string | null;is_quarantined?: boolean;metadata?: SnapshotMetadata;+ /** @nullable */+ ssim_score?: number | null;+ change_kind?: string;+ size_mismatch?: boolean;}export interface PaginatedSnapshotList {diff --git a/uv.lock b/uv.lockindex 7caa2f0030d2..0a531a49fcd2 100644--- a/uv.lock+++ b/uv.lock@@ -11,7 +11,7 @@ resolution-markers = [][options]-exclude-newer = "2026-04-28T12:47:33.729278Z"+exclude-newer = "2026-04-29T07:11:12.944613Z"exclude-newer-span = "P7D"[options.exclude-newer-package]@@ -4997,17 +4997,17 @@ wheels = [[[package]]name = "pixelhog"-version = "1.1.0"+version = "1.2.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/88/94/896a3aa2d6e10d68371c5e996d4dd163a6b865cebe41f169f91a83243116/pixelhog-1.1.0.tar.gz", hash = "sha256:c0a2635dbda09bf45ab14c082688ba602caa25666db765f13a091747bbfd6ced", size = 22462, upload-time = "2026-04-22T11:46:24.104Z" }+sdist = { url = "https://files.pythonhosted.org/packages/1f/5e/23e3cf43002b8e68e55da4b650b108909e6e38569170fc9c2611ddaf5dcf/pixelhog-1.2.0.tar.gz", hash = "sha256:919b9c3f90e89307ae1de816d7860cd3fa27a59e5e2da020f02953f30ebb56fd", size = 31973, upload-time = "2026-05-05T09:18:06.785Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/94/85/dfeea1e8ca9724ba0015e43814a408b5b51199750ee9eb772d39b2c99723/pixelhog-1.1.0-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:2c88337bde847b99ca7f357b2776dac152ca3cf26574d96922e945156a6642e1", size = 598717, upload-time = "2026-04-22T11:46:21.5Z" },- { url = "https://files.pythonhosted.org/packages/d9/94/5827891ea895c99e3bd941023619c181a1bfeb4b9e3f154e6fbc357a1e57/pixelhog-1.1.0-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:4b2d2080ef04672fefcd6b0e421335a19c81d23bee1ac074cb52cc8324de40d9", size = 589517, upload-time = "2026-04-22T11:46:20.046Z" },- { url = "https://files.pythonhosted.org/packages/97/a9/8541660036ad13be00c986a8d66540b1908d8b2769be62b021f86c1cf4eb/pixelhog-1.1.0-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c43918a0d432c5d571ff24ca5e8594bdf1bd709c1d8a46909a97d59c1c547465", size = 624535, upload-time = "2026-04-22T11:46:16.117Z" },- { url = "https://files.pythonhosted.org/packages/20/11/b8c7f8510dd0ab44b14223f17fffc998b5c0ea0afb94dde2c47173900c43/pixelhog-1.1.0-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f193e6e06bcb57b03ffb6c71a8e937e8c88b9f720b8a6633e5e4753f4bc54ed2", size = 659123, upload-time = "2026-04-22T11:46:17.415Z" },- { url = "https://files.pythonhosted.org/packages/0a/c7/be1bb07fbfda9e4f4c20d82428dcfc3da23c5d0e22d4e41c89ad507069ab/pixelhog-1.1.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:3911397ea6401c557c4877e61e393f280cfe188f1f22917d0512318187c91c55", size = 801023, upload-time = "2026-04-22T11:46:18.689Z" },- { url = "https://files.pythonhosted.org/packages/99/49/f2fd98acda01eefa84a318d6ba6a1f50fd4529eb208b34848e2010927930/pixelhog-1.1.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ac0e60fd7cd7358f71b076a8e89c83b656fe4491f8813d7b9c370e6da2aa9c38", size = 855059, upload-time = "2026-04-22T11:46:22.916Z" },- { url = "https://files.pythonhosted.org/packages/d8/c6/f75c90929f33c013ff7ce6c220872fc59b044ae3a7f424a8bede6ba89e0a/pixelhog-1.1.0-cp312-abi3-win_amd64.whl", hash = "sha256:39e07af50de54b589cff1f249209d7c68eaf243c99e7c1478d003d225e829fc1", size = 537830, upload-time = "2026-04-22T11:46:25.309Z" },+ { url = "https://files.pythonhosted.org/packages/a1/3b/860c2e4cfe1a26fdfd5c19afb4ba649710a83a9a5d0bfcdd4111068aba3b/pixelhog-1.2.0-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:82b33e6cddc730dd08314aea688d0f3ac50f1f52439c5655378838ce41bf3710", size = 660795, upload-time = "2026-05-05T09:17:59.02Z" },+ { url = "https://files.pythonhosted.org/packages/1a/e0/9822760802dd572b837fb381fcba8274509d76532b151f0a49ed2ca250e2/pixelhog-1.2.0-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:f0488d22181b166871a149458cefc84d5c6bac74766898a35053dcb7c163f802", size = 648839, upload-time = "2026-05-05T09:17:57.43Z" },+ { url = "https://files.pythonhosted.org/packages/da/07/d142e38d7dc60a467b97ef8f1a92d61cb1909bb8ffb0e9c27bec55e61bb0/pixelhog-1.2.0-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a2d70c505f17295b85a77c60c7fec8cee97a3c95100232cca2f86a5a590a579", size = 683699, upload-time = "2026-05-05T09:18:00.378Z" },+ { url = "https://files.pythonhosted.org/packages/79/7e/a04a4914a17774929d8fd1e0be0da71c1c310db14a0a37fbc33437a301f4/pixelhog-1.2.0-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:365834d17326109c63cf2da5204cb92ce84518798f9a5d08502331fe83dacb4d", size = 724161, upload-time = "2026-05-05T09:18:04.434Z" },+ { url = "https://files.pythonhosted.org/packages/73/07/da9179b7f0c9b118b9ae81a9a6d1849a2acbbdc86b9f6450ad05f0bdd8d2/pixelhog-1.2.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:05239693d9e5f844af52a082d082a8e191608f379257ce35bf5c197b52231970", size = 859951, upload-time = "2026-05-05T09:18:03.094Z" },+ { url = "https://files.pythonhosted.org/packages/27/c0/a5b1d61a18fcd060afda879fd95abb9f510d131e585cf477816c1f178ce4/pixelhog-1.2.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7ac96f4f9ee6c2505eb89412f6532e8cc9719ac730d1c156e30b22be878285cf", size = 916439, upload-time = "2026-05-05T09:18:01.65Z" },+ { url = "https://files.pythonhosted.org/packages/09/d2/c057e7c1a708ec91abd9071a068332adf5d92d064b49537c0fdf9164cfed/pixelhog-1.2.0-cp312-abi3-win_amd64.whl", hash = "sha256:3de6ddcea4cad183052a20f3d07d38ca23ff587bc7b6ffafdff1f98f914ca06b", size = 610639, upload-time = "2026-05-05T09:18:05.632Z" },][[package]]@@ -5492,7 +5492,7 @@ requires-dist = [{ name = "pandas", specifier = "~=2.2.2" },{ name = "paramiko", specifier = "==3.4.1" },{ name = "pillow", specifier = "==12.2.0" },- { name = "pixelhog", specifier = "~=1.1.0" },+ { name = "pixelhog", specifier = "~=1.2.0" },{ name = "playwright", specifier = "~=1.54.0" },{ name = "polars", specifier = "==1.37.1" },{ name = "posthoganalytics", specifier = "==7.13.0" },