: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): empty and stale states for the what to watch list (#118650)
Hayne Ryu28bad2ac35d8
diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksBlockedState.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksBlockedState.tsxnew file mode 100644index 000000000000..59b44a8ade11--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksBlockedState.tsx@@ -0,0 +1,151 @@+import { useActions, useMountedLogic, useValues } from 'kea'+import { useState } from 'react'++import * as asleepPng from '@posthog/brand/hoggies/png/asleep'+import { LemonBanner, LemonButton, LemonSwitch, Link } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'++import type { ReplayScannerApi } from '../../generated/api.schemas'+import { visionQuotaLogic } from '../../logics/visionQuotaLogic'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { formatCreditsMaybeUsd } from '../../utils/credits'+import { stoppedByFreeCredits } from '../scannerCopy'+import { watchPicksLogic } from '../watchPicksLogic'+import { watchPicksStaleLogic } from '../watchPicksStaleLogic'+import { WatchPicksStateFrame } from './WatchPicksStateFrame'++const RAISE_FACTOR = 1.5+const HedgehogAsleep = pngHoggie(asleepPng)++export function WatchPicksBlockedState({+ reason,+ size = 'small',+}: {+ reason: 'all-disabled' | 'all-capped' | 'quota-exhausted'+ size?: 'small' | 'large'+}): JSX.Element {+ const picksLogic = useMountedLogic(watchPicksLogic)+ const logic = watchPicksStaleLogic(picksLogic.props)+ const { scanners, quota, busyScannerId } = useValues(logic)+ const { showUsd } = useValues(visionQuotaLogic)+ const { toggleScanner, raiseLimit } = useActions(logic)+ const [raising, setRaising] = useState<string | null>(null)+ const editDisabledReason = getReplayVisionEditDisabledReason()++ if (reason === 'all-disabled') {+ return (+ <WatchPicksStateFrame+ size={size}+ image={HedgehogAsleep}+ title="None of your scanners are running"+ body="Turn one on and picks appear after the next matching recording."+ dataAttr="vision-watch-picks-block-disabled"+ footer={+ <Link to={urls.replayVision()} className="mt-1" data-attr="vision-watch-picks-block-open">+ Open Replay vision+ </Link>+ }+ >+ <div className="flex flex-col divide-y rounded border bg-bg-light text-left">+ {scanners.map((scanner: ReplayScannerApi) => (+ <div key={scanner.id} className="flex items-center justify-between gap-2 px-3 py-2">+ <div className="min-w-0">+ <div className="truncate text-xs font-semibold text-default">{scanner.name}</div>+ <div className="text-xs text-secondary">+ Off since <TZLabel time={scanner.updated_at} showPopover={false} noStyles />+ </div>+ </div>+ <LemonSwitch+ checked={scanner.enabled ?? false}+ disabledReason={editDisabledReason}+ loading={busyScannerId === scanner.id}+ onChange={(checked) => toggleScanner(scanner.id, checked)}+ data-attr="vision-watch-picks-block-toggle"+ />+ </div>+ ))}+ </div>+ </WatchPicksStateFrame>+ )+ }++ const capped = reason === 'all-capped' ? scanners.filter((scanner) => scanner.enabled && scanner.limit_reached) : []+ const resetsAt = quota?.period_end+ const freeSampleUsedUp = capped.length > 0 && capped.every((scanner) => stoppedByFreeCredits(scanner))+ return (+ <LemonBanner type="warning" className="m-2" data-attr="vision-watch-picks-block-capped">+ <div className="flex flex-col gap-2">+ <span className="font-semibold">+ {reason === 'quota-exhausted'+ ? 'Scanners paused: your Replay vision credits are used up for this period'+ : freeSampleUsedUp+ ? 'Scanners paused: your free sample is used up'+ : 'Scanners paused: every running scanner reached its credit limit'}+ </span>+ <span className="text-xs">+ {freeSampleUsedUp ? 'Set a budget to keep scanning, or wait. ' : ''}+ {resetsAt ? (+ <>+ Resets <TZLabel time={resetsAt} showPopover={false} noStyles />. Picks stop until then.+ </>+ ) : (+ 'Picks stop until the period resets.'+ )}+ </span>+ {capped.map((scanner) => {+ const current = scanner.credit_limit ?? 0+ const next = Math.ceil((current * RAISE_FACTOR) / 100) * 100 || 500+ const freeOnly = stoppedByFreeCredits(scanner)+ return (+ <div key={scanner.id} className="flex flex-wrap items-center justify-between gap-2 text-xs">+ <span className="font-semibold">{scanner.name}</span>+ {raising === scanner.id ? (+ <span className="flex items-center gap-1">+ <LemonButton+ size="xsmall"+ type="primary"+ loading={busyScannerId === scanner.id}+ onClick={() => {+ raiseLimit(scanner.id, next)+ setRaising(null)+ }}+ data-attr="vision-watch-picks-block-raise-confirm"+ >+ Set {formatCreditsMaybeUsd(next, showUsd)} a month+ </LemonButton>+ <LemonButton+ size="xsmall"+ onClick={() => setRaising(null)}+ data-attr="vision-watch-picks-block-raise-cancel"+ >+ Cancel+ </LemonButton>+ </span>+ ) : (+ <LemonButton+ size="xsmall"+ type="secondary"+ disabledReason={editDisabledReason}+ onClick={() => setRaising(scanner.id)}+ data-attr="vision-watch-picks-block-raise"+ >+ {freeOnly ? 'Set a budget' : 'Raise limit'}+ </LemonButton>+ )}+ </div>+ )+ })}+ <Link+ to={`${urls.replayVision()}?tab=usage`}+ className="text-xs"+ data-attr="vision-watch-picks-block-usage"+ >+ See usage+ </Link>+ </div>+ </LemonBanner>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksEmptyState.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksEmptyState.tsxindex 6dfdd607c858..9bfd0f46f244 100644--- a/products/replay_vision/frontend/replay_scanners/components/WatchPicksEmptyState.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksEmptyState.tsx@@ -1,27 +1,19 @@-import { useActions, useValues } from 'kea'-import { router } from 'kea-router'+import { useValues } from 'kea'-import * as townCrierPng from '@posthog/brand/hoggies/png/town-crier'-import { LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'+import { LemonSkeleton } from '@posthog/lemon-ui'-import { pngHoggie } from 'lib/brand/hoggies'import { cn } from 'lib/utils/css-classes'-import { urls } from 'scenes/urls'import { visionQuotaLogic } from '../../logics/visionQuotaLogic'import { visionScannersListLogic } from '../../logics/visionScannersListLogic'-import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'-import { markScannerGoalDraftIntent } from '../scannerHandoffIntent'import { resolveWatchFeedEmptyReason } from '../watchFeedEmptyState'--const HedgehogTownCrier = pngHoggie(townCrierPng)-const DEFAULT_GOAL =- 'Watch sessions and give me an overview of what people are doing in the product, so I know which sessions to look at, why, and where the interesting moment is.'+import { WatchPicksBlockedState } from './WatchPicksBlockedState'+import { WatchPicksQuietState } from './WatchPicksQuietState'+import { WatchPicksStarter } from './WatchPicksStarter'export function WatchPicksEmptyState({ size }: { size: 'small' | 'large' }): JSX.Element {const { scanners, scannersLoading } = useValues(visionScannersListLogic)const { quota, quotaLoading } = useValues(visionQuotaLogic)- const { push } = useActions(router)const large = size === 'large'if (scannersLoading || quotaLoading) {@@ -29,101 +21,12 @@ export function WatchPicksEmptyState({ size }: { size: 'small' | 'large' }): JSX}const reason = resolveWatchFeedEmptyReason({ scanners, quota, hasFeedFilters: false })-- let title: string- let body: string- let action: JSX.Element- switch (reason) {- case 'no-scanners':- title = 'Set up your first scanner'- body =- 'Tell a scanner what to look for and it watches recordings for you. Start with the default goal or write your own.'- action = (- <div className="flex flex-wrap items-center justify-center gap-2">- <LemonButton- type="primary"- size={large ? 'medium' : 'small'}- disabledReason={getReplayVisionEditDisabledReason()}- onClick={() => {- if (markScannerGoalDraftIntent(DEFAULT_GOAL)) {- push(urls.replayVisionTemplates())- } else {- push(urls.replayVisionTemplates(), { goal: DEFAULT_GOAL })- }- }}- data-attr="vision-watch-picks-draft-scanner"- >- Draft my scanner- </LemonButton>- <Link to={urls.replayVisionTemplates()} data-attr="vision-watch-picks-browse-templates">- Write my own goal- </Link>- </div>- )- break- case 'all-disabled':- title = 'None of your scanners are running'- body = 'Turn one on and its picks appear after the next matching recording.'- action = (- <LemonButton- type="secondary"- size="small"- onClick={() => push(urls.replayVision(), { tab: 'scanners' })}- data-attr="vision-watch-picks-see-scanners"- >- See scanners- </LemonButton>- )- break- case 'all-capped':- title = 'Every running scanner has reached its credit limit'- body = "They stop scanning until the period resets. Raise a scanner's limit to start it again."- action = (- <LemonButton- type="secondary"- size="small"- onClick={() => push(urls.replayVision(), { tab: 'usage' })}- data-attr="vision-watch-picks-see-usage"- >- See usage- </LemonButton>- )- break- case 'quota-exhausted':- title = 'Your Replay vision credits are used up for this period'- body = 'Scans are skipped until the period resets. Raise the limit to start them again.'- action = (- <LemonButton- type="secondary"- size="small"- onClick={() => push(urls.replayVision(), { tab: 'usage' })}- data-attr="vision-watch-picks-see-usage"- >- See usage- </LemonButton>- )- break- default:- title = 'Nothing to watch yet'- body = 'Your scanners are running. Picks appear here as they flag new recordings.'- action = (- <Link to={urls.replayVision()} data-attr="vision-watch-picks-empty-link">- Open Replay vision- </Link>- )+ if (reason === 'no-scanners') {+ return <WatchPicksStarter size={size} />+ }+ if (reason === 'all-disabled' || reason === 'all-capped' || reason === 'quota-exhausted') {+ return <WatchPicksBlockedState reason={reason} size={size} />}- return (- <div- className={cn(- 'flex flex-col items-center gap-2 text-center text-secondary',- large ? 'rounded border bg-bg-light p-8 text-sm' : 'p-4 text-xs'- )}- >- <HedgehogTownCrier className={large ? 'h-48 w-48' : 'h-24 w-24'} />- <span className={cn('font-semibold text-default', large ? 'text-lg' : 'text-sm')}>{title}</span>- <span className="max-w-lg">{body}</span>- <div className="mt-1">{action}</div>- </div>- )+ return <WatchPicksQuietState size={size} />}diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksExtraRows.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksExtraRows.tsxnew file mode 100644index 000000000000..e2ede7c47aa9--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksExtraRows.tsx@@ -0,0 +1,46 @@+import { useMountedLogic, useValues } from 'kea'+import { useEffect, useRef } from 'react'++import type { WatchFeedItemApi } from '../../generated/api.schemas'+import { watchPicksLogic } from '../watchPicksLogic'+import { watchPicksStaleLogic } from '../watchPicksStaleLogic'+import { watchPicksStarterLogic } from '../watchPicksStarterLogic'+import { WatchPickRow } from './WatchPickRow'++export function WatchPicksExtraRows(): JSX.Element | null {+ const picksLogic = useMountedLogic(watchPicksLogic)+ const { nextBest } = useValues(watchPicksStaleLogic(picksLogic.props))+ const { scannedAnyway } = useValues(watchPicksStarterLogic(picksLogic.props))+ const ref = useRef<HTMLDivElement>(null)+ const rows = scannedAnyway ?? nextBest++ useEffect(() => {+ if (rows) {+ ref.current?.scrollIntoView({ block: 'nearest' })+ }+ }, [rows])++ if (!rows) {+ return null+ }+ return (+ <div ref={ref} className="flex flex-col gap-0.5 border-t p-1" data-attr="vision-watch-picks-extra-rows">+ <span className="px-2 pt-1 text-xs font-semibold text-secondary">+ {scannedAnyway ? 'Scanned, nothing notable' : 'Newest results, not ranked'}+ </span>+ {rows.length === 0 ? (+ <span className="px-2 pb-1 text-xs text-secondary">No finished scans this week.</span>+ ) : (+ rows.map((observation, index) => (+ <WatchPickRow+ key={observation.id}+ item={{ observation, reason: { kind: 'recent' } } as WatchFeedItemApi}+ position={index}+ surface="list"+ isActive={false}+ />+ ))+ )}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksList.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksList.tsxindex 8b0c63d38580..ed762649fde0 100644--- a/products/replay_vision/frontend/replay_scanners/components/WatchPicksList.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksList.tsx@@ -1,16 +1,23 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'-import { LemonBanner, LemonSkeleton } from '@posthog/lemon-ui'+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'import { watchPicksLogic } from '../watchPicksLogic'+import { watchPicksStarterLogic } from '../watchPicksStarterLogic'import { WatchPickRow } from './WatchPickRow'import { WatchPicksEmptyState } from './WatchPicksEmptyState'+import { WatchPicksExtraRows } from './WatchPicksExtraRows'+import { WatchPicksStaleBanner } from './WatchPicksStaleBanner'+import { WatchPicksStarterStatus } from './WatchPicksStarterStatus'const LIST_TOP_COUNT = 5export function WatchPicksList(): JSX.Element {- const { picks, picksLoading, picksFailed, activeSessionId } = useValues(watchPicksLogic)- const { loadPicks } = useActions(watchPicksLogic)+ const picksLogic = useMountedLogic(watchPicksLogic)+ const { picks, picksLoading, picksFailed, activeSessionId } = useValues(picksLogic)+ const { loadPicks } = useActions(picksLogic)+ const { startedScanner, burstDone, burstStalled } = useValues(watchPicksStarterLogic(picksLogic.props))+ const burstActive = startedScanner !== null && (!burstDone || burstStalled)return (<div@@ -18,35 +25,56 @@ export function WatchPicksList(): JSX.Element {data-attr="vision-watch-picks-list"><div className="min-h-0 flex-1 overflow-y-auto">- {picksLoading || (picks === null && !picksFailed) ? (+ {picks === null && !picksFailed ? (<div className="flex flex-col gap-2 p-2" aria-busy>{[0, 1, 2, 3].map((i) => (<LemonSkeleton key={i} className="h-16 rounded" />))}</div>) : picksFailed ? (- <LemonBanner- type="error"- className="m-2"- action={{ children: 'Try again', onClick: loadPicks, 'data-attr': 'vision-watch-picks-retry' }}+ <div+ className="flex flex-col items-center gap-2 p-4 text-center text-xs text-secondary"+ data-attr="vision-watch-picks-failed">- Couldn't load what to watch.- </LemonBanner>+ <span className="text-sm font-semibold text-default">Couldn't load what to watch</span>+ <span>Something went wrong on our side. Try again in a moment.</span>+ <LemonButton+ type="secondary"+ size="small"+ className="mt-1"+ loading={picksLoading}+ onClick={loadPicks}+ data-attr="vision-watch-picks-retry"+ >+ Try again+ </LemonButton>+ </div>) : !picks || picks.length === 0 ? (- <WatchPicksEmptyState size="small" />+ startedScanner ? (+ <>+ <WatchPicksStarterStatus />+ <WatchPicksExtraRows />+ </>+ ) : (+ <WatchPicksEmptyState size="small" />+ )) : (- <div className="flex flex-col gap-0.5 p-1">- {picks.map((item, index) => (- <WatchPickRow- key={item.observation.id}- item={item}- position={index}- surface="list"- rank={index < LIST_TOP_COUNT ? index + 1 : undefined}- isActive={item.observation.session_id === activeSessionId}- />- ))}- </div>+ <>+ {burstActive ? <WatchPicksStarterStatus /> : <WatchPicksStaleBanner />}+ <div className="flex flex-col gap-0.5 p-1">+ {picks.map((item, index) => (+ <WatchPickRow+ key={item.observation.id}+ item={item}+ position={index}+ surface="list"+ rank={index < LIST_TOP_COUNT ? index + 1 : undefined}+ isActive={item.observation.session_id === activeSessionId}+ />+ ))}+ </div>+ <WatchPicksExtraRows />+ </>)}</div></div>diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksListColumn.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksListColumn.tsxindex 980f757e5639..844b29108ab1 100644--- a/products/replay_vision/frontend/replay_scanners/components/WatchPicksListColumn.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksListColumn.tsx@@ -1,9 +1,10 @@-import { useActions, useValues } from 'kea'+import { useActions, useMountedLogic, useValues } from 'kea'import { ReactNode } from 'react'import { LemonBadge, LemonSegmentedButton } from '@posthog/lemon-ui'import { watchPicksLogic } from '../watchPicksLogic'+import { watchPicksStarterLogic } from '../watchPicksStarterLogic'import { WatchPicksList } from './WatchPicksList'interface WatchPicksListColumnProps {@@ -11,8 +12,10 @@ interface WatchPicksListColumnProps {}export function WatchPicksListColumn({ recordingsList }: WatchPicksListColumnProps): JSX.Element {- const { effectiveListMode, unwatchedCount } = useValues(watchPicksLogic)- const { setListMode } = useActions(watchPicksLogic)+ const picksLogic = useMountedLogic(watchPicksLogic)+ const { effectiveListMode, unwatchedCount } = useValues(picksLogic)+ const { setListMode } = useActions(picksLogic)+ useMountedLogic(watchPicksStarterLogic(picksLogic.props))return (<>diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksQuietState.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksQuietState.tsxnew file mode 100644index 000000000000..c86ae5de70b2--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksQuietState.tsx@@ -0,0 +1,114 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import * as noirPng from '@posthog/brand/hoggies/png/noir-1'+import { LemonButton, LemonSelect, Link } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { TZLabel } from 'lib/components/TZLabel'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { formatCreditCount } from '../../utils/credits'+import { SWEEP_INTERVAL_MINUTES } from '../scannerStatus'+import { watchPicksLogic } from '../watchPicksLogic'+import { watchPicksStaleLogic } from '../watchPicksStaleLogic'+import { WatchPicksStateFrame } from './WatchPicksStateFrame'++const HedgehogNoir = pngHoggie(noirPng)++export function WatchPicksQuietState({ size }: { size: 'small' | 'large' }): JSX.Element {+ const picksLogic = useMountedLogic(watchPicksLogic)+ const logic = watchPicksStaleLogic(picksLogic.props)+ const {+ backfillCandidates,+ backfillScannerId,+ backfillEstimate,+ backfillEstimateLoading,+ backfillTotals,+ busyScannerId,+ lastSweptAt,+ } = useValues(logic)+ const { pickBackfillScanner, startBackfill } = useActions(logic)+ const large = size === 'large'+ const editDisabledReason = getReplayVisionEditDisabledReason()++ const started = backfillScannerId ? backfillTotals[backfillScannerId] : undefined+ const estimateReady = backfillEstimate?.scannerId === backfillScannerId ? backfillEstimate : null++ return (+ <WatchPicksStateFrame+ size={size}+ image={HedgehogNoir}+ title="Nothing to watch yet"+ body={+ <>+ {pluralize(backfillCandidates.length, 'scanner')} running+ {lastSweptAt && (+ <>+ , last sweep <TZLabel time={lastSweptAt} showPopover={false} noStyles />+ </>+ )}+ . New recordings are checked every {SWEEP_INTERVAL_MINUTES} minutes and picks appear here.+ </>+ }+ dataAttr="vision-watch-picks-quiet"+ footer={+ <Link to={urls.replayVision()} className="mt-1" data-attr="vision-watch-picks-empty-link">+ Open Replay vision+ </Link>+ }+ >+ {backfillCandidates.length > 0 &&+ (started === undefined ? (+ <>+ {backfillCandidates.length > 1 && (+ <LemonSelect+ size="small"+ fullWidth+ value={backfillScannerId}+ onChange={(value) => pickBackfillScanner(value)}+ options={backfillCandidates.map((scanner) => ({+ value: scanner.id,+ label: scanner.name,+ }))}+ data-attr="vision-watch-picks-quiet-scanner"+ />+ )}+ <LemonButton+ type="primary"+ size={large ? 'medium' : 'small'}+ fullWidth+ center+ loading={busyScannerId === backfillScannerId}+ disabledReason={+ editDisabledReason ??+ (estimateReady && estimateReady.sessions === 0+ ? 'No recording in the last 7 days matches this scanner'+ : null)+ }+ onClick={() => backfillScannerId && startBackfill(backfillScannerId)}+ data-attr="vision-watch-picks-quiet-backfill"+ >+ Scan the last 7 days now+ </LemonButton>+ <span className="text-xs">+ {backfillEstimateLoading+ ? 'Counting matching recordings'+ : estimateReady+ ? `${pluralize(estimateReady.sessions, 'recording')}, about ${formatCreditCount(estimateReady.credits)}`+ : 'Could not count matching recordings'}+ </span>+ </>+ ) : started === 0 ? (+ <span className="text-xs">+ No recording in the last 7 days matched. New ones are still scanned.+ </span>+ ) : (+ <span className="text-xs">+ Scanning {pluralize(started, 'recording')}. Results land here as they finish.+ </span>+ ))}+ </WatchPicksStateFrame>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksStaleBanner.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksStaleBanner.tsxnew file mode 100644index 000000000000..ee76f2649a7c--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksStaleBanner.tsx@@ -0,0 +1,146 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { pluralize } from 'lib/utils/strings'++import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { scannerEditUrl } from '../scannerEditorSceneLogic'+import { watchPicksLogic } from '../watchPicksLogic'+import { watchPicksStaleLogic } from '../watchPicksStaleLogic'+import { WatchPicksBlockedState } from './WatchPicksBlockedState'++export function WatchPicksStaleBanner(): JSX.Element | null {+ const picksLogic = useMountedLogic(watchPicksLogic)+ const logic = watchPicksStaleLogic(picksLogic.props)+ const { picks } = useValues(picksLogic)+ const {+ staleReason,+ droughtScanners,+ scanners,+ busyScannerId,+ backfillTotals,+ quietWeek,+ nextBest,+ nextBestLoading,+ } = useValues(logic)+ const { startBackfill, loadNextBest } = useActions(logic)+ const editDisabledReason = getReplayVisionEditDisabledReason()++ if (!staleReason) {+ return null+ }+ if (staleReason === 'all-disabled' || staleReason === 'all-capped' || staleReason === 'quota-exhausted') {+ return <WatchPicksBlockedState reason={staleReason} />+ }++ const newest = (picks ?? []).reduce<string | null>(+ (latest, pick) => (!latest || pick.observation.created_at > latest ? pick.observation.created_at : latest),+ null+ )+ const running = scanners.filter((scanner) => scanner.enabled && !scanner.limit_reached).length++ if (staleReason === 'drought') {+ return (+ <LemonBanner type="warning" className="m-2" data-attr="vision-watch-picks-stale-drought">+ <div className="flex flex-col gap-2 text-xs">+ {droughtScanners.map((scanner) => {+ const total = backfillTotals[scanner.id]+ return (+ <div key={scanner.id} className="flex flex-col gap-1">+ <span className="font-semibold">+ {scanner.name} has not matched anything since you changed it+ </span>+ {total === undefined ? (+ <div className="flex flex-wrap gap-2">+ <LemonButton+ size="xsmall"+ type="secondary"+ loading={busyScannerId === scanner.id}+ disabledReason={editDisabledReason}+ onClick={() => startBackfill(scanner.id)}+ data-attr="vision-watch-picks-stale-backfill"+ >+ Scan the last 7 days now+ </LemonButton>+ <Link+ to={scannerEditUrl(scanner.id, null)}+ data-attr="vision-watch-picks-stale-review"+ >+ Review filters+ </Link>+ </div>+ ) : total === 0 ? (+ <span>+ No recording in the last 7 days passes its filters.{' '}+ <Link+ to={scannerEditUrl(scanner.id, null)}+ data-attr="vision-watch-picks-stale-review"+ >+ Review filters+ </Link>+ </span>+ ) : (+ <span>+ Scanning {pluralize(total, 'recording')}. Results land here as they finish.+ </span>+ )}+ </div>+ )+ })}+ </div>+ </LemonBanner>+ )+ }++ if (staleReason === 'caught-up') {+ return (+ <div+ className="border-b bg-bg-light px-3 py-2 text-xs text-secondary"+ data-attr="vision-watch-picks-stale-caught-up"+ >+ <span className="font-semibold text-default">You are caught up.</span>{' '}+ {newest && (+ <>+ Last pick <TZLabel time={newest} showPopover={false} noStyles />.{' '}+ </>+ )}+ {pluralize(running, 'scanner')} running. New picks appear here without a refresh.+ </div>+ )+ }++ return (+ <div+ className="flex flex-col gap-1 border-b bg-bg-light px-3 py-2 text-xs"+ data-attr="vision-watch-picks-stale-quiet"+ >+ <span className="font-semibold">Quiet week</span>+ {quietWeek ? (+ <span className="text-secondary">+ {pluralize(quietWeek.scanned, 'recording')} scanned, {quietWeek.succeeded} finished, none stood out+ enough to be a pick.+ </span>+ ) : (+ <span className="text-secondary">+ Nothing new{newest ? ' since ' : ''}+ {newest && <TZLabel time={newest} showPopover={false} noStyles />}. {pluralize(running, 'scanner')}{' '}+ running.+ </span>+ )}+ {nextBest === null ? (+ <LemonButton+ size="xsmall"+ type="secondary"+ className="self-start"+ loading={nextBestLoading}+ onClick={loadNextBest}+ data-attr="vision-watch-picks-stale-next-best"+ >+ Show the newest results anyway+ </LemonButton>+ ) : null}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksStarter.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksStarter.tsxnew file mode 100644index 000000000000..f3cf4561bb40--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksStarter.tsx@@ -0,0 +1,115 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'+import { LemonBanner, LemonButton, LemonSegmentedButton, Link } from '@posthog/lemon-ui'++import { pngHoggie } from 'lib/brand/hoggies'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { visionQuotaLogic } from '../../logics/visionQuotaLogic'+import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'+import { formatCreditCount, formatCreditNumber, formatCreditsMaybeUsd } from '../../utils/credits'+import { watchPicksLogic } from '../watchPicksLogic'+import { BUDGET_PRESETS, QUICKSTART_SCANNER, TARGET_MONTHLY_SCANS } from '../watchPicksStarter'+import { watchPicksStarterLogic } from '../watchPicksStarterLogic'+import { WatchPicksStateFrame } from './WatchPicksStateFrame'++const SCANS_PER_DAY = Math.round(TARGET_MONTHLY_SCANS / 30)+const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)++export function WatchPicksStarter({ size }: { size: 'small' | 'large' }): JSX.Element {+ const { props: picksProps } = useMountedLogic(watchPicksLogic)+ const logic = watchPicksStarterLogic(picksProps)+ const { burstPlan, spendMode, freeAvailable, budget, starting, startError, freeCreditsLeft } = useValues(logic)+ const { setBudget, chooseBudget, startScanner } = useActions(logic)+ const { showUsd } = useValues(visionQuotaLogic)+ const large = size === 'large'+ const editDisabledReason = getReplayVisionEditDisabledReason()++ const burstCount = burstPlan.sessionIds.length+ const rows: [string, string][] = [+ [+ 'Scans now',+ burstCount > 0 ? pluralize(burstCount, 'recent recording') : 'nothing yet, no eligible recordings loaded',+ ],+ ['Then', `new recordings, about ${SCANS_PER_DAY} a day`],+ [+ 'Cost',+ spendMode === 'free'+ ? `free credits only${freeCreditsLeft !== null ? `, ${formatCreditCount(freeCreditsLeft)} left` : ''}. Stops by itself at the limit.`+ : freeAvailable+ ? 'a monthly budget you set. Free credits are used first.'+ : 'free credits are used up, so this scanner needs a monthly limit',+ ],+ ]+ return (+ <WatchPicksStateFrame+ size={size}+ image={HedgehogMagnifyingGlass}+ title="Nothing to watch yet"+ body={`Start ${QUICKSTART_SCANNER.name}, a scanner that reads each new recording and surfaces the ones worth watching.`}+ dataAttr="vision-watch-picks-starter"+ footer={+ <Link+ to={urls.replayVisionTemplates()}+ className="mt-1"+ data-attr="vision-watch-picks-starter-own-goal"+ >+ Write my own goal+ </Link>+ }+ >+ <div className="flex flex-col divide-y rounded border bg-bg-light text-left">+ {rows.map(([label, value]) => (+ <div key={label} className="flex flex-col gap-0.5 px-3 py-2">+ <span className="text-xs font-semibold text-default">{label}</span>+ <span className="text-xs text-secondary">{value}</span>+ </div>+ ))}+ </div>+ {spendMode === 'budget' && (+ <>+ <LemonSegmentedButton+ size="small"+ fullWidth+ value={budget}+ onChange={(value) => setBudget(value)}+ options={BUDGET_PRESETS.map((preset) => ({+ value: preset,+ label: formatCreditNumber(preset),+ 'data-attr': 'vision-watch-picks-starter-budget',+ }))}+ />+ <span className="text-xs">{formatCreditsMaybeUsd(budget, showUsd)} a month</span>+ </>+ )}+ {startError && <LemonBanner type="error">{startError}</LemonBanner>}+ <LemonButton+ type="primary"+ size={large ? 'medium' : 'small'}+ fullWidth+ center+ loading={starting}+ disabledReason={editDisabledReason}+ onClick={startScanner}+ data-attr="vision-watch-picks-starter-start"+ >+ {spendMode === 'free' ? 'Start free scanner' : `Start with ${formatCreditCount(budget)} a month`}+ </LemonButton>+ {freeAvailable && (+ <LemonButton+ type="tertiary"+ size={large ? 'medium' : 'small'}+ fullWidth+ center+ disabledReason={starting ? 'Starting' : null}+ onClick={() => chooseBudget(spendMode === 'free')}+ data-attr="vision-watch-picks-starter-toggle-budget"+ >+ {spendMode === 'free' ? 'Set a monthly budget instead' : 'Use free credits instead'}+ </LemonButton>+ )}+ </WatchPicksStateFrame>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksStarterStatus.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksStarterStatus.tsxnew file mode 100644index 000000000000..9e863f5d5f98--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksStarterStatus.tsx@@ -0,0 +1,99 @@+import { useActions, useMountedLogic, useValues } from 'kea'++import { LemonBanner, LemonButton, Spinner } from '@posthog/lemon-ui'++import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { pluralize } from 'lib/utils/strings'+import { urls } from 'scenes/urls'++import { watchPicksLogic } from '../watchPicksLogic'+import { watchPicksStarterLogic } from '../watchPicksStarterLogic'++export function WatchPicksStarterStatus(): JSX.Element | null {+ const picksLogic = useMountedLogic(watchPicksLogic)+ const { picks } = useValues(picksLogic)+ const logic = watchPicksStarterLogic(picksLogic.props)+ const { startedScanner, burstSessionIds, burstCounts, burstDone, burstStalled, scannedAnyway } = useValues(logic)+ const { showScannedAnyway } = useActions(logic)++ if (!startedScanner) {+ return null+ }+ const total = burstSessionIds.length+ const burstPicks = (picks ?? []).filter(+ (pick) =>+ pick.observation.scanner_id === startedScanner.id && burstSessionIds.includes(pick.observation.session_id)+ ).length+ const finished = Math.max(burstCounts.succeeded + burstCounts.failed, burstPicks)+ const hasPicks = (picks?.length ?? 0) > 0++ if (burstDone && !hasPicks) {+ return (+ <div className="flex flex-col gap-1 p-2" data-attr="vision-watch-picks-starter-nothing">+ <LemonBanner type="info">+ <div className="flex flex-col gap-2">+ <span className="font-semibold">+ {total > 0+ ? `${pluralize(burstCounts.succeeded, 'recording')} scanned, nothing stood out`+ : `${startedScanner.name} is on`}+ </span>+ <span className="text-xs">+ {burstStalled && burstCounts.pending > 0+ ? `${pluralize(burstCounts.pending, 'scan')} still running. New recordings are scanned as they finish and picks show up here.`+ : 'That happens on a quiet day. New recordings are scanned as they finish and picks show up here.'}+ </span>+ <div className="flex flex-wrap gap-2">+ {burstCounts.succeeded > 0 && scannedAnyway === null && (+ <LemonButton+ size="xsmall"+ type="secondary"+ onClick={showScannedAnyway}+ data-attr="vision-watch-picks-starter-show-anyway"+ >+ Show them anyway+ </LemonButton>+ )}+ <LemonButton+ size="xsmall"+ to={urls.replayVisionTemplates()}+ data-attr="vision-watch-picks-starter-another"+ >+ Try another scanner+ </LemonButton>+ </div>+ </div>+ </LemonBanner>+ </div>+ )+ }++ if (burstDone) {+ return burstStalled && burstCounts.pending > 0 ? (+ <div+ className="border-b bg-bg-light px-3 py-2 text-xs text-secondary"+ data-attr="vision-watch-picks-starter-stalled"+ >+ {pluralize(burstCounts.pending, 'scan')} still running. They show up here when they finish.+ </div>+ ) : null+ }++ return (+ <div+ className="flex flex-col gap-1 border-b bg-bg-light px-3 py-2 text-xs"+ data-attr="vision-watch-picks-starter-running"+ >+ <div className="flex items-center justify-between gap-2">+ <span className="flex items-center gap-1 font-semibold">+ <Spinner className="text-sm" />+ {startedScanner.name} is scanning+ </span>+ <span className="text-secondary">+ {finished} / {total}+ </span>+ </div>+ <LemonProgress percent={total === 0 ? 100 : (finished / total) * 100} />+ <span className="text-secondary">Results show up here as each scan finishes.</span>+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/WatchPicksStateFrame.tsx b/products/replay_vision/frontend/replay_scanners/components/WatchPicksStateFrame.tsxnew file mode 100644index 000000000000..77289f705c36--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/WatchPicksStateFrame.tsx@@ -0,0 +1,40 @@+import { ComponentType, ReactNode } from 'react'++import { cn } from 'lib/utils/css-classes'++interface WatchPicksStateFrameProps {+ size: 'small' | 'large'+ image: ComponentType<{ className?: string }>+ title: ReactNode+ body: ReactNode+ children?: ReactNode+ footer?: ReactNode+ dataAttr: string+}++export function WatchPicksStateFrame({+ size,+ image: Image,+ title,+ body,+ children,+ footer,+ dataAttr,+}: WatchPicksStateFrameProps): JSX.Element {+ const large = size === 'large'+ return (+ <div+ className={cn(+ 'flex flex-col items-center gap-2 text-center text-secondary',+ large ? 'rounded border bg-bg-light p-8 text-sm' : 'p-4 text-xs'+ )}+ data-attr={dataAttr}+ >+ <Image className={large ? 'h-48 w-48' : 'h-24 w-24'} />+ <span className={cn('font-semibold text-default', large ? 'text-lg' : 'text-sm')}>{title}</span>+ <span className="max-w-lg">{body}</span>+ {children && <div className="mt-1 flex w-full max-w-xs flex-col items-stretch gap-2">{children}</div>}+ {footer}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksLogic.test.ts b/products/replay_vision/frontend/replay_scanners/watchPicksLogic.test.tsindex ce7d7aca17cb..2f1602f8d24d 100644--- a/products/replay_vision/frontend/replay_scanners/watchPicksLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/watchPicksLogic.test.ts@@ -7,7 +7,7 @@ import { sessionRecordingsPlaylistLogic } from 'scenes/session-recordings/playliimport { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { PICKS_SHOWN_COUNT_STORAGE_KEY, watchPicksLogic } from './watchPicksLogic'+import { emptyImpressionsStorageKey, picksShownCountStorageKey, watchPicksLogic } from './watchPicksLogic'import { watchPicksVariantFromFlag } from './watchPicksVariant'describe('watchPicksLogic', () => {@@ -99,14 +99,14 @@ describe('watchPicksLogic', () => {])('reports the third impression as its own event (stored count %i)', async (stored, thirdTimeEvents) => {logic.unmount()playlistLogic.unmount()- localStorage.setItem(PICKS_SHOWN_COUNT_STORAGE_KEY, String(stored))+ localStorage.setItem(picksShownCountStorageKey(), String(stored))await mountList()expect(captureSpy.mock.calls.filter(([name]) => name === 'replay_vision_watch_picks_shown_third_time').map((call) => call[1])).toEqual(thirdTimeEvents)- expect(localStorage.getItem(PICKS_SHOWN_COUNT_STORAGE_KEY)).toBe(String(stored + 1))+ expect(localStorage.getItem(picksShownCountStorageKey())).toBe(String(stored + 1))})it.each([@@ -122,7 +122,32 @@ describe('watchPicksLogic', () => {})it.each([- ['the feed is empty', () => feedSpy.mockImplementation(() => [200, { results: [] }]), {}],+ [0, 'picks', '1'],+ [1, 'picks', '2'],+ [2, 'recordings', '2'],+ ])(+ 'opens an empty feed on the picks until %i untouched impressions, then on the recordings',+ async (stored, mode, storedAfter) => {+ logic.unmount()+ playlistLogic.unmount()+ feedSpy.mockImplementation(() => [200, { results: [] }])+ localStorage.setItem(emptyImpressionsStorageKey(), String(stored))+ await mountList()+ expect(logic.values.effectiveListMode).toBe(mode)+ expect(localStorage.getItem(emptyImpressionsStorageKey())).toBe(storedAfter)+ expect(shownEvents()).toEqual([])+ }+ )++ it('starting a scanner from the column keeps the picks open and forgets the empty impressions', async () => {+ localStorage.setItem(emptyImpressionsStorageKey(), '2')+ logic.actions.setListMode('recordings')+ logic.actions.adoptPicksMode()+ expect(logic.values.effectiveListMode).toBe('picks')+ expect(localStorage.getItem(emptyImpressionsStorageKey())).toBe('0')+ })++ it.each([['the feed fails', () => feedSpy.mockImplementation(() => [500, {}]), {}],['the link carries filters', () => {}, { filters: { date_from: '-30d' } }],['the link carries a saved filter', () => {}, { savedFilterId: 'sf-1' }],diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksLogic.ts b/products/replay_vision/frontend/replay_scanners/watchPicksLogic.tsindex 191c82d034d7..f01f27e56b45 100644--- a/products/replay_vision/frontend/replay_scanners/watchPicksLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/watchPicksLogic.ts@@ -49,14 +49,21 @@ const PICKS_DATE_FROM = '-7d'// impression of the picks (on the Watch tab or the in-list toggle) is reported// as its own event. The impression count lives in this browser onlyexport const PICKS_SHOWN_SURVEY_IMPRESSION = 3-export const PICKS_SHOWN_COUNT_STORAGE_KEY = 'replay-vision.watch-picks-shown-count'-const picksShownCount = localStorageSlot(PICKS_SHOWN_COUNT_STORAGE_KEY, z.number().int().nonnegative())+const teamStorageKey = (key: string) => (): string =>+ `${key}.${teamLogic.findMounted()?.values.currentTeamId ?? 'unknown'}`+export const picksShownCountStorageKey = teamStorageKey('replay-vision.watch-picks-shown-count')+const picksShownCount = localStorageSlot(picksShownCountStorageKey, z.number().int().nonnegative())+export const emptyImpressionsStorageKey = teamStorageKey('replay-vision.watch-picks-empty-impressions')+export const EMPTY_IMPRESSIONS_BEFORE_RECORDINGS = 2+const emptyImpressions = localStorageSlot(emptyImpressionsStorageKey, z.number().int().nonnegative())+const FOCUS_RELOAD_MIN_MS = 60_000// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface watchPicksLogicValues {currentTeamId: number | null // teamLogicactiveSessionId: string | nulleffectiveListMode: WatchPicksListMode+ emptyImpressionsAtMount: numberlistMode: WatchPicksListMode | nullmoreItems: WatchFeedItemApi[]openedOnDeepLink: boolean@@ -69,6 +76,9 @@ export interface watchPicksLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface watchPicksLogicActions {+ adoptPicksMode: () => {+ value: true+ }loadPicks: () => {value: true}@@ -117,8 +127,8 @@ export interface watchPicksLogicMeta {effectiveListMode: (listMode: WatchPicksListMode | null,openedOnDeepLink: boolean,- picks: WatchFeedItemApi[] | null,- picksFailed: boolean+ picksFailed: boolean,+ emptyImpressionsAtMount: number) => WatchPicksListModetopPicks: (picks: WatchFeedItemApi[] | null) => WatchFeedItemApi[]unwatchedCount: (picks: WatchFeedItemApi[] | null) => number@@ -145,6 +155,7 @@ export const watchPicksLogic: LogicWrapper<watchPicksLogicType> = kea<watchPicksactions({loadPicks: true,setListMode: (mode: WatchPicksListMode) => ({ mode }),+ adoptPicksMode: true,watchPick: (item: WatchFeedItemApi, position: number, surface: WatchPickSurface) => ({item,position,@@ -187,8 +198,10 @@ export const watchPicksLogic: LogicWrapper<watchPicksLogicType> = kea<watchPicks{ persist: true, storageKey: 'replay-vision.watch-picks-list-mode' },{setListMode: (_, { mode }) => mode,+ adoptPicksMode: () => 'picks',},],+ emptyImpressionsAtMount: [emptyImpressions.get() ?? 0, {}],openedOnDeepLink: [Boolean(props.playlistLogicProps &&@@ -213,15 +226,17 @@ export const watchPicksLogic: LogicWrapper<watchPicksLogicType> = kea<watchPicksselectors({effectiveListMode: [- (s) => [s.listMode, s.openedOnDeepLink, s.picks, s.picksFailed],+ (s) => [s.listMode, s.openedOnDeepLink, s.picksFailed, s.emptyImpressionsAtMount],(listMode: WatchPicksListMode | null,openedOnDeepLink: boolean,- picks: WatchFeedItemApi[] | null,- picksFailed: boolean+ picksFailed: boolean,+ emptyImpressionsAtMount: number): WatchPicksListMode =>listMode ??- (openedOnDeepLink || picksFailed || (picks !== null && picks.length === 0) ? 'recordings' : 'picks'),+ (openedOnDeepLink || picksFailed || emptyImpressionsAtMount >= EMPTY_IMPRESSIONS_BEFORE_RECORDINGS+ ? 'recordings'+ : 'picks'),],topPicks: [(s) => [s.picks],@@ -243,6 +258,13 @@ export const watchPicksLogic: LogicWrapper<watchPicksLogicType> = kea<watchPicksif (!values.picks || (props.playlistLogicProps && values.effectiveListMode !== 'picks')) {return}+ if (values.picks.length === 0) {+ if (props.playlistLogicProps && values.listMode === null && !cache.emptyImpressionNoted) {+ cache.emptyImpressionNoted = true+ emptyImpressions.set((emptyImpressions.get() ?? 0) + 1)+ }+ return+ }const view = props.playlistLogicProps ? 'list' : 'page'const shownCount = (picksShownCount.get() ?? 0) + 1picksShownCount.set(shownCount)@@ -261,8 +283,12 @@ export const watchPicksLogic: LogicWrapper<watchPicksLogicType> = kea<watchPicks}return {loadPicksSuccess: () => {+ cache.picksLoadedAt = Date.now()reportPicksShown()},+ adoptPicksMode: () => {+ emptyImpressions.set(0)+ },setListMode: ({ mode }) => {posthog.capture('replay_vision_watch_picks_list_mode_changed', { mode })if (mode === 'picks') {@@ -325,7 +351,16 @@ export const watchPicksLogic: LogicWrapper<watchPicksLogicType> = kea<watchPicks}}),- afterMount(({ actions }) => {+ afterMount(({ actions, cache }) => {actions.loadPicks()+ cache.disposables.add(() => {+ const onFocus = (): void => {+ if (Date.now() - (cache.picksLoadedAt ?? 0) >= FOCUS_RELOAD_MIN_MS) {+ actions.loadPicks()+ }+ }+ window.addEventListener('focus', onFocus)+ return () => window.removeEventListener('focus', onFocus)+ }, 'focus-reload')}),])diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksStaleLogic.ts b/products/replay_vision/frontend/replay_scanners/watchPicksStaleLogic.tsnew file mode 100644index 000000000000..4eb0ae839c5f--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/watchPicksStaleLogic.ts@@ -0,0 +1,606 @@+import {+ LogicWrapper,+ MakeLogicType,+ actions,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { dayjs } from 'lib/dayjs'+import posthog from 'lib/posthog-typed'+import { SessionRecordingPlaylistLogicProps } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'+import { teamLogic } from 'scenes/teamLogic'++import {+ visionScannersBackfillsCreate,+ visionScannersBackfillsEstimateCreate,+ visionScannersObservationsList,+ visionScannersObservationsStatsRetrieve,+ visionScannersPartialUpdate,+} from '../generated/api'+import type { ReplayObservationApi, ReplayScannerApi, VisionQuotaApi, WatchFeedItemApi } from '../generated/api.schemas'+import { visionQuotaLogic } from '../logics/visionQuotaLogic'+import { visionScannersListLogic } from '../logics/visionScannersListLogic'+import { scanDrought } from './scanDrought'+import { WatchFeedEmptyReason, resolveWatchFeedEmptyReason } from './watchFeedEmptyState'+import { watchPicksLogic } from './watchPicksLogic'+import { WatchPicksStaleReason, resolveWatchPicksStaleReason } from './watchPicksStaleState'++const DROUGHT_SCANNER_CAP = 10+const BACKFILL_DAYS = 7+const NEXT_BEST_COUNT = 5+const WINDOW_DATE_FROM = '-7d'+const BACKFILL_POLL_MS = 10_000+const BACKFILL_POLL_MAX = 60++export interface BackfillEstimate {+ scannerId: string+ sessions: number+ credits: number+}++function backfillWindow(): { window_start: string; window_end: string } {+ return {+ window_start: dayjs().subtract(BACKFILL_DAYS, 'day').toISOString(),+ window_end: dayjs().toISOString(),+ }+}++export interface QuietWeekStats {+ scanned: number+ succeeded: number+}++export interface WatchPicksStaleLogicProps {+ logicKey: string+ playlistLogicProps?: SessionRecordingPlaylistLogicProps+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface watchPicksStaleLogicValues {+ currentTeamId: number | null // teamLogic+ quota: VisionQuotaApi | null // visionQuotaLogic+ scanners: ReplayScannerApi[] // visionScannersListLogic+ picks: WatchFeedItemApi[] | null // watchPicksLogic+ backfillCandidates: ReplayScannerApi[]+ backfillEstimate: BackfillEstimate | null+ backfillEstimateLoading: boolean+ backfillScannerId: string | null+ backfillTotals: Record<string, number>+ blockReason: WatchFeedEmptyReason+ busyScannerId: string | null+ droughtScannerIds: string[]+ droughtScannerIdsLoading: boolean+ droughtScanners: ReplayScannerApi[]+ lastSweptAt: string | null+ nextBest: ReplayObservationApi[] | null+ nextBestLoading: boolean+ now: Date+ pickedBackfillScannerId: string | null+ quietWeek: QuietWeekStats | null+ quietWeekLoading: boolean+ staleReason: WatchPicksStaleReason | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface watchPicksStaleLogicActions {+ loadScannersSuccess: (+ scanners: ReplayScannerApi[],+ payload?:+ | {+ value: true+ }+ | undefined+ ) => {+ payload?: {+ value: true+ }+ scanners: ReplayScannerApi[]+ } // visionScannersListLogic+ loadPicksSuccess: (+ picks: WatchFeedItemApi[],+ payload?:+ | {+ value: true+ }+ | undefined+ ) => {+ payload?: {+ value: true+ }+ picks: WatchFeedItemApi[]+ } // watchPicksLogic+ backfillStarted: (+ scannerId: string,+ totalSessions: number+ ) => {+ scannerId: string+ totalSessions: number+ }+ loadBackfillEstimate: () => {+ value: true+ }+ loadBackfillEstimateFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadBackfillEstimateSuccess: (+ backfillEstimate: {+ credits: number+ scannerId: string+ sessions: number+ } | null,+ payload?: {+ value: true+ }+ ) => {+ backfillEstimate: {+ credits: number+ scannerId: string+ sessions: number+ } | null+ payload?: {+ value: true+ }+ }+ loadDroughtScannerIds: () => {+ value: true+ }+ loadDroughtScannerIdsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadDroughtScannerIdsSuccess: (+ droughtScannerIds: string[],+ payload?: {+ value: true+ }+ ) => {+ droughtScannerIds: string[]+ payload?: {+ value: true+ }+ }+ loadNextBest: () => {+ value: true+ }+ loadNextBestFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadNextBestSuccess: (+ nextBest: ReplayObservationApi[] | null,+ payload?: {+ value: true+ }+ ) => {+ nextBest: ReplayObservationApi[] | null+ payload?: {+ value: true+ }+ }+ loadQuietWeek: () => {+ value: true+ }+ loadQuietWeekFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadQuietWeekSuccess: (+ quietWeek: QuietWeekStats | null,+ payload?: {+ value: true+ }+ ) => {+ quietWeek: QuietWeekStats | null+ payload?: {+ value: true+ }+ }+ pickBackfillScanner: (scannerId: string | null) => {+ scannerId: string | null+ }+ raiseLimit: (+ scannerId: string,+ creditLimit: number+ ) => {+ creditLimit: number+ scannerId: string+ }+ scannerActionDone: (scannerId: string) => {+ scannerId: string+ }+ startBackfill: (scannerId: string) => {+ scannerId: string+ }+ toggleScanner: (+ scannerId: string,+ enabled: boolean+ ) => {+ enabled: boolean+ scannerId: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface watchPicksStaleLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ blockReason: (scanners: ReplayScannerApi[], quota: VisionQuotaApi | null) => WatchFeedEmptyReason+ staleReason: (+ picks: WatchFeedItemApi[] | null,+ blockReason: WatchFeedEmptyReason,+ droughtScannerIds: string[],+ now: Date+ ) => WatchPicksStaleReason | null+ backfillCandidates: (scanners: ReplayScannerApi[]) => ReplayScannerApi[]+ backfillScannerId: (+ pickedBackfillScannerId: string | null,+ backfillCandidates: ReplayScannerApi[]+ ) => string | null+ lastSweptAt: (backfillCandidates: ReplayScannerApi[]) => string | null+ droughtScanners: (scanners: ReplayScannerApi[], droughtScannerIds: string[]) => ReplayScannerApi[]+ }+}++export type watchPicksStaleLogicType = MakeLogicType<+ watchPicksStaleLogicValues,+ watchPicksStaleLogicActions,+ WatchPicksStaleLogicProps,+ watchPicksStaleLogicMeta+>++export const watchPicksStaleLogic: LogicWrapper<watchPicksStaleLogicType> = kea<watchPicksStaleLogicType>([+ props({} as WatchPicksStaleLogicProps),+ key((props) => props.logicKey),+ path((key) => ['products', 'replay_vision', 'frontend', 'replay_scanners', 'watchPicksStaleLogic', key]),++ connect((props: WatchPicksStaleLogicProps) => ({+ values: [+ teamLogic,+ ['currentTeamId'],+ visionScannersListLogic,+ ['scanners'],+ visionQuotaLogic,+ ['quota'],+ watchPicksLogic(props),+ ['picks'],+ ],+ actions: [visionScannersListLogic, ['loadScannersSuccess'], watchPicksLogic(props), ['loadPicksSuccess']],+ })),++ actions({+ loadDroughtScannerIds: true,+ loadQuietWeek: true,+ loadNextBest: true,+ toggleScanner: (scannerId: string, enabled: boolean) => ({ scannerId, enabled }),+ raiseLimit: (scannerId: string, creditLimit: number) => ({ scannerId, creditLimit }),+ startBackfill: (scannerId: string) => ({ scannerId }),+ backfillStarted: (scannerId: string, totalSessions: number) => ({ scannerId, totalSessions }),+ scannerActionDone: (scannerId: string) => ({ scannerId }),+ pickBackfillScanner: (scannerId: string | null) => ({ scannerId }),+ loadBackfillEstimate: true,+ }),++ loaders(({ values }) => ({+ droughtScannerIds: [+ [] as string[],+ {+ loadDroughtScannerIds: async (_, breakpoint) => {+ const teamId = values.currentTeamId+ if (!teamId) {+ return []+ }+ const now = new Date()+ const candidates = values.scanners+ .filter((scanner) => scanner.enabled && !scanner.limit_reached)+ .slice(0, DROUGHT_SCANNER_CAP)+ const results = await Promise.all(+ candidates.map(async (scanner) => {+ try {+ const stats = await visionScannersObservationsStatsRetrieve(String(teamId), scanner.id)+ return scanDrought(+ {+ ...scanner,+ enabled: scanner.enabled ?? false,+ sampling_rate: scanner.sampling_rate ?? 1,+ },+ stats.labels.version_markers,+ now+ )+ ? scanner.id+ : null+ } catch {+ return null+ }+ })+ )+ breakpoint()+ return results.filter((id): id is string => id !== null)+ },+ },+ ],+ quietWeek: [+ null as QuietWeekStats | null,+ {+ loadQuietWeek: async (_, breakpoint) => {+ const teamId = values.currentTeamId+ if (!teamId) {+ return null+ }+ const stats = await Promise.all(+ values.scanners.slice(0, DROUGHT_SCANNER_CAP).map((scanner) =>+ visionScannersObservationsStatsRetrieve(String(teamId), scanner.id, {+ date_from: WINDOW_DATE_FROM,+ }).catch(() => null)+ )+ )+ breakpoint()+ return stats.reduce<QuietWeekStats>(+ (acc, stat) => ({+ scanned: acc.scanned + (stat?.status_counts.total ?? 0),+ succeeded: acc.succeeded + (stat?.status_counts.succeeded ?? 0),+ }),+ { scanned: 0, succeeded: 0 }+ )+ },+ },+ ],+ backfillEstimate: [+ null as BackfillEstimate | null,+ {+ loadBackfillEstimate: async (_, breakpoint) => {+ const teamId = values.currentTeamId+ const scannerId = values.backfillScannerId+ if (!teamId || !scannerId) {+ return null+ }+ await breakpoint(100)+ const estimate = await visionScannersBackfillsEstimateCreate(+ String(teamId),+ scannerId,+ backfillWindow()+ )+ breakpoint()+ return { scannerId, sessions: estimate.total_sessions, credits: estimate.total_credits }+ },+ },+ ],+ nextBest: [+ null as ReplayObservationApi[] | null,+ {+ loadNextBest: async (_, breakpoint) => {+ const teamId = values.currentTeamId+ if (!teamId) {+ return null+ }+ const pages = await Promise.all(+ values.scanners.slice(0, DROUGHT_SCANNER_CAP).map((scanner) =>+ visionScannersObservationsList(String(teamId), scanner.id, {+ date_from: WINDOW_DATE_FROM,+ status: 'succeeded',+ order_by: '-created_at',+ limit: NEXT_BEST_COUNT,+ }).catch(() => null)+ )+ )+ breakpoint()+ return pages+ .flatMap((page) => page?.results ?? [])+ .sort((a, b) => b.created_at.localeCompare(a.created_at))+ .slice(0, NEXT_BEST_COUNT)+ },+ },+ ],+ })),++ reducers({+ pickedBackfillScannerId: [+ null as string | null,+ {+ pickBackfillScanner: (_, { scannerId }) => scannerId,+ },+ ],+ now: [+ new Date(),+ {+ loadPicksSuccess: () => new Date(),+ },+ ],+ busyScannerId: [+ null as string | null,+ {+ toggleScanner: (_, { scannerId }) => scannerId,+ raiseLimit: (_, { scannerId }) => scannerId,+ startBackfill: (_, { scannerId }) => scannerId,+ scannerActionDone: () => null,+ },+ ],+ backfillTotals: [+ {} as Record<string, number>,+ {+ backfillStarted: (state, { scannerId, totalSessions }) => ({ ...state, [scannerId]: totalSessions }),+ },+ ],+ }),++ selectors({+ blockReason: [+ (s) => [s.scanners, s.quota],+ (scanners: ReplayScannerApi[], quota: VisionQuotaApi | null): WatchFeedEmptyReason =>+ resolveWatchFeedEmptyReason({ scanners, quota, hasFeedFilters: false }),+ ],+ staleReason: [+ (s) => [s.picks, s.blockReason, s.droughtScannerIds, s.now],+ (+ picks: WatchFeedItemApi[] | null,+ blockReason: WatchFeedEmptyReason,+ droughtScannerIds: string[],+ now: Date+ ): WatchPicksStaleReason | null =>+ resolveWatchPicksStaleReason({ picks: picks ?? [], blockReason, droughtScannerIds, now }),+ ],+ backfillCandidates: [+ (s) => [s.scanners],+ (scanners: ReplayScannerApi[]): ReplayScannerApi[] =>+ scanners.filter((scanner) => scanner.enabled && !scanner.limit_reached),+ ],+ backfillScannerId: [+ (s) => [s.pickedBackfillScannerId, s.backfillCandidates],+ (picked: string | null, candidates: ReplayScannerApi[]): string | null =>+ candidates.some((scanner) => scanner.id === picked) ? picked : (candidates[0]?.id ?? null),+ ],+ lastSweptAt: [+ (s) => [s.backfillCandidates],+ (candidates: ReplayScannerApi[]): string | null =>+ candidates.reduce<string | null>(+ (latest, scanner) => (!latest || scanner.last_swept_at > latest ? scanner.last_swept_at : latest),+ null+ ),+ ],+ droughtScanners: [+ (s) => [s.scanners, s.droughtScannerIds],+ (scanners: ReplayScannerApi[], droughtScannerIds: string[]): ReplayScannerApi[] =>+ scanners.filter((scanner) => droughtScannerIds.includes(scanner.id)),+ ],+ }),++ listeners(({ actions, values, props, cache }) => {+ const refresh = (): void => {+ visionScannersListLogic.findMounted()?.actions.loadScanners()+ visionQuotaLogic.findMounted()?.actions.loadQuota()+ watchPicksLogic.findMounted(props)?.actions.loadPicks()+ }+ const act = (action: string, scannerId: string): void => {+ posthog.capture('replay_vision_watch_picks_stale_action', {+ reason: values.staleReason,+ action,+ scanner_id: scannerId,+ })+ }+ return {+ loadScannersSuccess: () => {+ if (values.picks && values.picks.length > 0) {+ cache.droughtsLoaded = true+ actions.loadDroughtScannerIds()+ }+ },+ loadPicksSuccess: ({ picks }) => {+ if (picks.length === 0 || values.scanners.length === 0) {+ return+ }+ if (!cache.droughtsLoaded) {+ cache.droughtsLoaded = true+ actions.loadDroughtScannerIds()+ } else if (values.staleReason === 'quiet-week' && values.quietWeek === null) {+ actions.loadQuietWeek()+ }+ },+ loadDroughtScannerIdsSuccess: () => {+ if (values.staleReason === 'quiet-week' && values.quietWeek === null) {+ actions.loadQuietWeek()+ }+ if (values.staleReason) {+ posthog.capture('replay_vision_watch_picks_stale_shown', { reason: values.staleReason })+ }+ },+ toggleScanner: async ({ scannerId, enabled }) => {+ const teamId = values.currentTeamId+ if (!teamId) {+ return+ }+ act(enabled ? 'enable' : 'disable', scannerId)+ try {+ await visionScannersPartialUpdate(String(teamId), scannerId, { enabled })+ refresh()+ } finally {+ actions.scannerActionDone(scannerId)+ }+ },+ raiseLimit: async ({ scannerId, creditLimit }) => {+ const teamId = values.currentTeamId+ if (!teamId) {+ return+ }+ act('raise_limit', scannerId)+ try {+ await visionScannersPartialUpdate(String(teamId), scannerId, {+ credit_limit: creditLimit,+ free_only: false,+ })+ refresh()+ } finally {+ actions.scannerActionDone(scannerId)+ }+ },+ backfillStarted: ({ totalSessions }) => {+ if (totalSessions === 0) {+ return+ }+ let polls = 0+ cache.disposables.add(() => {+ const timer = window.setInterval(() => {+ polls += 1+ const picks = watchPicksLogic.findMounted(props)?.values.picks ?? []+ if (polls > BACKFILL_POLL_MAX || picks.length > 0) {+ cache.disposables.dispose('backfill-poll')+ return+ }+ watchPicksLogic.findMounted(props)?.actions.loadPicks()+ }, BACKFILL_POLL_MS)+ return () => clearInterval(timer)+ }, 'backfill-poll')+ },+ startBackfill: async ({ scannerId }) => {+ const teamId = values.currentTeamId+ if (!teamId) {+ return+ }+ act('backfill', scannerId)+ const window = backfillWindow()+ try {+ const estimate = await visionScannersBackfillsEstimateCreate(String(teamId), scannerId, window)+ if (estimate.total_sessions > 0) {+ await visionScannersBackfillsCreate(String(teamId), scannerId, {+ ...window,+ max_total_credits: estimate.total_credits,+ })+ }+ actions.backfillStarted(scannerId, estimate.total_sessions)+ } catch {+ actions.backfillStarted(scannerId, 0)+ } finally {+ actions.scannerActionDone(scannerId)+ }+ },+ }+ }),++ subscriptions(({ actions }) => ({+ backfillScannerId: (scannerId: string | null) => {+ if (scannerId) {+ actions.loadBackfillEstimate()+ }+ },+ })),+])diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksStaleState.test.ts b/products/replay_vision/frontend/replay_scanners/watchPicksStaleState.test.tsnew file mode 100644index 000000000000..1b8b929fef4d--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/watchPicksStaleState.test.ts@@ -0,0 +1,29 @@+import type { WatchFeedItemApi } from '../generated/api.schemas'+import { type WatchPicksStaleReason, resolveWatchPicksStaleReason } from './watchPicksStaleState'++const now = new Date('2026-10-16T12:00:00Z')+const pick = (daysAgo: number, viewed: boolean): WatchFeedItemApi =>+ ({+ observation: { created_at: new Date(now.getTime() - daysAgo * 86_400_000).toISOString(), viewed },+ }) as unknown as WatchFeedItemApi++describe('resolveWatchPicksStaleReason', () => {+ it.each<[string, WatchFeedItemApi[], any, string[], WatchPicksStaleReason | null]>([+ ['no picks, so the empty state owns it', [], 'no-scanners', [], null],+ ['a fresh unwatched pick', [pick(0.5, false)], 'quiet-window', [], null],+ ['every pick watched but recent', [pick(1, true)], 'quiet-window', [], 'caught-up'],+ ['nothing newer than two days', [pick(3, false)], 'quiet-window', [], 'quiet-week'],+ ['a block before anything else', [pick(3, true)], 'all-capped', ['a'], 'all-capped'],+ ['an exhausted quota', [pick(1, true)], 'quota-exhausted', [], 'quota-exhausted'],+ ['a drought before a quiet week', [pick(3, false)], 'quiet-window', ['a'], 'drought'],+ [+ 'one fresh unwatched pick among old watched ones',+ [pick(5, true), pick(0.2, false)],+ 'quiet-window',+ [],+ null,+ ],+ ])('reads %s', (_name, picks, blockReason, droughtScannerIds, expected) => {+ expect(resolveWatchPicksStaleReason({ picks, blockReason, droughtScannerIds, now })).toBe(expected)+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksStaleState.ts b/products/replay_vision/frontend/replay_scanners/watchPicksStaleState.tsnew file mode 100644index 000000000000..6c9fdd6293e7--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/watchPicksStaleState.ts@@ -0,0 +1,43 @@+import type { WatchFeedItemApi } from '../generated/api.schemas'+import type { WatchFeedEmptyReason } from './watchFeedEmptyState'++export const STALE_AFTER_MS = 2 * 24 * 60 * 60 * 1000++export type WatchPicksStaleReason =+ | 'caught-up'+ | 'quiet-week'+ | 'drought'+ | 'quota-exhausted'+ | 'all-disabled'+ | 'all-capped'++export interface WatchPicksStaleInput {+ picks: WatchFeedItemApi[]+ blockReason: WatchFeedEmptyReason+ droughtScannerIds: string[]+ now: Date+}++export function resolveWatchPicksStaleReason({+ picks,+ blockReason,+ droughtScannerIds,+ now,+}: WatchPicksStaleInput): WatchPicksStaleReason | null {+ if (picks.length === 0) {+ return null+ }+ const newest = Math.max(...picks.map((pick) => new Date(pick.observation.created_at).getTime()))+ const old = now.getTime() - newest > STALE_AFTER_MS+ const allViewed = picks.every((pick) => pick.observation.viewed)+ if (!old && !allViewed) {+ return null+ }+ if (blockReason === 'quota-exhausted' || blockReason === 'all-disabled' || blockReason === 'all-capped') {+ return blockReason+ }+ if (droughtScannerIds.length > 0) {+ return 'drought'+ }+ return old ? 'quiet-week' : 'caught-up'+}diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksStarter.test.ts b/products/replay_vision/frontend/replay_scanners/watchPicksStarter.test.tsnew file mode 100644index 000000000000..4dd843204cb6--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/watchPicksStarter.test.ts@@ -0,0 +1,54 @@+import { planBurst, samplingRateForTarget, starterSpendMode } from './watchPicksStarter'++const recording = (id: string, overrides: Record<string, unknown> = {}): any => ({+ id,+ recording_duration: 120,+ active_seconds: 60,+ ongoing: false,+ ...overrides,+})++describe('watchPicksStarter', () => {+ const thirty = Array.from({ length: 30 }, (_, i) => recording(`s${i}`))++ it.each<[string, any[], number, 'free' | 'budget', number | null, number | null, number]>([+ ['caps at the burst maximum', thirty, 5, 'free', 2500, null, 25],+ [+ 'skips recordings the scan gate refuses',+ [recording('a', { recording_duration: 3 }), recording('b')],+ 5,+ 'free',+ 2500,+ null,+ 1,+ ],+ ['leaves a sweep reserve out of the free credits', thirty, 5, 'free', 100, null, 15],+ ['sizes to the budget when paying', thirty, 5, 'budget', 0, 50, 5],+ ['never goes negative', thirty, 5, 'free', 10, null, 0],+ ['uses the maximum when the allowance is unknown', thirty, 5, 'free', null, null, 25],+ ])('%s', (_name, recordings, price, mode, freeLeft, budget, expectedCount) => {+ const plan = planBurst(recordings, price, mode, freeLeft, budget)+ expect(plan.sessionIds).toHaveLength(expectedCount)+ expect(plan.credits).toBe(expectedCount * price)+ })++ it.each<[number | null, number]>([+ [null, 1],+ [120, 1],+ [300, 1],+ [600, 0.5],+ [9000, 0.03],+ [1_000_000, 0.01],+ ])('samples %p a month down to the target', (estimate, rate) => {+ expect(samplingRateForTarget(estimate, 300)).toBe(rate)+ })++ it.each<[number | null, 'free' | 'budget']>([+ [null, 'free'],+ [5, 'free'],+ [4, 'budget'],+ [0, 'budget'],+ ])('needs a budget once %p free credits cannot buy one scan', (freeLeft, mode) => {+ expect(starterSpendMode(freeLeft, 5)).toBe(mode)+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksStarter.ts b/products/replay_vision/frontend/replay_scanners/watchPicksStarter.tsnew file mode 100644index 000000000000..6567b31ddf16--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/watchPicksStarter.ts@@ -0,0 +1,55 @@+import type { SessionRecordingType } from '~/types'++import { recordingScanBlock } from '../utils/scanEligibility'+import type { SummarizerScannerConfig } from './types'++export const BURST_MAX_RECORDINGS = 25+export const TARGET_MONTHLY_SCANS = 300+export const FREE_SCANNER_CREDIT_LIMIT = 1500+export const BUDGET_PRESETS = [1000, 2500, 5000] as const+const BURST_SWEEP_RESERVE_SCANS = 5+export const QUICKSTART_SCANNER = {+ key: 'session_highlights',+ name: 'Session highlights',+ description: 'Summarizes each new recording and flags the ones worth watching.',+ scanner_type: 'summarizer' as const,+ scanner_config: {+ prompt: 'Summarize what the user was trying to do in this session and what got in their way. Call out anything unusual, surprising, or broken: errors, dead ends, repeated attempts, confusion, or an outcome that does not match what they set out to do. Be concrete and do not speculate.',+ length: 'medium',+ } satisfies SummarizerScannerConfig,+}++export type StarterSpendMode = 'free' | 'budget'++export interface BurstPlan {+ sessionIds: string[]+ credits: number+}++export function planBurst(+ recordings: readonly Pick<SessionRecordingType, 'id' | 'recording_duration' | 'active_seconds' | 'ongoing'>[],+ creditsPerObservation: number,+ spendMode: StarterSpendMode,+ freeCreditsLeft: number | null,+ budget: number | null+): BurstPlan {+ const eligible = recordings.filter((recording) => recordingScanBlock(recording) === null).map((r) => r.id)+ const allowance = spendMode === 'free' ? freeCreditsLeft : budget+ const affordable =+ allowance === null+ ? BURST_MAX_RECORDINGS+ : Math.max(0, Math.floor(allowance / creditsPerObservation) - BURST_SWEEP_RESERVE_SCANS)+ const sessionIds = eligible.slice(0, Math.min(BURST_MAX_RECORDINGS, affordable))+ return { sessionIds, credits: sessionIds.length * creditsPerObservation }+}++export function samplingRateForTarget(estimatedMonthlyAtFullRate: number | null, targetMonthly: number): number {+ if (estimatedMonthlyAtFullRate === null || estimatedMonthlyAtFullRate <= targetMonthly) {+ return 1+ }+ return Math.max(0.01, Math.round((targetMonthly / estimatedMonthlyAtFullRate) * 100) / 100)+}++export function starterSpendMode(freeCreditsLeft: number | null, creditsPerObservation: number): StarterSpendMode {+ return freeCreditsLeft !== null && freeCreditsLeft < creditsPerObservation ? 'budget' : 'free'+}diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksStarterLogic.test.ts b/products/replay_vision/frontend/replay_scanners/watchPicksStarterLogic.test.tsnew file mode 100644index 000000000000..6354e32921a9--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/watchPicksStarterLogic.test.ts@@ -0,0 +1,34 @@+import { router } from 'kea-router'++import { sessionRecordingsPlaylistLogic } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { watchPicksLogic } from './watchPicksLogic'+import { watchPicksStarterLogic } from './watchPicksStarterLogic'++describe('watchPicksStarterLogic', () => {+ it('plans the burst from the loaded recordings and starts on free credits', () => {+ useMocks({+ get: {+ '/api/projects/:team/vision/scanners/watch_feed/': () => [200, { results: [] }],+ '/api/environments/:team/vision/quota/': () => [+ 200,+ { free_monthly_credits: 2500, credits_used: 0, credit_limit: null },+ ],+ },+ })+ initKeaTests()+ router.actions.push('/replay/home')+ const playlistLogicProps = { logicKey: 'starter-test' }+ const playlist = sessionRecordingsPlaylistLogic(playlistLogicProps)+ playlist.mount()+ const picks = watchPicksLogic({ logicKey: 'starter-test', playlistLogicProps })+ picks.mount()+ const logic = watchPicksStarterLogic(picks.props)+ logic.mount()+ expect(logic.values.spendMode).toBe('free')+ expect(logic.values.candidateRecordings).toEqual(playlist.values.sessionRecordings)+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/watchPicksStarterLogic.ts b/products/replay_vision/frontend/replay_scanners/watchPicksStarterLogic.tsnew file mode 100644index 000000000000..d6a1a039050c--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/watchPicksStarterLogic.ts@@ -0,0 +1,527 @@+import {+ LogicWrapper,+ MakeLogicType,+ actions,+ afterMount,+ connect,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'+import { router } from 'kea-router'++import { lemonToast } from 'lib/lemon-ui/LemonToast'+import posthog from 'lib/posthog-typed'+import { pluralize } from 'lib/utils/strings'+import {+ SessionRecordingPlaylistLogicProps,+ sessionRecordingsPlaylistLogic,+} from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { NodeKind } from '~/queries/schema/schema-general'+import type { SessionRecordingType } from '~/types'++import {+ visionScannersBulkObserveCreate,+ visionScannersCreate,+ visionScannersEstimateCreate,+ visionScannersObservationsList,+} from '../generated/api'+import type { ReplayObservationApi, ReplayScannerApi } from '../generated/api.schemas'+import { visionQuotaLogic } from '../logics/visionQuotaLogic'+import { visionScannersListLogic } from '../logics/visionScannersListLogic'+import { formatCreditsMaybeUsd } from '../utils/credits'+import { DEFAULT_MODEL, DEFAULT_PROVIDER, OBSERVATION_CREDITS_BY_MODEL, scannerToApiBody } from './types'+import { watchPicksLogic } from './watchPicksLogic'+import {+ BURST_MAX_RECORDINGS,+ BUDGET_PRESETS,+ BurstPlan,+ FREE_SCANNER_CREDIT_LIMIT,+ QUICKSTART_SCANNER,+ StarterSpendMode,+ TARGET_MONTHLY_SCANS,+ planBurst,+ samplingRateForTarget,+ starterSpendMode,+} from './watchPicksStarter'++const BURST_POLL_MS = 10_000+const BURST_POLL_MAX = 60+const BURST_STALL_MS = 3 * 60_000+const BURST_RESUME_MAX_AGE_MS = 30 * 60_000++export interface BurstCounts {+ pending: number+ succeeded: number+ failed: number+}++export interface WatchPicksStarterLogicProps {+ logicKey: string+ playlistLogicProps?: SessionRecordingPlaylistLogicProps+}++type CandidateRecording = Pick<SessionRecordingType, 'id' | 'recording_duration' | 'active_seconds' | 'ongoing'>++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface watchPicksStarterLogicValues {+ currentTeamId: number | null // teamLogic+ freeCreditsLeft: number | null // visionQuotaLogic+ budget: number+ budgetChosen: boolean+ burstCounts: BurstCounts+ burstDone: boolean+ burstPlan: BurstPlan+ burstSessionIds: string[]+ burstStalled: boolean+ burstStartedAt: number+ burstTeamId: number | null+ candidateRecordings: CandidateRecording[]+ creditsPerObservation: number+ freeAvailable: boolean+ scannedAnyway: ReplayObservationApi[] | null+ spendMode: StarterSpendMode+ startError: string | null+ startedScanner: ReplayScannerApi | null+ starting: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface watchPicksStarterLogicActions {+ burstPolled: (counts: BurstCounts) => {+ counts: BurstCounts+ }+ burstSettled: (stalled?: boolean) => {+ stalled: boolean+ }+ chooseBudget: (budgetChosen: boolean) => {+ budgetChosen: boolean+ }+ pollBurst: () => {+ value: true+ }+ reset: () => {+ value: true+ }+ resumeBurst: () => {+ value: true+ }+ scannedAnywayLoaded: (observations: ReplayObservationApi[]) => {+ observations: ReplayObservationApi[]+ }+ scannerStarted: (+ scanner: ReplayScannerApi,+ sessionIds: string[],+ teamId: number+ ) => {+ scanner: ReplayScannerApi+ sessionIds: string[]+ teamId: number+ }+ setBudget: (budget: number) => {+ budget: number+ }+ showScannedAnyway: () => {+ value: true+ }+ startFailed: (message: string) => {+ message: string+ }+ startScanner: () => {+ value: true+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface watchPicksStarterLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ candidateRecordings: (arg: SessionRecordingType[]) => CandidateRecording[]+ freeAvailable: (freeCreditsLeft: number | null, creditsPerObservation: number) => boolean+ spendMode: (freeAvailable: boolean, budgetChosen: boolean) => StarterSpendMode+ burstPlan: (+ candidateRecordings: CandidateRecording[],+ creditsPerObservation: number,+ spendMode: StarterSpendMode,+ freeCreditsLeft: number | null,+ budget: number+ ) => BurstPlan+ }+}++export type watchPicksStarterLogicType = MakeLogicType<+ watchPicksStarterLogicValues,+ watchPicksStarterLogicActions,+ WatchPicksStarterLogicProps,+ watchPicksStarterLogicMeta+>++export const watchPicksStarterLogic: LogicWrapper<watchPicksStarterLogicType> = kea<watchPicksStarterLogicType>([+ props({} as WatchPicksStarterLogicProps),+ key((props) => props.logicKey),+ path((key) => ['products', 'replay_vision', 'frontend', 'replay_scanners', 'watchPicksStarterLogic', key]),++ connect(() => ({+ values: [teamLogic, ['currentTeamId'], visionQuotaLogic, ['freeCreditsLeft']],+ })),++ actions({+ setBudget: (budget: number) => ({ budget }),+ chooseBudget: (budgetChosen: boolean) => ({ budgetChosen }),+ startScanner: true,+ scannerStarted: (scanner: ReplayScannerApi, sessionIds: string[], teamId: number) => ({+ scanner,+ sessionIds,+ teamId,+ }),+ startFailed: (message: string) => ({ message }),+ pollBurst: true,+ burstPolled: (counts: BurstCounts) => ({ counts }),+ burstSettled: (stalled: boolean = false) => ({ stalled }),+ resumeBurst: true,+ showScannedAnyway: true,+ scannedAnywayLoaded: (observations: ReplayObservationApi[]) => ({ observations }),+ reset: true,+ }),++ reducers({+ budget: [+ BUDGET_PRESETS[1] as number,+ {+ setBudget: (_, { budget }) => budget,+ },+ ],+ budgetChosen: [+ false,+ {+ chooseBudget: (_, { budgetChosen }) => budgetChosen,+ reset: () => false,+ },+ ],+ starting: [+ false,+ {+ startScanner: () => true,+ scannerStarted: () => false,+ startFailed: () => false,+ },+ ],+ startError: [+ null as string | null,+ {+ startScanner: () => null,+ startFailed: (_, { message }) => message,+ reset: () => null,+ },+ ],+ startedScanner: [+ null as ReplayScannerApi | null,+ { persist: true, storageKey: 'replay-vision.watch-picks-starter.startedScanner' },+ {+ scannerStarted: (_, { scanner }) => scanner,+ reset: () => null,+ },+ ],+ burstSessionIds: [+ [] as string[],+ { persist: true, storageKey: 'replay-vision.watch-picks-starter.burstSessionIds' },+ {+ scannerStarted: (_, { sessionIds }) => sessionIds,+ reset: () => [],+ },+ ],+ burstCounts: [+ { pending: 0, succeeded: 0, failed: 0 } as BurstCounts,+ {+ scannerStarted: (_, { sessionIds }) => ({ pending: sessionIds.length, succeeded: 0, failed: 0 }),+ burstPolled: (_, { counts }) => counts,+ reset: () => ({ pending: 0, succeeded: 0, failed: 0 }),+ },+ ],+ burstDone: [+ false,+ { persist: true, storageKey: 'replay-vision.watch-picks-starter.burstDone' },+ {+ scannerStarted: (_, { sessionIds }) => sessionIds.length === 0,+ burstSettled: () => true,+ reset: () => false,+ },+ ],+ burstStartedAt: [+ 0,+ { persist: true, storageKey: 'replay-vision.watch-picks-starter.burstStartedAt' },+ {+ scannerStarted: () => Date.now(),+ reset: () => 0,+ },+ ],+ burstTeamId: [+ null as number | null,+ { persist: true, storageKey: 'replay-vision.watch-picks-starter.burstTeamId' },+ {+ scannerStarted: (_, { teamId }) => teamId,+ reset: () => null,+ },+ ],+ burstStalled: [+ false,+ {+ scannerStarted: () => false,+ burstSettled: (_, { stalled }) => stalled,+ reset: () => false,+ },+ ],+ scannedAnyway: [+ null as ReplayObservationApi[] | null,+ {+ scannedAnywayLoaded: (_, { observations }) => observations,+ reset: () => null,+ },+ ],+ }),++ selectors(({ props }) => ({+ candidateRecordings: [+ () => [+ props.playlistLogicProps+ ? sessionRecordingsPlaylistLogic(props.playlistLogicProps).selectors.sessionRecordings+ : () => [],+ ],+ (recordings: SessionRecordingType[]): CandidateRecording[] => recordings,+ ],+ creditsPerObservation: [() => [], (): number => OBSERVATION_CREDITS_BY_MODEL[DEFAULT_MODEL]],+ freeAvailable: [+ (s) => [s.freeCreditsLeft, s.creditsPerObservation],+ (freeCreditsLeft: number | null, creditsPerObservation: number): boolean =>+ starterSpendMode(freeCreditsLeft, creditsPerObservation) === 'free',+ ],+ spendMode: [+ (s) => [s.freeAvailable, s.budgetChosen],+ (freeAvailable: boolean, budgetChosen: boolean): StarterSpendMode =>+ freeAvailable && !budgetChosen ? 'free' : 'budget',+ ],+ burstPlan: [+ (s) => [s.candidateRecordings, s.creditsPerObservation, s.spendMode, s.freeCreditsLeft, s.budget],+ (+ candidateRecordings: CandidateRecording[],+ creditsPerObservation: number,+ spendMode: StarterSpendMode,+ freeCreditsLeft: number | null,+ budget: number+ ): BurstPlan => planBurst(candidateRecordings, creditsPerObservation, spendMode, freeCreditsLeft, budget),+ ],+ })),++ listeners(({ actions, values, props, cache }) => ({+ startScanner: async () => {+ const teamId = values.currentTeamId+ if (!teamId) {+ actions.startFailed('Could not create the scanner. Try again.')+ return+ }+ const template = QUICKSTART_SCANNER+ const query = { kind: NodeKind.RecordingsQuery }+ let estimatedAtFullRate: number | null = null+ try {+ const estimate = await visionScannersEstimateCreate(String(teamId), {+ query,+ sampling_rate: 1,+ model: DEFAULT_MODEL,+ })+ estimatedAtFullRate = estimate.estimated_observations_per_month+ } catch {+ estimatedAtFullRate = null+ }+ const samplingRate = samplingRateForTarget(estimatedAtFullRate, TARGET_MONTHLY_SCANS)+ const free = values.spendMode === 'free'+ const plan = values.burstPlan+ let scanner: ReplayScannerApi+ try {+ scanner = await visionScannersCreate(+ String(teamId),+ scannerToApiBody({+ name: template.name,+ description: template.description,+ scanner_type: template.scanner_type,+ scanner_config: structuredClone(template.scanner_config),+ model: DEFAULT_MODEL,+ provider: DEFAULT_PROVIDER,+ enabled: true,+ sampling_rate: samplingRate,+ sampling_mode: 'balanced',+ query,+ tags: [],+ free_only: free,+ credit_limit: free ? FREE_SCANNER_CREDIT_LIMIT : values.budget,+ creation_method: 'template',+ })+ )+ } catch {+ posthog.capture('replay_vision_watch_picks_starter_failed', { template: template.key, step: 'create' })+ actions.startFailed('Could not create the scanner. Try again.')+ return+ }+ let started: string[] = []+ if (plan.sessionIds.length > 0) {+ try {+ const response = await visionScannersBulkObserveCreate(String(teamId), scanner.id, {+ session_ids: plan.sessionIds,+ })+ started = response.results+ .filter(+ (result) => result.scan_outcome === 'started' || result.scan_outcome === 'already_running'+ )+ .map((result) => result.session_id)+ } catch {+ started = []+ }+ }+ posthog.capture('replay_vision_watch_picks_starter_started', {+ template: template.key,+ scanner_id: scanner.id,+ spend_mode: values.spendMode,+ sampling_rate: samplingRate,+ burst_planned: plan.sessionIds.length,+ burst_started: started.length,+ })+ visionScannersListLogic.findMounted()?.actions.loadScanners()+ visionQuotaLogic.findMounted()?.actions.loadQuota()+ watchPicksLogic.findMounted(props)?.actions.adoptPicksMode()+ if (!free) {+ const showUsd = visionQuotaLogic.findMounted()?.values.showUsd ?? false+ lemonToast.success(+ `${scanner.name} created with a ${formatCreditsMaybeUsd(values.budget, showUsd)} monthly limit.`,+ {+ button: {+ label: 'Change limit',+ action: () => router.actions.push(urls.replayVision(scanner.id)),+ dataAttr: 'vision-watch-picks-starter-change-limit',+ },+ }+ )+ }+ actions.scannerStarted(scanner, started, teamId)+ },+ scannerStarted: ({ sessionIds }) => {+ if (sessionIds.length > 0) {+ actions.resumeBurst()+ }+ },+ resumeBurst: () => {+ let polls = 0+ cache.lastProgress = values.burstCounts.succeeded + values.burstCounts.failed+ cache.lastProgressAt = Date.now()+ actions.pollBurst()+ cache.disposables.add(() => {+ const timer = window.setInterval(() => {+ polls += 1+ if (polls > BURST_POLL_MAX) {+ actions.burstSettled(true)+ return+ }+ actions.pollBurst()+ }, BURST_POLL_MS)+ return () => clearInterval(timer)+ }, 'burst-poll')+ },+ pollBurst: async (_, breakpoint) => {+ const teamId = values.currentTeamId+ const scanner = values.startedScanner+ if (!teamId || !scanner) {+ return+ }+ const burst = new Set(values.burstSessionIds)+ const response = await visionScannersObservationsList(String(teamId), scanner.id, {+ limit: BURST_MAX_RECORDINGS,+ order_by: '-created_at',+ })+ breakpoint()+ const rows = response.results.filter((row) => burst.has(row.session_id))+ const counts: BurstCounts = {+ pending: rows.filter((row) => row.status === 'pending' || row.status === 'running').length,+ succeeded: rows.filter((row) => row.status === 'succeeded').length,+ failed: rows.filter((row) => row.status === 'failed' || row.status === 'ineligible').length,+ }+ actions.burstPolled(counts)+ watchPicksLogic.findMounted(props)?.actions.loadPicks()+ const progress = counts.succeeded + counts.failed+ if (progress !== cache.lastProgress) {+ cache.lastProgress = progress+ cache.lastProgressAt = Date.now()+ }+ if (counts.pending === 0 && rows.length >= burst.size) {+ actions.burstSettled(false)+ } else if (Date.now() - (cache.lastProgressAt ?? Date.now()) > BURST_STALL_MS) {+ actions.burstSettled(true)+ }+ },+ burstSettled: ({ stalled }) => {+ cache.disposables.dispose('burst-poll')+ const picksLogicMounted = watchPicksLogic.findMounted(props)+ if (+ values.startedScanner &&+ values.burstCounts.succeeded > 0 &&+ picksLogicMounted &&+ picksLogicMounted.values.effectiveListMode !== 'picks'+ ) {+ lemonToast.info(+ `${values.startedScanner.name} finished scanning ${pluralize(values.burstCounts.succeeded, 'recording')}.`,+ {+ button: {+ label: 'Show what to watch',+ action: () => picksLogicMounted.actions.setListMode('picks'),+ dataAttr: 'vision-watch-picks-starter-finished-toast',+ },+ }+ )+ }+ posthog.capture('replay_vision_watch_picks_starter_settled', {+ scanner_id: values.startedScanner?.id,+ stalled,+ pending: values.burstCounts.pending,+ succeeded: values.burstCounts.succeeded,+ failed: values.burstCounts.failed,+ picks_count: watchPicksLogic.findMounted(props)?.values.picks?.length ?? 0,+ })+ },+ showScannedAnyway: async (_, breakpoint) => {+ const teamId = values.currentTeamId+ const scanner = values.startedScanner+ if (!teamId || !scanner) {+ return+ }+ const response = await visionScannersObservationsList(String(teamId), scanner.id, {+ limit: BURST_MAX_RECORDINGS,+ order_by: '-created_at',+ status: 'succeeded',+ })+ breakpoint()+ actions.scannedAnywayLoaded(response.results)+ },+ reset: () => {+ cache.disposables.dispose('burst-poll')+ },+ })),++ afterMount(({ actions, values }) => {+ if (!values.startedScanner) {+ return+ }+ const stale =+ values.burstDone ||+ values.burstTeamId !== values.currentTeamId ||+ Date.now() - values.burstStartedAt > BURST_RESUME_MAX_AGE_MS+ if (stale) {+ actions.reset()+ return+ }+ actions.resumeBurst()+ }),+])