Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): nudge first scans from the what to watch column (#124743)

Hayne Ryu595a81755401
diff --git a/products/replay_vision/frontend/components/DocsLink.tsx b/products/replay_vision/frontend/components/DocsLink.tsx
index 0b6f0fc8ea28..5200830a7156 100644
--- a/products/replay_vision/frontend/components/DocsLink.tsx
+++ b/products/replay_vision/frontend/components/DocsLink.tsx
@@ -10,6 +10,7 @@ export type VisionDocsPage =
| 'quota-and-limits'
| 'actions'
| 'webhooks'
+ | 'what-to-watch'
/** Raw docs URL for surfaces that need an href instead of a link, like ProductIntroduction's docsURL prop. */
export function visionDocsUrl(page?: VisionDocsPage): string {
@@ -20,16 +21,19 @@ export function visionDocsUrl(page?: VisionDocsPage): string {
export function VisionDocsLink({
page,
dataAttr,
+ onClick,
children,
}: {
page?: VisionDocsPage
dataAttr: string
+ onClick?: () => void
children: React.ReactNode
}): JSX.Element {
return (
<Link
to={`${visionDocsUrl(page)}?utm_medium=in-product&utm_campaign=empty-state-docs-link`}
target="_blank"
+ onClick={onClick}
data-attr={dataAttr}
>
{children}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ExampleObservations.tsx b/products/replay_vision/frontend/replay_scanners/components/ExampleObservations.tsx
index 8465a27f1102..bc7a1378df59 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ExampleObservations.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ExampleObservations.tsx
@@ -3,7 +3,7 @@ import { LemonTag } from '@posthog/lemon-ui'
import { cn } from 'lib/utils/css-classes'
-interface ExampleClip {
+export interface ExampleClip {
scannerName: string
scannerType: string
headline: string
@@ -14,7 +14,7 @@ interface ExampleClip {
* Invented, not sampled. A reader with no scanners has no observations to preview, so these stand in
* for the shape of a card rather than for anything their project has recorded.
*/
-const EXAMPLE_CLIPS: ExampleClip[] = [
+export const EXAMPLE_CLIPS: ExampleClip[] = [
{
scannerName: 'Checkout friction',
scannerType: 'Monitor',
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksEmptyState.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksEmptyState.tsx
index 6d983e0f50e3..77a2299a68f5 100644
--- a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksEmptyState.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksEmptyState.tsx
@@ -3,16 +3,21 @@ import { useEffect } from 'react'
import { LemonSkeleton } from '@posthog/lemon-ui'
+import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
import { cn } from 'lib/utils/css-classes'
import { teamLogic } from 'scenes/teamLogic'
+import { ProductKey } from '~/queries/schema/schema-general'
+
import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
import { visionScannersListLogic } from '../../logics/visionScannersListLogic'
import { resolveHighlightFeedEmptyReason } from '../highlightFeedEmptyState'
import { highlightPicksLogic } from '../highlightPicksLogic'
import { HighlightPicksBlockedState } from './HighlightPicksBlockedState'
+import { HighlightPicksNoRecordingsState } from './HighlightPicksNoRecordingsState'
import { HighlightPicksQuietState } from './HighlightPicksQuietState'
import { HighlightPicksReplayOffState } from './HighlightPicksReplayOffState'
+import { HighlightPicksShadowPreview } from './HighlightPicksShadowPreview'
import { HighlightPicksStarter } from './HighlightPicksStarter'
export function HighlightPicksEmptyState({ size }: { size: 'small' | 'large' }): JSX.Element {
@@ -21,6 +26,7 @@ export function HighlightPicksEmptyState({ size }: { size: 'small' | 'large' }):
const { currentTeam } = useValues(teamLogic)
const picksLogic = useMountedLogic(highlightPicksLogic)
const { emptyStateShown } = useActions(picksLogic)
+ const { status: replayStatus } = useValues(productSetupStatusLogic({ productKey: ProductKey.SESSION_REPLAY }))
const large = size === 'large'
const loading = scannersLoading || quotaLoading
@@ -31,6 +37,12 @@ export function HighlightPicksEmptyState({ size }: { size: 'small' | 'large' }):
quota,
sessionRecordingOptIn: currentTeam?.session_recording_opt_in ?? null,
hasFeedFilters: false,
+ hasRecordings:
+ replayStatus === 'has-data'
+ ? true
+ : replayStatus === 'needs-setup' || replayStatus === 'waiting-for-data'
+ ? false
+ : null,
})
useEffect(() => {
@@ -45,12 +57,30 @@ export function HighlightPicksEmptyState({ size }: { size: 'small' | 'large' }):
if (reason === 'replay-off') {
return <HighlightPicksReplayOffState size={size} />
}
+ if (reason === 'no-recordings') {
+ return (
+ <>
+ <HighlightPicksNoRecordingsState size={size} />
+ <HighlightPicksShadowPreview />
+ </>
+ )
+ }
if (reason === 'no-scanners') {
- return <HighlightPicksStarter size={size} />
+ return (
+ <>
+ <HighlightPicksStarter size={size} />
+ <HighlightPicksShadowPreview />
+ </>
+ )
}
if (reason === 'all-disabled' || reason === 'all-capped' || reason === 'quota-exhausted') {
return <HighlightPicksBlockedState reason={reason} size={size} />
}
- return <HighlightPicksQuietState size={size} />
+ return (
+ <>
+ <HighlightPicksQuietState size={size} />
+ <HighlightPicksShadowPreview />
+ </>
+ )
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksList.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksList.tsx
index 5a225e5e8b6d..b3e4634aeadf 100644
--- a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksList.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksList.tsx
@@ -2,11 +2,13 @@ import { useActions, useMountedLogic, useValues } from 'kea'
import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+import { VisionDocsLink } from '../../components/DocsLink'
import { highlightPicksLogic } from '../highlightPicksLogic'
import { highlightPicksStarterLogic } from '../highlightPicksStarterLogic'
import { HighlightPickRow } from './HighlightPickRow'
import { HighlightPicksEmptyState } from './HighlightPicksEmptyState'
import { HighlightPicksExtraRows } from './HighlightPicksExtraRows'
+import { HighlightPicksScanningState } from './HighlightPicksScanningState'
import { HighlightPicksStaleBanner } from './HighlightPicksStaleBanner'
import { HighlightPicksStarterStatus } from './HighlightPicksStarterStatus'
@@ -15,7 +17,7 @@ const LIST_TOP_COUNT = 5
export function HighlightPicksList(): JSX.Element {
const picksLogic = useMountedLogic(highlightPicksLogic)
const { picks, picksLoad, picksLoading, picksFailed, activeSessionId } = useValues(picksLogic)
- const { loadPicks } = useActions(picksLogic)
+ const { loadPicks, docsOpened } = useActions(picksLogic)
const { startedScanner, burstDone, burstStalled } = useValues(highlightPicksStarterLogic(picksLogic.props))
const burstActive = startedScanner !== null && (!burstDone || burstStalled)
@@ -50,7 +52,9 @@ export function HighlightPicksList(): JSX.Element {
</LemonButton>
</div>
) : !picks || picks.length === 0 ? (
- startedScanner ? (
+ startedScanner && !burstDone ? (
+ <HighlightPicksScanningState size="small" />
+ ) : startedScanner ? (
<>
<HighlightPicksStarterStatus />
<HighlightPicksExtraRows />
@@ -76,6 +80,18 @@ export function HighlightPicksList(): JSX.Element {
</>
)}
</div>
+ {picks && picks.length > 0 && (
+ <div className="flex items-center justify-between gap-2 border-t px-3 py-1.5 text-xs text-secondary">
+ <span>Picks from the last 7 days</span>
+ <VisionDocsLink
+ page="what-to-watch"
+ dataAttr="vision-highlight-picks-how-chosen"
+ onClick={docsOpened}
+ >
+ How picks are chosen
+ </VisionDocsLink>
+ </div>
+ )}
</div>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksNoRecordingsState.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksNoRecordingsState.tsx
new file mode 100644
index 000000000000..d4c751c965f8
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksNoRecordingsState.tsx
@@ -0,0 +1,51 @@
+import { useActions, useMountedLogic } from 'kea'
+
+import * as directorPng from '@posthog/brand/hoggies/png/director'
+import { LemonButton, Link } from '@posthog/lemon-ui'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import { OnboardingStepKey } from '~/types'
+
+import { highlightPicksLogic } from '../highlightPicksLogic'
+import { HighlightPicksStateFrame } from './HighlightPicksStateFrame'
+
+const HedgehogDirector = pngHoggie(directorPng)
+
+export function HighlightPicksNoRecordingsState({ size }: { size: 'small' | 'large' }): JSX.Element {
+ const { emptyStateAction } = useActions(useMountedLogic(highlightPicksLogic))
+ return (
+ <HighlightPicksStateFrame
+ size={size}
+ image={HedgehogDirector}
+ title="No recordings to scan yet"
+ body="Scanners watch recordings, so there is nothing for them to see until sessions arrive. Highlights show up once recording starts."
+ dataAttr="vision-highlight-picks-no-recordings"
+ footer={
+ <Link
+ to="https://posthog.com/docs/session-replay"
+ target="_blank"
+ className="mt-1"
+ onClick={() => emptyStateAction('no-recordings', 'replay_docs')}
+ data-attr="vision-highlight-picks-no-recordings-docs"
+ >
+ Session replay docs
+ </Link>
+ }
+ >
+ <LemonButton
+ type="primary"
+ size={size === 'large' ? 'medium' : 'small'}
+ fullWidth
+ center
+ to={urls.onboarding({ productKey: ProductKey.SESSION_REPLAY, stepKey: OnboardingStepKey.INSTALL })}
+ onClick={() => emptyStateAction('no-recordings', 'setup_replay')}
+ data-attr="vision-highlight-picks-no-recordings-setup"
+ >
+ Set up session replay
+ </LemonButton>
+ </HighlightPicksStateFrame>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksQuietState.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksQuietState.tsx
index f7996679e2c3..5f5e54d629c8 100644
--- a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksQuietState.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksQuietState.tsx
@@ -12,10 +12,15 @@ import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { formatCreditCount } from '../../utils/credits'
import { highlightPicksLogic } from '../highlightPicksLogic'
import { highlightPicksStaleLogic } from '../highlightPicksStaleLogic'
+import { weeklyVolume } from '../highlightPicksStarter'
+import { highlightPicksStarterLogic } from '../highlightPicksStarterLogic'
+import { highlightPicksVolumeLogic } from '../highlightPicksVolumeLogic'
import { SWEEP_INTERVAL_MINUTES } from '../scannerStatus'
import { HighlightPicksStateFrame } from './HighlightPicksStateFrame'
+import { HighlightPicksVolumeTiles } from './HighlightPicksVolumeTiles'
const HedgehogNoir = pngHoggie(noirPng)
+const SWEEP_STALE_MS = 60 * 60 * 1000
export function HighlightPicksQuietState({ size }: { size: 'small' | 'large' }): JSX.Element {
const picksLogic = useMountedLogic(highlightPicksLogic)
@@ -30,9 +35,13 @@ export function HighlightPicksQuietState({ size }: { size: 'small' | 'large' }):
lastSweptAt,
} = useValues(logic)
const { pickBackfillScanner, startBackfill } = useActions(logic)
+ const { candidateRecordings } = useValues(highlightPicksStarterLogic(picksLogic.props))
+ const { volumeEstimate, volumeEstimateLoading } = useValues(highlightPicksVolumeLogic)
const large = size === 'large'
const editDisabledReason = getReplayVisionEditDisabledReason()
+ const volume = weeklyVolume(volumeEstimate, candidateRecordings)
+ const sweepStale = !!lastSweptAt && Date.now() - new Date(lastSweptAt).getTime() > SWEEP_STALE_MS
const started = backfillScannerId ? backfillTotals[backfillScannerId] : undefined
const estimateReady = backfillEstimate?.scannerId === backfillScannerId ? backfillEstimate : null
@@ -42,15 +51,22 @@ export function HighlightPicksQuietState({ size }: { size: 'small' | 'large' }):
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.
- </>
+ sweepStale ? (
+ <>
+ {pluralize(backfillCandidates.length, 'scanner')} running, but the last sweep was{' '}
+ <TZLabel time={lastSweptAt} showPopover={false} noStyles />.
+ </>
+ ) : (
+ <>
+ {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-highlight-picks-quiet"
footer={
@@ -59,6 +75,11 @@ export function HighlightPicksQuietState({ size }: { size: 'small' | 'large' }):
</Link>
}
>
+ <HighlightPicksVolumeTiles
+ volume={volume}
+ loading={volumeEstimateLoading}
+ dataAttr="vision-highlight-picks-quiet-volume"
+ />
{backfillCandidates.length > 0 &&
(started === undefined ? (
<>
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksScanningState.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksScanningState.tsx
new file mode 100644
index 000000000000..acbdbd02810b
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksScanningState.tsx
@@ -0,0 +1,43 @@
+import { useMountedLogic, useValues } from 'kea'
+
+import * as magnifyingGlassPng from '@posthog/brand/hoggies/png/magnifying-glass'
+import { LemonSkeleton } from '@posthog/lemon-ui'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+
+import { highlightPicksLogic } from '../highlightPicksLogic'
+import { highlightPicksStarterLogic } from '../highlightPicksStarterLogic'
+import { HighlightPicksStateFrame } from './HighlightPicksStateFrame'
+
+const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
+const PLACEHOLDER_ROWS = 3
+
+export function HighlightPicksScanningState({ size }: { size: 'small' | 'large' }): JSX.Element {
+ const picksLogic = useMountedLogic(highlightPicksLogic)
+ const { burstSessionIds, burstCounts } = useValues(highlightPicksStarterLogic(picksLogic.props))
+ const total = burstSessionIds.length
+ const finished = burstCounts.succeeded + burstCounts.failed
+
+ return (
+ <>
+ <HighlightPicksStateFrame
+ size={size}
+ image={HedgehogMagnifyingGlass}
+ title="Scanning your sessions"
+ body="Highlights show up here a few minutes after scans finish."
+ dataAttr="vision-highlight-picks-scanning"
+ >
+ <LemonProgress percent={total === 0 ? 100 : (finished / total) * 100} />
+ <span className="text-xs text-secondary" translate="no">
+ {finished} of {total} scanned
+ </span>
+ </HighlightPicksStateFrame>
+ <div className="flex flex-col gap-2 p-2" aria-busy>
+ {Array.from({ length: Math.min(PLACEHOLDER_ROWS, Math.max(1, total - finished)) }, (_, i) => (
+ <LemonSkeleton key={i} className="h-16 rounded" />
+ ))}
+ </div>
+ </>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksShadowPreview.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksShadowPreview.tsx
new file mode 100644
index 000000000000..637f39109065
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksShadowPreview.tsx
@@ -0,0 +1,31 @@
+import { IconPlayFilled } from '@posthog/icons'
+
+import { EXAMPLE_CLIPS } from './ExampleObservations'
+import { HighlightPickRankBadge } from './HighlightPickRankBadge'
+
+export function HighlightPicksShadowPreview(): JSX.Element {
+ return (
+ <div className="relative flex flex-col gap-0.5 p-1" data-attr="vision-highlight-picks-shadow-preview">
+ <span className="px-2 py-1 text-xs text-secondary">Examples, not your data</span>
+ {EXAMPLE_CLIPS.map((clip, index) => (
+ <div key={clip.scannerName} className="flex w-full min-w-0 items-center gap-3 px-2 py-1 opacity-60">
+ <span className="relative flex h-16 w-28 shrink-0 items-center justify-center rounded bg-surface-secondary text-secondary">
+ <IconPlayFilled className="text-xl" />
+ <HighlightPickRankBadge rank={index + 1} size="small" />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="truncate text-sm font-semibold">{clip.headline}</span>
+ <span className="truncate text-xs text-secondary">
+ {clip.scannerName} · {clip.scannerType}
+ </span>
+ <span className="truncate text-xs text-secondary">{clip.reason}</span>
+ </span>
+ </div>
+ ))}
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-0 bg-gradient-to-b from-transparent from-40% to-[var(--color-bg-light)]"
+ />
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStaleBanner.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStaleBanner.tsx
index 88b91c2077e4..3a7bbb30b1da 100644
--- a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStaleBanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStaleBanner.tsx
@@ -1,15 +1,23 @@
import { useActions, useMountedLogic, useValues } from 'kea'
+import { combineUrl } from 'kea-router'
+import { ReactNode } from 'react'
-import { LemonBanner, LemonButton, Link } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { pluralize } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { highlightPicksLogic } from '../highlightPicksLogic'
import { highlightPicksStaleLogic } from '../highlightPicksStaleLogic'
import { scannerEditUrl } from '../scannerEditorSceneLogic'
+import { markScannerGoalDraftIntent } from '../scannerHandoffIntent'
import { HighlightPicksBlockedState } from './HighlightPicksBlockedState'
+import { SCANNER_GOAL_STARTERS } from './scannerGoalStarters'
+
+const QUIET_WEEK_GOAL_KEYS = ['dead_end', 'frustration_score']
+const quietWeekGoals = SCANNER_GOAL_STARTERS.filter((starter) => QUIET_WEEK_GOAL_KEYS.includes(starter.key))
export function HighlightPicksStaleBanner(): JSX.Element | null {
const picksLogic = useMountedLogic(highlightPicksLogic)
@@ -25,7 +33,7 @@ export function HighlightPicksStaleBanner(): JSX.Element | null {
nextBest,
nextBestLoading,
} = useValues(logic)
- const { startBackfill, loadNextBest } = useActions(logic)
+ const { startBackfill, loadNextBest, pickSharperGoal } = useActions(logic)
const editDisabledReason = getReplayVisionEditDisabledReason()
if (!staleReason) {
@@ -39,7 +47,8 @@ export function HighlightPicksStaleBanner(): JSX.Element | 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
+ const runningScanners = scanners.filter((scanner) => scanner.enabled && !scanner.limit_reached)
+ const running = runningScanners.length
if (staleReason === 'drought') {
return (
@@ -111,28 +120,60 @@ export function HighlightPicksStaleBanner(): JSX.Element | null {
)
}
+ const stats: [string, ReactNode][] = [
+ ['Scanned', quietWeek ? String(quietWeek.scanned) : null],
+ ['Picks', String((picks ?? []).length)],
+ ['Last pick', newest ? <TZLabel key="last-pick" time={newest} showPopover={false} noStyles /> : null],
+ ]
return (
<div
- className="flex flex-col gap-1 border-b bg-bg-light px-3 py-2 text-xs"
+ className="flex flex-col gap-2 border-b bg-bg-light px-3 py-2 text-xs"
data-attr="vision-highlight-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>
- )}
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="font-semibold">Quiet week</span>
+ {runningScanners.length === 1 && (
+ <span className="truncate text-secondary">{runningScanners[0].name}</span>
+ )}
+ </div>
+ <div className="flex gap-4">
+ {stats.map(([label, value]) => (
+ <div key={label} className="flex flex-col">
+ <span className="text-xxs font-bold uppercase tracking-wide text-secondary">{label}</span>
+ {value ? (
+ <span className="text-base font-bold leading-tight">{value}</span>
+ ) : (
+ <LemonSkeleton className="h-5 w-8" />
+ )}
+ </div>
+ ))}
+ </div>
+ <span className="text-secondary">Nothing stood out this week. Try a sharper goal.</span>
+ {quietWeekGoals.map((starter) => (
+ <LemonButton
+ key={starter.key}
+ type="secondary"
+ size="small"
+ fullWidth
+ icon={starter.icon}
+ disabledReason={editDisabledReason}
+ to={combineUrl(urls.replayVisionNewScanner(), { goal: starter.goal }).url}
+ onClick={() => {
+ markScannerGoalDraftIntent(starter.goal)
+ pickSharperGoal(starter.key)
+ }}
+ data-attr={`vision-highlight-picks-stale-goal-${starter.key}`}
+ >
+ <span className="flex min-w-0 flex-col text-left">
+ <span>{starter.question}</span>
+ <span className="truncate text-xxs font-normal text-secondary">{starter.goal}</span>
+ </span>
+ </LemonButton>
+ ))}
{nextBest === null ? (
<LemonButton
size="xsmall"
- type="secondary"
+ type="tertiary"
className="self-start"
loading={nextBestLoading}
onClick={loadNextBest}
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStarter.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStarter.tsx
index 3a619921634c..f662809e5944 100644
--- a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStarter.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStarter.tsx
@@ -1,7 +1,7 @@
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 { LemonBanner, LemonButton, LemonSegmentedButton, LemonSkeleton, Link } from '@posthog/lemon-ui'
import { pngHoggie } from 'lib/brand/hoggies'
import { pluralize } from 'lib/utils/strings'
@@ -11,63 +11,94 @@ import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { formatCreditCount, formatCreditNumber, formatCreditsMaybeUsd } from '../../utils/credits'
import { highlightPicksLogic } from '../highlightPicksLogic'
-import { BUDGET_PRESETS, QUICKSTART_SCANNER, TARGET_MONTHLY_SCANS } from '../highlightPicksStarter'
+import { BUDGET_PRESETS, TARGET_MONTHLY_SCANS, weeklyVolume } from '../highlightPicksStarter'
import { highlightPicksStarterLogic } from '../highlightPicksStarterLogic'
+import { highlightPicksVolumeLogic } from '../highlightPicksVolumeLogic'
import { HighlightPicksStateFrame } from './HighlightPicksStateFrame'
+import { HighlightPicksVolumeTiles } from './HighlightPicksVolumeTiles'
const SCANS_PER_DAY = Math.round(TARGET_MONTHLY_SCANS / 30)
const HedgehogMagnifyingGlass = pngHoggie(magnifyingGlassPng)
export function HighlightPicksStarter({ size }: { size: 'small' | 'large' }): JSX.Element {
- const { props: picksProps } = useMountedLogic(highlightPicksLogic)
- const logic = highlightPicksStarterLogic(picksProps)
- const { burstPlan, spendMode, freeAvailable, budget, starting, startError, freeCreditsLeft } = useValues(logic)
+ const picksLogic = useMountedLogic(highlightPicksLogic)
+ const { emptyStateAction } = useActions(picksLogic)
+ const logic = highlightPicksStarterLogic(picksLogic.props)
+ const { burstPlan, spendMode, freeAvailable, budget, starting, startError, freeCreditsLeft, candidateRecordings } =
+ useValues(logic)
const { setBudget, chooseBudget, startScanner } = useActions(logic)
+ const { volumeEstimate, volumeEstimateLoading } = useValues(highlightPicksVolumeLogic)
const { showUsd } = useValues(visionQuotaLogic)
const large = size === 'large'
const editDisabledReason = getReplayVisionEditDisabledReason()
+ const volume = weeklyVolume(volumeEstimate, candidateRecordings)
+ const loading = volumeEstimateLoading && !volume
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',
- ],
- ]
+ const costLine =
+ 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 (
<HighlightPicksStateFrame
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.`}
+ title={
+ loading ? (
+ <LemonSkeleton className="h-5 w-48" />
+ ) : volume ? (
+ 'Your week in recordings'
+ ) : (
+ 'Nothing to watch yet'
+ )
+ }
+ body={
+ volume || loading
+ ? null
+ : 'Start scanning your sessions. A scanner reads new recordings and surfaces the ones worth watching.'
+ }
dataAttr="vision-highlight-picks-starter"
footer={
- <Link
- to={urls.replayVisionNewScanner()}
- className="mt-1"
- data-attr="vision-highlight-picks-starter-own-goal"
- >
- Write my own goal
- </Link>
+ <div className="mt-1 flex flex-wrap items-baseline justify-center gap-x-3 gap-y-1">
+ {freeAvailable && (
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ disabledReason={starting ? 'Starting' : null}
+ onClick={() => {
+ emptyStateAction('no-scanners', spendMode === 'free' ? 'set_budget' : 'use_free')
+ chooseBudget(spendMode === 'free')
+ }}
+ data-attr="vision-highlight-picks-starter-toggle-budget"
+ >
+ {spendMode === 'free' ? 'Set a monthly budget instead' : 'Use free credits instead'}
+ </LemonButton>
+ )}
+ <Link
+ to={urls.replayVisionNewScanner()}
+ onClick={() => emptyStateAction('no-scanners', 'own_goal')}
+ data-attr="vision-highlight-picks-starter-own-goal"
+ >
+ Write my own goal
+ </Link>
+ </div>
}
>
- <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>
+ <HighlightPicksVolumeTiles
+ volume={volume}
+ loading={loading}
+ dataAttr="vision-highlight-picks-starter-volume"
+ />
+ {volume && (
+ <span className="text-xs text-secondary">
+ {burstCount > 0
+ ? `A scanner reads the newest ${burstCount} now and hands you the few worth opening.`
+ : 'A scanner reads new recordings and hands you the few worth opening.'}
+ </span>
+ )}
{spendMode === 'budget' && (
<>
<LemonSegmentedButton
@@ -95,21 +126,15 @@ export function HighlightPicksStarter({ size }: { size: 'small' | 'large' }): JS
onClick={startScanner}
data-attr="vision-highlight-picks-starter-start"
>
- {spendMode === 'free' ? 'Start free scanner' : `Start with ${formatCreditCount(budget)} a month`}
+ {spendMode === 'free'
+ ? burstCount > 0
+ ? `Scan ${pluralize(burstCount, 'recent recording')} for 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-highlight-picks-starter-toggle-budget"
- >
- {spendMode === 'free' ? 'Set a monthly budget instead' : 'Use free credits instead'}
- </LemonButton>
- )}
+ <span className="text-xxs text-secondary">
+ Then about {SCANS_PER_DAY} new recordings a day. {costLine}
+ </span>
</HighlightPicksStateFrame>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStarterStatus.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStarterStatus.tsx
index 8062cad319d6..d6bb1369484c 100644
--- a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStarterStatus.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksStarterStatus.tsx
@@ -13,7 +13,8 @@ export function HighlightPicksStarterStatus(): JSX.Element | null {
const picksLogic = useMountedLogic(highlightPicksLogic)
const { picks } = useValues(picksLogic)
const logic = highlightPicksStarterLogic(picksLogic.props)
- const { startedScanner, burstSessionIds, burstCounts, burstDone, burstStalled, scannedAnyway } = useValues(logic)
+ const { startedScanner, burstSessionIds, burstCounts, burstDone, burstStalled, scannedAnyway, feedWindowOpen } =
+ useValues(logic)
const { showScannedAnyway } = useActions(logic)
if (!startedScanner) {
@@ -33,14 +34,18 @@ export function HighlightPicksStarterStatus(): JSX.Element | null {
<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`}
+ {total === 0
+ ? 'Your scanner is on'
+ : feedWindowOpen
+ ? `${pluralize(burstCounts.succeeded, 'recording')} scanned`
+ : `${pluralize(burstCounts.succeeded, 'recording')} scanned, nothing stood out`}
</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.'}
+ : feedWindowOpen
+ ? 'Highlights show up here a few minutes after scans finish.'
+ : '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 && (
@@ -86,14 +91,14 @@ export function HighlightPicksStarterStatus(): JSX.Element | null {
<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
+ Scanning sessions
</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>
+ <span className="text-secondary">Highlights show up here a few minutes after scans finish.</span>
</div>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/HighlightPicksVolumeTiles.tsx b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksVolumeTiles.tsx
new file mode 100644
index 000000000000..3e803d3fd40f
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/HighlightPicksVolumeTiles.tsx
@@ -0,0 +1,39 @@
+import { LemonSkeleton } from '@posthog/lemon-ui'
+
+import type { WeeklyVolume } from '../highlightPicksStarter'
+
+function hoursLabel(hours: number): string {
+ return hours < 1 ? `${Math.max(1, Math.round(hours * 60))}m` : `${Math.round(hours)}h`
+}
+
+export function HighlightPicksVolumeTiles({
+ volume,
+ loading,
+ dataAttr,
+}: {
+ volume: WeeklyVolume | null
+ loading: boolean
+ dataAttr: string
+}): JSX.Element | null {
+ if (!volume) {
+ return loading ? <LemonSkeleton className="h-16 w-full rounded" /> : null
+ }
+ const tiles: [string, string, string][] = [
+ ['Recorded', String(volume.recorded), 'a week, estimated'],
+ ['To watch', volume.hours === null ? '-' : hoursLabel(volume.hours), 'at normal speed'],
+ ]
+ return (
+ <div className="grid grid-cols-2 gap-1.5" data-attr={dataAttr}>
+ {tiles.map(([label, value, caption]) => (
+ <div
+ key={label}
+ className="flex flex-col items-center gap-0.5 rounded border bg-bg-light px-1 py-2 text-center"
+ >
+ <span className="text-xxs font-bold uppercase tracking-wide text-secondary">{label}</span>
+ <span className="text-xl font-bold leading-tight">{value}</span>
+ <span className="text-xxs text-secondary">{caption}</span>
+ </div>
+ ))}
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/highlightFeedEmptyState.test.ts b/products/replay_vision/frontend/replay_scanners/highlightFeedEmptyState.test.ts
index d1f8e88a01b0..24595a8de3cd 100644
--- a/products/replay_vision/frontend/replay_scanners/highlightFeedEmptyState.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/highlightFeedEmptyState.test.ts
@@ -9,7 +9,17 @@ const quota = (exhausted: boolean): VisionQuotaApi => ({ exhausted }) as unknown
describe('resolveHighlightFeedEmptyReason', () => {
// The precedence between these is the behavior under test: a reader told to clear their filters
// while every scanner is off would clear them and still face an empty feed.
- it.each<[string, ReplayScannerApi[], VisionQuotaApi | null, boolean, HighlightFeedEmptyReason, (boolean | null)?]>([
+ it.each<
+ [
+ string,
+ ReplayScannerApi[],
+ VisionQuotaApi | null,
+ boolean,
+ HighlightFeedEmptyReason,
+ (boolean | null)?,
+ (boolean | null)?,
+ ]
+ >([
['no scanners at all', [], quota(false), false, 'no-scanners'],
['recording turned off, even with no scanners', [], quota(false), false, 'replay-off', false],
['recording turned off, even with an exhausted budget', [scanner()], quota(true), false, 'replay-off', false],
@@ -55,9 +65,38 @@ describe('resolveHighlightFeedEmptyReason', () => {
],
// Falls through rather than claiming a block it cannot see.
['a quiet window when the quota snapshot never answered', [scanner()], null, false, 'quiet-window'],
- ])('blames %s', (_name, scanners, quotaValue, hasFeedFilters, expected, sessionRecordingOptIn = null) => {
- expect(
- resolveHighlightFeedEmptyReason({ scanners, quota: quotaValue, sessionRecordingOptIn, hasFeedFilters })
- ).toBe(expected)
- })
+ ['no recordings before any scanner exists', [], quota(false), false, 'no-recordings', null, false],
+ ['no recordings over a quiet window', [scanner()], quota(false), false, 'no-recordings', null, false],
+ [
+ 'a block before missing recordings',
+ [scanner({ enabled: false })],
+ quota(false),
+ false,
+ 'all-disabled',
+ null,
+ false,
+ ],
+ [
+ 'a quiet window while the recordings probe is unanswered',
+ [scanner()],
+ quota(false),
+ false,
+ 'quiet-window',
+ null,
+ null,
+ ],
+ ])(
+ 'blames %s',
+ (_name, scanners, quotaValue, hasFeedFilters, expected, sessionRecordingOptIn = null, hasRecordings = null) => {
+ expect(
+ resolveHighlightFeedEmptyReason({
+ scanners,
+ quota: quotaValue,
+ sessionRecordingOptIn,
+ hasFeedFilters,
+ hasRecordings,
+ })
+ ).toBe(expected)
+ }
+ )
})
diff --git a/products/replay_vision/frontend/replay_scanners/highlightFeedEmptyState.ts b/products/replay_vision/frontend/replay_scanners/highlightFeedEmptyState.ts
index f7bf3e47ba69..c97e88a3b29f 100644
--- a/products/replay_vision/frontend/replay_scanners/highlightFeedEmptyState.ts
+++ b/products/replay_vision/frontend/replay_scanners/highlightFeedEmptyState.ts
@@ -6,6 +6,7 @@ import type { ReplayScannerApi, VisionQuotaApi } from '../generated/api.schemas'
*/
export type HighlightFeedEmptyReason =
| 'replay-off'
+ | 'no-recordings'
| 'no-scanners'
| 'quota-exhausted'
| 'all-disabled'
@@ -65,6 +66,7 @@ export interface HighlightFeedEmptyInput {
/** Null while the team has not loaded, which also reads as "no block seen". */
sessionRecordingOptIn: boolean | null
hasFeedFilters: boolean
+ hasRecordings?: boolean | null
}
/**
@@ -76,11 +78,15 @@ export function resolveHighlightFeedEmptyReason({
quota,
sessionRecordingOptIn,
hasFeedFilters,
+ hasRecordings = null,
}: HighlightFeedEmptyInput): HighlightFeedEmptyReason {
if (sessionRecordingOptIn === false) {
return 'replay-off'
}
if (scanners.length === 0) {
+ if (hasRecordings === false) {
+ return 'no-recordings'
+ }
// The scene gate answers this one first, so the feed sees it only when the setup probe
// failed open. The tab still has to offer the way in.
return 'no-scanners'
@@ -99,5 +105,5 @@ export function resolveHighlightFeedEmptyReason({
if (hasFeedFilters) {
return 'filtered'
}
- return 'quiet-window'
+ return hasRecordings === false ? 'no-recordings' : 'quiet-window'
}
diff --git a/products/replay_vision/frontend/replay_scanners/highlightPicksLogic.ts b/products/replay_vision/frontend/replay_scanners/highlightPicksLogic.ts
index 61b15086398e..7450c4464656 100644
--- a/products/replay_vision/frontend/replay_scanners/highlightPicksLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/highlightPicksLogic.ts
@@ -92,6 +92,16 @@ export interface highlightPicksLogicActions {
item: HighlightFeedItemApi
position: number
}
+ docsOpened: () => {
+ value: true
+ }
+ emptyStateAction: (
+ reason: HighlightFeedEmptyReason,
+ action: string
+ ) => {
+ action: string
+ reason: HighlightFeedEmptyReason
+ }
emptyStateShown: (reason: HighlightFeedEmptyReason) => {
reason: HighlightFeedEmptyReason
}
@@ -177,6 +187,8 @@ export const highlightPicksLogic: LogicWrapper<highlightPicksLogicType> = kea<hi
setPicksLoad: (load: HighlightFeedLoad) => ({ load }),
cardSeen: (item: HighlightFeedItemApi, position: number) => ({ item, position }),
emptyStateShown: (reason: HighlightFeedEmptyReason) => ({ reason }),
+ emptyStateAction: (reason: HighlightFeedEmptyReason, action: string) => ({ reason, action }),
+ docsOpened: true,
}),
loaders(({ values, actions }) => ({
@@ -303,6 +315,12 @@ export const highlightPicksLogic: LogicWrapper<highlightPicksLogicType> = kea<hi
cache.emptyStateShownReason = reason
posthog.capture('replay_vision_highlight_picks_empty_shown', { reason })
},
+ emptyStateAction: ({ reason, action }) => {
+ posthog.capture('replay_vision_highlight_picks_empty_action', { reason, action })
+ },
+ docsOpened: () => {
+ posthog.capture('replay_vision_highlight_picks_docs_opened')
+ },
cardSeen: ({ item, position }) => {
// Fallback rows below the picks were not served by the ranker, so they are not impressions of this load.
if (values.picksLoad?.positions[item.observation.id] !== undefined) {
diff --git a/products/replay_vision/frontend/replay_scanners/highlightPicksStaleLogic.ts b/products/replay_vision/frontend/replay_scanners/highlightPicksStaleLogic.ts
index 2c28901c0440..04efce7dfca8 100644
--- a/products/replay_vision/frontend/replay_scanners/highlightPicksStaleLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/highlightPicksStaleLogic.ts
@@ -228,6 +228,9 @@ export interface highlightPicksStaleLogicActions {
pickBackfillScanner: (scannerId: string | null) => {
scannerId: string | null
}
+ pickSharperGoal: (goalKey: string) => {
+ goalKey: string
+ }
raiseLimit: (
scannerId: string,
creditLimit: number
@@ -312,6 +315,7 @@ export const highlightPicksStaleLogic: LogicWrapper<highlightPicksStaleLogicType
scannerActionDone: (scannerId: string) => ({ scannerId }),
pickBackfillScanner: (scannerId: string | null) => ({ scannerId }),
loadBackfillEstimate: true,
+ pickSharperGoal: (goalKey: string) => ({ goalKey }),
}),
loaders(({ values }) => ({
@@ -512,14 +516,19 @@ export const highlightPicksStaleLogic: LogicWrapper<highlightPicksStaleLogicType
visionQuotaLogic.findMounted()?.actions.loadQuota()
highlightPicksLogic.findMounted(props)?.actions.loadPicks()
}
- const act = (action: string, scannerId: string): void => {
+ const act = (action: string, scannerId: string | null, extra: Record<string, string> = {}): void => {
posthog.capture('replay_vision_highlight_picks_stale_action', {
reason: values.staleReason,
action,
scanner_id: scannerId,
+ ...extra,
})
}
return {
+ pickSharperGoal: ({ goalKey }) => {
+ const running = values.scanners.filter((scanner) => scanner.enabled && !scanner.limit_reached)
+ act('sharper_goal', running.length === 1 ? running[0].id : null, { goal_key: goalKey })
+ },
loadScannersSuccess: () => {
if (values.picks && values.picks.length > 0) {
cache.droughtsLoaded = true
diff --git a/products/replay_vision/frontend/replay_scanners/highlightPicksStarter.test.ts b/products/replay_vision/frontend/replay_scanners/highlightPicksStarter.test.ts
index 98431189191a..fb2ea3b616bd 100644
--- a/products/replay_vision/frontend/replay_scanners/highlightPicksStarter.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/highlightPicksStarter.test.ts
@@ -1,4 +1,4 @@
-import { planBurst, samplingRateForTarget, starterSpendMode } from './highlightPicksStarter'
+import { planBurst, samplingRateForTarget, starterSpendMode, weeklyVolume } from './highlightPicksStarter'
const recording = (id: string, overrides: Record<string, unknown> = {}): any => ({
id,
@@ -51,4 +51,33 @@ describe('highlightPicksStarter', () => {
])('needs a budget once %p free credits cannot buy one scan', (freeLeft, mode) => {
expect(starterSpendMode(freeLeft, 5)).toBe(mode)
})
+
+ it.each<
+ [
+ string,
+ { matched_sessions_in_window: number; window_days: number } | null,
+ number[],
+ [number, number | null] | null,
+ ]
+ >([
+ [
+ 'scales a short window to a week',
+ { matched_sessions_in_window: 90, window_days: 3 },
+ [120, 240],
+ [210, 10.5],
+ ],
+ ['has no hours without durations', { matched_sessions_in_window: 70, window_days: 7 }, [], [70, null]],
+ ['is empty for a team without recordings', { matched_sessions_in_window: 0, window_days: 7 }, [120], null],
+ ['is empty before the estimate lands', null, [120], null],
+ ])('weekly volume %s', (_name, estimate, durations, expected) => {
+ const volume = weeklyVolume(
+ estimate,
+ durations.map((recording_duration) => ({ recording_duration }))
+ )
+ if (expected === null) {
+ expect(volume).toBeNull()
+ return
+ }
+ expect([volume?.recorded, volume?.hours]).toEqual(expected)
+ })
})
diff --git a/products/replay_vision/frontend/replay_scanners/highlightPicksStarter.ts b/products/replay_vision/frontend/replay_scanners/highlightPicksStarter.ts
index 6567b31ddf16..09faf83ee782 100644
--- a/products/replay_vision/frontend/replay_scanners/highlightPicksStarter.ts
+++ b/products/replay_vision/frontend/replay_scanners/highlightPicksStarter.ts
@@ -1,5 +1,6 @@
import type { SessionRecordingType } from '~/types'
+import type { EstimateResponseApi } from '../generated/api.schemas'
import { recordingScanBlock } from '../utils/scanEligibility'
import type { SummarizerScannerConfig } from './types'
@@ -8,6 +9,31 @@ 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 interface WeeklyVolume {
+ recorded: number
+ hours: number | null
+}
+
+export function weeklyVolume(
+ estimate: Pick<EstimateResponseApi, 'matched_sessions_in_window' | 'window_days'> | null,
+ recordings: readonly Pick<SessionRecordingType, 'recording_duration'>[]
+): WeeklyVolume | null {
+ if (!estimate || estimate.window_days <= 0) {
+ return null
+ }
+ const recorded = Math.round((estimate.matched_sessions_in_window / estimate.window_days) * 7)
+ if (recorded <= 0) {
+ return null
+ }
+ const durations = recordings
+ .map((recording) => recording.recording_duration)
+ .filter((duration): duration is number => typeof duration === 'number' && duration > 0)
+ const hours =
+ durations.length > 0
+ ? (recorded * (durations.reduce((sum, duration) => sum + duration, 0) / durations.length)) / 3600
+ : null
+ return { recorded, hours }
+}
export const QUICKSTART_SCANNER = {
key: 'session_highlights',
name: 'Session highlights',
diff --git a/products/replay_vision/frontend/replay_scanners/highlightPicksStarterLogic.ts b/products/replay_vision/frontend/replay_scanners/highlightPicksStarterLogic.ts
index c910cb3037ff..e66458301bda 100644
--- a/products/replay_vision/frontend/replay_scanners/highlightPicksStarterLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/highlightPicksStarterLogic.ts
@@ -50,12 +50,15 @@ import {
samplingRateForTarget,
starterSpendMode,
} from './highlightPicksStarter'
+import { highlightPicksVolumeLogic } from './highlightPicksVolumeLogic'
import { DEFAULT_MODEL, DEFAULT_PROVIDER, OBSERVATION_CREDITS_BY_MODEL, scannerToApiBody } from './types'
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
+const SETTLED_REFRESH_MS = 60_000
+const SETTLED_REFRESH_MAX = 10
export interface BurstCounts {
pending: number
@@ -85,6 +88,7 @@ export interface highlightPicksStarterLogicValues {
burstTeamId: number | null
candidateRecordings: CandidateRecording[]
creditsPerObservation: number
+ feedWindowOpen: boolean
freeAvailable: boolean
scannedAnyway: ReplayObservationApi[] | null
spendMode: StarterSpendMode
@@ -104,6 +108,9 @@ export interface highlightPicksStarterLogicActions {
chooseBudget: (budgetChosen: boolean) => {
budgetChosen: boolean
}
+ feedWindowElapsed: () => {
+ value: true
+ }
pollBurst: () => {
value: true
}
@@ -186,6 +193,7 @@ export const highlightPicksStarterLogic: LogicWrapper<highlightPicksStarterLogic
pollBurst: true,
burstPolled: (counts: BurstCounts) => ({ counts }),
burstSettled: (stalled: boolean = false) => ({ stalled }),
+ feedWindowElapsed: true,
resumeBurst: true,
showScannedAnyway: true,
scannedAnywayLoaded: (observations: ReplayObservationApi[]) => ({ observations }),
@@ -279,6 +287,14 @@ export const highlightPicksStarterLogic: LogicWrapper<highlightPicksStarterLogic
reset: () => false,
},
],
+ feedWindowOpen: [
+ false,
+ {
+ burstSettled: () => true,
+ feedWindowElapsed: () => false,
+ reset: () => false,
+ },
+ ],
scannedAnyway: [
null as ReplayObservationApi[] | null,
{
@@ -330,16 +346,20 @@ export const highlightPicksStarterLogic: LogicWrapper<highlightPicksStarterLogic
}
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
+ let estimatedAtFullRate: number | null =
+ highlightPicksVolumeLogic.findMounted()?.values.volumeEstimate?.estimated_observations_per_month ??
+ null
+ if (estimatedAtFullRate === 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'
@@ -470,6 +490,17 @@ export const highlightPicksStarterLogic: LogicWrapper<highlightPicksStarterLogic
},
burstSettled: ({ stalled }) => {
cache.disposables.dispose('burst-poll')
+ let refreshes = 0
+ cache.disposables.add(() => {
+ const timer = window.setInterval(() => {
+ refreshes += 1
+ highlightPicksLogic.findMounted(props)?.actions.loadPicks()
+ if (refreshes >= SETTLED_REFRESH_MAX) {
+ actions.feedWindowElapsed()
+ }
+ }, SETTLED_REFRESH_MS)
+ return () => clearInterval(timer)
+ }, 'settled-refresh')
const picksLogicMounted = highlightPicksLogic.findMounted(props)
if (
values.startedScanner &&
@@ -513,6 +544,7 @@ export const highlightPicksStarterLogic: LogicWrapper<highlightPicksStarterLogic
},
reset: () => {
cache.disposables.dispose('burst-poll')
+ cache.disposables.dispose('settled-refresh')
},
})),
diff --git a/products/replay_vision/frontend/replay_scanners/highlightPicksVolumeLogic.ts b/products/replay_vision/frontend/replay_scanners/highlightPicksVolumeLogic.ts
new file mode 100644
index 000000000000..be91aa8923a5
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/highlightPicksVolumeLogic.ts
@@ -0,0 +1,148 @@
+import { LogicWrapper, MakeLogicType, actions, connect, kea, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import { subscriptions } from 'kea-subscriptions'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { NodeKind } from '~/queries/schema/schema-general'
+
+import { visionScannersEstimateCreate } from '../generated/api'
+import type { EstimateResponseApi } from '../generated/api.schemas'
+import { DEFAULT_MODEL } from './types'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface highlightPicksVolumeLogicValues {
+ currentTeamId: number | null // teamLogic
+ cachedSnapshot: VolumeSnapshot | null
+ volumeEstimate: EstimateResponseApi | null
+ volumeEstimateLoading: boolean
+ volumeSnapshot: VolumeSnapshot | null
+ volumeSnapshotLoading: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface highlightPicksVolumeLogicActions {
+ loadVolumeEstimate: () => {
+ value: true
+ }
+ loadVolumeEstimateFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadVolumeEstimateSuccess: (
+ volumeSnapshot: VolumeSnapshot | null,
+ payload?: {
+ value: true
+ }
+ ) => {
+ volumeSnapshot: VolumeSnapshot | null
+ payload?: {
+ value: true
+ }
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface highlightPicksVolumeLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ volumeEstimate: (
+ volumeSnapshot: VolumeSnapshot | null,
+ currentTeamId: number | null
+ ) => EstimateResponseApi | null
+ volumeEstimateLoading: (volumeSnapshotLoading: boolean) => boolean
+ }
+}
+
+export type highlightPicksVolumeLogicType = MakeLogicType<
+ highlightPicksVolumeLogicValues,
+ highlightPicksVolumeLogicActions,
+ Record<string, any>,
+ highlightPicksVolumeLogicMeta
+>
+
+const ESTIMATE_TTL_MS = 6 * 60 * 60 * 1000
+
+export interface VolumeSnapshot {
+ teamId: number
+ estimate: EstimateResponseApi
+ fetchedAt: number
+}
+
+function freshSnapshot(snapshot: VolumeSnapshot | null, teamId: number | null): VolumeSnapshot | null {
+ if (!snapshot || snapshot.teamId !== teamId) {
+ return null
+ }
+ return Date.now() - snapshot.fetchedAt < ESTIMATE_TTL_MS ? snapshot : null
+}
+
+export const highlightPicksVolumeLogic: LogicWrapper<highlightPicksVolumeLogicType> =
+ kea<highlightPicksVolumeLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'highlightPicksVolumeLogic']),
+
+ connect(() => ({
+ values: [teamLogic, ['currentTeamId']],
+ })),
+
+ actions({
+ loadVolumeEstimate: true,
+ }),
+
+ loaders(({ values }) => ({
+ volumeSnapshot: [
+ null as VolumeSnapshot | null,
+ {
+ loadVolumeEstimate: async (_, breakpoint) => {
+ const teamId = values.currentTeamId
+ if (!teamId) {
+ return null
+ }
+ const cached = freshSnapshot(values.cachedSnapshot, teamId)
+ if (cached) {
+ return cached
+ }
+ let estimate: EstimateResponseApi | null = null
+ try {
+ estimate = await visionScannersEstimateCreate(String(teamId), {
+ query: { kind: NodeKind.RecordingsQuery },
+ sampling_rate: 1,
+ model: DEFAULT_MODEL,
+ })
+ } catch {
+ estimate = null
+ }
+ breakpoint()
+ if (!estimate) {
+ return values.cachedSnapshot?.teamId === teamId ? values.cachedSnapshot : null
+ }
+ return { teamId, estimate, fetchedAt: Date.now() }
+ },
+ },
+ ],
+ })),
+
+ reducers({
+ cachedSnapshot: [
+ null as VolumeSnapshot | null,
+ { persist: true, storageKey: 'replay-vision.highlight-picks-volume.snapshot' },
+ {
+ loadVolumeEstimateSuccess: (state, { volumeSnapshot }) => volumeSnapshot ?? state,
+ },
+ ],
+ }),
+
+ selectors({
+ volumeEstimate: [
+ (s) => [s.volumeSnapshot, s.currentTeamId],
+ (snapshot: VolumeSnapshot | null, teamId: number | null): EstimateResponseApi | null =>
+ snapshot && snapshot.teamId === teamId ? snapshot.estimate : null,
+ ],
+ volumeEstimateLoading: [(s) => [s.volumeSnapshotLoading], (loading: boolean): boolean => loading],
+ }),
+
+ subscriptions(({ actions }) => ({
+ currentTeamId: () => actions.loadVolumeEstimate(),
+ })),
+ ])