: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
import { useMemo } from 'react'
import { IconCopy, IconFlag, IconPulse, IconWarning } from '@posthog/icons'
import { LemonTag, Link } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { urls } from 'scenes/urls'
import type { BaselineEntryApi, BaselineQuarantineSummaryApi } from '../generated/api.schemas'
import { parseArea, parseTheme } from '../lib/parseIdentifier'
import { splitRepoFullName } from '../lib/repoPaths'
import { sourceRunPrNumber } from '../lib/runPredicates'
// Drift is shown as a percentage with one decimal — anything less is sub-pixel
// noise and not actionable; anything more on a thumbnail-sized card is illegible.
function formatDriftPct(value: number): string {
if (value >= 10) {
return `${value.toFixed(0)}%`
}
return `${value.toFixed(1)}%`
}
// Compact "12d left" / "today" / "expired" hint for the card. The exact date
// is in the tooltip so the strip stays readable inside a 220px-wide thumb.
function formatExpiryShort(expiresAt: string | null | undefined): string {
if (!expiresAt) {
return 'no expiry'
}
const now = dayjs()
const expiry = dayjs(expiresAt)
if (expiry.isBefore(now)) {
return 'expired'
}
const days = expiry.diff(now, 'day')
if (days === 0) {
return 'today'
}
if (days < 30) {
return `${days}d left`
}
return `${Math.round(days / 7)}w left`
}
function buildQuarantineTooltip(quarantine: BaselineQuarantineSummaryApi): JSX.Element {
// One <div> per line so the tooltip renders multi-line — the default
// Tooltip container has `white-space: normal`, which would collapse `\n`.
const lines: string[] = []
if (quarantine.reason) {
lines.push(quarantine.reason)
}
lines.push(
quarantine.expires_at ? `Expires ${dayjs(quarantine.expires_at).format('MMM D, YYYY')}` : 'No expiry set'
)
if (quarantine.created_by) {
const name = quarantine.created_by.first_name || quarantine.created_by.email
lines.push(`By ${name} · ${dayjs(quarantine.created_at).fromNow()}`)
}
if (quarantine.source_run) {
const prNumber = sourceRunPrNumber(quarantine.source_run)
const prSuffix = prNumber ? ` · PR #${prNumber}` : ''
lines.push(`From ${quarantine.source_run.commit_sha.slice(0, 8)} on ${quarantine.source_run.branch}${prSuffix}`)
}
return (
<>
{lines.map((line, i) => (
<div key={i}>{line}</div>
))}
</>
)
}
// Anything below this rounds to "0.0%" via the formatter above, which would
// render a misleading "no drift" chip on a card that does have drift. Hide
// the chip entirely below this floor; the data is still in the API response
// for anyone who wants the exact number.
const DRIFT_DISPLAY_FLOOR_PCT = 0.05
// Crossing this threshold tints the drift chip in the warning palette so the
// eye lands on the loudest cards first. Picked for visual hierarchy, not
// derived from the backend classifier — pixel/SSIM thresholds in
// `diffing.py` are unrelated to this UI hook.
const DRIFT_WARNING_THRESHOLD_PCT = 1
// Mirrors `BASELINE_DRIFT_RECENT_RUN_COUNT` in
// `products/visual_review/backend/facade/contracts.py`. Keep in sync — the
// backend value drives `recent_drift_avg`, this constant drives the copy.
export const RECENT_DRIFT_WINDOW = 10
export function SnapshotCard({
repoFullName,
entry,
thumbnailBasePath,
}: {
repoFullName: string
entry: BaselineEntryApi
thumbnailBasePath: string | null
}): JSX.Element {
const { theme } = parseTheme(entry.identifier)
const area = parseArea(entry.identifier)
const tolerateCount = entry.tolerate_count_30d
const variantCount = entry.active_variants_current_baseline
const driftPct = entry.recent_drift_avg ?? 0
const driftVisible = driftPct >= DRIFT_DISPLAY_FLOOR_PCT
const driftLoud = driftPct >= DRIFT_WARNING_THRESHOLD_PCT
// Only build the thumbnail URL when we know there's a thumbnail to fetch —
// otherwise the endpoint 404s and browsers show the broken-image glyph.
const thumbnailUrl =
thumbnailBasePath && entry.thumbnail_hash
? `${thumbnailBasePath}/${encodeURIComponent(entry.identifier)}/`
: null
const href = urls.visualReviewSnapshotHistory(...splitRepoFullName(repoFullName), entry.run_type, entry.identifier)
const hasMeta = driftVisible || tolerateCount > 0 || variantCount > 0 || entry.baseline_change_count > 0
const quarantine = entry.quarantine ?? null
const quarantinePrNumber = quarantine?.source_run ? sourceRunPrNumber(quarantine.source_run) : null
// Yellow ring (not a 1px border) so the card pulls the eye in a grid
// of hundreds — quarantine means "system stopped trusting this".
const cardClassName = entry.is_quarantined
? 'border border-warning rounded bg-bg-light overflow-hidden flex flex-col text-default hover:border-warning-dark transition-colors shadow-[0_0_0_1px_var(--warning)]'
: 'border border-border rounded bg-bg-light overflow-hidden flex flex-col text-default hover:border-primary transition-colors'
// Tooltip body is only consumed on hover — compute once per render of
// a quarantined card, not on every mouse-enter, and avoid building it
// at all for non-quarantined cards (most cards in a typical grid).
const quarantineTooltip = useMemo(() => (quarantine ? buildQuarantineTooltip(quarantine) : null), [quarantine])
return (
<Link
to={href}
// Without an explicit border-color, Tailwind's `border` falls back
// to `currentColor` — and Link sets `currentColor` to the primary
// orange. That painted every card with an orange frame.
className={cardClassName}
data-attr="visual-review-snapshot-card"
>
<div
// Thumbnails are bounded by pixelhog at THUMB_WIDTH (200) ×
// THUMB_HEIGHT (140), so we know the box can never overflow.
// Fix the height to the cap and align top so taller content
// anchors consistently across cards; shorter content lets
// the bg-light (or bg-3000 for dark variants) show beneath.
className={`relative h-[140px] flex items-start justify-center overflow-hidden border-b border-border ${
theme === 'dark' ? 'bg-bg-3000' : 'bg-bg-light'
}`}
>
{thumbnailUrl ? (
<img
src={thumbnailUrl}
alt={entry.identifier}
loading="lazy"
decoding="async"
className="max-w-full max-h-full object-contain"
/>
) : (
<span className="text-muted text-xs my-auto">No thumbnail</span>
)}
{/* Strip surfaces reason + expiry inline so the overview is
assessable at a glance — not just a color and icon. The
fallback corner badge handles old API responses that
don't yet return the summary. */}
{entry.is_quarantined &&
(quarantine ? (
<Tooltip title={quarantineTooltip}>
<div className="absolute top-0 left-0 right-0 bg-warning text-white flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-semibold leading-tight">
<IconWarning className="w-3 h-3 shrink-0" />
<span className="truncate min-w-0 flex-1" title={quarantine.reason}>
{quarantine.reason || 'Quarantined'}
</span>
<span className="shrink-0 opacity-90 tabular-nums">
{formatExpiryShort(quarantine.expires_at)}
</span>
</div>
</Tooltip>
) : (
<div className="absolute top-1.5 right-1.5">
<Tooltip title="Currently quarantined — excluded from gating">
<span className="inline-flex items-center justify-center h-5 min-w-5 px-1.5 rounded-full text-white text-[10px] font-semibold leading-none bg-warning">
<IconWarning className="w-3 h-3" />
</span>
</Tooltip>
</div>
))}
</div>
<div className="p-2 flex flex-col gap-1 min-w-0">
<div className="font-mono text-xs truncate" title={entry.identifier}>
{entry.identifier}
</div>
<div className="flex items-center justify-between gap-2 text-[11px] text-muted">
<LemonTag type="default" size="small">
{area}
</LemonTag>
{hasMeta && (
<div className="flex flex-wrap items-center justify-end gap-2 tabular-nums leading-none">
{driftVisible && (
<Tooltip
title={`Average pixel drift over the last ${RECENT_DRIFT_WINDOW} default-branch runs: ${driftPct.toFixed(
2
)}%`}
>
<span
className={`inline-flex items-center gap-0.5 ${
driftLoud ? 'text-warning-dark font-semibold' : ''
}`}
>
<IconPulse className="w-3 h-3" />
{formatDriftPct(driftPct)}
</span>
</Tooltip>
)}
{tolerateCount > 0 && (
<Tooltip
title={`Drift accepted ${tolerateCount} time${
tolerateCount === 1 ? '' : 's'
} in last 30 days (human or agent)`}
>
<span className="inline-flex items-center gap-0.5">
<IconFlag className="w-3 h-3" />
{tolerateCount}
</span>
</Tooltip>
)}
{variantCount > 0 && (
<Tooltip
title={`${variantCount} accepted variant${
variantCount === 1 ? '' : 's'
} of the current baseline`}
>
<span className="inline-flex items-center gap-0.5">
<IconCopy className="w-3 h-3" />
{variantCount}
</span>
</Tooltip>
)}
{entry.baseline_change_count > 0 && (
<Tooltip
title={`Baseline updated ${entry.baseline_change_count} time${
entry.baseline_change_count === 1 ? '' : 's'
} since inception`}
>
<span className="font-mono">↻ {entry.baseline_change_count}</span>
</Tooltip>
)}
</div>
)}
</div>
{quarantine && (
<div className="flex items-center justify-between gap-2 text-[10px] text-muted truncate">
<span className="truncate">
{quarantine.created_by
? `by ${quarantine.created_by.first_name || quarantine.created_by.email}`
: 'quarantined'}
</span>
{quarantine.source_run && (
<span className="font-mono shrink-0" title={`From run ${quarantine.source_run.commit_sha}`}>
{quarantinePrNumber
? `PR #${quarantinePrNumber}`
: quarantine.source_run.commit_sha.slice(0, 7)}
</span>
)}
</div>
)}
</div>
</Link>
)
}