: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(replay-vision): show a first-scan pending state on new scanners (#81440)
Arno Hillen0ee2fa465da3
diff --git a/products/replay_vision/frontend/logics/observationPolling.ts b/products/replay_vision/frontend/logics/observationPolling.tsindex 7b1c8085f3a0..ae56eee90b68 100644--- a/products/replay_vision/frontend/logics/observationPolling.ts+++ b/products/replay_vision/frontend/logics/observationPolling.ts@@ -13,11 +13,12 @@ interface ObservationPollDisposables {export function scheduleObservationPoll(disposables: ObservationPollDisposables,shouldPoll: boolean,- poll: () => void+ poll: () => void,+ intervalMs: number = POLL_INTERVAL_MS): void {if (shouldPoll) {disposables.add(() => {- const id = setTimeout(poll, POLL_INTERVAL_MS)+ const id = setTimeout(poll, intervalMs)return () => clearTimeout(id)}, POLL_KEY)} else {diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsxindex 0fe1f5831cf3..19377108fb9e 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx@@ -9,6 +9,7 @@ import { LemonProgress } from 'lib/lemon-ui/LemonProgress'import { creditsToUsd, formatCreditsRange } from '../../utils/credits'import { replayScannerLogic } from '../replayScannerLogic'+import { ReplayScannerTab, replayScannerSceneLogic } from '../replayScannerSceneLogic'import { scannerOverviewLogic } from '../scannerOverviewLogic'import { ScannerType } from '../types'import { ScannerInsightsChart } from './ScannerInsightsChart'@@ -434,11 +435,58 @@ function SummarizerOverview({ scannerId }: { scannerId: string }): JSX.Element |)}+// The interstitial a just-created scanner shows instead of the filters + charts, whose "no matching+// events" empty state would wrongly suggest the user's setup is broken while the first sweep runs.+// It also hides the overview's reload buttons, so when the background checks keep failing it has to+// surface that itself and offer a retry.+function FirstScanPendingPanel({ scannerId }: { scannerId: string }): JSX.Element {+ const { setActiveTab } = useActions(replayScannerSceneLogic)+ const { firstScanCheckFailing, overviewStatsApiLoading } = useValues(scannerOverviewLogic({ scannerId }))+ const { loadOverviewStats } = useActions(scannerOverviewLogic({ scannerId }))+ return (+ <div+ className="border rounded bg-surface-primary p-6 flex flex-col items-center gap-2 text-center"+ data-attr="vision-first-scan-pending"+ >+ {!firstScanCheckFailing && <Spinner className="text-2xl" />}+ <div className="font-semibold">First scan in progress</div>+ <div className="text-muted text-sm max-w-md">+ {firstScanCheckFailing+ ? "We couldn't check for results. We'll keep retrying, or you can retry now."+ : 'This scanner picks up new recordings on a schedule. Results usually appear within 15 minutes.'}+ </div>+ {firstScanCheckFailing && (+ <LemonButton+ type="secondary"+ size="small"+ loading={overviewStatsApiLoading}+ onClick={() => loadOverviewStats()}+ data-attr="vision-first-scan-pending-retry"+ >+ Retry+ </LemonButton>+ )}+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => setActiveTab(ReplayScannerTab.OnDemand)}+ data-attr="vision-first-scan-pending-scan-now"+ >+ Scan a recording now+ </LemonButton>+ </div>+ )+}+export function ScannerOverview({ scannerId }: { scannerId: string }): JSX.Element | null {const { scanner } = useValues(replayScannerLogic({ id: scannerId }))+ const { firstScanPending } = useValues(scannerOverviewLogic({ scannerId }))if (!scanner) {return null}+ if (firstScanPending) {+ return <FirstScanPendingPanel scannerId={scannerId} />+ }const scannerType: ScannerType = scanner.scanner_typeconst typeOverview =scannerType === 'monitor' ? (diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex c54033a41374..35361e8cb50f 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -349,6 +349,21 @@ describe('replayScannerLogic', () => {expect(createSpy).not.toHaveBeenCalled()expect(router.values.location.pathname).toContain('/replay-vision/new/configure')})++ it('submitting the final step creates the scanner, lands on it, and announces the first scan', async () => {+ const success = jest.spyOn(lemonToast, 'success')+ router.actions.push('/replay-vision/new/self-driving')+ scannerEditorSceneLogic.actions.setStep('self_driving')+ logic.actions.setScannerValues({ name: 'Test scanner', scanner_config: { prompt: 'Q?' } })+ await expectLogic(logic, () => logic.actions.submitScanner()).toFinishAllListeners()+ expect(createSpy).toHaveBeenCalledTimes(1)+ expect(router.values.location.pathname).toContain('/replay-vision/created-scanner')+ // The toast must tell the same story as the Overview's first-scan pending panel.+ expect(success).toHaveBeenCalledWith(+ 'Scanner created. First scan in progress.',+ expect.objectContaining({ button: expect.objectContaining({ label: 'Scan a recording now' }) })+ )+ })})describe('new scanner draft', () => {@@ -1048,6 +1063,23 @@ describe('replayScannerLogic', () => {})})+ describe('scannerWatermarkRefreshed', () => {+ // Guards the background watermark refresh against regressing to the full loadScannerSuccess+ // path, which resets the form from the server and refires the observation loads.+ it('advances the sweep watermark without resetting form edits or reloading observations', async () => {+ logic.actions.loadScannerSuccess({ ...logic.values.scanner!, id: 'abc', name: 'Loaded' })+ logic.actions.setScannerValues({ name: 'Edited' })++ const refreshed = { ...logic.values.scanner!, name: 'Loaded', last_swept_at: '2026-08-13T10:00:00Z' }+ // toDispatchActions moves the history pointer past the setup's own setScannerValues first.+ await expectLogic(logic, () => logic.actions.scannerWatermarkRefreshed(refreshed))+ .toDispatchActions(['scannerWatermarkRefreshed'])+ .toNotHaveDispatchedActions(['setScannerValues', 'loadObservations', 'loadObservationStats'])+ expect(logic.values.scanner?.name).toBe('Edited')+ expect(logic.values.scanner?.last_swept_at).toBe('2026-08-13T10:00:00Z')+ })+ })+describe('shouldGuardScannerNavigation', () => {const scannerId = 'abc-123'const configure = urls.replayVisionScannerConfigure(scannerId)diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 1fdef535a414..8c40a06c16d1 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -525,6 +525,9 @@ export interface replayScannerLogicActions {scannerSaved: (scanner: ScannerFormValues) => {scanner: ScannerFormValues}+ scannerWatermarkRefreshed: (scanner: ReplayScanner) => {+ scanner: ReplayScanner+ }setChartDateRange: (dateFrom: string | null,dateTo: string | null@@ -704,6 +707,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([loadScanner: true,loadScannerSuccess: (scanner: ScannerFormValues) => ({ scanner }),loadScannerFailure: true,+ // Background refetches use this instead of loadScannerSuccess, which also resets the form,+ // originalScanner, and submitIntent, and can refire the observation loads.+ scannerWatermarkRefreshed: (scanner: ReplayScanner) => ({ scanner }),setExperimentContext: (context: ExperimentScannerContext | null) => ({ context }),setExperimentVariantKeys: (variantKeys: string[]) => ({ variantKeys }),detachExperimentContext: true,@@ -847,8 +853,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([const response = await visionScannersCreate(String(teamId), scannerToApiBody(body))actions.scannerSaved(scanner)router.actions.replace(urls.replayVision(response.id))- // First results are minutes away on the schedule — hand off to the instant on-demand tab.- lemonToast.success('Scanner created', {+ // First scheduled results are minutes away, so the copy matches the Overview's+ // pending panel and the button hands off to the instant on-demand tab.+ lemonToast.success('Scanner created. First scan in progress.', {button: {label: 'Scan a recording now',action: () => router.actions.push(`${urls.replayVision(response.id)}?tab=on-demand`),@@ -977,6 +984,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([saveAffectedCohortFailure: () => null,},],+ scanner: {+ // Only the sweep watermark lands, so a background refresh can't clobber unsaved form edits.+ scannerWatermarkRefreshed: (state: ReplayScanner, { scanner }: { scanner: ReplayScanner }) =>+ state ? { ...state, last_swept_at: scanner.last_swept_at } : scanner,+ },experimentContext: [null as ExperimentScannerContext | null,{diff --git a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.tsindex 09937ca8b884..115227f3970c 100644--- a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts@@ -1,6 +1,8 @@import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { dayjs } from 'lib/dayjs'+import { lemonToast } from 'lib/lemon-ui/LemonToast'import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'@@ -20,7 +22,6 @@ const STATS = {const IMPACT = { affected_sessions: 0, affected_users: 0, sessions_without_user: 0, window_days: 14 }describe('scannerOverviewLogic', () => {- let logic: ReturnType<typeof scannerOverviewLogic.build>let statsRequests: string[]let impactRequests: string[]@@ -49,99 +50,126 @@ describe('scannerOverviewLogic', () => {},})initKeaTests()- logic = scannerOverviewLogic({ scannerId: 'sid' })- logic.mount()})- afterEach(() => logic.unmount())+ describe('with a mounted scanner', () => {+ let logic: ReturnType<typeof scannerOverviewLogic.build>- it('treats the default date range as inactive but any pill or non-default date as active', async () => {- await expectLogic(logic).toFinishAllListeners()- // A spurious "active" here would surface a Clear button on an untouched Overview.- expect(logic.values.hasActiveOverviewFilters).toBe(false)+ beforeEach(() => {+ logic = scannerOverviewLogic({ scannerId: 'sid' })+ logic.mount()+ })- await expectLogic(logic, () => logic.actions.setOverviewVerdictFilter(['no'])).toFinishAllListeners()- expect(logic.values.hasActiveOverviewFilters).toBe(true)+ afterEach(() => logic.unmount())- await expectLogic(logic, () => {- logic.actions.setOverviewVerdictFilter([])- logic.actions.setOverviewDateRange('-30d', null)- }).toFinishAllListeners()- expect(logic.values.hasActiveOverviewFilters).toBe(true)- })+ it('treats the default date range as inactive but any pill or non-default date as active', async () => {+ await expectLogic(logic).toFinishAllListeners()+ // A spurious "active" here would surface a Clear button on an untouched Overview.+ expect(logic.values.hasActiveOverviewFilters).toBe(false)- it('reloads stats with the active filters as query params', async () => {- await expectLogic(logic).toFinishAllListeners()- statsRequests = []+ await expectLogic(logic, () => logic.actions.setOverviewVerdictFilter(['no'])).toFinishAllListeners()+ expect(logic.values.hasActiveOverviewFilters).toBe(true)- await expectLogic(logic, () => {- logic.actions.setOverviewVerdictFilter(['no'])- logic.actions.setOverviewTagFilter(['checkout'])- }).toFinishAllListeners()+ await expectLogic(logic, () => {+ logic.actions.setOverviewVerdictFilter([])+ logic.actions.setOverviewDateRange('-30d', null)+ }).toFinishAllListeners()+ expect(logic.values.hasActiveOverviewFilters).toBe(true)+ })- // Only the overview reloads on these actions, so the newest stats request is its own.- const url = new URL(statsRequests[statsRequests.length - 1])- expect(url.searchParams.get('verdict')).toBe('no')- expect(url.searchParams.get('tags')).toBe('checkout')- })+ it('reloads stats with the active filters as query params', async () => {+ await expectLogic(logic).toFinishAllListeners()+ statsRequests = []- it('reloads impact with a window derived from the date range, clamped to the endpoint max', async () => {- await expectLogic(logic).toFinishAllListeners()- impactRequests = []+ await expectLogic(logic, () => {+ logic.actions.setOverviewVerdictFilter(['no'])+ logic.actions.setOverviewTagFilter(['checkout'])+ }).toFinishAllListeners()- await expectLogic(logic, () => logic.actions.setOverviewDateRange('-7d', null)).toFinishAllListeners()- expect(new URL(impactRequests[impactRequests.length - 1]).searchParams.get('window_days')).toBe('7')+ // Only the overview reloads on these actions, so the newest stats request is its own.+ const url = new URL(statsRequests[statsRequests.length - 1])+ expect(url.searchParams.get('verdict')).toBe('no')+ expect(url.searchParams.get('tags')).toBe('checkout')+ })- // A range past the endpoint's 90-day cap must clamp, not send an out-of-range value the API rejects.- await expectLogic(logic, () => logic.actions.setOverviewDateRange('-180d', null)).toFinishAllListeners()- expect(new URL(impactRequests[impactRequests.length - 1]).searchParams.get('window_days')).toBe('90')- })+ it('reloads impact with a window derived from the date range, clamped to the endpoint max', async () => {+ await expectLogic(logic).toFinishAllListeners()+ impactRequests = []- it('clearOverviewFilters resets the date back to the default, not null', async () => {- await expectLogic(logic, () => {- logic.actions.setOverviewDateRange('-90d', null)- logic.actions.setOverviewVerdictFilter(['no'])- }).toFinishAllListeners()-- // A null date would break the recent_days derivation the stats loader depends on.- await expectLogic(logic, () => logic.actions.clearOverviewFilters()).toFinishAllListeners()- expect(logic.values.overviewDateFrom).toBe('-14d')- expect(logic.values.overviewVerdictFilter).toEqual([])- expect(logic.values.hasActiveOverviewFilters).toBe(false)- })+ await expectLogic(logic, () => logic.actions.setOverviewDateRange('-7d', null)).toFinishAllListeners()+ expect(new URL(impactRequests[impactRequests.length - 1]).searchParams.get('window_days')).toBe('7')- describe('creditLimitStats', () => {- it('is null when the scanner has no limit, so callers render no panel instead of "0% of 0"', async () => {- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.creditLimitStats).toBeNull()- })-- it.each([- { used: 200, limit: 1000, expectedPct: 20, expectedReached: false },- { used: 1000, limit: 1000, expectedPct: 100, expectedReached: true },- { used: 1200, limit: 1000, expectedPct: 100, expectedReached: true },- // The server reports reached as soon as what's left can't cover one more scan, so this- // must come from the API and not be re-derived from usedPct.- { used: 990, limit: 1000, expectedPct: 99, expectedReached: true },- ])(- 'derives usedPct $expectedPct and limitReached $expectedReached from used=$used, limit=$limit',- async ({ used, limit, expectedPct, expectedReached }) => {- await expectLogic(logic, () =>- logic.actions.loadScannerSuccess({- ...logic.values.scanner,- credit_limit: limit,- credits_used_against_limit: used,- limit_reached: expectedReached,- })- ).toFinishAllListeners()- expect(logic.values.creditLimitStats).toEqual({- limit,- used,- usedPct: expectedPct,- limitReached: expectedReached,+ // A range past the endpoint's 90-day cap must clamp, not send an out-of-range value the API rejects.+ await expectLogic(logic, () => logic.actions.setOverviewDateRange('-180d', null)).toFinishAllListeners()+ expect(new URL(impactRequests[impactRequests.length - 1]).searchParams.get('window_days')).toBe('90')+ })++ it('clearOverviewFilters resets the date back to the default, not null', async () => {+ await expectLogic(logic, () => {+ logic.actions.setOverviewDateRange('-90d', null)+ logic.actions.setOverviewVerdictFilter(['no'])+ }).toFinishAllListeners()++ // A null date would break the recent_days derivation the stats loader depends on.+ await expectLogic(logic, () => logic.actions.clearOverviewFilters()).toFinishAllListeners()+ expect(logic.values.overviewDateFrom).toBe('-14d')+ expect(logic.values.overviewVerdictFilter).toEqual([])+ expect(logic.values.hasActiveOverviewFilters).toBe(false)+ })++ describe('drillIntoObservations', () => {+ it('navigates to the observations tab filtered to the clicked day, with the monitor verdict', async () => {+ // The mocked scanner is a monitor, so the drill-down should carry verdict=yes.+ await expectLogic(logic, () => logic.actions.drillIntoObservations('2026-05-04')).toFinishAllListeners()+ expect(router.values.location.pathname).toContain(urls.replayVision('sid'))+ expect(router.values.searchParams).toMatchObject({+ tab: 'observations',+ date_from: '2026-05-04',+ date_to: '2026-05-04',+ verdict: 'yes',})- }- )+ })++ it('ignores clicks on buckets that cannot map to a day filter', async () => {+ const before = router.values.location.pathname+ await expectLogic(logic, () => logic.actions.drillIntoObservations(undefined)).toFinishAllListeners()+ expect(router.values.location.pathname).toBe(before)+ })+ })++ describe('creditLimitStats', () => {+ it('is null when the scanner has no limit, so callers render no panel instead of "0% of 0"', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.creditLimitStats).toBeNull()+ })++ it.each([+ { used: 200, limit: 1000, expectedPct: 20, expectedReached: false },+ { used: 1000, limit: 1000, expectedPct: 100, expectedReached: true },+ { used: 1200, limit: 1000, expectedPct: 100, expectedReached: true },+ // The server reports reached as soon as what's left can't cover one more scan, so this+ // must come from the API and not be re-derived from usedPct.+ { used: 990, limit: 1000, expectedPct: 99, expectedReached: true },+ ])(+ 'derives usedPct $expectedPct and limitReached $expectedReached from used=$used, limit=$limit',+ async ({ used, limit, expectedPct, expectedReached }) => {+ await expectLogic(logic, () =>+ logic.actions.loadScannerSuccess({+ ...logic.values.scanner,+ credit_limit: limit,+ credits_used_against_limit: used,+ limit_reached: expectedReached,+ })+ ).toFinishAllListeners()+ expect(logic.values.creditLimitStats).toEqual({+ limit,+ used,+ usedPct: expectedPct,+ limitReached: expectedReached,+ })+ }+ )+ })})describe('observationsDrilldownSearchParams', () => {@@ -194,23 +222,171 @@ describe('scannerOverviewLogic', () => {})})- describe('drillIntoObservations', () => {- it('navigates to the observations tab filtered to the clicked day, with the monitor verdict', async () => {- // The mocked scanner is a monitor, so the drill-down should carry verdict=yes.- await expectLogic(logic, () => logic.actions.drillIntoObservations('2026-05-04')).toFinishAllListeners()- expect(router.values.location.pathname).toContain(urls.replayVision('sid'))- expect(router.values.searchParams).toMatchObject({- tab: 'observations',- date_from: '2026-05-04',- date_to: '2026-05-04',- verdict: 'yes',+ describe('firstScanPending', () => {+ let freshLogic: ReturnType<typeof scannerOverviewLogic.build>+ let scannerBody: Record<string, unknown>+ let statsBody: Record<string, unknown>+ let failRequests: boolean++ const SETTLED_STATS = {+ ...STATS,+ status_counts: { total: 3, succeeded: 3, failed: 0, ineligible: 0, in_flight: 0, success_rate: 1 },+ }++ beforeEach(() => {+ // A just-created scanner: watermark still at its seeded value 35 minutes before creation.+ scannerBody = {+ id: 'fresh',+ name: 'fresh',+ scanner_type: 'monitor',+ scanner_config: { prompt: 'p' },+ sampling_rate: 1,+ enabled: true,+ created_at: dayjs().subtract(2, 'minute').toISOString(),+ last_swept_at: dayjs().subtract(37, 'minute').toISOString(),+ }+ statsBody = STATS+ failRequests = false+ useMocks({+ get: {+ '/api/projects/:team/vision/scanners/:id/': () => (failRequests ? [500, {}] : [200, scannerBody]),+ '/api/projects/:team/vision/scanners/:id/observations/stats/': ({ request }) => {+ statsRequests.push(request.url)+ return failRequests ? [500, {}] : [200, statsBody]+ },+ },})+ freshLogic = scannerOverviewLogic({ scannerId: 'fresh' })+ })++ afterEach(() => {+ freshLogic.unmount()+ jest.useRealTimers()+ })++ it('is true for a fresh scanner awaiting its first sweep, except while overview filters slice the data', async () => {+ freshLogic.mount()+ await expectLogic(freshLogic).toFinishAllListeners()+ expect(freshLogic.values.firstScanPending).toBe(true)++ // Filters mean the user is inspecting data, so the normal panels must render.+ await expectLogic(freshLogic, () =>+ freshLogic.actions.setOverviewVerdictFilter(['no'])+ ).toFinishAllListeners()+ expect(freshLogic.values.firstScanPending).toBe(false)++ // A filtered flip must not latch as settled: clearing the filter brings the panel back.+ await expectLogic(freshLogic, () => freshLogic.actions.clearOverviewFilters()).toFinishAllListeners()+ expect(freshLogic.values.firstScanPending).toBe(true)+ })++ it('polls stats in the background while pending and stops once observations settle', async () => {+ // toFinishAllListeners hangs under fake timers (msw resolves responses on the clock),+ // so the whole test advances fake time instead, which also flushes microtasks.+ jest.useFakeTimers()+ freshLogic.mount()+ await jest.advanceTimersByTimeAsync(1_000)+ expect(freshLogic.values.firstScanPending).toBe(true)++ // Pending arms a background reload on the calmer first-scan interval. Each tick refreshes+ // stats and the watermark only; reloading impact per tick would triple the request count.+ const before = statsRequests.length+ const impactBefore = impactRequests.length+ await jest.advanceTimersByTimeAsync(16_000)+ expect(statsRequests.length).toBe(before + 1)+ expect(impactRequests.length).toBe(impactBefore)++ // Once observations settle, the pending state dissolves and polling stops.+ statsBody = SETTLED_STATS+ await jest.advanceTimersByTimeAsync(16_000)+ expect(freshLogic.values.firstScanPending).toBe(false)++ const after = statsRequests.length+ await jest.advanceTimersByTimeAsync(60_000)+ expect(statsRequests.length).toBe(after)+ })++ it('dissolves once the first sweep completes even when it matched nothing', async () => {+ jest.useFakeTimers()+ freshLogic.mount()+ await jest.advanceTimersByTimeAsync(1_000)+ expect(freshLogic.values.firstScanPending).toBe(true)++ // Stats stay all-zero forever here, so only the poll refetching the scanner's advanced+ // sweep watermark can clear pending before the stuck-scan cap.+ scannerBody = { ...scannerBody, last_swept_at: dayjs().toISOString() }+ await jest.advanceTimersByTimeAsync(16_000)+ expect(freshLogic.values.firstScanPending).toBe(false)+ })++ it('stays dissolved once it settles, even if a later check reports new work in flight', async () => {+ jest.useFakeTimers()+ freshLogic.mount()+ await jest.advanceTimersByTimeAsync(1_000)+ expect(freshLogic.values.firstScanPending).toBe(true)++ scannerBody = { ...scannerBody, last_swept_at: dayjs().toISOString() }+ await jest.advanceTimersByTimeAsync(16_000)+ expect(freshLogic.values.firstScanPending).toBe(false)++ // A follow-up sweep queueing observations must not swap the charts back out for the spinner.+ statsBody = { ...STATS, status_counts: { ...STATS.status_counts, total: 2, in_flight: 2 } }+ freshLogic.actions.loadOverviewStats()+ await jest.advanceTimersByTimeAsync(1_000)+ expect(freshLogic.values.firstScanPending).toBe(false)+ })++ it('keeps polling through a transient outage while pending, without toasting each retry', async () => {+ jest.useFakeTimers()+ const toastSpy = jest.spyOn(lemonToast, 'error')+ freshLogic.mount()+ await jest.advanceTimersByTimeAsync(1_000)+ expect(freshLogic.values.firstScanPending).toBe(true)++ // A stopped poll would freeze the pending panel, which hides every in-page reload control.+ failRequests = true+ await jest.advanceTimersByTimeAsync(16_000)+ expect(freshLogic.values.firstScanPending).toBe(true)+ expect(toastSpy).not.toHaveBeenCalled()++ failRequests = false+ statsBody = SETTLED_STATS+ await jest.advanceTimersByTimeAsync(16_000)+ expect(freshLogic.values.firstScanPending).toBe(false)+ })++ it('surfaces repeated failed checks on the panel instead of spinning silently', async () => {+ jest.useFakeTimers()+ freshLogic.mount()+ await jest.advanceTimersByTimeAsync(1_000)+ expect(freshLogic.values.firstScanCheckFailing).toBe(false)++ failRequests = true+ await jest.advanceTimersByTimeAsync(48_000)+ expect(freshLogic.values.firstScanPending).toBe(true)+ expect(freshLogic.values.firstScanCheckFailing).toBe(true)++ // One good response clears the failure notice.+ failRequests = false+ await jest.advanceTimersByTimeAsync(16_000)+ expect(freshLogic.values.firstScanCheckFailing).toBe(false)})- it('ignores clicks on buckets that cannot map to a day filter', async () => {- const before = router.values.location.pathname- await expectLogic(logic, () => logic.actions.drillIntoObservations(undefined)).toFinishAllListeners()- expect(router.values.location.pathname).toBe(before)+ it('caps a stuck first scan at an hour even when every check fails, then stops polling', async () => {+ jest.useFakeTimers()+ freshLogic.mount()+ await jest.advanceTimersByTimeAsync(1_000)+ expect(freshLogic.values.firstScanPending).toBe(true)++ // A dead endpoint (say the scanner was deleted in another tab) must still hit the age cap:+ // failed checks advance the selector's clock input, so pending can't stick forever.+ failRequests = true+ await jest.advanceTimersByTimeAsync(61 * 60_000)+ expect(freshLogic.values.firstScanPending).toBe(false)++ const after = statsRequests.length+ await jest.advanceTimersByTimeAsync(60_000)+ expect(statsRequests.length).toBe(after)})})})diff --git a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.tsindex e55e1caded7a..3bf2c147309f 100644--- a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts@@ -15,6 +15,7 @@ import {import { loaders } from 'kea-loaders'import { router } from 'kea-router'+import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { isNullBreakdown, isOtherBreakdown } from 'scenes/insights/utils'import { teamLogic } from 'scenes/teamLogic'@@ -22,8 +23,13 @@ import { urls } from 'scenes/urls'import { IntervalType } from '~/types'-import { visionScannersImpactRetrieve, visionScannersObservationsStatsRetrieve } from '../generated/api'+import {+ visionScannersImpactRetrieve,+ visionScannersObservationsStatsRetrieve,+ visionScannersRetrieve,+} from '../generated/api'import type { ObservationStatsApi, ScannerImpactApi } from '../generated/api.schemas'+import { scheduleObservationPoll } from '../logics/observationPolling'import { replayScannerLogic } from './replayScannerLogic'import type { ObservationVerdictValue, ObservationsUrlParams } from './replayScannerLogic'import type {@@ -43,9 +49,9 @@ import {deriveScorerHistogram,deriveScorerSummary,deriveSummarizerFacetStats,+ isAwaitingFirstResults,} from './scannerStats'-import type { ReplayScanner, ScannerType } from './types'-import type { ScannerFormValues } from './types'+import { type ReplayScanner, type ScannerFormValues, type ScannerType, scannerFromApi } from './types'export interface ScannerOverviewLogicProps {scannerId: string@@ -53,6 +59,13 @@ export interface ScannerOverviewLogicProps {const DEFAULT_DATE_FROM = '-14d'+// Calmer than the 3s in-flight default: first scheduled results take minutes, not seconds.+const FIRST_SCAN_POLL_INTERVAL_MS = 15_000++// The pending panel hides the overview's reload affordances, so after this many straight failed+// checks it has to admit the failure itself instead of spinning on a promise it can't verify.+const FIRST_SCAN_CHECK_FAILING_AFTER = 3+export interface CreditLimitStats {limit: numberused: number@@ -99,6 +112,9 @@ export interface scannerOverviewLogicValues {classifierTagStats: ClassifierTagStatscoverageStats: CoverageStatscreditLimitStats: CreditLimitStats | null+ firstScanCheckFailing: boolean+ firstScanPending: boolean+ firstScanSettled: booleanhasActiveOverviewFilters: booleanmonitorStats: MonitorStatsoverviewDateFrom: string | null@@ -107,6 +123,8 @@ export interface scannerOverviewLogicValues {overviewImpactLoading: booleanoverviewStatsApi: ObservationStatsApi | nulloverviewStatsApiLoading: boolean+ overviewStatsCheckedAt: number+ overviewStatsFailureCount: numberoverviewTagFilter: string[]overviewVerdictFilter: ObservationVerdictValue[]scorerHistogram: ScorerHistogram | null@@ -119,6 +137,9 @@ export interface scannerOverviewLogicActions {loadScannerSuccess: (scanner: ScannerFormValues) => {scanner: ScannerFormValues} // replayScannerLogic+ scannerWatermarkRefreshed: (scanner: ReplayScanner) => {+ scanner: ReplayScanner+ } // replayScannerLogicclearOverviewFilters: () => {value: true}@@ -153,6 +174,9 @@ export interface scannerOverviewLogicActions {loadOverviewStatsSuccess: (stats: ObservationStatsApi) => {stats: ObservationStatsApi}+ markFirstScanSettled: () => {+ value: true+ }setOverviewDateRange: (dateFrom: string | null,dateTo: string | null@@ -185,6 +209,14 @@ export interface scannerOverviewLogicMeta {scorerHistogram: (overviewStatsApi: ObservationStatsApi | null) => ScorerHistogram | nullsummarizerFacetStats: (overviewStatsApi: ObservationStatsApi | null) => SummarizerFacetStatscoverageStats: (overviewStatsApi: ObservationStatsApi | null) => CoverageStats+ firstScanPending: (+ overviewStatsApi: ObservationStatsApi | null,+ scanner: ScannerFormValues,+ hasActiveOverviewFilters: boolean,+ firstScanSettled: boolean,+ overviewStatsCheckedAt: number+ ) => boolean+ firstScanCheckFailing: (firstScanPending: boolean, overviewStatsFailureCount: number) => booleancreditLimitStats: (scanner: ScannerFormValues) => CreditLimitStats | null}}@@ -213,13 +245,15 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([connect((props: ScannerOverviewLogicProps) => ({values: [replayScannerLogic({ id: props.scannerId }), ['scanner']],- actions: [replayScannerLogic({ id: props.scannerId }), ['loadScannerSuccess']],+ // Bound at build time, so dispatching into the scanner logic can't depend on it being mounted.+ actions: [replayScannerLogic({ id: props.scannerId }), ['loadScannerSuccess', 'scannerWatermarkRefreshed']],})),actions({loadOverviewStats: true,loadOverviewStatsSuccess: (stats: ObservationStatsApi) => ({ stats }),loadOverviewStatsFailure: true,+ markFirstScanSettled: true,setOverviewDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setOverviewVerdictFilter: (values: ObservationVerdictValue[]) => ({ values }),setOverviewTagFilter: (values: string[]) => ({ values }),@@ -270,6 +304,30 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([loadOverviewStatsFailure: () => false,},],+ // The clock input for the stuck-scan age cap. Ticked on failures too, so the cap still fires+ // when the endpoint errors forever and no other selector input ever changes.+ overviewStatsCheckedAt: [+ Date.now(),+ {+ loadOverviewStatsSuccess: () => Date.now(),+ loadOverviewStatsFailure: () => Date.now(),+ },+ ],+ overviewStatsFailureCount: [+ 0,+ {+ loadOverviewStatsSuccess: () => 0,+ loadOverviewStatsFailure: (state) => state + 1,+ },+ ],+ // Latches the first-scan panel closed for the rest of the mount, so later in-flight+ // observations can't swap the charts back out for the spinner.+ firstScanSettled: [+ false,+ {+ markFirstScanSettled: () => true,+ },+ ],}),selectors({@@ -314,6 +372,34 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([(s) => [s.overviewStatsApi],(stats: ObservationStatsApi | null): CoverageStats => deriveCoverageStats(stats),],+ // While true the Overview swaps its filters + charts for a single "first scan in progress" panel,+ // so a brand-new scanner never shows the generic "no matching events" empty state. Active filters+ // mean the user is slicing data, so the normal panels render then. `overviewStatsCheckedAt`+ // stands in for the current time: reading the clock inside the selector would freeze the age+ // cap whenever the inputs stop changing (e.g. every poll request failing).+ firstScanPending: [+ (s) => [+ s.overviewStatsApi,+ s.scanner,+ s.hasActiveOverviewFilters,+ s.firstScanSettled,+ s.overviewStatsCheckedAt,+ ],+ (+ stats: ObservationStatsApi | null,+ scanner: ReplayScanner | null,+ hasFilters: boolean,+ settled: boolean,+ checkedAt: number+ ): boolean => !settled && !hasFilters && isAwaitingFirstResults(stats, scanner, dayjs(checkedAt)),+ ],+ // The pending panel hides the overview's reload buttons, so it has to surface a failing+ // background check itself instead of spinning forever.+ firstScanCheckFailing: [+ (s) => [s.firstScanPending, s.overviewStatsFailureCount],+ (pending: boolean, failureCount: number): boolean =>+ pending && failureCount >= FIRST_SCAN_CHECK_FAILING_AFTER,+ ],// Null when the scanner has no limit set, so callers can render nothing rather than a "0% of 0" panel.creditLimitStats: [(s) => [s.scanner],@@ -357,20 +443,90 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([],})),- listeners(({ actions, props, values }) => {+ listeners(({ actions, cache, props, values }) => {const reloadStats = (): void => actions.loadOverviewStats()// Only the date range changes the impact window; verdict/tag filters don't apply to impact.const reloadDateScoped = (): void => {actions.loadOverviewStats()actions.loadOverviewImpact()}+ // Pending also hangs off the scanner's sweep watermark, which only the scanner endpoint+ // reports; without refreshing it a first sweep that matches nothing would never clear+ // pending. Fetched directly because loadScanner flips scannerLoading, which blanks the scene,+ // and dispatched through the dedicated watermark action so a background refetch can't reset+ // the scanner form or refire the observation loads.+ const refreshScannerWatermark = async (): Promise<void> => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId || props.scannerId === 'new') {+ return+ }+ try {+ const response = await visionScannersRetrieve(String(teamId), props.scannerId)+ actions.scannerWatermarkRefreshed(scannerFromApi(response))+ } catch {+ // A failed background refresh just waits for the next poll tick.+ }+ }+ // Each tick refreshes stats and the sweep watermark in the background, so the pending panel+ // dissolves into the real Overview on its own. Failing ticks keep polling without toasting+ // (see the loadOverviewStats catch); the panel surfaces them via firstScanCheckFailing.+ const firstScanPollTick = (): void => {+ if (!values.firstScanPending) {+ cache.firstScanPollArmed = false+ return+ }+ // Re-arm at tick time rather than response time, so the gap stays one interval per tick+ // however the stats and watermark responses interleave.+ scheduleObservationPoll(cache.disposables, true, firstScanPollTick, FIRST_SCAN_POLL_INTERVAL_MS)+ actions.loadOverviewStats()+ void refreshScannerWatermark()+ }+ // The single owner of the poll timer and the pending latch, run after every action that can+ // move firstScanPending: arms once per pending spell (the tick re-arms itself), stops the+ // timer the moment pending clears, and latches the first true to false flip for this mount.+ // Filters also flip pending false, so only a flip with no filters active means results arrived;+ // latching on a filtered flip would keep the panel from returning once the filter is cleared.+ const syncFirstScanPoll = (): void => {+ const pending = values.firstScanPending+ if (cache.firstScanWasPending && !pending && !values.hasActiveOverviewFilters && !values.firstScanSettled) {+ actions.markFirstScanSettled()+ }+ cache.firstScanWasPending = cache.firstScanWasPending || pending+ if (!pending) {+ cache.firstScanPollArmed = false+ scheduleObservationPoll(cache.disposables, false, firstScanPollTick, FIRST_SCAN_POLL_INTERVAL_MS)+ } else if (!cache.firstScanPollArmed) {+ cache.firstScanPollArmed = true+ scheduleObservationPoll(cache.disposables, true, firstScanPollTick, FIRST_SCAN_POLL_INTERVAL_MS)+ }+ }return {- setOverviewDateRange: reloadDateScoped,- setOverviewVerdictFilter: reloadStats,- setOverviewTagFilter: reloadStats,- clearOverviewFilters: reloadDateScoped,- // Impact needs the scanner type; refire once the scanner (and its type) resolves.- loadScannerSuccess: () => actions.loadOverviewImpact(),+ setOverviewDateRange: () => {+ reloadDateScoped()+ syncFirstScanPoll()+ },+ setOverviewVerdictFilter: () => {+ reloadStats()+ syncFirstScanPoll()+ },+ setOverviewTagFilter: () => {+ reloadStats()+ syncFirstScanPoll()+ },+ clearOverviewFilters: () => {+ reloadDateScoped()+ syncFirstScanPoll()+ },+ loadOverviewStatsSuccess: syncFirstScanPoll,+ loadOverviewStatsFailure: syncFirstScanPoll,+ scannerWatermarkRefreshed: syncFirstScanPoll,+ // Impact needs the scanner type; refire once the scanner (and its type) resolves. The+ // poll syncs too: pending depends on the sweep watermark, which may resolve after the+ // first stats response.+ loadScannerSuccess: () => {+ actions.loadOverviewImpact()+ syncFirstScanPoll()+ },drillIntoObservations: ({ day, breakdown }) => {const searchParams = observationsDrilldownSearchParams({@@ -418,7 +574,10 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([if (error instanceof Error && isBreakpoint(error)) {throw error}- lemonToast.error('Failed to load overview stats')+ // Background retries behind the pending panel would otherwise stack a toast per interval.+ if (!values.firstScanPending) {+ lemonToast.error('Failed to load overview stats')+ }actions.loadOverviewStatsFailure()}},diff --git a/products/replay_vision/frontend/replay_scanners/scannerStats.test.ts b/products/replay_vision/frontend/replay_scanners/scannerStats.test.tsindex 1ef109b276a3..e16eabfa0614 100644--- a/products/replay_vision/frontend/replay_scanners/scannerStats.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerStats.test.ts@@ -1,8 +1,22 @@+import { dayjs } from 'lib/dayjs'+import type { ObservationStatsApi } from '../generated/api.schemas'-import { deriveSummarizerFacetStats } from './scannerStats'+import { deriveSummarizerFacetStats, isAwaitingFirstResults } from './scannerStats'++// Fully typed (no cast) so schema changes to ObservationStatsApi break these fixtures at compile time.+const emptyStats: ObservationStatsApi = {+ status_counts: { total: 0, succeeded: 0, failed: 0, ineligible: 0, in_flight: 0, success_rate: null },+ coverage: { recent_sessions: 0, total_sessions: 0, recent_days: 14 },+ labels: { up_total: 0, down_total: 0, by_day: [], by_rating_day: [], version_markers: [] },+ available_tags: [],+ monitor: null,+ classifier: null,+ scorer: null,+ summarizer: null,+}-// Partial on purpose: only the fields deriveSummarizerFacetStats reads.-const stats = {+const stats: ObservationStatsApi = {+ ...emptyStats,status_counts: { total: 10, succeeded: 8, failed: 1, ineligible: 1, in_flight: 0, success_rate: 0.8 },summarizer: {friction_ranked: [{ term: 'checkout stalls', count: 3 }],@@ -10,7 +24,58 @@ const stats = {total_with_facets: 4,total_with_friction: 3,},-} as ObservationStatsApi+}++describe('isAwaitingFirstResults', () => {+ const NOW = dayjs('2026-08-11T12:00:00Z')++ const statsWith = (counts: Partial<ObservationStatsApi['status_counts']>): ObservationStatsApi => ({+ ...emptyStats,+ status_counts: { ...emptyStats.status_counts, ...counts },+ })++ // Mirrors a fresh scanner: created moments ago, watermark seeded 35 minutes before creation.+ const scannerWith = (+ overrides: Partial<{ enabled: boolean; created_at: string; last_swept_at: string }> = {}+ ): Parameters<typeof isAwaitingFirstResults>[1] => ({+ enabled: true,+ created_at: NOW.subtract(2, 'minute').toISOString(),+ last_swept_at: NOW.subtract(37, 'minute').toISOString(),+ ...overrides,+ })++ const cases: [string, ObservationStatsApi | null, Parameters<typeof isAwaitingFirstResults>[1], boolean][] = [+ ['stats not loaded yet', null, scannerWith(), false],+ ['fresh scanner before its first sweep completes', statsWith({}), scannerWith(), true],+ [+ 'first observations still processing after the sweep',+ statsWith({ total: 2, in_flight: 2 }),+ scannerWith({ last_swept_at: NOW.subtract(1, 'minute').toISOString() }),+ true,+ ],+ ['settled observations exist', statsWith({ total: 1, succeeded: 1 }), scannerWith(), false],+ [+ 'first sweep done and genuinely nothing matched',+ statsWith({}),+ scannerWith({ last_swept_at: NOW.subtract(1, 'minute').toISOString() }),+ false,+ ],+ ['scanner disabled', statsWith({}), scannerWith({ enabled: false }), false],+ [+ 'stalled sweep past the first hour degrades to the normal empty state',+ statsWith({}),+ scannerWith({+ created_at: NOW.subtract(2, 'hour').toISOString(),+ last_swept_at: NOW.subtract(3, 'hour').toISOString(),+ }),+ false,+ ],+ ]++ it.each(cases)('%s', (_label, stats, scanner, expected) => {+ expect(isAwaitingFirstResults(stats, scanner, NOW)).toBe(expected)+ })+})describe('deriveSummarizerFacetStats', () => {it('uses every succeeded summary as the friction rate denominator, not just facet emitters', () => {diff --git a/products/replay_vision/frontend/replay_scanners/scannerStats.ts b/products/replay_vision/frontend/replay_scanners/scannerStats.tsindex e993ad78104c..d1ac6e73c89b 100644--- a/products/replay_vision/frontend/replay_scanners/scannerStats.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerStats.ts@@ -3,10 +3,11 @@// and scannerOverviewLogic (Overview tab: verdict mix / tag rankings / score distribution / coverage),// so the two tabs compute identical shapes from the same endpoint without duplicating the mapping.-import { dayjs } from 'lib/dayjs'+import { Dayjs, dayjs } from 'lib/dayjs'import { dateStringToDayJs } from 'lib/utils/dateFilters'import type { ObservationStatsApi } from '../generated/api.schemas'+import type { ReplayScanner } from './types'export interface ObservationStatusStats {total: number@@ -113,6 +114,36 @@ export function daysFromDateRange(dateFrom: string | null, dateTo: string | nullreturn Math.max(1, to.diff(from, 'day'))}+// Past this age a first sweep that never completed means something is stuck (throttled or stalled),+// so the UI should fall back to the normal empty states instead of promising results indefinitely.+const FIRST_RESULTS_MAX_AGE_MINUTES = 60++/**+ * True while a just-created scanner has no settled observations yet: its first sweep hasn't completed+ * (last_swept_at is seeded before created_at and only advances when a sweep tick finishes) or its+ * first observations are still processing.+ */+export function isAwaitingFirstResults(+ stats: ObservationStatsApi | null,+ scanner: Pick<ReplayScanner, 'enabled' | 'created_at' | 'last_swept_at'> | null,+ now: Dayjs = dayjs()+): boolean {+ // The wizard's unsaved form lacks the timestamps, so it can never read as pending.+ if (!stats || !scanner?.enabled || !scanner.created_at || !scanner.last_swept_at) {+ return false+ }+ const counts = stats.status_counts+ if (counts.succeeded + counts.failed + counts.ineligible > 0) {+ return false+ }+ const createdAt = dayjs(scanner.created_at)+ // Minutes rather than hours, since dayjs truncates diffs to whole units.+ if (now.diff(createdAt, 'minute') >= FIRST_RESULTS_MAX_AGE_MINUTES) {+ return false+ }+ return counts.in_flight > 0 || dayjs(scanner.last_swept_at).isBefore(createdAt)+}+export interface SummarizerFacetStats {frictionRanked: [string, number][]keywordRanked: [string, number][]