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.

45.9 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'

import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { teamLogic } from 'scenes/teamLogic'

import { Breadcrumb } from '~/types'

import {
    visualReviewReposQuarantineCreate,
    visualReviewReposQuarantineExpireCreate,
    visualReviewReposQuarantineList,
    visualReviewReposRetrieve,
    visualReviewRunsApproveCreate,
    visualReviewRunsFinalizeCreate,
    visualReviewRunsLiftOnMergeCreate,
    visualReviewRunsQuarantineLiftsCancelCreate,
    visualReviewRunsQuarantineLiftsList,
    visualReviewRunsRecomputeCreate,
    visualReviewRunsTolerateCreate,
    visualReviewRunsRetrieve,
    visualReviewRunsSnapshotsList,
    visualReviewRunsToleratedHashesList,
} from '../generated/api'
import type {
    QuarantineLiftEntryApi,
    QuarantinedIdentifierEntryApi,
    RepoApi,
    RunApi,
    SnapshotApi,
    ToleratedHashEntryApi,
} from '../generated/api.schemas'
import {
    type CleanQuarantinedGroups,
    groupCleanQuarantinedStories,
    liftOnMergeDisabledReason,
    liftRequestsByIdentifier,
} from '../lib/liftOnMerge'
import { type RecentTolerations, countRecentTolerations } from '../lib/quarantineNudge'
import { repoBreadcrumbs } from '../lib/repoBreadcrumbs'
import { isNotFoundError } from '../lib/repoIds'
import { runPath } from '../lib/repoPaths'
import { isReportingOnlyRun } from '../lib/runPredicates'
import { visualReviewPreferencesLogic } from './visualReviewPreferencesLogic'

export interface VisualReviewRunSceneLogicProps {
    runId: string
    // The repo named in the URL. Links use it until the run's repo loads.
    repoFullName?: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visualReviewRunSceneLogicValues {
    currentProjectId: number | string // teamLogic
    addImagesToComment: boolean // visualReviewPreferencesLogic
    breadcrumbs: Breadcrumb[]
    changedSnapshots: SnapshotApi[]
    cleanQuarantinedGroups: CleanQuarantinedGroups
    cleanQuarantinedSnapshots: SnapshotApi[]
    deepLinkedSnapshot: SnapshotApi | null
    deepLinkedSnapshotLoading: boolean
    failedThumbnails: Set<string>
    hasChanges: boolean
    isApprovingSnapshot: boolean
    isCancellingLift: boolean
    isFinalizing: boolean
    isRecomputing: boolean
    isReportingOnly: boolean
    isRequestingLift: boolean
    isRunInProgress: boolean
    isRunProcessing: boolean
    liftRequestByIdentifier: Record<string, QuarantineLiftEntryApi>
    quarantineLifts: QuarantineLiftEntryApi[]
    quarantineLiftsLoadFailed: boolean
    quarantineLiftsLoading: boolean
    quarantinedIdentifierSet: Set<string>
    quarantinedIdentifiers: QuarantinedIdentifierEntryApi[]
    quarantinedIdentifiersLoadFailed: boolean
    quarantinedIdentifiersLoading: boolean
    quarantinedRunSnapshots: SnapshotApi[]
    quarantinedRunSnapshotsLoadFailed: boolean
    quarantinedRunSnapshotsLoading: boolean
    recentTolerations: RecentTolerations | null
    repo: RepoApi | null
    repoFullName: string | null
    repoLoading: boolean
    run: RunApi | null
    runLoading: boolean
    runNotFound: boolean
    selectedLiftOnMergeDisabledReason: string | null
    selectedLiftRequest: QuarantineLiftEntryApi | null
    selectedSnapshot: SnapshotApi | null
    selectedSnapshotId: string | null
    showCleanQuarantined: boolean
    showQuarantinedThumbnails: boolean
    snapshots: SnapshotApi[]
    snapshotsLoaded: boolean
    snapshotsLoading: boolean
    sortedChangedSnapshots: SnapshotApi[]
    thumbnailBasePath: string | null
    toleratedHashes: ToleratedHashEntryApi[]
    toleratedHashesLoading: boolean
    unreviewedChangesCount: number
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visualReviewRunSceneLogicActions {
    rememberRepo: (
        teamId: number,
        repoFullName: string
    ) => {
        repoFullName: string
        teamId: number
    } // visualReviewPreferencesLogic
    setAddImagesToComment: (enabled: boolean) => {
        enabled: boolean
    } // visualReviewPreferencesLogic
    approveSnapshot: (snapshot: SnapshotApi) => {
        snapshot: SnapshotApi
    }
    approveSnapshotFailure: () => {
        value: true
    }
    approveSnapshotSuccess: () => {
        value: true
    }
    cancelLiftOnMerge: (requestId: string) => {
        requestId: string
    }
    cancelLiftOnMergeFailure: () => {
        value: true
    }
    cancelLiftOnMergeSuccess: () => {
        value: true
    }
    finalizeRun: () => {
        value: true
    }
    finalizeRunFailure: () => {
        value: true
    }
    finalizeRunSuccess: () => {
        value: true
    }
    loadDeepLinkedSnapshot: (snapshotId: string) => string
    loadDeepLinkedSnapshotFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadDeepLinkedSnapshotSuccess: (
        deepLinkedSnapshot: SnapshotApi | null,
        payload?: string
    ) => {
        deepLinkedSnapshot: SnapshotApi | null
        payload?: string
    }
    loadQuarantineLifts: () => any
    loadQuarantineLiftsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadQuarantineLiftsSuccess: (
        quarantineLifts: QuarantineLiftEntryApi[],
        payload?: any
    ) => {
        quarantineLifts: QuarantineLiftEntryApi[]
        payload?: any
    }
    loadQuarantinedIdentifiers: () => any
    loadQuarantinedIdentifiersFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadQuarantinedIdentifiersSuccess: (
        quarantinedIdentifiers: QuarantinedIdentifierEntryApi[],
        payload?: any
    ) => {
        quarantinedIdentifiers: QuarantinedIdentifierEntryApi[]
        payload?: any
    }
    loadQuarantinedRunSnapshots: () => any
    loadQuarantinedRunSnapshotsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadQuarantinedRunSnapshotsSuccess: (
        quarantinedRunSnapshots: SnapshotApi[],
        payload?: any
    ) => {
        quarantinedRunSnapshots: SnapshotApi[]
        payload?: any
    }
    loadRepo: () => any
    loadRepoFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRepoSuccess: (
        repo: RepoApi | null,
        payload?: any
    ) => {
        repo: RepoApi | null
        payload?: any
    }
    loadRun: () => any
    loadRunFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRunSuccess: (
        run: RunApi | null,
        payload?: any
    ) => {
        run: RunApi | null
        payload?: any
    }
    loadSnapshots: () => any
    loadSnapshotsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadSnapshotsSuccess: (
        snapshots: SnapshotApi[],
        payload?: any
    ) => {
        snapshots: SnapshotApi[]
        payload?: any
    }
    loadToleratedHashes: (identifier: string) => string
    loadToleratedHashesFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadToleratedHashesSuccess: (
        toleratedHashes: ToleratedHashEntryApi[],
        payload?: string
    ) => {
        toleratedHashes: ToleratedHashEntryApi[]
        payload?: string
    }
    markAsTolerated: (snapshot: SnapshotApi) => {
        snapshot: SnapshotApi
    }
    markThumbnailFailed: (identifier: string) => {
        identifier: string
    }
    quarantineSnapshot: (
        reason: string,
        identifiers: string[],
        expiresAt: string | null,
        sourceRunId?: string | null,
        notifyOwners?: boolean
    ) => {
        expiresAt: string | null
        identifiers: string[]
        notifyOwners: boolean
        reason: string
        sourceRunId: string | null
    }
    recomputeRun: () => {
        value: true
    }
    recomputeRunFailure: () => {
        value: true
    }
    recomputeRunSuccess: () => {
        value: true
    }
    requestLiftOnMerge: (snapshot: SnapshotApi) => {
        snapshot: SnapshotApi
    }
    requestLiftOnMergeFailure: () => {
        value: true
    }
    requestLiftOnMergeSuccess: () => {
        value: true
    }
    setRunNotFound: () => {
        value: true
    }
    setSelectedSnapshotId: (snapshotId: string | null) => {
        snapshotId: string | null
    }
    toggleCleanQuarantined: () => {
        value: true
    }
    toggleQuarantinedThumbnails: () => {
        value: true
    }
    unquarantineSnapshot: (snapshot: SnapshotApi) => {
        snapshot: SnapshotApi
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visualReviewRunSceneLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        selectedSnapshot: (
            snapshots: SnapshotApi[],
            selectedSnapshotId: string | null,
            quarantinedIdentifierSet: Set<string>,
            deepLinkedSnapshot: SnapshotApi | null
        ) => SnapshotApi | null
        recentTolerations: (
            toleratedHashes: ToleratedHashEntryApi[],
            toleratedHashesLoading: boolean
        ) => RecentTolerations | null
        changedSnapshots: (snapshots: SnapshotApi[]) => SnapshotApi[]
        sortedChangedSnapshots: (changedSnapshots: SnapshotApi[]) => SnapshotApi[]
        hasChanges: (changedSnapshots: SnapshotApi[]) => boolean
        unreviewedChangesCount: (changedSnapshots: SnapshotApi[]) => number
        quarantinedIdentifierSet: (
            quarantinedIdentifiers: QuarantinedIdentifierEntryApi[],
            run: RunApi | null
        ) => Set<string>
        liftRequestByIdentifier: (
            quarantineLifts: QuarantineLiftEntryApi[],
            quarantinedIdentifiers: QuarantinedIdentifierEntryApi[],
            run: RunApi | null
        ) => Record<string, QuarantineLiftEntryApi>
        cleanQuarantinedSnapshots: (quarantinedRunSnapshots: SnapshotApi[]) => SnapshotApi[]
        cleanQuarantinedGroups: (
            cleanQuarantinedSnapshots: SnapshotApi[],
            liftRequestByIdentifier: Record<string, QuarantineLiftEntryApi>,
            quarantinedIdentifiers: QuarantinedIdentifierEntryApi[]
        ) => CleanQuarantinedGroups
        selectedLiftRequest: (
            selectedSnapshot: SnapshotApi | null,
            liftRequestByIdentifier: Record<string, QuarantineLiftEntryApi>
        ) => QuarantineLiftEntryApi | null
        selectedLiftOnMergeDisabledReason: (
            selectedSnapshot: SnapshotApi | null,
            run: RunApi | null,
            quarantineLiftsLoading: boolean,
            quarantineLiftsLoadFailed: boolean
        ) => string | null
        repoFullName: (repo: RepoApi | null, arg: any) => string | null
        thumbnailBasePath: (run: RunApi | null, currentProjectId: number | string) => string | null
        isRunInProgress: (run: RunApi | null) => boolean
        isRunProcessing: (run: RunApi | null) => boolean
        isReportingOnly: (run: RunApi | null) => boolean
        breadcrumbs: (repo: RepoApi | null, repoFullName: string | null) => Breadcrumb[]
    }
}

export type visualReviewRunSceneLogicType = MakeLogicType<
    visualReviewRunSceneLogicValues,
    visualReviewRunSceneLogicActions,
    VisualReviewRunSceneLogicProps,
    visualReviewRunSceneLogicMeta
>

function loadSelectedSnapshotIfMissing(
    values: visualReviewRunSceneLogicType['values'],
    actions: visualReviewRunSceneLogicType['actions']
): void {
    const { selectedSnapshotId } = values
    if (selectedSnapshotId && values.snapshotsLoaded && !values.selectedSnapshot) {
        actions.loadDeepLinkedSnapshot(selectedSnapshotId)
    }
}

export const visualReviewRunSceneLogic = kea<visualReviewRunSceneLogicType>([
    path(['products', 'visual_review', 'frontend', 'scenes', 'visualReviewRunSceneLogic']),
    props({} as VisualReviewRunSceneLogicProps),
    key((props) => props.runId),
    connect(() => ({
        values: [teamLogic, ['currentProjectId'], visualReviewPreferencesLogic, ['addImagesToComment']],
        actions: [visualReviewPreferencesLogic, ['setAddImagesToComment', 'rememberRepo']],
    })),
    actions({
        setRunNotFound: true,
        setSelectedSnapshotId: (snapshotId: string | null) => ({ snapshotId }),
        finalizeRun: true,
        finalizeRunSuccess: true,
        finalizeRunFailure: true,
        approveSnapshot: (snapshot: SnapshotApi) => ({ snapshot }),
        approveSnapshotSuccess: true,
        approveSnapshotFailure: true,
        markAsTolerated: (snapshot: SnapshotApi) => ({ snapshot }),
        quarantineSnapshot: (
            reason: string,
            identifiers: string[],
            expiresAt: string | null,
            sourceRunId: string | null = null,
            notifyOwners: boolean = false
        ) => ({
            reason,
            identifiers,
            expiresAt,
            sourceRunId,
            notifyOwners,
        }),
        unquarantineSnapshot: (snapshot: SnapshotApi) => ({ snapshot }),
        requestLiftOnMerge: (snapshot: SnapshotApi) => ({ snapshot }),
        requestLiftOnMergeSuccess: true,
        requestLiftOnMergeFailure: true,
        cancelLiftOnMerge: (requestId: string) => ({ requestId }),
        cancelLiftOnMergeSuccess: true,
        cancelLiftOnMergeFailure: true,
        recomputeRun: true,
        recomputeRunSuccess: true,
        recomputeRunFailure: true,
        markThumbnailFailed: (identifier: string) => ({ identifier }),
        toggleQuarantinedThumbnails: true,
        toggleCleanQuarantined: true,
    }),
    reducers({
        // kea-loaders keeps the last success when a load fails, which would let the
        // previous snapshot's tolerations drive the quarantine nudge. Clearing at the
        // start, not on failure, also keeps an overtaken failure from wiping newer data.
        toleratedHashes: [
            [] as ToleratedHashEntryApi[],
            {
                loadToleratedHashes: () => [],
            },
        ],
        selectedSnapshotId: [
            null as string | null,
            {
                setSelectedSnapshotId: (_, { snapshotId }) => snapshotId,
            },
        ],
        runNotFound: [
            false,
            {
                setRunNotFound: () => true,
                loadRunSuccess: (state, { run }) => (run ? false : state),
            },
        ],
        snapshotsLoaded: [
            false,
            {
                loadSnapshotsSuccess: () => true,
            },
        ],
        isFinalizing: [
            false,
            {
                finalizeRun: () => true,
                finalizeRunSuccess: () => false,
                finalizeRunFailure: () => false,
            },
        ],
        isApprovingSnapshot: [
            false,
            {
                approveSnapshot: () => true,
                approveSnapshotSuccess: () => false,
                approveSnapshotFailure: () => false,
            },
        ],
        isRecomputing: [
            false,
            {
                recomputeRun: () => true,
                recomputeRunSuccess: () => false,
                recomputeRunFailure: () => false,
            },
        ],
        isRequestingLift: [
            false,
            {
                requestLiftOnMerge: () => true,
                requestLiftOnMergeSuccess: () => false,
                requestLiftOnMergeFailure: () => false,
            },
        ],
        // Busy until the list reloads, so the cancel button of the stale pending entry cannot be clicked again.
        isCancellingLift: [
            false,
            {
                cancelLiftOnMerge: () => true,
                cancelLiftOnMergeFailure: () => false,
                loadQuarantineLiftsSuccess: () => false,
                loadQuarantineLiftsFailure: () => false,
            },
        ],
        quarantineLiftsLoadFailed: [
            false,
            {
                loadQuarantineLifts: () => false,
                loadQuarantineLiftsSuccess: () => false,
                loadQuarantineLiftsFailure: () => true,
            },
        ],
        quarantinedIdentifiersLoadFailed: [
            false,
            {
                loadQuarantinedIdentifiers: () => false,
                loadQuarantinedIdentifiersSuccess: () => false,
                loadQuarantinedIdentifiersFailure: () => true,
            },
        ],
        quarantinedRunSnapshotsLoadFailed: [
            false,
            {
                loadQuarantinedRunSnapshots: () => false,
                loadQuarantinedRunSnapshotsSuccess: () => false,
                loadQuarantinedRunSnapshotsFailure: () => true,
            },
        ],
        failedThumbnails: [
            new Set<string>() as Set<string>,
            {
                markThumbnailFailed: (state: Set<string>, { identifier }: { identifier: string }) => {
                    const next = new Set(state)
                    next.add(identifier)
                    return next
                },
            },
        ],
        showQuarantinedThumbnails: [
            false,
            {
                toggleQuarantinedThumbnails: (state) => !state,
            },
        ],
        // Closed by default: most runs render some quarantined stories clean, and only the author of a
        // fix for one of them needs the list.
        showCleanQuarantined: [
            false,
            {
                toggleCleanQuarantined: (state) => !state,
            },
        ],
    }),
    loaders(({ actions, props, values }) => ({
        run: [
            null as RunApi | null,
            {
                loadRun: async () => {
                    try {
                        return await visualReviewRunsRetrieve(String(values.currentProjectId), props.runId)
                    } catch (error) {
                        if (isNotFoundError(error)) {
                            actions.setRunNotFound()
                            return null
                        }
                        throw error
                    }
                },
            },
        ],
        snapshots: [
            [] as SnapshotApi[],
            {
                loadSnapshots: async () => {
                    try {
                        const response = await visualReviewRunsSnapshotsList(
                            String(values.currentProjectId),
                            props.runId,
                            {
                                limit: 10000,
                                include_quarantined: true,
                                exclude_unchanged: true,
                            }
                        )
                        return response.results
                    } catch (error) {
                        // The run itself is missing, and loadRun renders NotFound for it.
                        if (isNotFoundError(error)) {
                            return []
                        }
                        throw error
                    }
                },
            },
        ],
        // A deep link can name an unchanged snapshot (the snapshot history page links to every
        // baseline move), which the changes-only list above does not hold.
        deepLinkedSnapshot: [
            null as SnapshotApi | null,
            {
                loadDeepLinkedSnapshot: async (snapshotId: string, breakpoint) => {
                    let response
                    try {
                        response = await visualReviewRunsSnapshotsList(String(values.currentProjectId), props.runId, {
                            include_quarantined: true,
                            snapshot_id: snapshotId,
                        })
                    } catch (error) {
                        if (isNotFoundError(error)) {
                            return null
                        }
                        throw error
                    }
                    breakpoint()
                    // The user may have gone back to a snapshot cached here, which starts no request.
                    if (values.selectedSnapshotId !== snapshotId) {
                        return values.deepLinkedSnapshot
                    }
                    return response.results[0] ?? null
                },
            },
        ],
        repo: [
            null as RepoApi | null,
            {
                loadRepo: async () => {
                    const run = values.run
                    if (!run) {
                        return null
                    }
                    return visualReviewReposRetrieve(String(values.currentProjectId), run.repo_id)
                },
            },
        ],
        toleratedHashes: [
            [] as ToleratedHashEntryApi[],
            {
                loadToleratedHashes: async (identifier: string, breakpoint) => {
                    const response = await visualReviewRunsToleratedHashesList(
                        String(values.currentProjectId),
                        props.runId,
                        { identifier }
                    )
                    // Drop a response that a newer selection overtook, so it can't land last.
                    breakpoint()
                    return response.results
                },
            },
        ],
        quarantinedIdentifiers: [
            [] as QuarantinedIdentifierEntryApi[],
            {
                loadQuarantinedIdentifiers: async () => {
                    const run = values.run
                    if (!run) {
                        return []
                    }
                    // The endpoint pages at 100. A quarantine past the first page would drop its lift request.
                    const response = await visualReviewReposQuarantineList(
                        String(values.currentProjectId),
                        run.repo_id,
                        { run_type: run.run_type, limit: 1000 }
                    )
                    return response.results
                },
            },
        ],
        // The changes-only list leaves out a quarantined story that rendered unchanged, which is the
        // story a fix for the flake produces and the one to request a lift for.
        quarantinedRunSnapshots: [
            [] as SnapshotApi[],
            {
                loadQuarantinedRunSnapshots: async () => {
                    if (!values.run?.pr_number) {
                        return []
                    }
                    const response = await visualReviewRunsSnapshotsList(String(values.currentProjectId), props.runId, {
                        limit: 1000,
                        include_quarantined: true,
                        quarantined_only: true,
                    })
                    return response.results
                },
            },
        ],
        quarantineLifts: [
            [] as QuarantineLiftEntryApi[],
            {
                loadQuarantineLifts: async () => {
                    if (!values.run?.pr_number) {
                        return []
                    }
                    return visualReviewRunsQuarantineLiftsList(String(values.currentProjectId), props.runId)
                },
            },
        ],
    })),
    selectors({
        selectedSnapshot: [
            (s) => [s.snapshots, s.selectedSnapshotId, s.quarantinedIdentifierSet, s.deepLinkedSnapshot],
            (
                snapshots: SnapshotApi[],
                selectedSnapshotId: string | null,
                quarantinedIdentifierSet: Set<string>,
                deepLinkedSnapshot: SnapshotApi | null
            ): SnapshotApi | null => {
                if (selectedSnapshotId) {
                    return (
                        snapshots.find((s) => s.id === selectedSnapshotId) ||
                        (deepLinkedSnapshot?.id === selectedSnapshotId ? deepLinkedSnapshot : null)
                    )
                }
                const changed = snapshots.filter((s) => s.result !== 'unchanged')
                const changedNotQuarantined = changed.filter((s) => !quarantinedIdentifierSet.has(s.identifier))
                return changedNotQuarantined[0] || changed[0] || snapshots[0] || null
            },
        ],
        // Null while loading, so the list of a previous snapshot never drives the quarantine nudge.
        recentTolerations: [
            (s) => [s.toleratedHashes, s.toleratedHashesLoading],
            (toleratedHashes: ToleratedHashEntryApi[], toleratedHashesLoading: boolean): RecentTolerations | null =>
                toleratedHashesLoading ? null : countRecentTolerations(toleratedHashes, dayjs()),
        ],
        changedSnapshots: [
            (s) => [s.snapshots],
            (snapshots: SnapshotApi[]): SnapshotApi[] => snapshots.filter((s) => s.result !== 'unchanged'),
        ],
        sortedChangedSnapshots: [
            (s) => [s.changedSnapshots],
            (changedSnapshots: SnapshotApi[]): SnapshotApi[] => {
                // Group by base identifier (strip theme suffix like --dark / --light)
                const getBaseIdentifier = (identifier: string): string => {
                    const parts = identifier.split('--')
                    const last = parts[parts.length - 1]
                    if (last === 'dark' || last === 'light') {
                        return parts.slice(0, -1).join('--')
                    }
                    return identifier
                }

                // Group snapshots by base identifier
                const groups = new Map<string, SnapshotApi[]>()
                for (const snapshot of changedSnapshots) {
                    const base = getBaseIdentifier(snapshot.identifier)
                    const group = groups.get(base) || []
                    group.push(snapshot)
                    groups.set(base, group)
                }

                // 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(severity))
                    const maxB = Math.max(...b.map(severity))
                    return maxB - maxA
                })

                return sortedGroups.flat()
            },
        ],
        hasChanges: [
            (s) => [s.changedSnapshots],
            (changedSnapshots: SnapshotApi[]): boolean => changedSnapshots.length > 0,
        ],
        unreviewedChangesCount: [
            (s) => [s.changedSnapshots],
            (changedSnapshots: SnapshotApi[]): number =>
                changedSnapshots.filter((s) => s.review_state !== 'approved' && s.review_state !== 'tolerated').length,
        ],
        quarantinedIdentifierSet: [
            (s) => [s.quarantinedIdentifiers, s.run],
            (quarantinedIdentifiers: QuarantinedIdentifierEntryApi[], run: RunApi | null): Set<string> =>
                new Set(
                    quarantinedIdentifiers
                        .filter(
                            (q: QuarantinedIdentifierEntryApi) =>
                                q.run_type === run?.run_type && (!q.expires_at || new Date(q.expires_at) > new Date())
                        )
                        .map((q: QuarantinedIdentifierEntryApi) => q.identifier)
                ),
        ],
        // Lift requests cover the whole pull request, which can hold runs of other run types. A request
        // made under an earlier quarantine of the same story does not describe the active one, even an
        // applied request, which would otherwise show "Quarantine lifted" for the new quarantine.
        liftRequestByIdentifier: [
            (s) => [s.quarantineLifts, s.quarantinedIdentifiers, s.run],
            (
                quarantineLifts: QuarantineLiftEntryApi[],
                quarantinedIdentifiers: QuarantinedIdentifierEntryApi[],
                run: RunApi | null
            ): Record<string, QuarantineLiftEntryApi> => {
                const activeQuarantineIds = new Set(quarantinedIdentifiers.map((q) => q.id))
                return liftRequestsByIdentifier(
                    quarantineLifts.filter(
                        (r) => r.run_type === run?.run_type && activeQuarantineIds.has(r.quarantine_id)
                    )
                )
            },
        ],
        cleanQuarantinedSnapshots: [
            (s) => [s.quarantinedRunSnapshots],
            // `unchanged` also covers tolerated variants, and a lift needs the exact baseline picture.
            (quarantinedRunSnapshots: SnapshotApi[]): SnapshotApi[] =>
                quarantinedRunSnapshots.filter((s) => {
                    const renderedHash = s.current_artifact?.content_hash
                    const baselineHash = s.baseline_artifact?.content_hash
                    return s.result === 'unchanged' && (!renderedHash || !baselineHash || renderedHash === baselineHash)
                }),
        ],
        cleanQuarantinedGroups: [
            (s) => [s.cleanQuarantinedSnapshots, s.liftRequestByIdentifier, s.quarantinedIdentifiers],
            (
                cleanQuarantinedSnapshots: SnapshotApi[],
                liftRequestByIdentifier: Record<string, QuarantineLiftEntryApi>,
                quarantinedIdentifiers: QuarantinedIdentifierEntryApi[]
            ): CleanQuarantinedGroups =>
                groupCleanQuarantinedStories(
                    cleanQuarantinedSnapshots,
                    liftRequestByIdentifier,
                    quarantinedIdentifiers
                ),
        ],
        selectedLiftRequest: [
            (s) => [s.selectedSnapshot, s.liftRequestByIdentifier],
            (
                selectedSnapshot: SnapshotApi | null,
                liftRequestByIdentifier: Record<string, QuarantineLiftEntryApi>
            ): QuarantineLiftEntryApi | null =>
                selectedSnapshot ? (liftRequestByIdentifier[selectedSnapshot.identifier] ?? null) : null,
        ],
        selectedLiftOnMergeDisabledReason: [
            (s) => [s.selectedSnapshot, s.run, s.quarantineLiftsLoading, s.quarantineLiftsLoadFailed],
            (
                selectedSnapshot: SnapshotApi | null,
                run: RunApi | null,
                quarantineLiftsLoading: boolean,
                quarantineLiftsLoadFailed: boolean
            ): string | null => {
                // Until the list arrives, a pending request for this story can exist without showing.
                if (quarantineLiftsLoading) {
                    return 'Loading the lift requests of this pull request'
                }
                if (quarantineLiftsLoadFailed) {
                    return 'Could not load the lift requests of this pull request. Refresh the page.'
                }
                if (run?.is_stale) {
                    return 'Request the lift from the latest run of this pull request'
                }
                return selectedSnapshot ? liftOnMergeDisabledReason(selectedSnapshot) : null
            },
        ],
        // The URL can name another repo after a rename or a hand edit, so the run's own repo wins once it loads.
        repoFullName: [
            (s) => [s.repo, (_, p) => p.repoFullName],
            (repo: RepoApi | null, repoFullName: string | undefined): string | null =>
                repo?.repo_full_name || repoFullName || null,
        ],
        thumbnailBasePath: [
            (s) => [s.run, s.currentProjectId],
            (run: RunApi | null, projectId: number | string): string | null => {
                if (!run || !projectId) {
                    return null
                }
                return `/api/projects/${projectId}/visual_review/repos/${run.repo_id}/thumbnails`
            },
        ],
        isRunInProgress: [
            (s) => [s.run],
            (run: RunApi | null): boolean => run?.status === 'pending' || run?.status === 'processing',
        ],
        isRunProcessing: [(s) => [s.run], (run: RunApi | null): boolean => run?.status === 'processing'],
        isReportingOnly: [(s) => [s.run], (run: RunApi | null): boolean => isReportingOnlyRun(run)],
        // The branch names the run in the page's own trail, so the top bar stops at the repository like the tabs do.
        breadcrumbs: [
            (s) => [s.repo, s.repoFullName],
            (repo: RepoApi | null, repoFullName: string | null): Breadcrumb[] =>
                repoBreadcrumbs(repo?.repo_full_name ?? repoFullName),
        ],
    }),
    listeners(({ actions, values, props }) => ({
        setSelectedSnapshotId: () => {
            const snapshot = values.selectedSnapshot
            if (snapshot) {
                actions.loadToleratedHashes(snapshot.identifier)
            }
            loadSelectedSnapshotIfMissing(values, actions)
        },
        loadDeepLinkedSnapshotSuccess: () => {
            const snapshot = values.selectedSnapshot
            if (snapshot) {
                actions.loadToleratedHashes(snapshot.identifier)
            }
        },
        loadRunSuccess: ({ run }) => {
            if (!run) {
                return
            }
            actions.loadRepo()
            actions.loadQuarantinedIdentifiers()
            actions.loadQuarantineLifts()
            actions.loadQuarantinedRunSnapshots()
        },
        loadRepoSuccess: ({ repo }) => {
            if (!repo) {
                return
            }
            actions.rememberRepo(repo.team_id, repo.repo_full_name)
            // The repo request can finish after the user moved on while this logic is still mounted.
            const stillOnThisRun = router.values.location.pathname.endsWith(`/runs/${props.runId}`)
            if (
                stillOnThisRun &&
                props.repoFullName &&
                props.repoFullName.toLowerCase() !== repo.repo_full_name.toLowerCase()
            ) {
                router.actions.replace(
                    runPath(props.runId, repo.repo_full_name),
                    router.values.searchParams,
                    router.values.hashParams
                )
            }
        },
        loadSnapshotsSuccess: () => {
            const snapshot = values.selectedSnapshot
            if (snapshot) {
                actions.loadToleratedHashes(snapshot.identifier)
            }
            loadSelectedSnapshotIfMissing(values, actions)
        },
        finalizeRun: async () => {
            const { run } = values
            if (!run) {
                return
            }

            try {
                const addImages = values.addImagesToComment
                // approve_all approves any still-pending changes (tolerated ones are left alone),
                // commits the approved baseline, and greens the gate.
                await visualReviewRunsFinalizeCreate(String(values.currentProjectId), props.runId, {
                    approve_all: true,
                    add_images_to_comment_on_pr: addImages,
                })
                actions.finalizeRunSuccess()
                posthog.capture('visual_review_run_finalized', { added_images_to_comment: addImages })
                lemonToast.success(
                    addImages
                        ? 'Run finalized — baseline committed, PR commented with snapshots'
                        : 'Run finalized — baseline committed, PR commented'
                )
                actions.loadRun()
                // Patch in place — refetching all snapshots after finalize made the whole grid
                // flash and lost the user's selection. Server is the source of truth on next mount;
                // we only need the UI to reflect the change immediately.
                actions.loadSnapshotsSuccess(
                    values.snapshots.map((s) =>
                        s.review_state === 'pending' &&
                        s.result !== 'unchanged' &&
                        !values.quarantinedIdentifierSet.has(s.identifier)
                            ? { ...s, review_state: 'approved' }
                            : s
                    )
                )
            } catch (e: any) {
                actions.finalizeRunFailure()
                lemonToast.error(e?.detail || e?.message || 'Failed to finalize run')
            }
        },
        approveSnapshot: async ({ snapshot }) => {
            if (!snapshot.current_artifact?.content_hash) {
                lemonToast.error('No artifact to approve')
                actions.approveSnapshotFailure()
                return
            }

            const approvalPayload = {
                snapshots: [
                    {
                        identifier: snapshot.identifier,
                        new_hash: snapshot.current_artifact.content_hash,
                    },
                ],
            }

            // Find the next pending snapshot in sorted order before the async call.
            // Skip quarantined snapshots when they're hidden, otherwise approving advances
            // onto an unrelated quarantined item the user can't see in the thumbnail strip.
            const sorted = values.sortedChangedSnapshots
            const currentIdx = sorted.findIndex((s) => s.id === snapshot.id)
            const nextPending = sorted
                .slice(currentIdx + 1)
                .find(
                    (s) =>
                        s.review_state === 'pending' &&
                        (values.showQuarantinedThumbnails || !values.quarantinedIdentifierSet.has(s.identifier))
                )

            try {
                await visualReviewRunsApproveCreate(String(values.currentProjectId), props.runId, approvalPayload)
                actions.approveSnapshotSuccess()
                lemonToast.success('Snapshot approved')
                actions.loadRun()
                // Patch only the approved snapshot — refetching the whole list flashed
                // the entire viewer and dropped the user's place.
                actions.loadSnapshotsSuccess(
                    values.snapshots.map((s) => (s.id === snapshot.id ? { ...s, review_state: 'approved' } : s))
                )
                if (nextPending) {
                    actions.setSelectedSnapshotId(nextPending.id)
                }
            } catch (e: any) {
                actions.approveSnapshotFailure()
                lemonToast.error(e?.detail || e?.message || 'Failed to approve snapshot')
            }
        },
        markAsTolerated: async ({ snapshot }) => {
            try {
                await visualReviewRunsTolerateCreate(String(values.currentProjectId), props.runId, {
                    snapshot_id: snapshot.id,
                })
                lemonToast.success('Marked as tolerated')
                actions.loadRun()
                actions.loadSnapshotsSuccess(
                    values.snapshots.map((s) => (s.id === snapshot.id ? { ...s, review_state: 'tolerated' } : s))
                )
            } catch (e: any) {
                lemonToast.error(e?.detail || e?.message || 'Failed to mark as tolerated')
            }
        },
        quarantineSnapshot: async ({ reason, identifiers, expiresAt, sourceRunId, notifyOwners }) => {
            const { run } = values
            if (!run) {
                return
            }
            // Default to the current run when the caller didn't supply a source
            // (the diff viewer doesn't have one for new quarantines). Extending
            // an existing quarantine passes through the prior source so the
            // "what was wrong" link survives across renewals.
            const effectiveSourceRunId = sourceRunId ?? run.id
            try {
                await Promise.all(
                    identifiers.map((identifier, index) =>
                        visualReviewReposQuarantineCreate(String(values.currentProjectId), run.repo_id, run.run_type, {
                            identifier,
                            reason,
                            expires_at: expiresAt,
                            source_run_id: effectiveSourceRunId,
                            // Theme variants of one story share a team, so only the first asks for a notice.
                            notify_owners: notifyOwners && index === 0,
                        })
                    )
                )
                const count = identifiers.length
                lemonToast.success(`${count} identifier${count > 1 ? 's' : ''} quarantined`)
                actions.loadQuarantinedIdentifiers()
            } catch (e: any) {
                lemonToast.error(e?.detail || e?.message || 'Failed to quarantine')
            }
        },
        recomputeRun: async () => {
            try {
                const result = await visualReviewRunsRecomputeCreate(String(values.currentProjectId), props.runId)
                actions.recomputeRunSuccess()

                if (result.ci_rerun_triggered) {
                    lemonToast.success(
                        result.counts_changed ? 'Counts updated, CI job re-triggered' : 'CI job re-triggered'
                    )
                } else if (result.ci_rerun_error) {
                    if (result.counts_changed) {
                        lemonToast.success('Counts updated')
                    }
                    lemonToast.warning(`CI re-trigger failed: ${result.ci_rerun_error}`)
                } else {
                    lemonToast.success(result.counts_changed ? 'Counts updated' : 'No changes needed')
                }
                actions.loadRun()
                actions.loadSnapshots()
            } catch (e: any) {
                actions.recomputeRunFailure()
                lemonToast.error(e?.detail || e?.message || 'Failed to recompute')
            }
        },
        requestLiftOnMerge: async ({ snapshot }) => {
            const { run } = values
            if (!run?.pr_number) {
                actions.requestLiftOnMergeFailure()
                return
            }
            try {
                await visualReviewRunsLiftOnMergeCreate(String(values.currentProjectId), props.runId, {
                    identifier: snapshot.identifier,
                })
                actions.requestLiftOnMergeSuccess()
                posthog.capture('visual_review_lift_on_merge_requested', { snapshot_result: snapshot.result })
                lemonToast.success(`The quarantine lifts when #${run.pr_number} merges`)
                actions.loadQuarantineLifts()
            } catch (e: any) {
                actions.requestLiftOnMergeFailure()
                lemonToast.error(e?.detail || e?.message || 'Could not request the lift. Try again.')
            }
        },
        cancelLiftOnMerge: async ({ requestId }) => {
            try {
                await visualReviewRunsQuarantineLiftsCancelCreate(
                    String(values.currentProjectId),
                    props.runId,
                    requestId
                )
                actions.cancelLiftOnMergeSuccess()
                posthog.capture('visual_review_lift_on_merge_canceled')
                lemonToast.success('Lift canceled. The quarantine stays.')
                actions.loadQuarantineLifts()
            } catch (e: any) {
                actions.cancelLiftOnMergeFailure()
                lemonToast.error(e?.detail || e?.message || 'Could not cancel the lift. Try again.')
                // The request may have been applied or cancelled elsewhere since the page loaded.
                actions.loadQuarantineLifts()
            }
        },
        unquarantineSnapshot: async ({ snapshot }) => {
            const { run } = values
            if (!run) {
                return
            }
            try {
                await visualReviewReposQuarantineExpireCreate(
                    String(values.currentProjectId),
                    run.repo_id,
                    run.run_type,
                    { identifier: snapshot.identifier }
                )
                lemonToast.success('Identifier unquarantined — future runs will gate on it again')
                actions.loadQuarantinedIdentifiers()
            } catch (e: any) {
                lemonToast.error(e?.detail || e?.message || 'Failed to unquarantine')
            }
        },
    })),
    urlToAction(({ actions, values, props }) => ({
        '/visual-review/repos/:repoOwner/:repoName/runs/:runId': ({ runId }, searchParams, hashParams) => {
            if (runId !== props.runId) {
                return
            }
            // Old PR comments carry the selection as `?snapshot=`, so read it when the hash has none.
            const snapshot = hashParams.snapshot ?? searchParams.snapshot
            if (snapshot && snapshot !== values.selectedSnapshotId) {
                actions.setSelectedSnapshotId(snapshot)
            }
        },
    })),
    actionToUrl(({ props, values }) => ({
        setSelectedSnapshotId: ({ snapshotId }) => {
            const path = runPath(props.runId, values.repoFullName ?? undefined)
            // The hash now carries the selection, so an old `?snapshot=` must not outlive it.
            const { snapshot: _oldSnapshot, ...searchParams } = router.values.searchParams
            if (snapshotId) {
                return [path, searchParams, { snapshot: snapshotId }]
            }
            return [path, searchParams]
        },
    })),
    afterMount(({ actions }) => {
        actions.loadRun()
        actions.loadSnapshots()
    }),
])