:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay-vision): show loading indicators for insights and stats (#65786)
Tue Haulund4cd701f61492
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex 47d7c172c165..86f31061c2d9 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'import { router } from 'kea-router'import { IconPencil, IconPlus, IconRefresh, IconSearch, IconTrash } from '@posthog/icons'-import { LemonButton, LemonInput, LemonSwitch, LemonTable, Link } from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonSwitch, LemonTable, Link, Spinner } from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { XRayHog } from 'lib/components/hedgehogs'@@ -51,6 +51,7 @@ export function ReplayScannersScene(): JSX.Element {createdByOptions,hasActiveFilters,scannerStats,+ scannerStatsLoading,} = useValues(replayScannersLogic)const { loadScanners, deleteScanner, toggleScannerEnabled, setScannersFilters, clearFilters } =useActions(replayScannersLogic)@@ -219,7 +220,13 @@ export function ReplayScannersScene(): JSX.Element {action={() => push(urls.replayVisionTemplates())}/>- {(scannerStats?.total ?? 0) > 0 && <VisionMetrics />}+ {(scannerStats?.total ?? 0) > 0 ? (+ <VisionMetrics />+ ) : scannerStatsLoading ? (+ <div className="flex items-center justify-center h-72 bg-bg-light rounded">+ <Spinner className="text-2xl" />+ </div>+ ) : null}<div className="flex flex-col gap-3"><div className="flex items-center gap-2">diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsxindex c2c7867a2e7a..c72f64f4d97d 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerInsightsChart.tsx@@ -1,13 +1,16 @@import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { Spinner } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'-import { Query } from '~/queries/Query/Query'import { InsightVizNode, NodeKind, ProductKey, TrendsQuery } from '~/queries/schema/schema-general'import {AnyPropertyFilter,BaseMathType,ChartDisplayType,+ InsightLogicProps,PropertyFilterType,PropertyMathType,PropertyOperator,@@ -15,6 +18,7 @@ import {import { replayScannerLogic } from '../replayScannerLogic'import { ScannerType } from '../types'+import { VisionInsightChart } from './VisionInsightChart'const RECORDING_OBSERVED_EVENT = '$recording_observed'const COLLECTION_ID = 'replay-vision-scanner-insights'@@ -148,19 +152,35 @@ export function ScannerInsightsChart({scannerId: stringscannerType: ScannerType}): JSX.Element {- const { chartDateFrom, chartDateTo, coverageStats } = useValues(replayScannerLogic({ id: scannerId }))+ const { chartDateFrom, chartDateTo, coverageStats, observationStatsApiLoading } = useValues(+ replayScannerLogic({ id: scannerId })+ )const { setChartDateRange } = useActions(replayScannerLogic({ id: scannerId }))+ // Memoized so a re-render (e.g. stats arriving) can't churn the query and abort an in-flight load.// `tags.productKey` is required for ClickHouse query tagging; without it the runner aborts.- const source: TrendsQuery = {- ...buildQuery(scannerId, scannerType, chartDateFrom, chartDateTo),- tags: { productKey: ProductKey.REPLAY_VISION },- }+ const chartQuery = useMemo<InsightVizNode>(+ () => ({+ kind: NodeKind.InsightVizNode,+ source: {+ ...buildQuery(scannerId, scannerType, chartDateFrom, chartDateTo),+ tags: { productKey: ProductKey.REPLAY_VISION },+ },+ }),+ [scannerId, scannerType, chartDateFrom, chartDateTo]+ )+ const chartInsightProps = useMemo<InsightLogicProps>(+ () => ({+ dashboardItemId: `new-replay-vision-scanner-${scannerId}-chart`,+ dataNodeCollectionId: COLLECTION_ID,+ }),+ [scannerId]+ )return (<div className="border rounded p-4 bg-surface-primary space-y-3"><div className="flex items-baseline justify-between gap-2"><div><div className="text-sm font-medium">{chartTitle(scannerType)}</div>- {coverageStats.totalSessions > 0 && (+ {coverageStats.totalSessions > 0 ? (<div className="text-xs text-muted tabular-nums mt-0.5">Scanned <span className="font-semibold text-default">{coverageStats.recentSessions}</span>{' '}session@@ -168,7 +188,11 @@ export function ScannerInsightsChart({{coverageStats.recentDays === 1 ? '' : 's'} ·{' '}<span className="font-semibold text-default">{coverageStats.totalSessions}</span> total</div>- )}+ ) : observationStatsApiLoading ? (+ <div className="text-xs text-muted mt-0.5 flex items-center gap-1.5">+ <Spinner /> Loading coverage…+ </div>+ ) : null}</div><DateFilterdateFrom={chartDateFrom}@@ -176,20 +200,7 @@ export function ScannerInsightsChart({onChange={(from, to) => setChartDateRange(from ?? null, to ?? null)}/></div>- <div className="InsightCard h-80">- <Query- query={{ kind: NodeKind.InsightVizNode, source } as InsightVizNode}- readOnly- embedded- inSharedMode- context={{- insightProps: {- dashboardItemId: `new-replay-vision-scanner-${scannerId}-chart`,- dataNodeCollectionId: COLLECTION_ID,- },- }}- />- </div>+ <VisionInsightChart query={chartQuery} insightProps={chartInsightProps} className="InsightCard h-80" /></div>)}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsxindex 1b7522b3f1a0..b0f51af763d4 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { IconRefresh, IconRewindPlay } from '@posthog/icons'-import { LemonButton, LemonTable, LemonTag, LemonTagType, Link, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonTable, LemonTag, LemonTagType, Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'@@ -91,6 +91,7 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):hasActiveObservationFilters,availableTags,observationStats,+ observationStatsApiLoading,scanner,triggeringOnDemandObservation,refreshing,@@ -253,7 +254,7 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):</LemonButton></Tooltip></div>- {observationStats.total > 0 && (+ {observationStats.total > 0 ? (<div className="flex gap-4 text-sm"><Metric label="Total" value={observationStats.total} />{observationStats.successRate !== null && (@@ -273,7 +274,11 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):<Metric label="In flight" value={observationStats.inFlight} />)}</div>- )}+ ) : observationStatsApiLoading ? (+ <div className="flex items-center text-muted text-sm">+ <Spinner />+ </div>+ ) : null}</div></div><LemonTablediff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsxindex 25eb7e2bef87..ccce4b0159b0 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx@@ -1,7 +1,7 @@import { useValues } from 'kea'import { useMemo } from 'react'-import { LemonTag } from '@posthog/lemon-ui'+import { LemonTag, Spinner } from '@posthog/lemon-ui'import { BarChart } from '@posthog/quill-charts'import { buildTheme } from 'lib/charts/utils/theme'@@ -37,16 +37,31 @@ function OverviewPanel({)}+// Spinner while stats load, otherwise the empty-state message — shared by the type-specific overview panels.+function PanelEmpty({ loading, message }: { loading: boolean; message: string }): JSX.Element {+ if (loading) {+ return (+ <div className="flex items-center justify-center py-6 text-muted">+ <Spinner />+ </div>+ )+ }+ return <div className="text-muted text-sm">{message}</div>+}+function MonitorOverview({ scannerId }: { scannerId: string }): JSX.Element {- const { monitorStats, hasActiveObservationFilters } = useValues(replayScannerLogic({ id: scannerId }))+ const { monitorStats, hasActiveObservationFilters, observationStatsApiLoading } = useValues(+ replayScannerLogic({ id: scannerId })+ )const { yesTotal, noTotal, inconclusiveTotal } = monitorStatsconst total = yesTotal + noTotal + inconclusiveTotalif (total === 0) {return (<OverviewPanel title="Verdict mix">- <div className="text-muted text-sm">- {hasActiveObservationFilters ? 'No verdicts match the current filter.' : 'No verdicts yet.'}- </div>+ <PanelEmpty+ loading={observationStatsApiLoading}+ message={hasActiveObservationFilters ? 'No verdicts match the current filter.' : 'No verdicts yet.'}+ /></OverviewPanel>)}@@ -84,7 +99,7 @@ function MonitorOverview({ scannerId }: { scannerId: string }): JSX.Element {}function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element | null {- const { scanner, classifierTagStats, hasActiveObservationFilters } = useValues(+ const { scanner, classifierTagStats, hasActiveObservationFilters, observationStatsApiLoading } = useValues(replayScannerLogic({ id: scannerId }))const { fixedRanked, freeformRanked } = classifierTagStats@@ -103,7 +118,7 @@ function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element |const renderRanked = (ranked: [string, number][], emptyMessage: string): JSX.Element => {if (ranked.length === 0) {- return <div className="text-muted text-sm">{emptyMessage}</div>+ return <PanelEmpty loading={observationStatsApiLoading} message={emptyMessage} />}// Cap at the 5 most common so the panels stay compact.const top = ranked.slice(0, 5)@@ -150,18 +165,21 @@ function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element |}function ScorerOverview({ scannerId }: { scannerId: string }): JSX.Element {- const { scorerSummary, scorerHistogram, hasActiveObservationFilters } = useValues(+ const { scorerSummary, scorerHistogram, hasActiveObservationFilters, observationStatsApiLoading } = useValues(replayScannerLogic({ id: scannerId }))const theme = useMemo(() => buildTheme(), [])if (!scorerSummary || !scorerHistogram) {return (<OverviewPanel title="Score distribution">- <div className="text-muted text-sm">- {hasActiveObservationFilters- ? 'No scored observations match the current filter.'- : 'No scored observations yet.'}- </div>+ <PanelEmpty+ loading={observationStatsApiLoading}+ message={+ hasActiveObservationFilters+ ? 'No scored observations match the current filter.'+ : 'No scored observations yet.'+ }+ /></OverviewPanel>)}diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionInsightChart.test.ts b/products/replay_vision/frontend/replay_scanners/components/VisionInsightChart.test.tsnew file mode 100644index 000000000000..06f75ffdd1c9--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/VisionInsightChart.test.ts@@ -0,0 +1,18 @@+import { ChartOverlayState, chartOverlayState } from './VisionInsightChart'++describe('chartOverlayState', () => {+ // `insightData` is always a truthy object from the selector, so the decision must hinge on `result`, not the object.+ const cases: [string, { result?: unknown } | null | undefined, boolean, ChartOverlayState][] = [+ ['null insightData while loading', null, true, 'loading'],+ ['null insightData settled (cancelled/never-loaded)', null, false, 'error'],+ ['truthy object with no result while loading', { result: undefined }, true, 'loading'],+ ['truthy object with no result settled', { result: undefined }, false, 'error'],+ ['loaded with rows', { result: [{ x: 1 }] }, false, 'none'],+ ['loaded but empty result', { result: [] }, false, 'none'],+ ['loaded, ignores a stale loading flag during refresh', { result: [{ x: 1 }] }, true, 'none'],+ ]++ it.each(cases)('%s', (_label, insightData, loading, expected) => {+ expect(chartOverlayState(insightData, loading)).toEqual(expected)+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionInsightChart.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionInsightChart.tsxnew file mode 100644index 000000000000..6336b2eb36d8--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/VisionInsightChart.tsx@@ -0,0 +1,68 @@+import clsx from 'clsx'+import { useActions, useValues } from 'kea'++import { LemonButton, Spinner } from '@posthog/lemon-ui'++import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { Query } from '~/queries/Query/Query'+import { InsightVizNode } from '~/queries/schema/schema-general'+import { InsightLogicProps } from '~/types'++interface VisionInsightChartProps {+ query: InsightVizNode+ /** Must be stable (memoized) — it keys the underlying insight logic. */+ insightProps: InsightLogicProps+ /** Sizing classes for the chart container — pass the same layout the chart sat in before, the chart sizes against it. */+ className?: string+}++export type ChartOverlayState = 'none' | 'loading' | 'error'++/**+ * `insightData` is always a truthy object, but `insightData.result` is `undefined` until a query resolves (an empty+ * result is `[]`), so it — not the object — is the real "is there anything to render" signal. No data while loading is+ * a spinner; no data once settled is a failed/cancelled query we surface as a retry rather than a blank box.+ */+export function chartOverlayState(+ insightData: { result?: unknown } | null | undefined,+ loading: boolean+): ChartOverlayState {+ if (insightData?.result != null) {+ return 'none'+ }+ return loading ? 'loading' : 'error'+}++/**+ * Embedded insight chart with a guaranteed loading/error state. Off a dashboard, InsightViz can fall through to a+ * blank box when a query is cancelled or hasn't resolved (its empty/refresh fallbacks are dashboard-only), so we+ * overlay our own spinner/retry whenever there's no response to render.+ */+export function VisionInsightChart({ query, insightProps, className }: VisionInsightChartProps): JSX.Element {+ const logic = insightVizDataLogic(insightProps)+ const { insightData, insightDataLoading } = useValues(logic)+ const { loadData } = useActions(logic)++ const overlay = chartOverlayState(insightData, insightDataLoading)++ return (+ <div className={clsx('relative', className)}>+ <Query query={query} readOnly embedded inSharedMode context={{ insightProps }} />+ {overlay !== 'none' && (+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-bg-light">+ {overlay === 'loading' ? (+ <Spinner className="text-2xl" />+ ) : (+ <>+ <span className="text-muted text-sm">Couldn't load this chart.</span>+ <LemonButton size="small" type="secondary" onClick={() => loadData('force_async')}>+ Retry+ </LemonButton>+ </>+ )}+ </div>+ )}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsxindex cb12e5b90ef6..b1e15794c6d4 100644--- a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx@@ -1,12 +1,12 @@import { useActions, useValues } from 'kea'+import { useMemo } from 'react'-import { Tooltip } from '@posthog/lemon-ui'+import { Spinner, Tooltip } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'-import { Query } from '~/queries/Query/Query'-import { InsightVizNode, NodeKind, ProductKey, TrendsQuery } from '~/queries/schema/schema-general'-import { BaseMathType, ChartDisplayType } from '~/types'+import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { BaseMathType, ChartDisplayType, InsightLogicProps } from '~/types'import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'import { visionQuotaLogic } from '../../logics/visionQuotaLogic'@@ -15,6 +15,7 @@ import { replayScannersLogic } from '../replayScannersLogic'import { SCANNER_TYPE_OPTIONS } from '../types'import { QuotaMeterBar, QuotaMeterLegendItem } from './QuotaMeterBar'import { QuotaStatusLine } from './QuotaStatusLine'+import { VisionInsightChart } from './VisionInsightChart'const RECORDING_OBSERVED_EVENT = '$recording_observed'const COLLECTION_ID = 'replay-vision-list-observations'@@ -22,29 +23,40 @@ const COLLECTION_ID = 'replay-vision-list-observations'export function VisionMetrics(): JSX.Element {const { scannerStats, chartDateFrom, chartDateTo } = useValues(replayScannersLogic)const { setChartDateRange } = useActions(replayScannersLogic)- const { quota } = useValues(visionQuotaLogic)+ const { quota, quotaLoading } = useValues(visionQuotaLogic)const projection = projectQuota(quota)const { resetsOn, status, percentLabel, usedPct, projectedPct } = projectionconst hasCap = (quota?.monthly_quota ?? 0) > 0const styles = QUOTA_STATUS_STYLES[status]+ // Memoized so a re-render (e.g. stats/quota arriving) can't churn the query and abort an in-flight load.// `tags.productKey` is required for ClickHouse query tagging; without it the runner aborts.- const chartSource: TrendsQuery = {- kind: NodeKind.TrendsQuery,- series: [- {- kind: NodeKind.EventsNode,- event: RECORDING_OBSERVED_EVENT,- math: BaseMathType.TotalCount,- name: 'Observations',+ const chartQuery = useMemo<InsightVizNode>(+ () => ({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: RECORDING_OBSERVED_EVENT,+ math: BaseMathType.TotalCount,+ name: 'Observations',+ },+ ],+ trendsFilter: { display: ChartDisplayType.ActionsLineGraph },+ dateRange: { date_from: chartDateFrom, date_to: chartDateTo },+ interval: 'day',+ tags: { productKey: ProductKey.REPLAY_VISION },},- ],- trendsFilter: { display: ChartDisplayType.ActionsLineGraph },- dateRange: { date_from: chartDateFrom, date_to: chartDateTo },- interval: 'day',- tags: { productKey: ProductKey.REPLAY_VISION },- }+ }),+ [chartDateFrom, chartDateTo]+ )+ const chartInsightProps = useMemo<InsightLogicProps>(+ () => ({ dashboardItemId: 'new-replay-vision-list-observations-chart', dataNodeCollectionId: COLLECTION_ID }),+ []+ )return (<div className="flex flex-col lg:flex-row gap-4 h-72">@@ -58,20 +70,11 @@ export function VisionMetrics(): JSX.Element {/></div><p className="text-muted text-xs mb-3">Across all scanners</p>- <div className="flex-1 flex flex-col min-h-0">- <Query- query={{ kind: NodeKind.InsightVizNode, source: chartSource } as InsightVizNode}- readOnly- embedded- inSharedMode- context={{- insightProps: {- dashboardItemId: 'new-replay-vision-list-observations-chart',- dataNodeCollectionId: COLLECTION_ID,- },- }}- />- </div>+ <VisionInsightChart+ query={chartQuery}+ insightProps={chartInsightProps}+ className="flex-1 flex flex-col min-h-0"+ /></div><div className="flex flex-1 flex-col gap-4">@@ -154,6 +157,10 @@ export function VisionMetrics(): JSX.Element {</span></div></>+ ) : quotaLoading ? (+ <div className="flex items-center py-2">+ <Spinner />+ </div>) : (<div className="text-3xl font-semibold">—</div>)}