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.

18.3 KB
Raw Blame
import { useActions, useValues } from 'kea'

import { IconGear } from '@posthog/icons'
import {
    LemonBanner,
    LemonButton,
    LemonInput,
    LemonSegmentedButton,
    LemonSkeleton,
    LemonTable,
    Link,
} from '@posthog/lemon-ui'
import { Button } from '@posthog/quill'

import { NotFound } from 'lib/components/NotFound'
import { dayjs } from 'lib/dayjs'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LinkPrimitive } from 'lib/lemon-ui/Link'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'

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

import { ActivityCell } from '../components/FlakinessActivityCell'
import { MarginCell } from '../components/FlakinessMarginCell'
import { QuarantineCell } from '../components/FlakinessQuarantineCell'
import { StateCell } from '../components/FlakinessStateCell'
import { FLAKE_RATE_DAYS, FlakinessStatRow } from '../components/FlakinessStatRow'
import { QuarantineAction } from '../components/QuarantineAction'
import { SnapshotFacetSidebar } from '../components/SnapshotFacetSidebar'
import { VisualReviewSceneTitle } from '../components/VisualReviewSceneTitle'
import { VisualReviewTabs } from '../components/VisualReviewTabs'
import type { FlakinessEntryApi } from '../generated/api.schemas'
import { repoFullNameFromParams, splitRepoFullName } from '../lib/repoPaths'
import {
    DecoratedEntry,
    VisualReviewFlakinessSceneLogicProps,
    visualReviewFlakinessSceneLogic,
} from './visualReviewFlakinessSceneLogic'

export const scene: SceneExport = {
    component: VisualReviewFlakinessScene,
    logic: visualReviewFlakinessSceneLogic,
    paramsToProps: ({ params: { repoOwner, repoName } }): VisualReviewFlakinessSceneLogicProps => ({
        repoFullName: repoFullNameFromParams(repoOwner, repoName),
    }),
}

function formatLastSeen(lastFlakedAt: string | null | undefined): string {
    if (!lastFlakedAt) {
        return 'never'
    }
    const days = dayjs().diff(dayjs(lastFlakedAt), 'day')
    return days === 0 ? 'today' : `${days}d ago`
}

export function VisualReviewFlakinessScene(): JSX.Element {
    const {
        overview,
        overviewLoading,
        repoNotFound,
        repoFullName,
        filteredEntries,
        statCounts,
        facetGroups,
        facetSelection,
        filters,
        thumbnailBasePath,
        loadError,
        pendingQuarantineKeys,
    } = useValues(visualReviewFlakinessSceneLogic)
    const {
        loadOverview,
        setPreset,
        toggleType,
        toggleArea,
        toggleTeam,
        setSearch,
        setSort,
        clearAllFilters,
        quarantineIdentifier,
        unquarantineIdentifier,
    } = useActions(visualReviewFlakinessSceneLogic)
    const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')

    const isFiltered =
        filters.typeKeys.length > 0 || filters.areas.length > 0 || filters.teams.length > 0 || filters.search.length > 0
    const hasPopulation = (overview?.entries.length ?? 0) > 0

    const confirmLift = (entry: FlakinessEntryApi): void => {
        LemonDialog.open({
            title: 'Lift this quarantine?',
            description: 'Runs will gate on this snapshot again, so a rendering difference will fail them.',
            primaryButton: {
                children: 'Lift quarantine',
                status: 'danger',
                onClick: () => unquarantineIdentifier(entry.identifier, entry.run_type),
            },
            secondaryButton: { children: 'Cancel' },
        })
    }

    if (repoNotFound) {
        return <NotFound object="visual review repo" />
    }

    return (
        <SceneContent>
            <VisualReviewSceneTitle
                repoFullName={repoFullName}
                activeTab="flakiness"
                actions={
                    todayRailNav ? (
                        <Button variant="outline" render={<LinkPrimitive to={urls.visualReviewSettings()} />}>
                            <IconGear />
                            Settings
                        </Button>
                    ) : (
                        <LemonButton size="small" type="secondary" icon={<IconGear />} to={urls.visualReviewSettings()}>
                            Settings
                        </LemonButton>
                    )
                }
            />
            <VisualReviewTabs activeKey="flakiness" repoFullName={repoFullName} />

            <LemonBanner type="info">
                A snapshot that renders differently from its baseline either fails the run, or stays under the diff
                threshold and gets absorbed as an allowed variant. Rates below count the last {FLAKE_RATE_DAYS} days of
                runs on the default branch. Being absorbed is not the same as being stable: it holds only while the diff
                stays under the threshold, which is what the threshold column shows.
            </LemonBanner>

            {!loadError && <FlakinessStatRow counts={statCounts} preset={filters.preset} onChange={setPreset} />}

            {overview && (
                <div className="text-xs text-muted">
                    <span className="font-semibold text-default">
                        {overview.totals.listed.toLocaleString()} snapshots
                    </span>{' '}
                    have something to show here, out of {overview.totals.tracked.toLocaleString()} with a current
                    baseline. The rest passed every run and carry no quarantine.
                </div>
            )}

            {overview?.truncated && (
                <LemonBanner type="info">
                    Showing the {overview.entries.length.toLocaleString()} snapshots that most need attention. This repo
                    has more than the page can list, so filtering here only searches the ones above.
                </LemonBanner>
            )}

            {hasPopulation && (
                <div className="flex items-center gap-2 flex-wrap">
                    <LemonInput
                        type="search"
                        placeholder="Filter by name…"
                        value={filters.search}
                        onChange={(value) => setSearch(value)}
                        className="flex-1 min-w-60"
                    />
                    <span className="text-xs text-muted">Sort</span>
                    <LemonSegmentedButton
                        size="small"
                        value={filters.sort}
                        onChange={(value) => setSort(value as 'failures' | 'recent')}
                        options={[
                            { value: 'failures', label: 'Most failures' },
                            { value: 'recent', label: 'Most recent' },
                        ]}
                    />
                    {isFiltered && (
                        <button
                            type="button"
                            className="text-xs text-muted hover:text-default"
                            onClick={clearAllFilters}
                        >
                            Clear all
                        </button>
                    )}
                </div>
            )}

            {overviewLoading && !overview ? (
                <div className="flex flex-col gap-2">
                    {Array.from({ length: 8 }).map((_, index) => (
                        <LemonSkeleton key={index} className="h-12 w-full" />
                    ))}
                </div>
            ) : loadError ? (
                <LemonBanner
                    type="error"
                    action={{
                        children: 'Try again',
                        onClick: () => loadOverview(),
                        'data-attr': 'visual-review-flakiness-retry',
                    }}
                >
                    Could not load flakiness for this repo. {loadError}
                </LemonBanner>
            ) : !hasPopulation ? (
                <div className="flex flex-col items-center justify-center py-20 gap-2 text-center">
                    <p className="m-0 font-semibold">No snapshot needs attention</p>
                    <p className="m-0 text-xs text-muted max-w-md">
                        Snapshots show up here once one fails the gate on a default-branch run, gets close to the diff
                        threshold, or is quarantined. Small differences well under the threshold are not listed.
                    </p>
                </div>
            ) : (
                <div className="flex flex-col sm:flex-row gap-6 items-start">
                    <SnapshotFacetSidebar
                        groups={facetGroups}
                        selection={facetSelection}
                        onToggle={(group, value) => {
                            if (group === 'type') {
                                toggleType(value)
                            } else if (group === 'area') {
                                toggleArea(value)
                            } else if (group === 'team') {
                                toggleTeam(value)
                            }
                        }}
                    />

                    <div className="flex-1 min-w-0">
                        <LemonTable
                            dataSource={filteredEntries}
                            rowKey={(entry: DecoratedEntry) => `${entry.run_type}::${entry.identifier}`}
                            emptyState="No snapshots match these filters."
                            columns={[
                                {
                                    title: 'Snapshot',
                                    key: 'identifier',
                                    render: (_, entry: DecoratedEntry) => (
                                        <div className="flex gap-2 items-start min-w-0">
                                            {entry.thumbnail_hash && thumbnailBasePath && (
                                                <img
                                                    src={`${thumbnailBasePath}/${encodeURIComponent(
                                                        entry.identifier
                                                    )}/?run_type=${encodeURIComponent(entry.run_type)}`}
                                                    alt=""
                                                    loading="lazy"
                                                    className="w-10 h-7 object-cover rounded border border-border shrink-0"
                                                />
                                            )}
                                            <div className="min-w-0">
                                                <Link
                                                    to={urls.visualReviewSnapshotHistory(
                                                        ...splitRepoFullName(repoFullName),
                                                        entry.run_type,
                                                        entry.identifier
                                                    )}
                                                    className="font-mono text-xs break-all"
                                                >
                                                    {entry.identifier}
                                                </Link>
                                                <div className="text-[11px] text-muted mt-0.5">
                                                    {entry.run_type} · {entry._area}
                                                </div>
                                            </div>
                                        </div>
                                    ),
                                },
                                {
                                    title: 'State',
                                    key: 'state',
                                    width: 108,
                                    render: (_, entry: DecoratedEntry) => <StateCell entry={entry} />,
                                },
                                {
                                    title: 'Failing runs',
                                    key: 'activity',
                                    align: 'right',
                                    width: 190,
                                    render: (_, entry: DecoratedEntry) => <ActivityCell entry={entry} />,
                                },
                                {
                                    title: 'Threshold left',
                                    key: 'margin',
                                    align: 'right',
                                    width: 130,
                                    render: (_, entry: DecoratedEntry) => <MarginCell entry={entry} />,
                                },
                                {
                                    title: 'Last seen',
                                    key: 'last_seen',
                                    align: 'right',
                                    width: 100,
                                    render: (_, entry: DecoratedEntry) => (
                                        // Highlight follows the server's verdict. Deriving it from
                                        // the day count here drifts at the window edge, because
                                        // dayjs truncates to whole days and the server compares
                                        // exact timestamps.
                                        <span
                                            className={`font-mono text-xs ${
                                                entry.hard_count > 0 ? 'text-danger font-semibold' : 'text-muted'
                                            }`}
                                        >
                                            {formatLastSeen(entry.last_flaked_at)}
                                        </span>
                                    ),
                                },
                                {
                                    title: 'Quarantine',
                                    key: 'quarantine',
                                    render: (_, entry: DecoratedEntry) => <QuarantineCell entry={entry} />,
                                },
                                {
                                    title: '',
                                    key: 'actions',
                                    width: 150,
                                    render: (_, entry: DecoratedEntry) => {
                                        const pending = pendingQuarantineKeys.includes(
                                            `${entry.run_type}::${entry.identifier}`
                                        )
                                            ? 'Saving…'
                                            : null
                                        return (
                                            <div className="flex gap-1 justify-end">
                                                <QuarantineAction
                                                    pendingReason={pending}
                                                    identifier={entry.identifier}
                                                    mode={entry.is_quarantined ? 'extend' : 'create'}
                                                    triggerLabel={entry.is_quarantined ? 'Extend' : 'Quarantine'}
                                                    initialReason={entry.quarantine?.reason}
                                                    initialExpiresAt={entry.quarantine?.expires_at}
                                                    sourceRunId={entry.quarantine?.source_run?.id ?? null}
                                                    runType={entry.run_type}
                                                    onQuarantine={(
                                                        reason,
                                                        identifiers,
                                                        expiresAt,
                                                        sourceRunId,
                                                        notifyOwners
                                                    ) => {
                                                        identifiers.forEach((identifier, index) =>
                                                            quarantineIdentifier(
                                                                identifier,
                                                                entry.run_type,
                                                                reason,
                                                                expiresAt,
                                                                sourceRunId,
                                                                // One notice per story, not per theme variant.
                                                                notifyOwners && index === 0
                                                            )
                                                        )
                                                    }}
                                                />
                                                {entry.is_quarantined && (
                                                    <LemonButton
                                                        size="xsmall"
                                                        type="secondary"
                                                        data-attr="visual-review-flakiness-lift"
                                                        onClick={() => confirmLift(entry)}
                                                        loading={!!pending}
                                                        disabledReason={pending ?? undefined}
                                                    >
                                                        Lift
                                                    </LemonButton>
                                                )}
                                            </div>
                                        )
                                    },
                                },
                            ]}
                        />
                    </div>
                </div>
            )}
        </SceneContent>
    )
}

export default VisualReviewFlakinessScene