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.

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

import { IconBell, IconCheck, IconInfo } from '@posthog/icons'
import { LemonButton, Tooltip } from '@posthog/lemon-ui'
import { useAnimatedNumber } from '@posthog/quill-charts'

import { Spinner } from 'lib/lemon-ui/Spinner'
import { humanFriendlyNumber } from 'lib/utils/numbers'

import { type RecalculationPayload, experimentMetricsLogic } from '~/scenes/experiments/experimentMetricsLogic'
import { experimentResultsNotificationLogic } from '~/scenes/experiments/experimentResultsNotificationLogic'
import { useRetryCountdownLabel } from '~/scenes/experiments/MetricsView/shared/MetricRetryState'
import { Experiment } from '~/types'

/**
 * Status line for an in-flight recalculation. Renders only while a run is actually executing
 * (`cold` / `refreshing`); loading-from-latest and terminal states show nothing — the metric rows
 * carry their own loading and error affordances. ExperimentView renders it once the experiment has metrics.
 */
export function RecalculationStatus({ experiment }: { experiment: Experiment }): JSX.Element | null {
    const { recalculationDisplayState, currentRecalculation, liveRowsProgress, metricRetries, nextRetryAt } = useValues(
        experimentMetricsLogic({ experiment })
    )
    /**
     * Mounted here rather than inside the in-flight branch so the finish-edge subscription that
     * fires the browser notification is still alive when the bar disappears on the terminal state.
     */
    const notificationLogic = experimentResultsNotificationLogic({ experiment })
    const { notifyWhenResultsReady } = useValues(notificationLogic)
    const { subscribeToResultsNotification } = useActions(notificationLogic)

    if (recalculationDisplayState !== 'cold' && recalculationDisplayState !== 'refreshing') {
        return null
    }
    return (
        <InFlightStatus
            recalculation={currentRecalculation}
            liveRowsProgress={liveRowsProgress}
            retryingCount={Object.keys(metricRetries).length}
            nextRetryAt={nextRetryAt}
            notifyWhenResultsReady={notifyWhenResultsReady}
            onSubscribe={subscribeToResultsNotification}
        />
    )
}

function InFlightStatus({
    recalculation,
    liveRowsProgress,
    retryingCount,
    nextRetryAt,
    notifyWhenResultsReady,
    onSubscribe,
}: {
    recalculation: RecalculationPayload | null
    liveRowsProgress: { recalculationId: string; rowsRead: number; estimatedRows: number } | null
    retryingCount: number
    nextRetryAt: string | null
    notifyWhenResultsReady: boolean
    onSubscribe: () => void
}): JSX.Element {
    const succeeded = recalculation?.completed_metrics ?? 0
    const failed = recalculation?.failed_metrics ?? 0
    const total = recalculation?.total_metrics ?? 0
    const nextRetryLabel = useRetryCountdownLabel(nextRetryAt)
    /**
     * Pending (not yet resolved, not currently sampled as running) keeps the segment truthful in those gaps.
     * Retrying metrics are unresolved too, but get their own slice so slow runs read as alive, not stuck.
     */
    const pending = Math.max(0, total - succeeded - failed - retryingCount)
    return (
        <StatusBar>
            <span className="flex flex-wrap items-center gap-x-1.5 gap-y-0.5">
                <Spinner textColored className="text-sm text-accent" />
                <CountsSegment pending={pending} retrying={retryingCount} succeeded={succeeded} failed={failed} />
                {retryingCount > 0 && (
                    <span className="text-muted text-xs whitespace-nowrap">· next retry {nextRetryLabel}</span>
                )}
                <span className="text-muted text-xs whitespace-nowrap">· running in the background</span>
                <Tooltip title="We're computing each metric against the latest data. This runs server-side so you can leave this page; results appear as each metric finishes.">
                    <IconInfo className="text-muted text-xs" />
                </Tooltip>
                {liveRowsProgress && liveRowsProgress.recalculationId === recalculation?.id && (
                    <ClimbingRows
                        rowsRead={liveRowsProgress.rowsRead}
                        estimatedRows={liveRowsProgress.estimatedRows || undefined}
                    />
                )}
            </span>
            {notifyWhenResultsReady ? (
                <LemonButton
                    size="xsmall"
                    icon={<IconCheck />}
                    disabledReason="Keep this tab open to get notified"
                    className="ml-auto"
                >
                    We'll notify you
                </LemonButton>
            ) : (
                <LemonButton size="xsmall" icon={<IconBell />} onClick={onSubscribe} className="ml-auto">
                    Notify me
                </LemonButton>
            )}
        </StatusBar>
    )
}

function StatusBar({ children }: { children: React.ReactNode }): JSX.Element {
    return (
        <div className="mb-2 flex min-h-8 w-full flex-wrap items-center gap-2.5 rounded border border-primary bg-surface-secondary px-2.5 py-1 text-sm">
            {children}
        </div>
    )
}

function CountsSegment({
    pending,
    retrying,
    succeeded,
    failed,
}: {
    pending: number
    retrying: number
    succeeded: number
    failed: number
}): JSX.Element {
    // "running" is only shown when the live sample caught a query mid-flight; pending covers the rest.
    const parts: JSX.Element[] = []

    if (pending > 0) {
        parts.push(<span key="pending">{pending} pending</span>)
    }
    if (retrying > 0) {
        parts.push(
            <span key="retrying" className="text-warning">
                {retrying} retrying
            </span>
        )
    }
    parts.push(
        <span key="succeeded" className="text-success">
            {succeeded} succeeded
        </span>
    )
    if (failed > 0) {
        parts.push(
            <span key="failed" className="text-danger">
                {failed} failed
            </span>
        )
    }
    return (
        <span className="flex flex-wrap items-center gap-1 font-medium">
            {parts.map((part, i) => (
                <span key={part.key} className="flex items-center gap-1 whitespace-nowrap">
                    {i > 0 && <span>·</span>}
                    {part}
                </span>
            ))}
        </span>
    )
}

function ClimbingRows({ rowsRead, estimatedRows }: { rowsRead: number; estimatedRows?: number }): JSX.Element {
    const showCeiling = estimatedRows !== undefined && estimatedRows >= rowsRead

    const animatedRowsRead = useAnimatedNumber(rowsRead, 350)
    const animatedEstimatedTotal = useAnimatedNumber(estimatedRows ?? 0, 350)

    return (
        <span className="text-muted text-xs whitespace-nowrap">
            {/* The counts are bare text nodes React tracks individually, and the `showCeiling` one
                comes and goes. Once a page-translation extension replaces them with <font> elements,
                removing one throws removeChild NotFoundError and the rest freeze at the translated
                value (react#11538). Only the numbers opt out of translation. */}
            <span translate="no">
                · {humanFriendlyNumber(animatedRowsRead, 0)}
                {showCeiling && ` / ${humanFriendlyNumber(animatedEstimatedTotal, 0)}`}
            </span>{' '}
            rows read
        </span>
    )
}