: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
feat(experiments): add a new global loading status indicator (#65684)
Rodrigo Iloroc030bc35b420
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsxindex ecd7a77919c3..49ee216ce36e 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx@@ -4,6 +4,8 @@ import { IconSparkles } from '@posthog/icons'import { LemonTabs } from '@posthog/lemon-ui'import { ActivityLog } from 'lib/components/ActivityLog/ActivityLog'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { PendingChangeRequestBanner } from 'scenes/approvals/PendingChangeRequestBanner'import { EXPERIMENT_MIN_EXPOSURES_FOR_RESULTS } from 'scenes/experiments/constants'import { WebExperimentImplementationDetails } from 'scenes/experiments/WebExperimentImplementationDetails'@@ -25,6 +27,7 @@ import { SharedMetricDetailsModal } from '../Metrics/SharedMetricDetailsModal'import { SharedMetricModal } from '../Metrics/SharedMetricModal'import { sharedMetricModalLogic } from '../Metrics/sharedMetricModalLogic'import { Metrics } from '../MetricsView/new/Metrics'+import { RecalculationStatus } from '../MetricsView/shared/RecalculationStatus'import { isLegacyExperiment } from '../utils'import { DistributionModal, DistributionTable } from './DistributionTable'import { ExperimentDebugPanel } from './ExperimentExecutionPathComparison'@@ -71,8 +74,12 @@ const AiAnalysisTab = (): JSX.Element => {}const MetricsTab = (): JSX.Element => {- const { orderedPrimaryMetricsWithResults, orderedSecondaryMetricsWithResults, isExperimentLaunched } =+ const { experiment, orderedPrimaryMetricsWithResults, orderedSecondaryMetricsWithResults, isExperimentLaunched } =useValues(experimentLogic)+ const { featureFlags } = useValues(featureFlagLogic)++ const hasMetrics = orderedPrimaryMetricsWithResults.length > 0 || orderedSecondaryMetricsWithResults.length > 0+ const showRecalculationStatus = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION] && hasMetricsreturn (<>@@ -83,8 +90,14 @@ const MetricsTab = (): JSX.Element => {<MultiVariantBiasWarning /></div>+ {showRecalculationStatus && (+ <div className="mb-2">+ <RecalculationStatus experiment={experiment} />+ </div>+ )}+{/* Modern metrics view */}- {orderedPrimaryMetricsWithResults.length === 0 && orderedSecondaryMetricsWithResults.length === 0 ? (+ {!hasMetrics ? (<EmptyMetricsPanel isLaunched={isExperimentLaunched} />) : (<>diff --git a/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx b/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsxindex bedbc9b29bb2..c2b8b9cf4ef7 100644--- a/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ResultsNotificationBanner.tsx@@ -4,28 +4,19 @@ import { useEffect } from 'react'import { IconClock } from '@posthog/icons'import { LemonBanner, LemonButton } from '@posthog/lemon-ui'-import { FEATURE_FLAGS } from 'lib/constants'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'--import { Experiment } from '~/types'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { experimentLogic } from '../experimentLogic'-import { experimentMetricsLogic } from '../experimentMetricsLogic'-import { experimentResultsNotificationLogic } from '../experimentResultsNotificationLogic'-import { isSavedExperiment } from '../utils'/**- * "Results are taking a while" banner. On the recalculation flow it reads the standalone- * experimentResultsNotificationLogic (driven by isRecalculating); the legacy flow keeps reading the- * equivalent state on experimentLogic.+ * Legacy "results are taking a while" banner. On the recalculation flow the RecalculationStatus bar+ * owns the notify affordance, so this renders nothing there.*/export function ResultsNotificationBanner(): JSX.Element | null {- const { experiment } = useValues(experimentLogic)- const { featureFlags } = useValues(featureFlagLogic)- const recalculationFlow = !!featureFlags[FEATURE_FLAGS.EXPERIMENTS_METRICS_RECALCULATION]+ const recalculationFlow = useFeatureFlag('EXPERIMENTS_METRICS_RECALCULATION')- if (recalculationFlow && isSavedExperiment(experiment)) {- return <RecalculationNotificationBanner experiment={experiment} />+ if (recalculationFlow) {+ return null}return <LegacyNotificationBanner />}@@ -82,23 +73,6 @@ function NotificationBannerView({)}-function RecalculationNotificationBanner({ experiment }: { experiment: Experiment }): JSX.Element | null {- const notificationLogic = experimentResultsNotificationLogic({ experiment })- const { showNotificationOffer, notifyWhenResultsReady } = useValues(notificationLogic)- const { subscribeToResultsNotification, dismissNotificationOffer } = useActions(notificationLogic)- const { isRecalculating } = useValues(experimentMetricsLogic({ experiment }))-- return (- <NotificationBannerView- showNotificationOffer={showNotificationOffer}- notifyWhenResultsReady={notifyWhenResultsReady}- isLoading={isRecalculating}- onSubscribe={subscribeToResultsNotification}- onDismiss={dismissNotificationOffer}- />- )-}-function LegacyNotificationBanner(): JSX.Element | null {const {showNotificationOffer,diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsxindex 3845cf16eb22..3def0a539b01 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricRowGroup.tsx@@ -596,14 +596,9 @@ export function MetricRowGroup({useActions(experimentLogic)const { variants } = useValues(experimentLogic)const { featureFlags } = useValues(featureFlagLogic)- const { isRecalculating, isMetricRecalculating } = useValues(experimentMetricsLogic({ experiment }))+ const { isRecalculating } = useValues(experimentMetricsLogic({ experiment }))const { triggerRecalculation } = useActions(experimentMetricsLogic({ experiment }))- /**- * Dim the stale value in place while a non-cold recalc refreshes this metric; block clicks on it.- */- const recalculatingClassName = isMetricRecalculating(metric.uuid) ? 'opacity-40 pointer-events-none' : ''-/*** On the recalculation flow, retrying a single metric just re-runs the whole recalculation (plus* exposures), same as the manual reload. The legacy flow retries the single metric in place.@@ -802,10 +797,7 @@ export function MetricRowGroup({return (<>- <tr- className={clsx('hover:bg-bg-hover group [&:last-child>td]:border-b-0', recalculatingClassName)}- style={noResultStateStyle}- >+ <tr className="hover:bg-bg-hover group [&:last-child>td]:border-b-0" style={noResultStateStyle}>{/* Metric column - always visible */}<tdclassName={`w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${@@ -911,10 +903,7 @@ export function MetricRowGroup({)}{/* Baseline row */}- <tr- className={clsx('hover:bg-bg-hover group [&:last-child>td]:border-b-0', recalculatingClassName)}- style={FIXED_HEIGHT_STYLE}- >+ <tr className="hover:bg-bg-hover group [&:last-child>td]:border-b-0" style={FIXED_HEIGHT_STYLE}>{/* Metric column - with rowspan */}<tdclassName={`w-1/5 border-r p-3 align-top text-left relative overflow-hidden ${!isLastMetric ? 'border-b' : ''} ${isAlternatingRow ? 'bg-bg-table' : 'bg-bg-light'}`}@@ -1044,7 +1033,7 @@ export function MetricRowGroup({return (<trkey={`${metric.uuid}-${variant.key}`}- className={clsx('hover:bg-bg-hover group [&:last-child>td]:border-b-0', recalculatingClassName)}+ className="hover:bg-bg-hover group [&:last-child>td]:border-b-0"style={FIXED_HEIGHT_STYLE}onMouseEnter={(e) => handleTooltipMouseEnter(e, variant)}onMouseLeave={handleTooltipMouseLeave}diff --git a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsxindex c1de1b9b9cd7..7f69fe31ff62 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx@@ -1,4 +1,4 @@-import { useActions } from 'kea'+import { useActions, useValues } from 'kea'import { useState } from 'react'import { IconCopy, IconEllipsis, IconPencil, IconStack, IconTarget, IconTrash } from '@posthog/icons'@@ -6,6 +6,9 @@ import { LemonButton, LemonDialog, LemonDropdown, LemonMenu, LemonTag, Tooltip }import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { Spinner } from 'lib/lemon-ui/Spinner'+import { experimentMetricsLogic } from 'scenes/experiments/experimentMetricsLogic'import { isMetricThresholdCueVisible } from 'scenes/experiments/ExperimentMetricThreshold'import { METRIC_CONTEXTS, experimentMetricModalLogic } from 'scenes/experiments/Metrics/experimentMetricModalLogic'import { sharedMetricDetailsModalLogic } from 'scenes/experiments/Metrics/sharedMetricDetailsModalLogic'@@ -202,6 +205,10 @@ export const MetricHeader = ({const canAddBreakdown = (metric.breakdownFilter?.breakdowns || []).length < MAX_BREAKDOWNS+ const recalculationEnabled = useFeatureFlag('EXPERIMENTS_METRICS_RECALCULATION')+ const { isMetricRecalculating } = useValues(experimentMetricsLogic({ experiment }))+ const showRecalculatingTag = recalculationEnabled && isMetricRecalculating(metric.uuid)+return (<div className="text-xs font-semibold flex flex-col justify-between h-full"><div className="deprecated-space-y-1">@@ -281,6 +288,11 @@ export const MetricHeader = ({)}</div><div className="flex flex-wrap items-center gap-1">+ {showRecalculatingTag && (+ <LemonTag type="highlight" size="medium" icon={<Spinner textColored />}>+ Recalculating+ </LemonTag>+ )}<LemonTag type="muted" size="small">{getMetricTag(metric)}</LemonTag>diff --git a/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx b/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsxnew file mode 100644index 000000000000..b09bb514f79a--- /dev/null+++ b/frontend/src/scenes/experiments/MetricsView/shared/RecalculationStatus.tsx@@ -0,0 +1,188 @@+import { useActions, useValues } from 'kea'++import { IconBell, IconCheck, IconInfo } from '@posthog/icons'+import { LemonButton, Tooltip } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'+import { Spinner } from 'lib/lemon-ui/Spinner'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import { experimentMetricsLogic } from '~/scenes/experiments/experimentMetricsLogic'+import { experimentResultsNotificationLogic } from '~/scenes/experiments/experimentResultsNotificationLogic'+import { Experiment } from '~/types'++import type { ExperimentMetricsRecalculationApi } from 'products/experiments/frontend/generated/api.schemas'++/**+ * Always-on status line for the recalculation flow. Renders exactly one state from+ * `recalculationDisplayState`; the in-flight states read live ClickHouse progress off the poll.+ * Only rendered behind EXPERIMENTS_METRICS_RECALCULATION (see ExperimentView).+ */+export function RecalculationStatus({ experiment }: { experiment: Experiment }): JSX.Element {+ const { recalculationDisplayState, currentRecalculation, totalMetricsCount } = 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 swaps to a terminal state.+ */+ const notificationLogic = experimentResultsNotificationLogic({ experiment })+ const { notifyWhenResultsReady } = useValues(notificationLogic)+ const { subscribeToResultsNotification } = useActions(notificationLogic)++ switch (recalculationDisplayState) {+ case 'initial':+ return (+ <StatusBar>+ <span className="flex items-center gap-1.5 whitespace-nowrap">+ <Spinner textColored className="text-sm text-accent" />+ <span className="font-medium">Loading metrics…</span>+ </span>+ </StatusBar>+ )+ case 'cold':+ case 'refreshing':+ return (+ <InFlightStatus+ recalculation={currentRecalculation}+ notifyWhenResultsReady={notifyWhenResultsReady}+ onSubscribe={subscribeToResultsNotification}+ />+ )+ case 'partial':+ case 'resting':+ return (+ <StatusBar>+ <span className="flex items-center gap-1.5 whitespace-nowrap">+ <IconCheck className="text-success text-sm" />+ <span className="font-medium">+ {totalMetricsCount} {totalMetricsCount === 1 ? 'metric' : 'metrics'}+ </span>+ {recalculationDisplayState === 'partial' && (+ <span className="text-danger font-medium">+ · {currentRecalculation?.failed_metrics} failed+ </span>+ )}+ </span>+ {currentRecalculation?.completed_at && (+ <>+ <LemonDivider vertical className="h-3.5" />+ <span className="flex items-center gap-1 whitespace-nowrap text-muted text-xs [&_span]:align-baseline">+ <span>Refreshed</span>+ <TZLabel time={currentRecalculation.completed_at} timestampStyle="relative" />+ </span>+ </>+ )}+ </StatusBar>+ )+ }+}++function InFlightStatus({+ recalculation,+ notifyWhenResultsReady,+ onSubscribe,+}: {+ recalculation: ExperimentMetricsRecalculationApi | null+ notifyWhenResultsReady: boolean+ onSubscribe: () => void+}): JSX.Element {+ const rowsRead = recalculation?.rows_read ?? undefined+ const succeeded = recalculation?.completed_metrics ?? 0+ const failed = recalculation?.failed_metrics ?? 0+ const total = recalculation?.total_metrics ?? 0+ /**+ * Pending (not yet resolved, not currently sampled as running) keeps the segment truthful in those gaps.+ */+ const pending = Math.max(0, total - succeeded - failed)+ return (+ <StatusBar>+ <span className="flex items-center gap-1.5 whitespace-nowrap">+ <Spinner textColored className="text-sm text-accent" />+ <CountsSegment pending={pending} succeeded={succeeded} failed={failed} />+ <span className="text-muted text-xs">· 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>+ {rowsRead !== undefined && (+ <ClimbingRows+ rowsRead={rowsRead}+ estimatedRows={recalculation?.estimated_rows_total ?? 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="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,+ succeeded,+ failed,+}: {+ pending: 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>)+ }+ 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 items-center gap-1 whitespace-nowrap font-medium">+ {parts.map((part, i) => (+ <span key={part.key} className="flex items-center gap-1">+ {i > 0 && <span>·</span>}+ {part}+ </span>+ ))}+ </span>+ )+}++function ClimbingRows({ rowsRead, estimatedRows }: { rowsRead: number; estimatedRows?: number }): JSX.Element {+ const showCeiling = estimatedRows !== undefined && estimatedRows >= rowsRead+ return (+ <span className="text-muted text-xs whitespace-nowrap">+ · {humanFriendlyNumber(rowsRead, 0)}+ {showCeiling && ` / ${humanFriendlyNumber(estimatedRows, 0)}`} rows+ </span>+ )+}diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.test.tsindex cb0566a6b9bc..76e967d8b8a8 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.test.ts@@ -52,7 +52,6 @@ const completedRecalculation = {status: 'completed',completed_metrics: 2,started_at: new Date().toISOString(),- // Fresh by default (within the 24h window) so tests using this fixture don't auto-trigger.completed_at: new Date().toISOString(),query_to: '2026-06-10T00:05:00Z',results: [@@ -61,11 +60,6 @@ const completedRecalculation = {],}-// completed_at far in the past → older than the 24h staleness threshold.-const staleCompletedRecalculation = {- ...completedRecalculation,- completed_at: '2020-01-01T00:00:00Z',-}const freshCompletedRecalculation = completedRecalculationconst pendingRecalculation = { ...baseRecalculation, id: 'recalc-2', status: 'pending' }@@ -383,36 +377,9 @@ describe('experimentMetricsLogic', () => {expect(capturedBody).toEqual({ trigger: 'cold_run' })})- it('auto-triggers a stale_refresh recalculation when the latest completed run is stale (>24h)', async () => {- let capturedBody: any- useMocks({- get: {- '/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [- 200,- staleCompletedRecalculation,- ],- },- post: {- // Return a terminal run so triggerRecalculation finishes without arming a poll timer.- '/api/projects/:team_id/experiments/:id/metrics_recalculation/': async ({ request }) => {- capturedBody = await request.json()- return [201, completedRecalculation2]- },- },- })- mountLogic()-- // Stale results still load, but a fresh run is kicked off in the background.- await expectLogic(logic)- .toDispatchActions(['setCurrentRecalculation', 'triggerRecalculation'])- .toFinishAllListeners()- expect(logic.values.primaryMetricsResults[0]).toEqual(primaryResult)- expect(capturedBody).toEqual({ trigger: 'stale_refresh' })- })-- it('does not auto-trigger when the latest completed run is fresh', async () => {- // freshCompletedRecalculation has result_source 'recalculation' (a real run), so neither the- // staleness path nor the timeseries-fallback path fires.+ it('does not auto-trigger when the latest completed run is healthy', async () => {+ // freshCompletedRecalculation has result_source 'recalculation' (a real run) with all metrics+ // resolved, so neither the config-change heal path nor the timeseries-fallback path fires.useMocks({get: {'/api/projects/:team_id/experiments/:id/metrics_recalculation/latest/': () => [diff --git a/frontend/src/scenes/experiments/experimentMetricsLogic.ts b/frontend/src/scenes/experiments/experimentMetricsLogic.tsindex 7fc659e829df..b803543c904c 100644--- a/frontend/src/scenes/experiments/experimentMetricsLogic.ts+++ b/frontend/src/scenes/experiments/experimentMetricsLogic.ts@@ -3,7 +3,6 @@ import { actions, afterMount, connect, kea, key, listeners, path, props, reducerimport { lemonToast } from '@posthog/lemon-ui'import { FEATURE_FLAGS } from 'lib/constants'-import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'import { projectLogic } from 'scenes/projectLogic'@@ -40,7 +39,6 @@ export interface ExperimentMetricsLogicProps {}const RECALCULATION_POLL_INTERVAL_MS = 2000-const RECALCULATION_STALE_AFTER_HOURS = 24const MAX_POLL_RETRIES = 5export const RECALCULATION_STATUSES = {@@ -52,13 +50,6 @@ export const RECALCULATION_STATUSES = {export type RecalculationStatuses = (typeof RECALCULATION_STATUSES)[keyof typeof RECALCULATION_STATUSES]-const isRecalculationStale = (recalculation: ExperimentMetricsRecalculationApi): boolean => {- if (!recalculation.completed_at) {- return false- }- return dayjs().diff(dayjs(recalculation.completed_at), 'hours') >= RECALCULATION_STALE_AFTER_HOURS-}-/*** transform shared metrics into experiment metrics.*/@@ -230,7 +221,30 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([total: recalc?.total_metrics ?? 0,}),],+ // Total metrics on the experiment itself, independent of whether a recalculation run exists yet.+ // Sourced from the experiment so the count is truthful on first render, before the first run loads.+ totalMetricsCount: [+ () => [(_, props) => props.experiment],+ (experiment: Experiment): number =>+ metricsInOrder(experiment, 'primary').length + metricsInOrder(experiment, 'secondary').length,+ ],lastRefresh: [(s) => [s.currentRecalculation], (recalc): string | null => recalc?.query_to ?? null],+ recalculationDisplayState: [+ (s) => [s.recalculationLoading, s.currentRecalculation],+ (recalculationLoading, recalculation): 'initial' | 'cold' | 'refreshing' | 'partial' | 'resting' => {+ if (!recalculation) {+ return recalculationLoading ? 'initial' : 'resting'+ }+ const inFlight =+ recalculationLoading ||+ recalculation.status === RECALCULATION_STATUSES.pending ||+ recalculation.status === RECALCULATION_STATUSES.in_progress+ if (inFlight) {+ return (recalculation.results?.length ?? 0) > 0 ? 'refreshing' : 'cold'+ }+ return recalculation.failed_metrics > 0 ? 'partial' : 'resting'+ },+ ],// Predicate the table uses to dim a metric whose stale value is still being refreshed.isMetricRecalculating: [(s) => [s.recalculatingMetricUuids],@@ -423,14 +437,6 @@ export const experimentMetricsLogic = kea<experimentMetricsLogicType>([actions.triggerRecalculation('config_change')return}-- /**- * if the recalculation resutls are stale, trigger a new recalculation- * without hiding the existing resutls.- */- if (isRecalculationStale(recalculation)) {- actions.triggerRecalculation('stale_refresh')- }} catch (error: any) {if (error?.status === 404) {/**diff --git a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.tsindex 183d36e686df..796cb1ff7ef9 100644--- a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts+++ b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.test.ts@@ -13,7 +13,12 @@ import { experimentMetricsLogic } from './experimentMetricsLogic'import { experimentResultsNotificationLogic } from './experimentResultsNotificationLogic'const EXPERIMENT = experimentJson as unknown as Experiment-const OFFER_DELAY_MS = 10_000++const dispatchBeforeUnload = (): boolean => {+ const event = new Event('beforeunload', { cancelable: true })+ window.dispatchEvent(event)+ return event.defaultPrevented+}describe('experimentResultsNotificationLogic', () => {let logic: ReturnType<typeof experimentResultsNotificationLogic.build>@@ -54,49 +59,28 @@ describe('experimentResultsNotificationLogic', () => {})afterEach(() => {- jest.useRealTimers()logic?.unmount()metricsLogic?.unmount()})- it('offers the notification banner once a recalculation has run for the delay', async () => {- jest.useFakeTimers()- // Recalculation starts → the offer timer begins.+ it('fires notifyResultsReady and resets the subscription when the recalculation finishes', async () => {metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'in_progress' } as any)- expect(logic.values.showNotificationOffer).toBe(false)-- await jest.advanceTimersByTimeAsync(OFFER_DELAY_MS)- expect(logic.values.showNotificationOffer).toBe(true)- })-- it('resets the offer when the recalculation finishes', async () => {- jest.useFakeTimers()- metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'in_progress' } as any)- await jest.advanceTimersByTimeAsync(OFFER_DELAY_MS)- expect(logic.values.showNotificationOffer).toBe(true)+ logic.actions.setNotifyWhenResultsReady(true)- // Recalculation completes → offer is cleared.metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'completed' } as any)await expectLogic(logic).toDispatchActions(['notifyResultsReady'])- expect(logic.values.showNotificationOffer).toBe(false)expect(logic.values.notifyWhenResultsReady).toBe(false)})- it('dismissNotificationOffer clears both flags', () => {- logic.actions.setShowNotificationOffer(true)+ it('warns before unload while subscribed and stops once results land', async () => {+ metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'in_progress' } as any)+ expect(dispatchBeforeUnload()).toBe(false)+logic.actions.setNotifyWhenResultsReady(true)- logic.actions.dismissNotificationOffer()- expect(logic.values.showNotificationOffer).toBe(false)- expect(logic.values.notifyWhenResultsReady).toBe(false)- })+ expect(dispatchBeforeUnload()).toBe(true)- it('dismissing the offer disposes the pending timer so it cannot re-show the banner', async () => {- jest.useFakeTimers()- metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'in_progress' } as any)- // Dismiss before the offer timer fires.- logic.actions.dismissNotificationOffer()- await jest.advanceTimersByTimeAsync(OFFER_DELAY_MS)- // The timer was disposed, so the offer must stay dismissed.- expect(logic.values.showNotificationOffer).toBe(false)+ metricsLogic.actions.setCurrentRecalculation({ id: 'x', status: 'completed' } as any)+ await expectLogic(logic).toDispatchActions(['notifyResultsReady'])+ expect(dispatchBeforeUnload()).toBe(false)})})diff --git a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.ts b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.tsindex efdf296434eb..d8ff9113ce53 100644--- a/frontend/src/scenes/experiments/experimentResultsNotificationLogic.ts+++ b/frontend/src/scenes/experiments/experimentResultsNotificationLogic.ts@@ -12,14 +12,10 @@ export interface ExperimentResultsNotificationLogicProps {experiment: Experiment}-// How long a recalculation must run before we offer the "notify me when ready" banner.-const NOTIFICATION_OFFER_DELAY_MS = 10_000-/**- * Standalone "results are taking a while" notification for the recalculation flow: offers a banner- * once a recalculation has been running for a bit, and (if the user opts in) fires a browser- * notification when it finishes. Driven entirely by `experimentMetricsLogic.isRecalculating` so it's- * decoupled from how results are loaded. The legacy equivalent still lives in experimentLogic.+ * Browser notification for the recalculation flow: the status bar's "Notify me" button opts in, and a+ * notification fires when the run finishes. Driven entirely by `experimentMetricsLogic.isRecalculating`+ * so it's decoupled from how results are loaded. The legacy equivalent still lives in experimentLogic.*/export const experimentResultsNotificationLogic = kea<experimentResultsNotificationLogicType>([props({} as ExperimentResultsNotificationLogicProps),@@ -29,33 +25,19 @@ export const experimentResultsNotificationLogic = kea<experimentResultsNotificatvalues: [experimentMetricsLogic({ experiment: props.experiment }), ['isRecalculating']],})),actions({- setShowNotificationOffer: (show: boolean) => ({ show }),setNotifyWhenResultsReady: (notify: boolean) => ({ notify }),- dismissNotificationOffer: true,subscribeToResultsNotification: true,notifyResultsReady: true,}),reducers({- showNotificationOffer: [- false,- {- setShowNotificationOffer: (_, { show }) => show,- dismissNotificationOffer: () => false,- },- ],notifyWhenResultsReady: [false,{setNotifyWhenResultsReady: (_, { notify }) => notify,- dismissNotificationOffer: () => false,},],}),listeners(({ props, values, actions, cache }) => ({- dismissNotificationOffer: () => {- // Stop the pending offer timer so it can't re-show the banner after the user dismissed it.- cache.disposables.dispose('notificationOfferTimer')- },subscribeToResultsNotification: async () => {if (!('Notification' in window)) {lemonToast.error('Your browser does not support notifications.')@@ -73,6 +55,30 @@ export const experimentResultsNotificationLogic = kea<experimentResultsNotificat)}},+ setNotifyWhenResultsReady: ({ notify }) => {+ /**+ * Warn before closing the tab while subscribed: the notification can only fire from this page.+ * Must survive tab-hide (closing a background tab still fires beforeunload), so it opts out of+ * pause-on-page-hide.+ */+ if (notify) {+ cache.disposables.add(+ () => {+ const handler = (e: BeforeUnloadEvent): void => {+ e.preventDefault()+ // Legacy fallback (Chrome/Edge < 119); preventDefault is the modern trigger.+ e.returnValue = true+ }+ window.addEventListener('beforeunload', handler)+ return () => window.removeEventListener('beforeunload', handler)+ },+ 'beforeUnloadGuard',+ { pauseOnPageHidden: false }+ )+ } else {+ cache.disposables.dispose('beforeUnloadGuard')+ }+ },// Fire the browser notification (if subscribed) once a recalculation finishes.notifyResultsReady: () => {if (values.notifyWhenResultsReady && 'Notification' in window && Notification.permission === 'granted') {@@ -86,8 +92,6 @@ export const experimentResultsNotificationLogic = kea<experimentResultsNotificatnotification.close()}}- cache.disposables.dispose('notificationOfferTimer')- actions.setShowNotificationOffer(false)actions.setNotifyWhenResultsReady(false)},})),@@ -95,30 +99,11 @@ export const experimentResultsNotificationLogic = kea<experimentResultsNotificat* Subscriptions (not listeners) on purpose: we react to the EDGE of `isRecalculating`, a derived* boolean composed from two upstream actions (setCurrentRecalculation + setRecalculationLoading) on* experimentMetricsLogic. There's no single action whose handler cleanly expresses "the derived value- * just flipped", so this is the skill's sanctioned subscriptions case. The (next, prev) args give us- * the transition for free instead of hand-tracking a previous value across two listeners.+ * just flipped", so this is the skill's sanctioned subscriptions case.*/- subscriptions(({ actions, cache }) => ({+ subscriptions(({ actions }) => ({isRecalculating: (isRecalculating: boolean, previous: boolean | undefined) => {- if (isRecalculating && !previous) {- /**- * A recalculation just started: offer the banner after it has been running a while. The- * timer must keep running while the tab is hidden (the point is to notify a user who has- * navigated away), so it opts out of pause-on-page-hide.- */- cache.disposables.add(- () => {- const timer = setTimeout(- () => actions.setShowNotificationOffer(true),- NOTIFICATION_OFFER_DELAY_MS- )- return () => clearTimeout(timer)- },- 'notificationOfferTimer',- { pauseOnPageHidden: false }- )- } else if (!isRecalculating && previous) {- // Fire the notification (if subscribed) and reset the offer.+ if (!isRecalculating && previous) {actions.notifyResultsReady()}},