Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

35.7 KB
Raw Blame
import { useActions, useValues } from 'kea'
import React from 'react'

import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'
import { IconChevronLeft, IconChevronRight } from '@posthog/icons'
import { LemonButton, LemonCheckbox, LemonSkeleton, Link } from '@posthog/lemon-ui'
import { PostHogCaptureOnViewed } from '@posthog/react'

import { pngHoggie } from 'lib/brand/hoggies'
import { NotFound } from 'lib/components/NotFound'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'
import { KeyboardShortcut } from 'lib/lemon-ui/KeyboardShortcut/KeyboardShortcut'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

import { SceneContent } from '~/layout/scenes/components/SceneContent'

import { CleanQuarantinedSnapshots } from '../components/CleanQuarantinedSnapshots'
import { CleanQuarantinedToggle } from '../components/CleanQuarantinedToggle'
import { SnapshotChangeBadge, hasSnapshotChangeBadge } from '../components/SnapshotChangeBadge'
import { SnapshotDiffViewer } from '../components/SnapshotDiffViewer'
import { SnapshotStatusIndicator } from '../components/SnapshotStatusIndicator'
import { VisualReviewSceneTitle } from '../components/VisualReviewSceneTitle'
import { VisualReviewTabs } from '../components/VisualReviewTabs'
import { VisualReviewTrail } from '../components/VisualReviewTrail'
import type { SnapshotApi } from '../generated/api.schemas'
import { repoFullNameFromParams, runPath, splitRepoFullName } from '../lib/repoPaths'
import { QuillFinalizeRunActions } from './QuillFinalizeRunActions'
import { VisualReviewRunSceneLogicProps, visualReviewRunSceneLogic } from './visualReviewRunSceneLogic'

const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)

export const scene: SceneExport = {
    component: VisualReviewRunScene,
    logic: visualReviewRunSceneLogic,
    paramsToProps: ({ params: { repoOwner, repoName, runId } }): VisualReviewRunSceneLogicProps => ({
        runId: runId || '',
        repoFullName: repoFullNameFromParams(repoOwner, repoName),
    }),
}

/** The repository title, the tabs with Runs active, and the trail from the runs list to this run. */
function RunSceneHeader({
    repoFullName,
    branch,
    actions,
}: {
    repoFullName: string | null
    branch: string | null
    actions?: JSX.Element
}): JSX.Element {
    return (
        <>
            {repoFullName && <VisualReviewSceneTitle repoFullName={repoFullName} activeTab="runs" actions={actions} />}
            {repoFullName && <VisualReviewTabs activeKey="runs" repoFullName={repoFullName} />}
            <VisualReviewTrail
                crumbs={[
                    {
                        label: 'Runs',
                        to: repoFullName
                            ? urls.visualReviewRepoRuns(...splitRepoFullName(repoFullName))
                            : urls.visualReviewRuns(),
                    },
                    ...(branch ? [{ label: branch }] : []),
                ]}
            />
        </>
    )
}

function SnapshotThumbnail({
    snapshot,
    isSelected,
    isQuarantined,
    thumbnailSrc,
    fallbackSrc,
    onThumbnailFailed,
    onClick,
}: {
    snapshot: SnapshotApi
    isSelected: boolean
    isQuarantined: boolean
    thumbnailSrc: string | null
    fallbackSrc: string | null
    onThumbnailFailed: () => void
    onClick: () => void
}): JSX.Element {
    const parts = snapshot.identifier.split('--')
    const theme = parts[parts.length - 1]
    const isTheme = theme === 'dark' || theme === 'light'
    const shortName = parts.length > 1 ? parts.slice(1, isTheme ? -1 : undefined).join(' · ') : snapshot.identifier

    const isReviewed = snapshot.review_state === 'approved' || snapshot.review_state === 'tolerated'
    const showBadge = isReviewed || isQuarantined
    // 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

    return (
        <button
            type="button"
            onClick={onClick}
            data-attr="visual-review-snapshot-thumbnail"
            className="relative flex flex-col items-center gap-1 shrink-0 rounded overflow-hidden p-1.5 transition-colors"
            // eslint-disable-next-line react/forbid-dom-props
            style={{
                background: isSelected ? 'var(--primary-3000-button-bg)' : 'transparent',
                border: '1.5px solid',
                borderColor: isSelected ? 'var(--primary-3000-button-border)' : 'var(--border)',
                boxShadow: isSelected ? '0 3px 0 -1px var(--primary-3000-frame-bg)' : 'none',
            }}
        >
            {showBadge && (
                <>
                    <span
                        className={`absolute top-0 right-0 w-7 h-7 z-10 ${
                            isQuarantined
                                ? 'bg-warning'
                                : snapshot.review_state === 'approved'
                                  ? 'bg-success'
                                  : 'bg-muted'
                        }`}
                        // eslint-disable-next-line react/forbid-dom-props
                        style={{ clipPath: 'polygon(0 0, 100% 0, 100% 100%)' }}
                    />
                    <span className="absolute top-[3px] right-[3px] z-10 text-white text-[10px] leading-none font-bold">
                        {isQuarantined ? 'Q' : snapshot.review_state === 'approved' ? '✓' : '~'}
                    </span>
                </>
            )}
            <div className="w-[84px] h-[58px] rounded-sm overflow-hidden bg-bg-3000 relative">
                {imgSrc ? (
                    <img
                        src={imgSrc}
                        alt=""
                        width={84}
                        height={58}
                        loading="lazy"
                        decoding="async"
                        className={`w-full h-full object-contain ${isQuarantined ? 'grayscale opacity-40' : ''}`}
                        onError={thumbnailSrc ? onThumbnailFailed : undefined}
                    />
                ) : (
                    <div className="w-full h-full flex items-center justify-center">
                        <span className="text-[10px] text-muted">No image</span>
                    </div>
                )}
                {isQuarantined && (
                    <span className="absolute inset-0 flex items-center justify-center z-10 text-[10px] font-semibold text-warning-dark bg-warning/20 uppercase tracking-wide">
                        Quarantined
                    </span>
                )}
            </div>
            <div className="flex items-center gap-1 max-w-[87px] w-full">
                {hasDiff ? (
                    <SnapshotChangeBadge snapshot={snapshot} size="small" />
                ) : (
                    <SnapshotStatusIndicator
                        result={snapshot.result || 'unchanged'}
                        reviewState=""
                        classificationReason={snapshot.classification_reason}
                        size="small"
                    />
                )}
                <span className={`text-[11px] truncate ${isSelected ? 'font-medium' : 'text-muted'}`}>{shortName}</span>
            </div>
        </button>
    )
}

function QuarantinedThumbnailsToggle({
    hiddenCount,
    isExpanded,
    onClick,
}: {
    hiddenCount: number
    isExpanded: boolean
    onClick: () => void
}): JSX.Element {
    const label = isExpanded
        ? 'Hide quarantined'
        : `${hiddenCount} quarantined item${hiddenCount === 1 ? '' : 's'} hidden`

    return (
        <button
            type="button"
            onClick={onClick}
            aria-expanded={isExpanded}
            data-attr="visual-review-toggle-quarantined-thumbnails"
            className="shrink-0 text-xs text-muted hover:text-default hover:underline underline-offset-2 transition-colors"
        >
            {label}
        </button>
    )
}

const PENDING_STALE_THRESHOLD_MS = 15 * 60 * 1000

function RunInProgressEmptyState({
    isProcessing,
    createdAt,
    ciJobUrl,
}: {
    isProcessing: boolean
    createdAt: string
    ciJobUrl?: string
}): JSX.Element {
    const ageMs = Date.now() - new Date(createdAt).getTime()
    const isStale = !isProcessing && ageMs > PENDING_STALE_THRESHOLD_MS

    const title = isProcessing ? 'Processing diffs' : isStale ? 'Still waiting for snapshots' : 'Waiting for snapshots'
    const copy = isProcessing
        ? 'Snapshots are being compared against the baseline. This usually takes under a minute.'
        : isStale
          ? 'This run has been waiting for over 15 minutes. The CI job may have failed before uploading snapshots.'
          : 'This run is waiting for the CI job to upload snapshot artifacts. It will appear here once the upload completes.'

    return (
        <PostHogCaptureOnViewed
            name="visual-review-run-in-progress-shown"
            properties={{ is_processing: isProcessing, is_stale: isStale }}
            className="flex flex-col items-center justify-center text-center gap-3 py-12 px-6"
            data-attr="visual-review-run-in-progress"
        >
            {isStale ? (
                <LemonBanner type="warning" className="w-full max-w-lg mb-4">
                    The CI job hasn't reported back.{' '}
                    {ciJobUrl ? (
                        <Link to={ciJobUrl} target="_blank" className="font-semibold">
                            Check CI logs
                        </Link>
                    ) : (
                        'Check your CI logs to see if the job failed.'
                    )}
                </LemonBanner>
            ) : null}
            <HedgehogMagnifyingGlass className="w-32 h-32" />
            <h2 className="m-0">{title}</h2>
            <p className="max-w-md text-tertiary m-0">
                {copy}
                {isProcessing && <Spinner textColored className="ml-2 align-middle" />}
            </p>
        </PostHogCaptureOnViewed>
    )
}

export function VisualReviewRunScene(): JSX.Element {
    const {
        run,
        snapshots,
        snapshotsLoading,
        deepLinkedSnapshotLoading,
        selectedSnapshot,
        selectedSnapshotId,
        sortedChangedSnapshots,
        toleratedHashes,
        toleratedHashesLoading,
        recentTolerations,
        quarantinedIdentifiers,
        quarantinedIdentifierSet,
        showQuarantinedThumbnails,
        cleanQuarantinedSnapshots,
        cleanQuarantinedGroups,
        showCleanQuarantined,
        quarantinedRunSnapshotsLoading,
        quarantinedRunSnapshotsLoadFailed,
        quarantineLiftsLoading,
        quarantineLiftsLoadFailed,
        quarantinedIdentifiersLoading,
        quarantinedIdentifiersLoadFailed,
        repoFullName,
        isFinalizing,
        isApprovingSnapshot,
        isRecomputing,
        isRequestingLift,
        isCancellingLift,
        selectedLiftRequest,
        selectedLiftOnMergeDisabledReason,
        isRunInProgress,
        isRunProcessing,
        isReportingOnly,
        failedThumbnails,
        thumbnailBasePath,
        addImagesToComment,
        runNotFound,
    } = useValues(visualReviewRunSceneLogic)
    const {
        setSelectedSnapshotId,
        finalizeRun,
        approveSnapshot,
        markAsTolerated,
        quarantineSnapshot,
        unquarantineSnapshot,
        requestLiftOnMerge,
        cancelLiftOnMerge,
        recomputeRun,
        markThumbnailFailed,
        toggleQuarantinedThumbnails,
        toggleCleanQuarantined,
        setAddImagesToComment,
    } = useActions(visualReviewRunSceneLogic)
    const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')

    const quarantinedNavCount = sortedChangedSnapshots.filter((s: SnapshotApi) =>
        quarantinedIdentifierSet.has(s.identifier)
    ).length
    const isHiddenQuarantined = (s: SnapshotApi): boolean =>
        quarantinedIdentifierSet.has(s.identifier) && s.id !== selectedSnapshot?.id
    const visibleNavSnapshots = showQuarantinedThumbnails
        ? sortedChangedSnapshots
        : sortedChangedSnapshots.filter((s: SnapshotApi) => !isHiddenQuarantined(s))
    const hiddenQuarantinedCount = sortedChangedSnapshots.length - visibleNavSnapshots.length
    const showQuarantinedToggle = quarantinedNavCount > 0 && (hiddenQuarantinedCount > 0 || showQuarantinedThumbnails)
    // Stays out of view until the quarantined stories load, so the footer never offers an empty list.
    const showCleanQuarantinedToggle =
        !isReportingOnly &&
        !quarantinedRunSnapshotsLoading &&
        (quarantinedRunSnapshotsLoadFailed || cleanQuarantinedSnapshots.length > 0)
    const showFooterToggles = showQuarantinedToggle || showCleanQuarantinedToggle

    // Navigate over what's actually visible — when quarantined items are hidden, next/previous
    // must skip them rather than selecting a hidden quarantined snapshot.
    const currentIndex = selectedSnapshot
        ? visibleNavSnapshots.findIndex((s: SnapshotApi) => s.id === selectedSnapshot.id)
        : -1
    const hasPrevious = currentIndex > 0
    const hasNext = currentIndex >= 0 && currentIndex < visibleNavSnapshots.length - 1

    const goToPrevious = (): void => {
        if (hasPrevious) {
            setSelectedSnapshotId(visibleNavSnapshots[currentIndex - 1].id)
        }
    }

    const goToNext = (): void => {
        if (hasNext) {
            setSelectedSnapshotId(visibleNavSnapshots[currentIndex + 1].id)
        }
    }

    useKeyboardHotkeys(
        {
            p: { action: goToPrevious, disabled: !hasPrevious },
            n: { action: goToNext, disabled: !hasNext },
        },
        [currentIndex, visibleNavSnapshots.length]
    )

    // Show skeleton only on initial load — once `run` is populated, keep showing it
    // even while a background refetch is in flight (e.g. after approve/tolerate),
    // otherwise the whole scene flashes to skeleton on every mutation.
    if (runNotFound) {
        return <NotFound object="visual review run" />
    }

    if (!run) {
        return (
            <SceneContent>
                <RunSceneHeader repoFullName={repoFullName} branch={null} />
                <div className="space-y-4 py-4">
                    <LemonSkeleton className="h-8 w-1/3" />
                    <div className="flex gap-2">
                        <LemonSkeleton className="h-6 w-20" />
                        <LemonSkeleton className="h-6 w-16" />
                        <LemonSkeleton className="h-6 w-16" />
                    </div>
                    <LemonSkeleton className="h-24 w-full" />
                    <LemonSkeleton className="h-64 w-full" />
                </div>
            </SceneContent>
        )
    }

    if (isRunInProgress) {
        return (
            <SceneContent>
                <RunSceneHeader repoFullName={repoFullName} branch={run.branch} />
                <RunInProgressEmptyState
                    isProcessing={isRunProcessing}
                    createdAt={run.created_at}
                    ciJobUrl={run.metadata?.ci_job_url as string | undefined}
                />
            </SceneContent>
        )
    }

    if (run.status === 'failed') {
        return (
            <SceneContent>
                <RunSceneHeader repoFullName={repoFullName} branch={run.branch} />
                <LemonBanner type="error">
                    This run failed to process.{run.error_message ? ` ${run.error_message}` : ''} Check the CI logs for
                    details, or rerun the job to try again.
                </LemonBanner>
            </SceneContent>
        )
    }

    const initialSnapshotsLoading = snapshotsLoading && snapshots.length === 0

    // Quarantined snapshots don't need review — exclude from pending count
    const reviewPending = snapshots.filter(
        (s: SnapshotApi) =>
            s.result !== 'unchanged' && s.review_state === 'pending' && !quarantinedIdentifierSet.has(s.identifier)
    ).length
    const reviewApproved = snapshots.filter((s: SnapshotApi) => s.review_state === 'approved').length
    const reviewTolerated = snapshots.filter((s: SnapshotApi) => s.review_state === 'tolerated').length

    // Diff summary (server-side counts)
    const diffChanged = run.summary.changed
    const diffNew = run.summary.new
    const diffRemoved = run.summary.removed
    const diffTolerated = Math.max(0, (run.summary.tolerated_matched ?? 0) - reviewTolerated)
    const hasChanges = diffChanged > 0 || diffNew > 0 || diffRemoved > 0

    // Predict whether recompute would flip the gate — uses client-side quarantine set
    // which updates immediately, unlike summary.unresolved which requires a recompute round-trip
    const allChangesResolved =
        !initialSnapshotsLoading &&
        run.status === 'completed' &&
        !run.approved &&
        !run.is_stale &&
        hasChanges &&
        snapshots
            .filter((s: SnapshotApi) => s.result !== 'unchanged')
            .every(
                (s: SnapshotApi) =>
                    quarantinedIdentifierSet.has(s.identifier) ||
                    s.review_state === 'tolerated' ||
                    s.review_state === 'approved'
            )

    const hasMore = diffChanged + diffNew + diffRemoved > reviewPending + reviewApproved + reviewTolerated

    // Re-trigger calls the GitHub API `/actions/jobs/{job_id}/rerun`; the backend needs both the
    // job ID and the workflow run ID (it binds the rerun to the originating run), wired in via
    // `JOB_CHECK_RUN_ID` and `GITHUB_RUN_ID`. Older runs and forks without those env vars can't
    // be re-triggered — don't offer the banner when the rerun would just error.
    const ciRetriggerUnavailableReason =
        !run.metadata?.github_check_run_id || !run.metadata?.github_run_id
            ? "This run wasn't recorded with a CI job ID, so it can't be re-triggered. Push a new commit to re-run CI."
            : undefined

    const handleApproveSnapshot = (): void => {
        if (selectedSnapshot) {
            approveSnapshot(selectedSnapshot)
        }
    }

    return (
        <SceneContent>
            <RunSceneHeader
                repoFullName={repoFullName}
                branch={run.branch}
                actions={
                    !isReportingOnly && !run.approved && !run.is_stale && (reviewPending > 0 || reviewApproved > 0) ? (
                        todayRailNav ? (
                            <QuillFinalizeRunActions
                                addImagesToComment={addImagesToComment}
                                setAddImagesToComment={setAddImagesToComment}
                                isFinalizing={isFinalizing}
                                finalizeRun={finalizeRun}
                                reviewPending={reviewPending}
                            />
                        ) : (
                            <div className="flex flex-wrap items-center gap-2">
                                <LemonCheckbox
                                    checked={addImagesToComment}
                                    onChange={setAddImagesToComment}
                                    disabledReason={isFinalizing ? 'Finalizing…' : undefined}
                                    label="Add snapshots to the PR comment"
                                    info="The PR comment is always posted; tick this to attach the before/after snapshot images to it. Remembered for next time."
                                    data-attr="visual-review-add-images-to-comment"
                                />
                                <LemonButton
                                    type="primary"
                                    onClick={finalizeRun}
                                    loading={isFinalizing}
                                    data-attr="visual-review-finalize-run"
                                >
                                    {reviewPending > 0 ? `Approve ${reviewPending} and finalize` : 'Finalize run'}
                                </LemonButton>
                            </div>
                        )
                    ) : undefined
                }
            />

            {isReportingOnly && (
                <LemonBanner type="info" className="mb-4">
                    Tracking-only run, so there's nothing to approve. Default-branch pushes and merge-queue runs record
                    visual changes for history and report them to GitHub as a non-blocking status.
                </LemonBanner>
            )}

            {run.is_stale && (
                <LemonBanner type="warning" className="mb-4">
                    This run has been superseded by a newer run.{' '}
                    {run.superseded_by_id && (
                        <Link to={runPath(run.superseded_by_id, repoFullName ?? undefined)} className="font-semibold">
                            View latest run
                        </Link>
                    )}
                </LemonBanner>
            )}

            {!isReportingOnly && allChangesResolved && reviewApproved === 0 && !ciRetriggerUnavailableReason && (
                <LemonBanner
                    type="info"
                    className="mb-4"
                    action={{
                        children: 'Re-trigger CI',
                        loading: isRecomputing,
                        onClick: recomputeRun,
                        'data-attr': 'visual-review-recompute-run',
                    }}
                >
                    All changes are resolved by tolerating or quarantining — re-trigger to update the commit status and
                    pass the gate. (No baseline commit needed; approved changes are shipped via Finalize run.)
                </LemonBanner>
            )}

            {/* Snapshots panel — thumbnail strip as nav, diff viewer as body */}
            <div className="border rounded-lg overflow-hidden">
                {/* Header: summary + thumbnail strip */}
                <div className="bg-bg-light border-b">
                    <div className="flex flex-wrap items-center justify-between gap-2 px-3 pt-3 pb-2">
                        {initialSnapshotsLoading ? (
                            <>
                                <LemonSkeleton className="h-4 w-40" />
                                <LemonSkeleton className="h-4 w-40" />
                            </>
                        ) : (
                            <>
                                {/* Review summary (left) — what humans decided */}
                                <span className="text-xs text-muted flex flex-wrap items-center gap-1.5">
                                    <span className="font-semibold text-default">Review</span>
                                    {[
                                        reviewPending > 0 && (
                                            <span key="pend">
                                                <span className="font-semibold">{reviewPending}</span>
                                                {hasMore ? '+' : ''} pending
                                            </span>
                                        ),
                                        reviewApproved > 0 && (
                                            <span key="appr" className="text-success">
                                                {reviewApproved} approved
                                            </span>
                                        ),
                                        reviewTolerated > 0 && <span key="tol">{reviewTolerated} tolerated</span>,
                                    ]
                                        .filter(Boolean)
                                        .reduce<React.ReactNode[]>(
                                            (acc, el, i) => (i === 0 ? [el] : [...acc, ' · ', el]),
                                            []
                                        )}
                                </span>
                                {/* Diff summary (right) — what the system found */}
                                <span className="text-xs text-muted flex flex-wrap items-center gap-1.5">
                                    <span className="font-semibold text-default">Diff</span>
                                    {[
                                        diffChanged > 0 && (
                                            <span key="ch" className="text-warning-dark">
                                                {diffChanged} changed
                                            </span>
                                        ),
                                        diffNew > 0 && (
                                            <span key="new" className="text-success">
                                                {diffNew} added
                                            </span>
                                        ),
                                        diffRemoved > 0 && (
                                            <span key="rm" className="text-danger">
                                                {diffRemoved} removed
                                            </span>
                                        ),
                                        diffTolerated > 0 && <span key="tol">{diffTolerated} auto-tolerated</span>,
                                    ]
                                        .filter(Boolean)
                                        .reduce<React.ReactNode[]>(
                                            (acc, el, i) => (i === 0 ? [el] : [...acc, ' · ', el]),
                                            []
                                        )}
                                </span>
                            </>
                        )}
                    </div>

                    {sortedChangedSnapshots.length > 0 && (
                        <div className="flex gap-1.5 overflow-x-auto px-3 pb-3">
                            {visibleNavSnapshots.map((snapshot: SnapshotApi) => {
                                const hasThumbnail = thumbnailBasePath && !failedThumbnails.has(snapshot.identifier)
                                return (
                                    <SnapshotThumbnail
                                        key={snapshot.id}
                                        snapshot={snapshot}
                                        isSelected={selectedSnapshot?.id === snapshot.id}
                                        isQuarantined={quarantinedIdentifierSet.has(snapshot.identifier)}
                                        thumbnailSrc={
                                            hasThumbnail
                                                ? `${thumbnailBasePath}/${encodeURIComponent(snapshot.identifier)}/`
                                                : null
                                        }
                                        fallbackSrc={snapshot.current_artifact?.download_url ?? null}
                                        onThumbnailFailed={() => markThumbnailFailed(snapshot.identifier)}
                                        onClick={() => setSelectedSnapshotId(snapshot.id)}
                                    />
                                )
                            })}
                        </div>
                    )}

                    {/* Pagination — below thumbnails, right-aligned */}
                    {(showFooterToggles || sortedChangedSnapshots.length > 1) && (
                        <div
                            className={`flex flex-wrap items-center gap-2 px-3 pb-2 ${
                                showFooterToggles ? 'justify-between' : 'justify-end'
                            }`}
                        >
                            {showFooterToggles && (
                                <div className="flex flex-wrap items-center gap-1.5 text-xs text-muted">
                                    {showQuarantinedToggle && (
                                        <QuarantinedThumbnailsToggle
                                            hiddenCount={hiddenQuarantinedCount}
                                            isExpanded={showQuarantinedThumbnails}
                                            onClick={toggleQuarantinedThumbnails}
                                        />
                                    )}
                                    {showQuarantinedToggle && showCleanQuarantinedToggle && <span>·</span>}
                                    {showCleanQuarantinedToggle && (
                                        <CleanQuarantinedToggle
                                            cleanCount={cleanQuarantinedSnapshots.length}
                                            loadFailed={quarantinedRunSnapshotsLoadFailed}
                                            isExpanded={showCleanQuarantined}
                                            onClick={toggleCleanQuarantined}
                                        />
                                    )}
                                </div>
                            )}
                            {visibleNavSnapshots.length > 1 && (
                                <div className="flex items-center gap-2">
                                    <LemonButton
                                        size="xsmall"
                                        icon={<IconChevronLeft />}
                                        sideIcon={<KeyboardShortcut p />}
                                        onClick={goToPrevious}
                                        disabledReason={!hasPrevious ? 'No previous snapshot' : undefined}
                                        data-attr="visual-review-snapshot-previous"
                                    >
                                        Previous
                                    </LemonButton>
                                    {currentIndex >= 0 && (
                                        <span className="text-xs text-muted">
                                            {currentIndex + 1} of {visibleNavSnapshots.length}
                                        </span>
                                    )}
                                    <LemonButton
                                        size="xsmall"
                                        icon={<KeyboardShortcut n />}
                                        sideIcon={<IconChevronRight />}
                                        onClick={goToNext}
                                        disabledReason={!hasNext ? 'No next snapshot' : undefined}
                                        data-attr="visual-review-snapshot-next"
                                    >
                                        Next
                                    </LemonButton>
                                </div>
                            )}
                        </div>
                    )}

                    {showCleanQuarantinedToggle &&
                        showCleanQuarantined &&
                        // A failed reload keeps the previous rows, which no longer describe this run.
                        !quarantinedRunSnapshotsLoadFailed &&
                        run.pr_number != null && (
                            <CleanQuarantinedSnapshots
                                groups={cleanQuarantinedGroups}
                                prNumber={run.pr_number}
                                // The groups read both lists, so either one still loading or failed leaves them unknown.
                                liftsLoading={quarantineLiftsLoading || quarantinedIdentifiersLoading}
                                liftsLoadFailed={quarantineLiftsLoadFailed || quarantinedIdentifiersLoadFailed}
                                selectedSnapshotId={selectedSnapshotId}
                                onSelect={setSelectedSnapshotId}
                            />
                        )}
                </div>

                {/* Body: diff viewer */}
                <div className="p-4">
                    {selectedSnapshot ? (
                        <SnapshotDiffViewer
                            snapshot={selectedSnapshot}
                            toleratedHashes={toleratedHashes}
                            toleratedHashesLoading={toleratedHashesLoading}
                            recentTolerations={recentTolerations}
                            onApprove={handleApproveSnapshot}
                            isApproving={isApprovingSnapshot}
                            onMarkTolerated={() => markAsTolerated(selectedSnapshot)}
                            quarantineEntry={
                                quarantinedIdentifiers.find(
                                    (q) =>
                                        q.identifier === selectedSnapshot.identifier &&
                                        q.run_type === run.run_type &&
                                        (!q.expires_at || new Date(q.expires_at) > new Date())
                                ) ?? null
                            }
                            onQuarantine={(reason, identifiers, expiresAt, sourceRunId, notifyOwners) =>
                                quarantineSnapshot(reason, identifiers, expiresAt, sourceRunId, notifyOwners)
                            }
                            onUnquarantine={() => unquarantineSnapshot(selectedSnapshot)}
                            liftRequest={selectedLiftRequest}
                            liftOnMergeDisabledReason={selectedLiftOnMergeDisabledReason}
                            isRequestingLift={isRequestingLift}
                            isCancellingLift={isCancellingLift}
                            onRequestLiftOnMerge={
                                isReportingOnly ? undefined : () => requestLiftOnMerge(selectedSnapshot)
                            }
                            onCancelLiftOnMerge={cancelLiftOnMerge}
                            commitSha={run.commit_sha}
                            prNumber={run.pr_number}
                            repoFullName={repoFullName}
                            runType={run.run_type}
                            githubRunId={(run.metadata?.github_run_id as string) || null}
                            isReportingOnly={isReportingOnly}
                            isRecomputing={isRecomputing}
                            onRecompute={
                                !isReportingOnly && run.status === 'completed' && !run.approved && !run.is_stale
                                    ? recomputeRun
                                    : undefined
                            }
                            recomputeDisabledReason={
                                ciRetriggerUnavailableReason ??
                                (!allChangesResolved ? 'Re-trigger would not change the outcome' : undefined)
                            }
                        />
                    ) : snapshotsLoading || deepLinkedSnapshotLoading ? (
                        <div className="space-y-3 py-4">
                            <LemonSkeleton className="h-6 w-1/4" />
                            <LemonSkeleton className="h-48 w-full" />
                        </div>
                    ) : selectedSnapshotId ? (
                        <div className="text-center text-muted py-8">
                            Couldn't load this snapshot. It may not belong to this run. Pick a snapshot from the list
                            above, or reload the page.
                        </div>
                    ) : sortedChangedSnapshots.length > 0 ? (
                        <div className="text-center text-muted py-8">Select a snapshot to view details</div>
                    ) : (
                        <div className="text-center text-muted py-8">No visual changes in this run</div>
                    )}
                </div>
            </div>
        </SceneContent>
    )
}

export default VisualReviewRunScene