:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): let users set a scanner limit as an observation count (#115742)
Tue Haulund433362002896
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsxindex 323dac198ef7..4795991fa76f 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx@@ -1,12 +1,17 @@import { useActions, useValues } from 'kea'-import { LemonCard, LemonInput, LemonSwitch } from '@posthog/lemon-ui'+import { LemonCard, LemonInput, LemonSegmentedButton, LemonSwitch } from '@posthog/lemon-ui'import { LemonField } from 'lib/lemon-ui/LemonField'import { LemonLabel } from 'lib/lemon-ui/LemonLabel'-import { creditsToUsd } from '../../utils/credits'-import { replayScannerLogic } from '../replayScannerLogic'+import { creditsToUsd, formatCredits } from '../../utils/credits'+import {+ CreditLimitUnit,+ creditsToObservations,+ observationsToCredits,+ replayScannerLogic,+} from '../replayScannerLogic'import { MAX_CREDIT_LIMIT } from '../types'interface ScannerCreditLimitProps {@@ -15,9 +20,36 @@ interface ScannerCreditLimitProps {export function ScannerCreditLimit({ scannerId }: ScannerCreditLimitProps): JSX.Element {const { creditLimitState } = useValues(replayScannerLogic({ id: scannerId }))- const { setScannerValues } = useActions(replayScannerLogic({ id: scannerId }))- const { limit, isOn, estimatedMonthly, creditsPerObservation, isBelowEstimate, cannotAffordOneScan, seedValue } =- creditLimitState+ const { setScannerValues, setCreditLimitUnit } = useActions(replayScannerLogic({ id: scannerId }))+ const {+ limit,+ unit,+ observationLimit,+ isOn,+ estimatedMonthly,+ estimatedMonthlyObservations,+ creditsPerObservation,+ isBelowEstimate,+ cannotAffordOneScan,+ seedValue,+ } = creditLimitState+ const observationPrice = unit === 'observations' ? creditsPerObservation : null+ const input =+ observationPrice != null+ ? {+ value: observationLimit,+ max: creditsToObservations(MAX_CREDIT_LIMIT, observationPrice),+ suffix: 'observations',+ toCredits: (amount: number) => observationsToCredits(amount, observationPrice),+ summary: limit != null ? `${formatCredits(limit)} per period` : null,+ }+ : {+ value: limit,+ max: MAX_CREDIT_LIMIT,+ suffix: 'credits',+ toCredits: (amount: number) => amount,+ summary: limit != null ? `≈ ${creditsToUsd(limit)} per period` : null,+ }return (<LemonField name="credit_limit">@@ -25,7 +57,7 @@ export function ScannerCreditLimit({ scannerId }: ScannerCreditLimitProps): JSX.<LemonCard hoverEffect={false} className="p-3 space-y-3"><div className="flex items-start justify-between gap-2"><div className="space-y-1">- <LemonLabel>Credit limit</LemonLabel>+ <LemonLabel>Scanner limit</LemonLabel><div className="text-xs text-muted">Cap what this scanner spends in a billing period, on top of your organization's limit.</div>@@ -43,11 +75,32 @@ export function ScannerCreditLimit({ scannerId }: ScannerCreditLimitProps): JSX.</div>{isOn && (<>- <div className="flex items-center gap-4">- <div className="w-40">+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">+ <LemonSegmentedButton<CreditLimitUnit>+ size="small"+ value={unit}+ onChange={setCreditLimitUnit}+ options={[+ {+ value: 'credits',+ label: 'Credits',+ 'data-attr': 'vision-scanner-credit-limit-unit-credits',+ },+ {+ value: 'observations',+ label: 'Observations',+ 'data-attr': 'vision-scanner-credit-limit-unit-observations',+ disabledReason:+ creditsPerObservation == null+ ? 'The price of one observation for this model is not known yet'+ : undefined,+ },+ ]}+ />+ <div className="w-48"><LemonInputtype="number"- value={limit ?? undefined}+ value={input.value ?? undefined}onChange={(v) =>// The toggle is materialized on edit too, so clearing a loaded limit blocks the save.setScannerValues({@@ -55,32 +108,36 @@ export function ScannerCreditLimit({ scannerId }: ScannerCreditLimitProps): JSX.credit_limit:v == null || !Number.isFinite(v)? null- : Math.max(1, Math.round(v)),+ : input.toCredits(Math.max(1, Math.round(v))),})}min={1}- max={MAX_CREDIT_LIMIT}+ max={input.max}step={1}- suffix={<span>credits</span>}+ suffix={<span>{input.suffix}</span>}/></div><span className="text-sm text-muted">- {limit != null && `≈ ${creditsToUsd(limit)} per period`}- {limit != null && estimatedMonthly != null && ' · '}+ {input.summary}+ {input.summary != null && estimatedMonthly != null && ' · '}{estimatedMonthly != null &&`Estimated usage: ${creditsToUsd(estimatedMonthly)} a month`}</span></div>{cannotAffordOneScan ? (<div className="text-xs text-warning">- One scan by this scanner costs {creditsPerObservation} credits, so this limit stops- it before it scans anything. Raise it to at least {creditsPerObservation} credits.+ {observationPrice != null+ ? 'This limit allows 0 observations, so the scanner stops before it scans anything. Raise it to at least 1 observation.'+ : `One scan by this scanner costs ${creditsPerObservation} credits, so this limit stops it before it scans anything. Raise it to at least ${creditsPerObservation} credits.`}</div>) : (isBelowEstimate && (<div className="text-xs text-warning">- This is below the estimated {creditsToUsd(estimatedMonthly ?? 0)} a month, so- the scanner is likely to stop before the period resets.+ This is below the estimated{' '}+ {observationPrice != null && estimatedMonthlyObservations != null+ ? `${estimatedMonthlyObservations.toLocaleString('en-US')} observations`+ : creditsToUsd(estimatedMonthly ?? 0)}{' '}+ a month, so the scanner is likely to stop before the period resets.</div>))}diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 6777629e6f3a..9bf17faa1e76 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -15,6 +15,7 @@ import { useMocks } from '~/mocks/jest'import { NodeKind } from '~/queries/schema/schema-general'import { initKeaTests } from '~/test/init'+import { ScannerModelEnumApi } from '../generated/api.schemas'import { parseCsvParam, parseNumericParam, parseSortParam } from '../utils/urlParams'import {buildObservationListParams,@@ -725,7 +726,7 @@ describe('replayScannerLogic', () => {await expectLogic(logic).toFinishAllListeners()expect(logic.values.creditLimitState).toMatchObject({ limit: null, isOn: true })expect(logic.values.scannerValidationErrors).toMatchObject({- credit_limit: 'Enter a credit limit, or turn the limit off',+ credit_limit: 'Enter a limit, or turn the limit off',})})@@ -1057,10 +1058,10 @@ describe('replayScannerLogic', () => {})})- it('seeds at least one credit for a tiny but non-zero forecast', async () => {+ it('seeds at least one scan for a tiny but non-zero forecast', async () => {estimate(0.3)await expectLogic(logic).toMatchValues({- creditLimitState: expect.objectContaining({ seedValue: 1 }),+ creditLimitState: expect.objectContaining({ seedValue: 15 }),})})@@ -1076,7 +1077,11 @@ describe('replayScannerLogic', () => {it('flags a limit below the forecast and one below a single scan', async () => {estimate(100, 15)- logic.actions.setScannerValues({ credit_limit_enabled: true, credit_limit: 10 })+ logic.actions.setScannerValues({+ model: ScannerModelEnumApi.Gemini38Flash,+ credit_limit_enabled: true,+ credit_limit: 10,+ })await expectLogic(logic).toMatchValues({creditLimitState: expect.objectContaining({limit: 10,@@ -1086,6 +1091,33 @@ describe('replayScannerLogic', () => {}),})})++ it.each([+ ['the loaded estimate, which is authoritative', false, 7],+ ['the model table while the estimate reloads for a new model', true, 5],+ ])('prices an observation from %s', async (_name, reloading, expectedPrice) => {+ logic.actions.setScannerValues({ model: ScannerModelEnumApi.Gemini3FlashPreview })+ estimate(100, 7)+ if (reloading) {+ logic.actions.requestScannerEstimate()+ }+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({ creditsPerObservation: expectedPrice }),+ })+ })++ it('keeps the credits and recounts the observations when the model changes', async () => {+ logic.actions.setScannerValues({+ model: ScannerModelEnumApi.Gemini3FlashPreview,+ credit_limit_enabled: true,+ credit_limit: 40,+ })+ logic.actions.setCreditLimitUnit('observations')+ logic.actions.setScannerValue('model', ScannerModelEnumApi.Gemini38Flash)+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({ limit: 40, observationLimit: 2 }),+ })+ })})describe('credit limit on a loaded scanner', () => {@@ -1121,7 +1153,7 @@ describe('replayScannerLogic', () => {await expectLogic(editLogic).toMatchValues({creditLimitState: expect.objectContaining({ limit: null, isOn: true }),scannerValidationErrors: expect.objectContaining({- credit_limit: 'Enter a credit limit, or turn the limit off',+ credit_limit: 'Enter a limit, or turn the limit off',}),})})diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex 520d44c64e5a..31a6cd148cb0 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -100,6 +100,7 @@ import { findScannerTemplate, newScanner } from './scannerTemplates'import {ExperimentScannerConfig,MAX_CREDIT_LIMIT,+ OBSERVATION_CREDITS_BY_MODEL,OBSERVATION_LIST_URL_PARAM_KEYS,SamplingMode,ScannerConfig,@@ -412,11 +413,25 @@ export function buildObservationListParams(// doesn't bind on ordinary month-to-month variance.const CREDIT_LIMIT_SEED_HEADROOM = 2+export type CreditLimitUnit = 'credits' | 'observations'++// Admission needs the full price of a scan, so a remainder under one price admits nothing.+export function creditsToObservations(credits: number, creditsPerObservation: number): number {+ return Math.floor(credits / creditsPerObservation)+}++export function observationsToCredits(observations: number, creditsPerObservation: number): number {+ return Math.min(observations * creditsPerObservation, MAX_CREDIT_LIMIT)+}+export interface CreditLimitState {/** The limit in credits, or null when the field is empty or the limit is off. */limit: number | null+ unit: CreditLimitUnit+ observationLimit: number | nullisOn: booleanestimatedMonthly: number | null+ estimatedMonthlyObservations: number | nullcreditsPerObservation: number | nullisBelowEstimate: booleancannotAffordOneScan: boolean@@ -436,6 +451,7 @@ export interface replayScannerLogicValues {copyingAllObservations: booleancreationMethod: ScannerCreationMethodEnumApicreditLimitState: CreditLimitState+ creditLimitUnit: CreditLimitUnitdurationValidationError: string | nullestimateRequestVersion: numberexperimentContext: ExperimentScannerContext | null@@ -714,6 +730,9 @@ export interface replayScannerLogicActions {dateFrom: string | nulldateTo: string | null}+ setCreditLimitUnit: (unit: CreditLimitUnit) => {+ unit: CreditLimitUnit+ }setExperimentContext: (context: ExperimentScannerContext | null) => {context: ExperimentScannerContext | null}@@ -896,7 +915,12 @@ export interface replayScannerLogicMeta {availableTags: (observationStatsApi: ObservationStatsApi | null) => string[]observationStats: (observationStatsApi: ObservationStatsApi | null) => ObservationStatusStatssidePanelContext: (scanner: ScannerFormValues, isNew: boolean) => SidePanelSceneContext | null- creditLimitState: (scanner: ScannerFormValues, scannerEstimate: EstimateResponseApi | null) => CreditLimitState+ creditLimitState: (+ scanner: ScannerFormValues,+ scannerEstimate: EstimateResponseApi | null,+ scannerEstimateLoading: boolean,+ creditLimitUnit: CreditLimitUnit+ ) => CreditLimitState}}@@ -914,6 +938,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([actions({setObservationsActive: (active: boolean) => ({ active }),+ setCreditLimitUnit: (unit: CreditLimitUnit) => ({ unit }),loadScanner: true,loadScannerSuccess: (scanner: ScannerFormValues) => ({ scanner }),loadScannerFailure: true,@@ -1051,13 +1076,13 @@ export const replayScannerLogic = kea<replayScannerLogicType>([credit_limit:creditLimitEnabled && scanner.credit_limit == null? // The toggle is on with an empty field. Block the save rather than silently saving as unlimited.- 'Enter a credit limit, or turn the limit off'+ 'Enter a limit, or turn the limit off': scanner.credit_limit == null ||(Number.isInteger(scanner.credit_limit) &&scanner.credit_limit >= 1 &&scanner.credit_limit <= MAX_CREDIT_LIMIT)? undefined- : `Credit limit must be a whole number between 1 and ${MAX_CREDIT_LIMIT.toLocaleString()}`,+ : `The limit must be a whole number of credits between 1 and ${MAX_CREDIT_LIMIT.toLocaleString()}`,scanner_config: Object.keys(configErrors).length > 0 ? configErrors : undefined,}},@@ -1217,6 +1242,15 @@ export const replayScannerLogic = kea<replayScannerLogicType>([reducers({observationsActive: [false, { setObservationsActive: (_, { active }) => active }],+ // UI-only: the API stores every limit in credits, so a reopened scanner shows credits again.+ creditLimitUnit: [+ 'credits' as CreditLimitUnit,+ {+ setCreditLimitUnit: (_, { unit }) => unit,+ startFromTemplate: () => 'credits',+ discardScannerDraft: () => 'credits',+ },+ ],scannerDraftSavedAt: [null as number | null,{@@ -1727,15 +1761,30 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// derive it from having a limit set. Decoding it here keeps the form validator and the editor// card from drifting apart on what "on but empty" means.creditLimitState: [- (s) => [s.scanner, s.scannerEstimate],- (scanner: ScannerFormValues | null, estimate: EstimateResponseApi | null): CreditLimitState => {+ (s) => [s.scanner, s.scannerEstimate, s.scannerEstimateLoading, s.creditLimitUnit],+ (+ scanner: ScannerFormValues | null,+ estimate: EstimateResponseApi | null,+ estimateLoading: boolean,+ unit: CreditLimitUnit+ ): CreditLimitState => {const limit = typeof scanner?.credit_limit === 'number' ? scanner.credit_limit : nullconst estimatedMonthly = estimate?.estimated_credits_per_month ?? null- const creditsPerObservation = estimate?.credits_per_observation ?? null+ // A reloading estimate still prices the previous model, so the model table stands in until it lands.+ const creditsPerObservation =+ (estimateLoading ? undefined : estimate?.credits_per_observation) ??+ (scanner ? OBSERVATION_CREDITS_BY_MODEL[scanner.model] : undefined) ??+ nullreturn {limit,+ unit: creditsPerObservation ? unit : 'credits',+ observationLimit:+ limit !== null && creditsPerObservation+ ? creditsToObservations(limit, creditsPerObservation)+ : null,isOn: scanner?.credit_limit_enabled ?? limit !== null,estimatedMonthly,+ estimatedMonthlyObservations: estimate?.estimated_observations_per_month ?? null,creditsPerObservation,isBelowEstimate: limit !== null && estimatedMonthly !== null && limit < estimatedMonthly,// A cap under one scan's cost never admits a single scan, so the scanner is stopped from@@ -1745,7 +1794,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// No estimate yet, or a zero one: null leaves the field empty rather than inventing a number.seedValue:estimatedMonthly !== null && estimatedMonthly > 0- ? Math.max(1, Math.round(estimatedMonthly * CREDIT_LIMIT_SEED_HEADROOM))+ ? // A seed under one scan's price would stop the scanner before its first scan.+ Math.max(+ creditsPerObservation ?? 1,+ Math.round(estimatedMonthly * CREDIT_LIMIT_SEED_HEADROOM)+ ): null,}},