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): offer free scanners in the goal flow and scanner settings (#116154)

Tue Haulund6be18b89e8a3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 0b110b1bb94f..d631c7519755 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -13671,9 +13671,17 @@ snapshots:
scenes-app-replay-vision--scanner-alerts-empty--light:
hash: v1.k794b7964.d9ace49fb0b86c802c61268205a8d0a4fec36ee11893addb69f3f382d6413c23.lQIQpu4oUttcUZcu6v656AAUXPTC4X6hzOW1-lLWbdU
scenes-app-replay-vision--scanner-editor-budget--dark:
- hash: v1.k794b7964.fc115f9b472561e1a7464b75405a09aea3cad690d4489bb5571466730cdafed8.H8IE0r67APlDwXvHJYTonS5KAn1KWZNw1YglrdU5E8w
+ hash: v1.k794b7964.c6df6165d933a8096361cc85ee353beaebeadbb9473fa917982d48cfa6777e97.2j7oCxgpfbLkjwzXosZfRgODU_ZorTCziDrhPWe6im8
scenes-app-replay-vision--scanner-editor-budget--light:
- hash: v1.k794b7964.c0b580ca3bba7d80b1dd4811f52cc6f46544d03a3b727fcceb572b2b2e3fd3b6.EwqoyogmEud1JvYjU8Uo7cDpqzTFJ0macesvvd4VByQ
+ hash: v1.k794b7964.de36908c3a345ca095a7ead89e22302ebc3452340061838aa28e3fb51f5480cc.HVwxJ47qOlRG61qSi2XWC0E9br8CufAWBEfavVFulF0
+ scenes-app-replay-vision--scanner-editor-budget-free-only--dark:
+ hash: v1.k794b7964.203a184757f487d04964a9fcc54e0084966cba1e2bdcae1dc76538b72e24c165.p4Rm-emww6MXQFt5h6vgQrglyELym6vrD96_h98uBaw
+ scenes-app-replay-vision--scanner-editor-budget-free-only--light:
+ hash: v1.k794b7964.4d48516b1d74e05dd68c2a2f17009307a4747d73413ea55c4d1293aa74f260f3.cRBJna7DEc4oWY8p27bUQw_ufqDnjuAmMhw1JhkXFEs
+ scenes-app-replay-vision--scanner-editor-budget-free-only-nearly-used--dark:
+ hash: v1.k794b7964.5c83e3bace9f8046ed5a67f38504ea70b032b323b8e0baef469a971b6c7d93dc.Dl3I3V7XIi2oaFu0ggwgEsEvaAruvVceEc3J5yJlJH0
+ scenes-app-replay-vision--scanner-editor-budget-free-only-nearly-used--light:
+ hash: v1.k794b7964.421b9aeab0f131863e1544212b4dda065807a298d7250d30831e539e229a8e9f.1Y87Xtwt38CC7aZR3FNNC4HhmAqDZj4LBaQLfhz_hxQ
scenes-app-replay-vision--scanner-editor-configure--dark:
hash: v1.k794b7964.07148958cd17ddb6f5e92153e6020b88a5c0faadd1d30453af7dcd3842efe1be.mbfalsNTUY56lRXxDljiT-ZQ19WP2LSF7Ngnn21lRsw
scenes-app-replay-vision--scanner-editor-configure--light:
@@ -13683,9 +13691,17 @@ snapshots:
scenes-app-replay-vision--scanner-editor-details--light:
hash: v1.k794b7964.6a0bec1cca5a2d30c5ae7ad47d071406b55c337c4b6574d0c601d97ef5f56749.ebPyjAyNgVrgCHUvj3sL2nLQm23sw5Pe28YYdK94Gtw
scenes-app-replay-vision--scanner-editor-goal-flow--dark:
- hash: v1.k794b7964.2ca6853b04f3ffeeb15ea3deacf14cc5e25f60359d0317e6fa73c262ab77b680.AMC5UPwrP-Wm9gb1fc-OBY0kQdt8g-tp04OF5WkMwmY
+ hash: v1.k794b7964.4e4f1adef25e8ecdab67f67e509caebdfbb8098500f3a070d89a695ac8f91852.mkbyvXbnVWikExo74IoI1pwSOKN6uuAYkQ9Gu9TJ0pk
scenes-app-replay-vision--scanner-editor-goal-flow--light:
- hash: v1.k794b7964.e47a57726a0631ab9c557b543ae744a7c54f542861d1163be8a893ab45cf8415.X-yyqBDmpTMOKm4dpRqyBdwU02uLLpDbphgFmBqVa5U
+ hash: v1.k794b7964.29d093aecbf976edb75dc11d72308bd72779a2c87bc669f3d98596748d72bb77.d4netmI6e388wifkra4IA4HOOuF8Et-oNrIYegrxM5Q
+ scenes-app-replay-vision--scanner-editor-goal-flow-budget--dark:
+ hash: v1.k794b7964.7057b5e8825ff9fb5bf4397dd4b40f423038367cb81aebc519ef62c68bd78fd6.lDf8ThWKFgRsClSogBWyLfDEtkB3tRA1diKxBHqAfTo
+ scenes-app-replay-vision--scanner-editor-goal-flow-budget--light:
+ hash: v1.k794b7964.644e1350b0953c9df13cf881fde9f63e6b6c7831241f0792e0a17c75be410221.VD8tZXOJbq8zsFeLTpTHDVCeTGIKSlgmUoVh71RDwZc
+ scenes-app-replay-vision--scanner-editor-goal-flow-free-credits-used--dark:
+ hash: v1.k794b7964.4e020db337e427c01e8d7870cd07c7c12b27ea8715b0b2e945d45b7444f05852.nHfzx6tV51Cj5FLdfFWGGO_UVt2-5CHAFKh5Tzsq7x8
+ scenes-app-replay-vision--scanner-editor-goal-flow-free-credits-used--light:
+ hash: v1.k794b7964.ecb94f70f6b13b80d47a3a7f59b45c1f9a9012ecef1ff0a56fbd8eba088cad39.pnydN1giJjbyCc7o0n98joUjg46NcA7L4NKWGkqbvuA
scenes-app-replay-vision--scanner-editor-goal-overview--dark:
hash: v1.k794b7964.f01ae73fc01d6f402ea1587d8fa62cd0195288283e5f02640a7d533b4ad09bfd.udZKrn75onISEkfnNqDPgFTA1zHMAm5n383-eNRdoPw
scenes-app-replay-vision--scanner-editor-goal-overview--light:
@@ -13694,6 +13710,10 @@ snapshots:
hash: v1.k794b7964.eb9e640621c319777e9d0f35160e175e5740430705ed29e2b00190a416916561.LnXPwb9D0h9JoDXETFIZmQ9mX_kexX838Nm7XfM33TA
scenes-app-replay-vision--scanner-editor-goal-overview-experiment--light:
hash: v1.k794b7964.d2d2658ddbf2aace36438d92fa5aa1689badeb9445c1c55322234d0e3a0d66ce.AMSsv3Q7mbqIiVnfFXikAe3a0i4NMkDGtc9JJc-ZE_U
+ scenes-app-replay-vision--scanner-editor-goal-overview-free-only--dark:
+ hash: v1.k794b7964.c3c29df373cd8e663770b097f02a4772ffc2ba0c51e10a245fb5cf8ef7bdff68.rPAbWs7-3bfCc9X1HQcY30nfQscWET-stKmszLHV-fo
+ scenes-app-replay-vision--scanner-editor-goal-overview-free-only--light:
+ hash: v1.k794b7964.2abc94dc57d65cb6ecea210e7bdb23750f93dd5acdf32f1b0410b041bc0f3ed7.BSXIKK9m6yVzc_yZ5pmgl39D3y6ZaYmJpnULVOEULsM
scenes-app-replay-vision--scanner-editor-goal-overview-loading--dark:
hash: v1.k794b7964.bfb3f7c4a3b32b7aa090636568df7f158f48f08c78de444d35a5cc6bec4e94b6.56aJziWdamTTKgo5cUbmTCjJKmsI46FfoaDAJn3IDRM
scenes-app-replay-vision--scanner-editor-goal-overview-loading--light:
@@ -13714,6 +13734,10 @@ snapshots:
hash: v1.k794b7964.a060cb9d164a15686ce334352ae24b5ee6f8c561e35edaf8b3889df2d8dcc21c.w8siIriw-LxD3au0e9X5v4kxkDJhrytYHlRU46bGPmc
scenes-app-replay-vision--scanner-on-demand--light:
hash: v1.k794b7964.4f80fe334520d4ac3d53d57efd5b38f8fb3780a21bb14d1cf49e5c64c6fc9774.zDHnsM7FpSJ2Vr92ByUKjtSZHmttioSDdkJQOXzZjgo
+ scenes-app-replay-vision--scanner-overview-free-credits-used--dark:
+ hash: v1.k794b7964.7311c7f7325d8c64a1c0d0841194fd356086abe58801fde1f8586e7641faf10d.pUUvS0GXMC0QwBrdZCp9fAw1xhA_dVMX9ODs_EJ_6S4
+ scenes-app-replay-vision--scanner-overview-free-credits-used--light:
+ hash: v1.k794b7964.c49f1ea3d9cf609856d2651e90d1ebf5361ebd0e4e889aef1f6ee9f1e682e19a.Xd7sTZMtkxfSqTWPNgbhozMq3p0NUg34HSMu134B_94
scenes-app-replay-vision--scanner-scan-drought--dark:
hash: v1.k794b7964.5c09744ba06f15580bfd640c2a809591bb56086af17814fe74274f0acaf11d33.OZTilyTCRycOtXM67McARvKkGn8D3KKAdw5-XaD1zO4
scenes-app-replay-vision--scanner-scan-drought--light:
@@ -13735,13 +13759,17 @@ snapshots:
scenes-app-replay-vision--scanner-templates--light:
hash: v1.k794b7964.1f88a5eb5ce04ca6bea3009c62f23eb09af6e2540f21ef1e1e20fb53c3b38777.XnkQTLfdifTRzsriW4EbOkCXkWBJ1WLlBhE8dPsjcEc
scenes-app-replay-vision--scanners-list--dark:
- hash: v1.k794b7964.c3a212d13b5d70d398df7db8b425613e1b91007267adf6a77da252af0b89de24.iovwm_CkajG06SHN_jrb0wt8TDX8ho8o6oLsjf_bYLI
+ hash: v1.k794b7964.2758cee6b30dcaf69088df587d8268274df7f5ad3231f648a9a6272e9b3a2b28.zsk643UdOn5LqvKjlHe3a_GOfg7KK7Gba-Jxchq0ifQ
scenes-app-replay-vision--scanners-list--light:
- hash: v1.k794b7964.91fde78bdd55bab3532beef9c28633c8a21a1aeaed55542aa832cb308af2b6bb.KLVMXXmplwrhcJfDtO3gSpGbzkfcJGeIOxiJlmqMdKo
+ hash: v1.k794b7964.f9f71d5e06a2d353b57589e7d720fd9e6b8313e2366878ab089bc92a9c20a14d.0JxZecxgUUTqEWwZm2v2qDMeDb4xC0BjO6dv_oNHTUg
scenes-app-replay-vision--scanners-list-empty--dark:
hash: v1.k794b7964.a521fd50b667cfab5ae7ed053b6da09a9968209dc20bac555dac760812c4a00d.G7vZH_-WgliA6P3jBIZuxtJgqs9W34BsyUFFpcTYafQ
scenes-app-replay-vision--scanners-list-empty--light:
hash: v1.k794b7964.533b2eaad9875974cc55fa28ebaf6b24b8809536d845a614cd395300d1d108e5.BKc-ktztjTfLqTBgG-fnUpDTEFqICcHZ_xkPhKCwZ8k
+ scenes-app-replay-vision--scanners-list-free-credits-used--dark:
+ hash: v1.k794b7964.c6d5609a9cdaadffafc763163d15fae0b918db6066d42cf3df59088eb995fd0c.mJGyvipWzwmtym1W9BMzOxJlGghI0ceFjsm884WUl1U
+ scenes-app-replay-vision--scanners-list-free-credits-used--light:
+ hash: v1.k794b7964.578a22f03d65a653f71dfa0b7185cd7ed2cd6144e11384c247ebc0faa46a52b0.mtKmXf5BW_epTvLupJTCmBeVaFw3oIgR5sjmiIZECNM
scenes-app-replay-vision--scorer-observations--dark:
hash: v1.k794b7964.2d5145a8fcaad02ebc6d16a530bf2d97ff34eed6cfc18f1a1fe8c348760b5990.p9kMGT3wLWAKTEHGTGakFkOC7pWiACFi_gbPg9tI4Vo
scenes-app-replay-vision--scorer-observations--light:
@@ -13751,9 +13779,9 @@ snapshots:
scenes-app-replay-vision--scorer-overview--light:
hash: v1.k794b7964.67d50146c3f5fcd743a33d5f4c95bfd4aca12a97b4976f9bdc89776291ce1317.11oEZq8rNQ0VM5_BOYbMHyuOVL34UXyYC_xuX8bF7IE
scenes-app-replay-vision--startup-program-cap--dark:
- hash: v1.k794b7964.0da88e35099b508b507df343cb958c1d4a6b2d623076feff2b585d1585990907.LIJaA6mA9kt7JnMdPHYObeFSrRcJvzZaOakPh6R8Ueg
+ hash: v1.k794b7964.e020e2ebfef49b75a87a64ac5c9f4b134bcfb1769a3f1f9aad575fca1f897801.znS5HWNDLZXt1DlQg2jWteB4bd6YpQkVzmEXbxmyahM
scenes-app-replay-vision--startup-program-cap--light:
- hash: v1.k794b7964.39eabf9f358e4da21a214c506b23a3c70a70f19ea59970e28fb0236fb6530045.lR5IrOPs59svhDKBh4F5re0XZLWc8K-MSCcum8hYvqA
+ hash: v1.k794b7964.0fa283cf1aed809f0f720c69ffc62140f19cbe3b2896a1a5c4ea62b9e092e62c.SgwJvYDCKviGkVIDszU7JZlgLiGLgDrVho2W3gPEdeg
scenes-app-replay-vision--summarizer-overview--dark:
hash: v1.k794b7964.31974c29767b97bd6d2af3eca6b30078665246f6ec4c9cfd5019d6cbf9bcbb99.ROiKfq5AAOCnx_vqHYoiuJoOy1gHtQQKiP52EbOxjTM
scenes-app-replay-vision--summarizer-overview--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 4a1fbe3b4303..b1983f2d35cd 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -598,7 +598,7 @@ export const FEATURE_FLAGS = {
UX_REMOVE_SIDEPANEL: 'ux-remove-sidepanel', // owner: #team-surveys
VISION_ENTRYPOINT_REPLAY_FILTERS: 'vision-entrypoint-replay-filters', // owner: #team-replay, cross-sell entry point from the replay filters panel
VISION_EXPERIMENT_SCANNER: 'experiment-scanner', // owner: #team-replay, experiment scanners overall: the type in the scanner editor, creating one from experiments, and the variants tab
- VISION_GOAL_FLOW_V2: 'vision-goal-flow-v2', // owner: #team-replay multivariate=control,test — gate on === 'test'; a truthy check turns on for control too
+ VISION_GOAL_FLOW_V3: 'vision-goal-flow-v3', // owner: #team-replay multivariate=control,test — gate on === 'test'; a truthy check turns on for control too
VISUAL_REVIEW: 'visual-review', // owner: #team-devex
WAREHOUSE_MULTI_DESTINATION: 'warehouse-multi-destination', // owner: #team-warehouse-sources
WAREHOUSE_PERSON_PROPERTIES: 'warehouse-person-properties', // owner: @tomowers #team-warehouse-sources, gates warehouse -> person properties (person-target custom property sources)
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 0f5a37d28d84..83b01bac14b2 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -190,7 +190,7 @@ _QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")
# The goal-based creation flow's flag. Multivariate so it can graduate to an experiment without a
# rename; server-side so a client/rollout skew cannot half-apply the new flow.
-GOAL_FLOW_FLAG = "vision-goal-flow-v2"
+GOAL_FLOW_FLAG = "vision-goal-flow-v3"
class ScannerCreationMethod(models.TextChoices):
diff --git a/products/replay_vision/frontend/components/SummarizeRecordingBar.tsx b/products/replay_vision/frontend/components/SummarizeRecordingBar.tsx
index 291dfc343c35..1183f8d9acac 100644
--- a/products/replay_vision/frontend/components/SummarizeRecordingBar.tsx
+++ b/products/replay_vision/frontend/components/SummarizeRecordingBar.tsx
@@ -16,7 +16,7 @@ import { AccessControlLevel } from '~/types'
import type { ReplayScannerApi } from '../generated/api.schemas'
import { observationsDockLogic } from '../logics/observationsDockLogic'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
-import { LIMIT_REACHED_TOOLTIP } from '../replay_scanners/scannerCopy'
+import { limitReachedTooltip } from '../replay_scanners/scannerCopy'
import { getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { BUILT_IN_SUMMARY_LABEL, isSummaryObservation } from '../utils/observation'
import { quotaUx } from '../utils/quotaProjection'
@@ -59,7 +59,7 @@ function useSummarizeBlockedReason(
getReplayVisionEditDisabledReason((scanner?.user_access_level as AccessControlLevel | null) ?? undefined) ??
// `observe` answers 402 for a scanner that has spent its own credit limit, so a capped one is
// refused here rather than by a failed request. The built-in prompt has no per-scanner limit.
- (scanner?.limit_reached ? LIMIT_REACHED_TOOLTIP : null) ??
+ (scanner?.limit_reached ? limitReachedTooltip(scanner) : null) ??
scanBlock?.reason ??
quotaDisabledReason
}
diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
index 4ea1760b7dad..58b88b30f100 100644
--- a/products/replay_vision/frontend/logics/visionQuotaLogic.ts
+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
@@ -9,7 +9,7 @@ import type { BillingType } from '~/types'
import { environmentVisionQuotaRetrieve } from '../generated/api'
import type { VisionQuotaApi } from '../generated/api.schemas'
import { billableCredits } from '../utils/credits'
-import { hasBillableSpend, isFreeAllocationOnly } from '../utils/quotaProjection'
+import { freeCreditsLeft, hasBillableSpend, isFreeAllocationOnly } from '../utils/quotaProjection'
import { applyStartupCap, startupCapCredits } from '../utils/startupCap'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -18,6 +18,7 @@ export interface visionQuotaLogicValues {
billedCredits: number
billedLimitCredits: number
displayQuota: VisionQuotaApi | null
+ freeCreditsLeft: number | null
onFreePlan: boolean
quota: VisionQuotaApi | null
quotaLoading: boolean
@@ -64,6 +65,7 @@ export interface visionQuotaLogicMeta {
showStartupCap: (startupCapCredits: number | null) => boolean
showStartupCapLine: (startupCapCredits: number | null, displayQuota: VisionQuotaApi | null) => boolean
showUsd: (quota: VisionQuotaApi | null) => boolean
+ freeCreditsLeft: (quota: VisionQuotaApi | null) => number | null
onFreePlan: (quota: VisionQuotaApi | null) => boolean
billedCredits: (displayQuota: VisionQuotaApi | null) => number
billedLimitCredits: (displayQuota: VisionQuotaApi | null) => number
@@ -145,6 +147,7 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([
],
/** Whether spend converts to a bill, so the `≈ $` anchors are worth showing. */
showUsd: [(s) => [s.quota], (quota: VisionQuotaApi | null) => hasBillableSpend(quota)],
+ freeCreditsLeft: [(s) => [s.quota], (quota: VisionQuotaApi | null): number | null => freeCreditsLeft(quota)],
/** On the free plan: shapes copy, since running out of free credits isn't hitting a spend limit. */
onFreePlan: [(s) => [s.quota], (quota: VisionQuotaApi | null) => isFreeAllocationOnly(quota)],
// Billed figures come off `displayQuota` so a startup-capped org's dollars respect the cap.
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index ed6658924764..388c14b1edb2 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -609,6 +609,7 @@ const estimate = {
credits_per_observation: 1,
estimated_credits_per_month: 92,
other_enabled_scanners_monthly_credits: 5108,
+ free_only_monthly_credits_left: 2500,
sampling_rate: 0.05,
}
@@ -1920,7 +1921,7 @@ export const StartupProgramCap: StoryObj = {
export const ScannerEditorGoalFlow: StoryObj = {
parameters: {
pageUrl: urls.replayVisionScannerTemplate('new'),
- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V2]: 'test' },
+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },
},
}
@@ -1958,7 +1959,7 @@ const goalDraft: DraftScannerResponseApi = {
export const ScannerEditorGoalOverview: StoryObj = {
parameters: {
pageUrl: urls.replayVisionScannerOverview('new'),
- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V2]: 'test' },
+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },
},
decorators: [
(StoryFn) => {
@@ -1986,7 +1987,7 @@ export const ScannerEditorGoalOverview: StoryObj = {
export const ScannerEditorGoalOverviewExperiment: StoryObj = {
parameters: {
pageUrl: urls.replayVisionScannerOverview('new'),
- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V2]: 'test' },
+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },
},
decorators: [
mswDecorator({
@@ -2070,7 +2071,7 @@ export const ScannerEditorGoalOverviewExperiment: StoryObj = {
export const ScannerEditorGoalOverviewLoading: StoryObj = {
parameters: {
pageUrl: urls.replayVisionScannerOverview('new'),
- featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V2]: 'test' },
+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },
testOptions: { waitForLoadersToDisappear: false, waitForSelector: '.LemonSkeleton' },
},
decorators: [
@@ -2090,6 +2091,141 @@ export const ScannerEditorGoalOverviewLoading: StoryObj = {
],
}
+// Free-only scanners stop when the org's free credits run out, so these quotas sit on either side of that.
+const freeCreditsLeftQuota: VisionQuotaApi = { ...quota, credits_used: 600, credits_settled: 600, remaining: 9400 }
+const freeCreditsUsedQuota: VisionQuotaApi = { ...quota, credits_used: 2600, credits_settled: 2600, remaining: 7400 }
+
+const freeOnlyScanner: ReplayScannerApi = {
+ ...summarizerScanner,
+ id: '00000000-0000-0000-0000-00000000000e',
+ name: 'Free checkout summaries',
+ free_only: true,
+ credit_limit: null,
+ credits_used_against_limit: 600,
+ limit_reached: false,
+}
+
+const freeOnlyLimitReachedScanner: ReplayScannerApi = {
+ ...freeOnlyScanner,
+ credits_used_against_limit: 2600,
+ limit_reached: true,
+}
+
+// Large enough that the free credits left, not the estimate, bound the forecast.
+const largeEstimate = { ...estimate, estimated_observations_per_month: 3000, estimated_credits_per_month: 3000 }
+
+// The headroom is the free credits left as a monthly rate over the 20 days to June 1.
+const freeOnlyEditorDecorator = (
+ quotaResponse: VisionQuotaApi,
+ freeHeadroom: number
+): ReturnType<typeof mswDecorator> =>
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/vision/scanners/:id/': freeOnlyScanner,
+ '/api/projects/:team_id/vision/quota/': quotaResponse,
+ },
+ post: {
+ '/api/projects/:team_id/vision/scanners/estimate/': {
+ ...largeEstimate,
+ free_only_monthly_credits_left: freeHeadroom,
+ },
+ },
+ })
+
+// The list shows a free-only scanner that ran out as stopped, with the free-credits reason on hover.
+export const ScannersListFreeCreditsUsed: StoryObj = {
+ parameters: { pageUrl: `${urls.replayVision()}?tab=scanners` },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:team_id/vision/scanners/': {
+ ...scanners,
+ results: scanners.results.map((scanner) =>
+ scanner.id === summarizerScanner.id
+ ? { ...freeOnlyLimitReachedScanner, id: scanner.id }
+ : scanner
+ ),
+ },
+ '/api/projects/:team_id/vision/quota/': freeCreditsUsedQuota,
+ },
+ }),
+ ],
+}
+
+// The status strip explains the free-credits stop and how to keep scanning.
+export const ScannerOverviewFreeCreditsUsed: StoryObj = {
+ parameters: { pageUrl: urls.replayVision(summarizerScanner.id) },
+ decorators: [
+ overviewDecorator({ ...freeOnlyLimitReachedScanner, id: summarizerScanner.id }, summarizerStats),
+ mswDecorator({ get: { '/api/projects/:team_id/vision/quota/': freeCreditsUsedQuota } }),
+ ],
+}
+
+// Plenty of free credits left: the forecast still caps this scanner at what they cover.
+export const ScannerEditorBudgetFreeOnly: StoryObj = {
+ parameters: { pageUrl: urls.replayVisionScannerBudget(freeOnlyScanner.id) },
+ decorators: [freeOnlyEditorDecorator(freeCreditsLeftQuota, 2850)],
+}
+
+// 100 free credits left: the forecast shrinks to what they cover instead of warning about the org limit.
+export const ScannerEditorBudgetFreeOnlyNearlyUsed: StoryObj = {
+ parameters: { pageUrl: urls.replayVisionScannerBudget(freeOnlyScanner.id) },
+ decorators: [freeOnlyEditorDecorator(quota, 150)],
+}
+
+// The goal flow with "Set a budget" picked instead of the free default.
+export const ScannerEditorGoalFlowBudget: StoryObj = {
+ parameters: {
+ pageUrl: urls.replayVisionScannerTemplate('new'),
+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },
+ },
+ decorators: [
+ (StoryFn) => {
+ const logic = replayScannerLogic({ id: 'new' })
+ logic.mount()
+ logic.actions.setGoalSpendMode('budget')
+ return <StoryFn />
+ },
+ ],
+}
+
+// No free credits left this period, so "Free" is disabled and the budget input shows.
+export const ScannerEditorGoalFlowFreeCreditsUsed: StoryObj = {
+ parameters: {
+ pageUrl: urls.replayVisionScannerTemplate('new'),
+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },
+ },
+ decorators: [mswDecorator({ get: { '/api/projects/:team_id/vision/quota/': freeCreditsUsedQuota } })],
+}
+
+// A free draft whose estimate is more than the monthly free credits cover.
+export const ScannerEditorGoalOverviewFreeOnly: StoryObj = {
+ parameters: {
+ pageUrl: urls.replayVisionScannerOverview('new'),
+ featureFlags: { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' },
+ },
+ decorators: [
+ mswDecorator({ post: { '/api/projects/:team_id/vision/scanners/estimate/': largeEstimate } }),
+ (StoryFn) => {
+ const logic = replayScannerLogic({ id: 'new' })
+ logic.mount()
+ logic.actions.draftScannerFromGoalSuccess(goalDraft)
+ logic.actions.setScannerValues({
+ name: goalDraft.name,
+ description: goalDraft.description,
+ scanner_type: goalDraft.scanner_type as ScannerType,
+ scanner_config: goalDraft.scanner_config as ScannerConfig,
+ query: goalDraft.query as RecordingsQuery,
+ sampling_mode: goalDraft.sampling_mode as SamplingMode,
+ sampling_rate: 0.0001,
+ free_only: true,
+ credit_limit: null,
+ })
+ return <StoryFn />
+ },
+ ],
+}
+
// A summary that carries chapters, so the result card gains Summary and Timeline tabs.
const timelineObservationDetail = (() => {
const withChapters = timelineSummary({ chapters: LONG, inactive: LONG_INACTIVE })
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
index 29898500dc6a..56ddd0d5cf6b 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
@@ -7,10 +7,8 @@ import {
LemonButton,
LemonDivider,
LemonInput,
- LemonSwitch,
LemonTable,
LemonTabs,
- LemonTag,
Link,
Spinner,
Tooltip,
@@ -40,13 +38,16 @@ import { visionQuotaLogic } from '../logics/visionQuotaLogic'
import { ObservationSearch } from '../search/ObservationSearch'
import { getReplayVisionDeleteDisabledReason, getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { creditsToUsd, formatCreditCount } from '../utils/credits'
+import { quotaBannerState } from '../utils/quotaProjection'
import { CreateScannerButton } from './components/CreateScannerButton'
+import { ScannerStatusLabel } from './components/ScannerStatusLabel'
import { VisionMetrics } from './components/VisionMetrics'
import { VisionUsageTab } from './components/VisionUsageTab'
import { WatchFeedTab } from './components/WatchFeedTab'
import { ReplayScannerTab } from './replayScannerSceneLogic'
import { type ScannersSorting, SCANNERS_PAGE_SIZE, replayScannersLogic } from './replayScannersLogic'
-import { LIMIT_REACHED_TOOLTIP } from './scannerCopy'
+import { limitReachedTooltip } from './scannerCopy'
+import { scannerStatus } from './scannerStatus'
import { ENABLED_OPTIONS, EnabledFilter, scannerTypeOptions, ScannerType, ReplayScanner } from './types'
function ScannerRowActions({ scanner }: { scanner: ReplayScanner }): JSX.Element {
@@ -128,7 +129,6 @@ export function ReplayScannersScene(): JSX.Element {
scannersPage,
scannersTotal,
scannersSort,
- togglingIds,
search,
enabledFilter,
scannerTypeFilter,
@@ -140,10 +140,11 @@ export function ReplayScannersScene(): JSX.Element {
scannerStats,
scannerStatsLoading,
} = useValues(replayScannersLogic)
- const { loadScanners, toggleScannerEnabled, setScannersFilters, clearFilters } = useActions(replayScannersLogic)
+ const { loadScanners, setScannersFilters, clearFilters } = useActions(replayScannersLogic)
const { push } = useActions(router)
const { searchParams } = useValues(router)
- const { showUsd } = useValues(visionQuotaLogic)
+ const { showUsd, quota } = useValues(visionQuotaLogic)
+ const quotaExhausted = quotaBannerState(quota).kind === 'exhausted'
const { featureFlags } = useValues(featureFlagLogic)
const activeTab = KNOWN_TABS.includes(searchParams.tab) ? searchParams.tab : DEFAULT_TAB
@@ -167,31 +168,23 @@ export function ReplayScannersScene(): JSX.Element {
{
title: 'Status',
key: 'enabled',
- render: (_, scanner) => (
- <div className="flex items-center gap-2">
- <LemonSwitch
- checked={scanner.enabled}
- onChange={() => toggleScannerEnabled(scanner.id)}
- disabledReason={
- togglingIds.includes(scanner.id)
- ? 'Updating…'
- : getReplayVisionEditDisabledReason(scanner.user_access_level)
- }
- size="small"
- data-attr="vision-scanner-toggle-enabled"
- data-ph-capture-attribute-scanner-type={scanner.scanner_type}
- data-ph-capture-attribute-will-be-enabled={!scanner.enabled}
- />
- <span className={`inline-block min-w-[4.5rem] ${scanner.enabled ? 'text-success' : 'text-muted'}`}>
- {scanner.enabled ? 'Enabled' : 'Disabled'}
- </span>
- {scanner.limit_reached && (
- <Tooltip title={LIMIT_REACHED_TOOLTIP}>
- <LemonTag type="danger">Limit reached</LemonTag>
- </Tooltip>
- )}
- </div>
- ),
+ render: (_, scanner) => {
+ const status = scannerStatus(scanner, { quotaExhausted, drought: null })
+ const tooltip =
+ status.kind === 'limit_reached'
+ ? limitReachedTooltip(scanner)
+ : status.kind === 'quota_exhausted'
+ ? "Your organization's Replay Vision credits are used up for this billing period."
+ : null
+ return (
+ <Tooltip title={tooltip}>
+ {/* The tooltip attaches its trigger to a DOM element, which the label component is not. */}
+ <span>
+ <ScannerStatusLabel status={status} className="whitespace-nowrap" />
+ </span>
+ </Tooltip>
+ )
+ },
sorter: true,
},
{
diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
index fa7c2897b738..1b1331ba978b 100644
--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx
@@ -114,7 +114,7 @@ export function ScannerEditorSceneComponent(): JSX.Element {
const { searchParams } = useValues(router)
const { featureFlags } = useValues(featureFlagLogic)
// Multivariate flag; a truthy check would turn the goal flow on for control too.
- const goalFlow = featureFlags[FEATURE_FLAGS.VISION_GOAL_FLOW_V2] === 'test'
+ const goalFlow = featureFlags[FEATURE_FLAGS.VISION_GOAL_FLOW_V3] === 'test'
// Read once on mount, because the wizard strips the deep-link params as soon as it consumes them.
const [experimentDeepLink] = useState(() => parseExperimentScannerParams(router.values.searchParams) !== null)
// Reached a form step by clicking Edit on the goal overview: the overview is home, not a wizard
@@ -205,8 +205,7 @@ export function ScannerEditorSceneComponent(): JSX.Element {
</div>
<h1 className="text-2xl font-bold m-0">What should the scanner find out?</h1>
<p className="text-base text-secondary max-w-2xl mx-auto m-0">
- Describe the goal, set a monthly budget, and the agent drafts the whole scanner
- for you to review.
+ Describe the goal, and the agent drafts the whole scanner for you to review.
</p>
</div>
<ScannerGoalFlow />
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx
index 937499dc68df..f9fff4479dc2 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx
@@ -19,7 +19,7 @@ interface ScannerCreditLimitProps {
}
export function ScannerCreditLimit({ scannerId }: ScannerCreditLimitProps): JSX.Element {
- const { creditLimitState } = useValues(replayScannerLogic({ id: scannerId }))
+ const { creditLimitState, scanner } = useValues(replayScannerLogic({ id: scannerId }))
const { setScannerValues, setCreditLimitUnit } = useActions(replayScannerLogic({ id: scannerId }))
const {
limit,
@@ -57,7 +57,23 @@ 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>Scanner limit</LemonLabel>
+ <LemonLabel htmlFor="vision-scanner-free-only">Free credits only</LemonLabel>
+ <div className="text-xs text-muted">
+ Scan only while your organization has free monthly credits left, so this scanner never
+ adds to your bill. It pauses when they run out and starts again when the billing period
+ resets.
+ </div>
+ </div>
+ <LemonSwitch
+ checked={!!scanner?.free_only}
+ onChange={(checked) => setScannerValues({ free_only: checked })}
+ id="vision-scanner-free-only"
+ data-attr="vision-scanner-free-only-toggle"
+ />
+ </div>
+ <div className="flex items-start justify-between gap-2">
+ <div className="space-y-1">
+ <LemonLabel htmlFor="vision-scanner-credit-limit">Scanner limit</LemonLabel>
<div className="text-xs text-muted">
Cap what this scanner spends in a billing period. Your organization's limit still
applies.
@@ -71,6 +87,7 @@ export function ScannerCreditLimit({ scannerId }: ScannerCreditLimitProps): JSX.
credit_limit: checked ? seedValue : null,
})
}
+ id="vision-scanner-credit-limit"
data-attr="vision-scanner-credit-limit-toggle"
/>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx
index ab6f78eb9789..d83b5371785a 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalFlow.tsx
@@ -2,14 +2,16 @@ import { useActions, useValues } from 'kea'
import { useState } from 'react'
import { IconChevronRight, IconPlus, IconSparkles } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonTextArea } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonSegmentedButton, LemonTextArea } from '@posthog/lemon-ui'
+import { PopoverReferenceContext } from 'lib/lemon-ui/Popover/Popover'
import { aiConsentLogic } from 'scenes/settings/organization/aiConsentLogic'
import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
+import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
-import { creditsToUsd } from '../../utils/credits'
-import { replayScannerLogic } from '../replayScannerLogic'
+import { creditsToUsd, formatCreditCount } from '../../utils/credits'
+import { GoalSpendMode, goalSpendChoice, replayScannerLogic } from '../replayScannerLogic'
import { ScannerTemplate, defaultScannerTemplates } from '../scannerTemplates'
import { ScannerResumeDraftBanner } from './ScannerResumeDraftBanner'
import { SCANNER_TEMPLATE_ICONS } from './scannerTemplateIcons'
@@ -20,20 +22,32 @@ import { startScannerFromTemplate } from './startScannerFromTemplate'
const MIN_SCAN_BUDGET = 1
const MAX_SCAN_BUDGET = 100000000
+interface PendingDraft {
+ goal: string
+ templateKey?: string
+ budget: number | undefined
+ freeOnly: boolean
+}
+
/** The goal-based creation flow: a typed goal and a monthly budget on the left, one-click starting
* points on the right. Both draft a full scanner through the agent and land the user on the overview
* step to review it, so a one-click start still gets a scanner fitted to the project. */
export function ScannerGoalFlow(): JSX.Element {
const logic = replayScannerLogic({ id: 'new' })
- const { goalDraftInput, goalBudgetInput, goalDraftLoading, experimentContext } = useValues(logic)
- const { draftScannerFromGoal, setGoalDraftInput, setGoalBudgetInput } = useActions(logic)
+ const { goalDraftInput, goalBudgetInput, goalSpendMode, goalDraftLoading, experimentContext } = useValues(logic)
+ const { draftScannerFromGoal, setGoalDraftInput, setGoalBudgetInput, setGoalSpendMode } = useActions(logic)
const { dataProcessingAccepted } = useValues(aiConsentLogic)
- const [pendingDraft, setPendingDraft] = useState<{ goal: string; templateKey?: string } | null>(null)
+ const { freeCreditsLeft } = useValues(visionQuotaLogic)
+ // The spend choice is captured with the goal, so a quota that loads while consent is open cannot change it.
+ const [pendingDraft, setPendingDraft] = useState<PendingDraft | null>(null)
// Drafting creates a scanner, so it needs the same editor access as the rest of the wizard.
const editDisabledReason = getReplayVisionEditDisabledReason()
+ const spend = goalSpendChoice(goalSpendMode, goalBudgetInput, freeCreditsLeft)
+ const spendMode = spend.mode
const budgetValid =
- goalBudgetInput != null && goalBudgetInput >= MIN_SCAN_BUDGET && goalBudgetInput <= MAX_SCAN_BUDGET
+ spendMode === 'free' ||
+ (goalBudgetInput != null && goalBudgetInput >= MIN_SCAN_BUDGET && goalBudgetInput <= MAX_SCAN_BUDGET)
const startDisabledReason =
editDisabledReason ??
(!budgetValid ? 'Enter a monthly credit budget' : goalDraftLoading ? 'Drafting your scanner' : null)
@@ -42,13 +56,17 @@ export function ScannerGoalFlow(): JSX.Element {
startDisabledReason ?? (!goalDraftInput.trim() ? 'Describe what you want to find out' : null)
const start = (goal: string, templateKey?: string): void => {
+ const request = { goal, templateKey, budget: spend.budget, freeOnly: spendMode === 'free' }
// Drafting calls an AI endpoint the backend rejects without org consent; interpose the
// popover instead of letting the request 400.
if (!dataProcessingAccepted) {
- setPendingDraft({ goal, templateKey })
+ setPendingDraft(request)
return
}
- draftScannerFromGoal(goal, goalBudgetInput ?? undefined, templateKey)
+ draft(request)
+ }
+ const draft = ({ goal, templateKey, budget, freeOnly }: PendingDraft): void => {
+ draftScannerFromGoal(goal, budget, templateKey, freeOnly)
}
const startFromTypedGoal = (): void => {
if (!typedGoalDisabledReason) {
@@ -72,7 +90,7 @@ export function ScannerGoalFlow(): JSX.Element {
hidden={pendingDraft === null}
onApprove={() => {
if (pendingDraft) {
- draftScannerFromGoal(pendingDraft.goal, goalBudgetInput ?? undefined, pendingDraft.templateKey)
+ draft(pendingDraft)
}
setPendingDraft(null)
}}
@@ -107,31 +125,64 @@ export function ScannerGoalFlow(): JSX.Element {
) : null}
</div>
- <div className="flex flex-col gap-1">
- <label htmlFor="vision-goal-flow-budget" className="text-sm font-semibold">
- About how much do you want to spend a month?
- </label>
- <div className="flex flex-wrap items-center gap-3">
- <LemonInput
- id="vision-goal-flow-budget"
- type="number"
- min={MIN_SCAN_BUDGET}
- max={MAX_SCAN_BUDGET}
- value={goalBudgetInput ?? undefined}
- onChange={(value) => setGoalBudgetInput(value ?? null)}
- suffix={<span className="text-muted">credits</span>}
- className="w-40"
- data-attr="vision-goal-flow-budget"
+ <div className="flex flex-col gap-2">
+ <span className="text-sm font-semibold">How much should this scanner use?</span>
+ {/* The card sits inside the consent popover's reference, which would give these buttons dropdown arrows. */}
+ <PopoverReferenceContext.Provider value={null}>
+ <LemonSegmentedButton<GoalSpendMode>
+ size="small"
+ value={spendMode}
+ onChange={setGoalSpendMode}
+ options={[
+ {
+ value: 'free',
+ label: 'Free',
+ disabledReason: spend.freeDisabledReason ?? undefined,
+ 'data-attr': 'vision-goal-flow-spend-free',
+ },
+ {
+ value: 'budget',
+ label: 'Set a budget',
+ 'data-attr': 'vision-goal-flow-spend-budget',
+ },
+ ]}
/>
- {budgetValid && goalBudgetInput != null ? (
- <span className="text-xs text-muted">
- ≈ {creditsToUsd(goalBudgetInput)} a month
+ </PopoverReferenceContext.Provider>
+ {spendMode === 'free' ? (
+ <div className="text-xs text-muted">
+ The scanner only uses your free monthly credits
+ {/* Its own span, so page translation cannot strand the changing balance. */}
+ <span>
+ {freeCreditsLeft != null ? ` (${formatCreditCount(freeCreditsLeft)} left)` : ''}
</span>
- ) : null}
- </div>
- <div className="text-xs text-muted">
- 1,000 credits ≈ $10. The agent picks the model and fits the scanner to this.
- </div>
+ . It pauses when they run out, so it never adds to your bill.
+ </div>
+ ) : (
+ <>
+ <div className="flex flex-wrap items-center gap-3">
+ <LemonInput
+ id="vision-goal-flow-budget"
+ aria-label="Monthly credit budget"
+ type="number"
+ min={MIN_SCAN_BUDGET}
+ max={MAX_SCAN_BUDGET}
+ value={goalBudgetInput ?? undefined}
+ onChange={(value) => setGoalBudgetInput(value ?? null)}
+ suffix={<span className="text-muted">credits a month</span>}
+ className="w-48"
+ data-attr="vision-goal-flow-budget"
+ />
+ {budgetValid && goalBudgetInput != null ? (
+ <span className="text-xs text-muted">
+ ≈ {creditsToUsd(goalBudgetInput)} a month
+ </span>
+ ) : null}
+ </div>
+ <div className="text-xs text-muted">
+ 1,000 credits ≈ $10. The agent picks the model and fits the scanner to this.
+ </div>
+ </>
+ )}
</div>
<div className="flex items-center justify-between mt-auto">
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
index d37c8e1cf751..0f7598dd6179 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerGoalOverview.tsx
@@ -18,8 +18,9 @@ import { AnyPropertyFilter, PropertyFilterType } from '~/types'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
import { creditsToUsd, formatCreditCount } from '../../utils/credits'
+import { freeCreditsCoverage } from '../../utils/quotaProjection'
import { scannerExperimentScope, scopeVariantsLabel } from '../experimentTargeting'
-import { replayScannerLogic } from '../replayScannerLogic'
+import { DEFAULT_GOAL_BUDGET, replayScannerLogic } from '../replayScannerLogic'
import { ScannerEditorStep, scannerStepUrlWithParams } from '../scannerEditorSceneLogic'
import {
OBSERVATION_CREDITS_BY_MODEL,
@@ -302,8 +303,10 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E
// The budget is credits, so compare the projected credit cost against the cap (which the draft
// set to the stated budget). The rate cannot go below the minimum, so a budget under that floor
// projects above it.
- const budgetCredits = scanner.credit_limit ?? goalBudgetInput
+ const budgetCredits = scanner.credit_limit ?? (scanner.free_only ? DEFAULT_GOAL_BUDGET : goalBudgetInput)
const overBudget = monthlyCredits != null && budgetCredits != null && monthlyCredits > budgetCredits
+ // A free-only scanner without its own cap can never bill, so it gets a credit count and a note instead of a cost.
+ const freeCreditsOnly = !!scanner.free_only && scanner.credit_limit == null
const saveDisabledReason =
getReplayVisionEditDisabledReason(scanner.user_access_level) ??
@@ -401,28 +404,52 @@ export function ScannerGoalOverview({ scannerId }: { scannerId: string }): JSX.E
<StatRow label="Activity filter">
<LemonTag type="muted">{activityFilterLabel(scanner.sampling_mode)}</LemonTag>
</StatRow>
- <StatRow label="Cost estimate">
+ <StatRow label={freeCreditsOnly ? 'Free credits' : 'Cost estimate'}>
{monthlyCredits != null ? (
- <span>
- about {formatCreditCount(monthlyCredits)} a month (≈ {creditsToUsd(monthlyCredits)})
- </span>
+ freeCreditsOnly ? (
+ overBudget ? (
+ <span>
+ uses all <span>{DEFAULT_GOAL_BUDGET.toLocaleString()}</span> of your free
+ credits a month
+ </span>
+ ) : (
+ <span>
+ uses about <span>{monthlyCredits.toLocaleString()}</span> of your{' '}
+ <span>{DEFAULT_GOAL_BUDGET.toLocaleString()}</span> free credits a month
+ </span>
+ )
+ ) : (
+ <span>
+ about {formatCreditCount(monthlyCredits)} a month (≈ {creditsToUsd(monthlyCredits)})
+ </span>
+ )
) : scannerEstimateLoading ? (
<Spinner />
) : (
<span className="text-muted">Not available</span>
)}
</StatRow>
+ {scanner.free_only && !freeCreditsOnly ? (
+ <StatRow label="Spend">
+ <span className="text-muted">Free credits only</span>
+ </StatRow>
+ ) : null}
{scanner.credit_limit != null ? (
<StatRow label="Monthly cap">
<span className="text-muted">{formatCreditCount(scanner.credit_limit)}</span>
</StatRow>
) : null}
</div>
- {overBudget ? (
+ {overBudget && freeCreditsOnly ? (
+ <LemonBanner type="info">
+ Your free credits cover about{' '}
+ <span>{freeCreditsCoverage(DEFAULT_GOAL_BUDGET, monthlyCredits)}</span> of the month. After that
+ it pauses until they reset.
+ </LemonBanner>
+ ) : overBudget ? (
<LemonBanner type="warning">
- This is already at the lowest sampling rate, so it will watch about{' '}
- {monthlyObservations?.toLocaleString()} recordings a month, more than your budget covers. To
- watch fewer, narrow which recordings are eligible above, for example by device type or country.
+ Your budget won't last the month at about <span>{monthlyObservations?.toLocaleString()}</span>{' '}
+ recordings a month. Narrow the eligible recordings above.
</LemonBanner>
) : null}
</OverviewSection>
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
index 0588aa0b25cc..db5b5a1d043c 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
@@ -34,6 +34,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
onFreePlan,
startupCapCredits,
showStartupCapLine,
+ freeCreditsLeft,
} = useValues(visionQuotaLogic)
if (!scanner) {
@@ -44,6 +45,11 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
// The estimate already applies the quality filter and sampling rate backend-side.
const projectedObservations = scannerEstimate?.estimated_observations_per_month ?? null
const projectedCredits = scannerEstimate?.estimated_credits_per_month ?? null
+ // A free-only scanner stops when the free credits run out, and shares them with the other free-only scanners.
+ const thisScannerCredits =
+ projectedCredits !== null && scanner.free_only && scannerEstimate
+ ? Math.min(projectedCredits, scannerEstimate.free_only_monthly_credits_left)
+ : projectedCredits
const used = quota?.credits_used ?? 0
const cap = quota?.credit_limit ?? 0
@@ -73,7 +79,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
{
key: 'this-scanner',
label: 'Projected (this scanner)',
- credits: projectedCredits ?? 0,
+ credits: thisScannerCredits ?? 0,
kind: 'monthly-rate',
// The model resolves this to the card's status colour, which depends on the projection it is part of.
barClass: QUOTA_STATUS_CLASS,
@@ -82,7 +88,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
])
const { projection, periodEndPct, hasCap } = model
const { resetsOn } = projection
- const newFleetMonthly = othersMonthly + (projectedCredits ?? 0)
+ const newFleetMonthly = othersMonthly + (thisScannerCredits ?? 0)
// Nothing proposed yet, so the forecast isn't a verdict on this scanner.
const effectiveStatus: QuotaStatus = projectedCredits === null ? 'safe' : model.status
@@ -97,7 +103,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
Spent this billing period: <strong>{formatCreditCount(used)}</strong>
</div>
<div>
- Projected from this scanner: <strong>~{formatCreditCount(projectedCredits ?? 0)}/month</strong>
+ Projected from this scanner: <strong>~{formatCreditCount(thisScannerCredits ?? 0)}/month</strong>
</div>
<div>
Projected from other scanners: <strong>~{formatCreditCount(othersMonthly)}/month</strong>
@@ -164,6 +170,14 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
)}
</div>
+ {scanner.free_only && freeCreditsLeft !== null && (
+ <div className="text-xs text-muted">
+ Uses free credits only, so it stops when they run out.{' '}
+ <span>{formatCreditCount(freeCreditsLeft)}</span> left until{' '}
+ <span>{resetsOn ?? 'the period ends'}</span>.
+ </div>
+ )}
+
{/* `hasCap` is also false while quota is still loading, so require a resolved snapshot before
telling anyone their billing limit is missing. */}
{quota !== null && !hasCap && projectedCredits !== null && (
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerStatusLabel.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerStatusLabel.tsx
new file mode 100644
index 000000000000..690e525919a7
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerStatusLabel.tsx
@@ -0,0 +1,45 @@
+import type { ScannerStatus } from '../scannerStatus'
+
+export type StatusTone = 'success' | 'warning' | 'danger' | 'muted'
+
+// Green and yellow mean the scanner is still sweeping, so their dot pulses. Tailwind's own pulse runs at 2s,
+// which reads as urgent, so this slows it to 3s; reduced-motion users get a still dot.
+const ACTIVE_PULSE = 'animate-[pulse_3s_cubic-bezier(0.4,0,0.6,1)_infinite] motion-reduce:animate-none'
+
+const TONE_DOT: Record<StatusTone, string> = {
+ success: 'bg-success',
+ warning: 'bg-warning',
+ danger: 'bg-danger',
+ muted: 'bg-muted',
+}
+
+const STATUS_LABEL: Record<ScannerStatus['kind'], { label: string; tone: StatusTone }> = {
+ off: { label: 'Off', tone: 'muted' },
+ limit_reached: { label: 'Stopped', tone: 'danger' },
+ quota_exhausted: { label: 'Stopped', tone: 'danger' },
+ starting: { label: 'Starting', tone: 'warning' },
+ delayed: { label: 'Delayed', tone: 'warning' },
+ no_matches: { label: 'No matches', tone: 'warning' },
+ throttled: { label: 'Throttled', tone: 'warning' },
+ running: { label: 'Running', tone: 'success' },
+}
+
+export function scannerStatusTone(status: ScannerStatus): StatusTone {
+ return STATUS_LABEL[status.kind].tone
+}
+
+/** The status dot and label, shared by the scanner list and the scanner page so the two always agree. */
+export function ScannerStatusLabel({ status, className }: { status: ScannerStatus; className?: string }): JSX.Element {
+ const { label, tone } = STATUS_LABEL[status.kind]
+ return (
+ <span className={`inline-flex items-center gap-2 ${className ?? ''}`}>
+ <span
+ className={`size-2 rounded-full shrink-0 ${TONE_DOT[tone]} ${
+ tone === 'success' || tone === 'warning' ? ACTIVE_PULSE : ''
+ }`}
+ aria-hidden
+ />
+ <span>{label}</span>
+ </span>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx
index d1a70942b115..3a01a0c56599 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerStatusStrip.tsx
@@ -3,6 +3,8 @@ import { useActions, useValues } from 'kea'
import { LemonSwitch, Link } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
import { percentage } from 'lib/utils/numbers'
import { pluralize } from 'lib/utils/strings'
@@ -15,22 +17,10 @@ import { quotaBannerState } from '../../utils/quotaProjection'
import { replayScannerLogic } from '../replayScannerLogic'
import { ReplayScannerTab } from '../replayScannerSceneLogic'
import { scanDrought } from '../scanDrought'
-import { LIMIT_REACHED_TOOLTIP } from '../scannerCopy'
+import { limitReachedTooltip, stoppedByFreeCredits } from '../scannerCopy'
import { scannerEditUrl } from '../scannerEditorSceneLogic'
import { ScannerStatus, SWEEP_INTERVAL_MINUTES, scannerStatus, spendAgainstLimit } from '../scannerStatus'
-
-type StatusTone = 'success' | 'warning' | 'danger' | 'muted'
-
-// Green and yellow mean the scanner is still sweeping, so their dot pulses. Tailwind's own pulse runs at 2s,
-// which reads as urgent, so this slows it to 3s; reduced-motion users get a still dot.
-const ACTIVE_PULSE = 'animate-[pulse_3s_cubic-bezier(0.4,0,0.6,1)_infinite] motion-reduce:animate-none'
-
-const TONE_DOT: Record<StatusTone, string> = {
- success: 'bg-success',
- warning: 'bg-warning',
- danger: 'bg-danger',
- muted: 'bg-muted',
-}
+import { ScannerStatusLabel } from './ScannerStatusLabel'
function formatInterval(minutes: number): string {
// The throttle factor is any integer, so only whole hours read better in hours.
@@ -40,88 +30,60 @@ function formatInterval(minutes: number): string {
return minutes === 60 ? 'hour' : pluralize(minutes / 60, 'hour')
}
-function statusCopy(
- status: ScannerStatus,
- resetsOn: string | null
-): { label: string; tone: StatusTone; detail: React.ReactNode } {
+function statusDetail(status: ScannerStatus, resetsOn: string | null, periodEndsOn: string | null): React.ReactNode {
switch (status.kind) {
case 'off':
- return {
- label: 'Off',
- tone: 'muted',
- detail:
- status.reason === 'no_sampling'
- ? 'Sampling is set to 0%, so no recordings are scanned.'
- : "This scanner doesn't scan new recordings.",
- }
+ return status.reason === 'no_sampling'
+ ? 'Sampling is set to 0%, so no recordings are scanned.'
+ : "This scanner doesn't scan new recordings."
case 'limit_reached':
- return { label: 'Stopped', tone: 'danger', detail: LIMIT_REACHED_TOOLTIP }
+ return stoppedByFreeCredits(status)
+ ? `Paused until your free credits reset${periodEndsOn ? ` on ${periodEndsOn}` : ''}. Recordings until then are skipped.`
+ : limitReachedTooltip(status)
case 'quota_exhausted':
- return {
- label: 'Stopped',
- tone: 'danger',
- detail: `Your organization's Replay Vision credits are used up${resetsOn ? ` until ${resetsOn}` : ''}.`,
- }
+ return `Your organization's Replay Vision credits are used up${resetsOn ? ` until ${resetsOn}` : ''}.`
case 'starting':
- return {
- label: 'Starting',
- tone: 'warning',
- detail: 'The first scan is running. Results usually appear within 15 minutes.',
- }
+ return 'The first scan is running. Results usually appear within 15 minutes.'
case 'delayed':
- return {
- label: 'Delayed',
- tone: 'warning',
- detail: (
- <>
- Last checked for new recordings <TZLabel time={status.lastCheckedAt} />. Checks resume on their
- own. If this lasts, contact support.
- </>
- ),
- }
+ return (
+ <>
+ Last checked for new recordings <TZLabel time={status.lastCheckedAt} />. Checks resume on their own.
+ If this lasts, contact support.
+ </>
+ )
case 'no_matches':
- return {
- label: 'No matches',
- tone: 'warning',
- detail: `${
- status.drought.everScanned
- ? 'Nothing has matched since the last configuration change.'
- : 'Nothing has matched yet.'
- } The filters may match no recordings${
- status.drought.samplingRate < 1
- ? `, or ${percentage(status.drought.samplingRate)} sampling skipped them`
- : ''
- }.`,
- }
+ return `${
+ status.drought.everScanned
+ ? 'Nothing has matched since the last configuration change.'
+ : 'Nothing has matched yet.'
+ } The filters may match no recordings${
+ status.drought.samplingRate < 1
+ ? `, or ${percentage(status.drought.samplingRate)} sampling skipped them`
+ : ''
+ }.`
case 'throttled':
- return {
- label: 'Throttled',
- tone: 'warning',
- detail: (
- <>
- Its filters read a lot of data, so it checks for new recordings every{' '}
- {formatInterval(status.intervalMinutes)} instead of every{' '}
- {formatInterval(SWEEP_INTERVAL_MINUTES)}. Last checked <TZLabel time={status.lastCheckedAt} />.
- </>
- ),
- }
+ return (
+ <>
+ Its filters read a lot of data, so it checks for new recordings every{' '}
+ {formatInterval(status.intervalMinutes)} instead of every {formatInterval(SWEEP_INTERVAL_MINUTES)}.
+ Last checked <TZLabel time={status.lastCheckedAt} />.
+ </>
+ )
case 'running':
- return {
- label: 'Running',
- tone: 'success',
- detail: (
- <>
- Checks for new recordings every {formatInterval(status.intervalMinutes)}. Last checked{' '}
- <TZLabel time={status.lastCheckedAt} />.
- </>
- ),
- }
+ return (
+ <>
+ Checks for new recordings every {formatInterval(status.intervalMinutes)}. Last checked{' '}
+ <TZLabel time={status.lastCheckedAt} />.
+ </>
+ )
}
}
export function ScannerStatusStrip({ scannerId }: { scannerId: string }): JSX.Element | null {
- const { scanner, observationStatsApi, togglingEnabled } = useValues(replayScannerLogic({ id: scannerId }))
- const { toggleEnabled } = useActions(replayScannerLogic({ id: scannerId }))
+ const { scanner, observationStatsApi, togglingEnabled, turningOffFreeOnly } = useValues(
+ replayScannerLogic({ id: scannerId })
+ )
+ const { toggleEnabled, turnOffFreeOnly } = useActions(replayScannerLogic({ id: scannerId }))
const { quota } = useValues(visionQuotaLogic)
if (!scanner) {
return null
@@ -131,9 +93,11 @@ export function ScannerStatusStrip({ scannerId }: { scannerId: string }): JSX.El
quotaExhausted: quotaState.kind === 'exhausted',
drought: scanDrought(scanner, observationStatsApi?.labels.version_markers ?? null, new Date()),
})
- const { label, tone, detail } = statusCopy(status, quotaState.kind ? quotaState.resetsOn : null)
+ const periodEndsOn = quota ? dayjs.utc(quota.period_end).format('MMMM D') : null
+ const detail = statusDetail(status, quotaState.kind ? quotaState.resetsOn : null, periodEndsOn)
+ const pausedByFreeCredits = status.kind === 'limit_reached' && stoppedByFreeCredits(status)
const editDisabledReason = getReplayVisionEditDisabledReason(scanner.user_access_level)
- const spend = spendAgainstLimit(scanner)
+ const spend = spendAgainstLimit(scanner, quota)
return (
// min-h-38 matches the empty scout card beside it, so the two line up when there is no report yet.
@@ -159,16 +123,16 @@ export function ScannerStatusStrip({ scannerId }: { scannerId: string }): JSX.El
<div className="grid grid-cols-1 @2xl:grid-cols-2 gap-x-8 gap-y-4 items-start">
<div className="min-w-0 flex flex-col gap-1">
<div className="flex items-center gap-2">
- <span
- className={`size-2 rounded-full shrink-0 ${TONE_DOT[tone]} ${
- tone === 'success' || tone === 'warning' ? ACTIVE_PULSE : ''
- }`}
- aria-hidden
- />
- <span className="text-sm font-semibold">{label}</span>
+ <ScannerStatusLabel status={status} className="text-sm font-semibold" />
</div>
<div className="text-xs text-muted pl-4">
{detail}
+ {pausedByFreeCredits && quotaState.kind === 'exhausted' && (
+ <span>
+ {' '}
+ Your organization's spend limit is used up too, so raise it in billing as well.
+ </span>
+ )}
{status.kind === 'no_matches' && (
<>
{' '}
@@ -181,10 +145,40 @@ export function ScannerStatusStrip({ scannerId }: { scannerId: string }): JSX.El
</>
)}
</div>
+ {pausedByFreeCredits && (
+ <div className="pl-4 pt-1 flex flex-wrap items-center justify-between gap-x-3 gap-y-1">
+ <span className="text-xs text-muted">
+ Turn it off to keep scanning now. Scans past your free credits are billed.
+ </span>
+ <LemonSwitch
+ checked
+ onChange={() =>
+ LemonDialog.open({
+ title: 'Turn off free credits only?',
+ description:
+ scanner.credit_limit != null
+ ? `This scanner will keep scanning after your free credits run out. Scans past them are billed, up to its limit of ${scanner.credit_limit.toLocaleString('en-US')} credits a month.`
+ : "This scanner will keep scanning after your free credits run out. Scans past them are billed, up to your organization's spend limit.",
+ primaryButton: { children: 'Turn off', onClick: () => turnOffFreeOnly() },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ loading={turningOffFreeOnly}
+ disabledReason={editDisabledReason}
+ label="Free credits only"
+ size="small"
+ bordered
+ data-attr="vision-scanner-status-turn-off-free-only"
+ data-ph-capture-attribute-scanner-type={scanner.scanner_type}
+ />
+ </div>
+ )}
</div>
<div className="min-w-0 flex flex-col gap-1">
<div className="flex items-center justify-between gap-2 text-sm">
- <span className="font-semibold">Spending limit for this scanner</span>
+ <span className="font-semibold">
+ {spend?.freeCredits ? 'Free credits' : 'Spending limit for this scanner'}
+ </span>
{spend && <span className="text-xs text-muted tabular-nums">{spend.usedPct}%</span>}
</div>
{spend ? (
@@ -194,7 +188,9 @@ export function ScannerStatusStrip({ scannerId }: { scannerId: string }): JSX.El
strokeColor={scanner.limit_reached ? 'var(--danger)' : undefined}
/>
<span className="text-xs text-muted tabular-nums">
- {formatCreditsRange(spend.used, spend.limit)} used this billing period
+ {spend.freeCredits
+ ? `${Math.min(spend.used, spend.limit).toLocaleString('en-US')} of ${spend.limit.toLocaleString('en-US')} free credits used`
+ : `${formatCreditsRange(spend.used, spend.limit)} used this billing period`}
</span>
</>
) : (
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
index 03d8ef14a77c..46e5f6ca2c30 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
@@ -37,7 +37,7 @@ import { ExperimentScannerConfigFields } from './ExperimentScannerConfigFields'
function useManualWithoutAi(scannerId: string): boolean {
const { isNew, goalDraft } = useValues(replayScannerLogic({ id: scannerId }))
const { featureFlags } = useValues(featureFlagLogic)
- return isNew && !goalDraft && featureFlags[FEATURE_FLAGS.VISION_GOAL_FLOW_V2] === 'test'
+ return isNew && !goalDraft && featureFlags[FEATURE_FLAGS.VISION_GOAL_FLOW_V3] === 'test'
}
export const SUMMARIZER_LENGTH_OPTIONS: { value: SummarizerScannerConfig['length']; label: string }[] = [
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index 9bf17faa1e76..8dea5afd0a92 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -19,6 +19,7 @@ import { ScannerModelEnumApi } from '../generated/api.schemas'
import { parseCsvParam, parseNumericParam, parseSortParam } from '../utils/urlParams'
import {
buildObservationListParams,
+ goalSpendChoice,
ObservationStatusValue,
ObservationTriggeredByValue,
ObservationVerdictValue,
@@ -230,6 +231,108 @@ describe('replayScannerLogic', () => {
expect(logic.values.goalDraft).toBeNull()
})
+ it.each([
+ {
+ flow: 'goal flow, free',
+ variant: 'test',
+ solved: true,
+ freeOnly: true,
+ expectFree: true,
+ creditLimit: null,
+ },
+ {
+ flow: 'goal flow, budget',
+ variant: 'test',
+ solved: true,
+ freeOnly: false,
+ expectFree: false,
+ creditLimit: 4000,
+ },
+ {
+ flow: 'goal flow, free, costing failed',
+ variant: 'test',
+ solved: false,
+ freeOnly: true,
+ expectFree: true,
+ creditLimit: null,
+ },
+ {
+ flow: 'control arm asked for free',
+ variant: 'control',
+ solved: false,
+ freeOnly: true,
+ expectFree: false,
+ creditLimit: 4000,
+ },
+ ])(
+ 'applies the spend choice to the drafted scanner: $flow',
+ async ({ variant, solved, freeOnly, expectFree, creditLimit }) => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: variant })
+ draftSpy.mockReturnValue([
+ 200,
+ {
+ name: 'Overview',
+ description: 'Summarizes sessions.',
+ scanner_type: 'summarizer',
+ scanner_config: { prompt: 'Summarize the session.' },
+ rationale: '',
+ query: null,
+ credit_limit: 4000,
+ ...(solved ? { sampling_mode: 'balanced', sampling_rate: 0.5 } : {}),
+ },
+ ])
+ router.actions.push(urls.replayVisionScannerTemplate('new'))
+
+ await expectLogic(logic, () =>
+ logic.actions.draftScannerFromGoal('what are users doing?', 2500, undefined, freeOnly)
+ ).toFinishAllListeners()
+
+ expect(!!logic.values.scanner?.free_only).toEqual(expectFree)
+ expect(logic.values.scanner?.credit_limit ?? null).toEqual(creditLimit)
+ }
+ )
+
+ it('keeps a free draft free when the goal-flow flag changes while the request runs', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'test' })
+ draftSpy.mockImplementation(() => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: 'control' })
+ return [
+ 200,
+ {
+ name: 'Overview',
+ description: 'Summarizes sessions.',
+ scanner_type: 'summarizer',
+ scanner_config: { prompt: 'Summarize the session.' },
+ rationale: '',
+ query: null,
+ credit_limit: 4000,
+ sampling_mode: 'balanced',
+ sampling_rate: 0.5,
+ },
+ ]
+ })
+ router.actions.push(urls.replayVisionScannerTemplate('new'))
+
+ await expectLogic(logic, () =>
+ logic.actions.draftScannerFromGoal('what are users doing?', 2500, undefined, true)
+ ).toFinishAllListeners()
+
+ expect(logic.values.scanner).toMatchObject({ free_only: true, credit_limit: null })
+ })
+
+ it.each([
+ { case: 'free credits left', mode: 'free' as const, left: 800, expected: { mode: 'free', budget: 2500 } },
+ {
+ case: 'free credits used up',
+ mode: 'free' as const,
+ left: 0,
+ expected: { mode: 'budget', budget: 3000 },
+ },
+ { case: 'budget chosen', mode: 'budget' as const, left: 800, expected: { mode: 'budget', budget: 3000 } },
+ ])('picks the spend for a goal draft: $case', ({ mode, left, expected }) => {
+ expect(goalSpendChoice(mode, 3000, left)).toMatchObject(expected)
+ })
+
it('keeps the default query (every session) when the draft has no session filter', async () => {
draftSpy.mockReturnValue([
200,
@@ -1231,6 +1334,36 @@ describe('replayScannerLogic', () => {
updated_at: '2026-09-24T10:00:00Z',
})
})
+
+ it('turns off free credits only with a patch of that one field and clears the stopped state', async () => {
+ let patchedBody: any
+ useMocks({
+ patch: {
+ '/api/projects/:team/vision/scanners/:id/': async ({ request }: { request: Request }) => {
+ patchedBody = await request.json()
+ return [
+ 200,
+ {
+ ...loadedScanner,
+ free_only: false,
+ limit_reached: false,
+ limit_from_free_credits: false,
+ },
+ ]
+ },
+ },
+ })
+ await expectLogic(editLogic, () => editLogic.actions.loadScanner()).toFinishAllListeners()
+ editLogic.actions.setScannerValues({ free_only: true, limit_reached: true, limit_from_free_credits: true })
+ await expectLogic(editLogic, () => editLogic.actions.turnOffFreeOnly()).toDispatchActions([
+ 'turnOffFreeOnlySuccess',
+ ])
+ expect(patchedBody).toEqual({ free_only: false })
+ const running = { free_only: false, limit_reached: false, limit_from_free_credits: false }
+ expect(editLogic.values.scanner).toMatchObject(running)
+ expect(editLogic.values.originalScanner).toMatchObject(running)
+ expect(editLogic.values.turningOffFreeOnly).toBe(false)
+ })
})
describe('buildObservationListParams', () => {
@@ -1776,19 +1909,33 @@ describe('replayScannerLogic', () => {
})
it.each([
- ['a typed goal', undefined, null],
- ['a goal starter', 'dead_end', 'dead_end'],
- ])('drafting from %s reports the AI path without the goal text', async (_, templateKey, reportedKey) => {
- const captureSpy = jest.spyOn(posthog, 'capture')
- await expectLogic(logic, () => {
- logic.actions.draftScannerFromGoal(' find users who get stuck ', undefined, templateKey)
- }).toFinishAllListeners()
- expect(captureSpy).toHaveBeenCalledWith('replay_vision_scanner_creation_started', {
- creation_method: 'ai',
- template_key: reportedKey,
- goal_length: 'find users who get stuck'.length,
- })
- })
+ ['a typed goal', undefined, null, undefined, null],
+ ['a goal starter', 'dead_end', 'dead_end', undefined, null],
+ ['the goal flow with free credits', undefined, null, 'test', 'free'],
+ ['the control arm, which never gets free-only', undefined, null, 'control', null],
+ ])(
+ 'drafting from %s reports the AI path without the goal text',
+ async (_, templateKey, reportedKey, goalFlowVariant, spendMode) => {
+ featureFlagLogic.actions.setFeatureFlags([], {
+ [FEATURE_FLAGS.VISION_GOAL_FLOW_V3]: goalFlowVariant ?? false,
+ })
+ const captureSpy = jest.spyOn(posthog, 'capture')
+ await expectLogic(logic, () => {
+ logic.actions.draftScannerFromGoal(
+ ' find users who get stuck ',
+ goalFlowVariant ? 2500 : undefined,
+ templateKey,
+ true
+ )
+ }).toFinishAllListeners()
+ expect(captureSpy).toHaveBeenCalledWith('replay_vision_scanner_creation_started', {
+ creation_method: 'ai',
+ template_key: reportedKey,
+ spend_mode: spendMode,
+ goal_length: 'find users who get stuck'.length,
+ })
+ }
+ )
it('the last path taken is what the save reports', async () => {
// Each of these replaces the form, so someone who drafts with AI and then picks a
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 31a6cd148cb0..f2ec48412899 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -53,12 +53,13 @@ import type {
EstimateResponseApi,
ObservationStatsApi,
ReplayObservationApi,
+ ReplayScannerApi,
TagSuggestionApi,
} from '../generated/api.schemas'
import type { ScannerCreationMethodEnumApi, ScannerTypeEnumApi } from '../generated/api.schemas'
import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from '../logics/observationPolling'
import { requestObservationRetry } from '../logics/observationRetry'
-import { refreshVisionQuota } from '../logics/visionQuotaLogic'
+import { refreshVisionQuota, visionQuotaLogic } from '../logics/visionQuotaLogic'
import { neighborFilterParams } from '../observations/replayObservationLogic'
import { lastObservationsPage } from '../observations/replayObservationSceneLogic'
import { observationClipboardText } from '../utils/observation'
@@ -204,6 +205,11 @@ function experimentScannersEnabled(): boolean {
return !!featureFlagLogic.values.featureFlags[FEATURE_FLAGS.VISION_EXPERIMENT_SCANNER]
}
+/** The control arm gets legacy drafts, so it never makes a free-only scanner. */
+function goalFlowEnabled(): boolean {
+ return featureFlagLogic.values.featureFlags[FEATURE_FLAGS.VISION_GOAL_FLOW_V3] === 'test'
+}
+
/** The experiment a goal draft named, in the experiment type's config or in the legacy targeting. */
function draftExperimentScope(goalDraft: DraftScannerResponseApi): ScannerExperimentScope | null {
if (goalDraft.scanner_type === 'experiment') {
@@ -415,6 +421,37 @@ const CREDIT_LIMIT_SEED_HEADROOM = 2
export type CreditLimitUnit = 'credits' | 'observations'
+export type GoalSpendMode = 'free' | 'budget'
+
+// Equals the free monthly credits (FREE_TIER_MONTHLY_CREDITS in backend/billing.py). Change both values together.
+export const DEFAULT_GOAL_BUDGET = 2500
+
+export interface GoalSpendChoice {
+ mode: GoalSpendMode
+ /** What the drafter sizes the scanner to: the monthly free credits in free mode, else the typed budget. */
+ budget: number | undefined
+ freeDisabledReason: string | null
+}
+
+/** One answer for the goal flow and the armed-goal draft, so neither drafts a free scanner with no free credits. */
+export function goalSpendChoice(
+ mode: GoalSpendMode,
+ budgetInput: number | null,
+ freeCreditsLeft: number | null
+): GoalSpendChoice {
+ const freeDisabledReason =
+ freeCreditsLeft != null && freeCreditsLeft <= 0
+ ? 'Your organization has used its free credits for this billing period'
+ : null
+ const effectiveMode = freeDisabledReason ? 'budget' : mode
+ return {
+ mode: effectiveMode,
+ // A scanner outlives this period, so free mode sizes it to the monthly free credits, not to what is left now.
+ budget: effectiveMode === 'free' ? DEFAULT_GOAL_BUDGET : (budgetInput ?? undefined),
+ freeDisabledReason,
+ }
+}
+
// 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)
@@ -439,6 +476,18 @@ export interface CreditLimitState {
seedValue: number | null
}
+/** The fields a free-only change moves, copied from the saved scanner so the status updates without a reload. */
+function freeOnlyFields(
+ saved: ReplayScannerApi
+): Pick<ReplayScannerApi, 'free_only' | 'limit_reached' | 'limit_from_free_credits' | 'credits_used_against_limit'> {
+ return {
+ free_only: saved.free_only,
+ limit_reached: saved.limit_reached,
+ limit_from_free_credits: saved.limit_from_free_credits,
+ credits_used_against_limit: saved.credits_used_against_limit,
+ }
+}
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface replayScannerLogicValues {
affectedCohort: {
@@ -459,6 +508,7 @@ export interface replayScannerLogicValues {
goalDraft: DraftScannerResponseApi | null
goalDraftInput: string
goalDraftLoading: boolean
+ goalSpendMode: GoalSpendMode
hasActiveObservationFilters: boolean
hasObservationsInFlight: boolean
hasUnsavedChanges: boolean
@@ -512,6 +562,7 @@ export interface replayScannerLogicValues {
tagSuggestionsLoading: boolean
togglingEnabled: boolean
triggeringOnDemandObservation: boolean
+ turningOffFreeOnly: boolean
turningOnSelfDriving: boolean
}
@@ -550,9 +601,12 @@ export interface replayScannerLogicActions {
draftScannerFromGoal: (
goal: string,
monthlyCreditBudget?: number,
- templateKey?: string
+ templateKey?: string,
+ freeOnly?: boolean
) => {
+ freeOnly: boolean
goal: string
+ goalFlow: boolean
monthlyCreditBudget: number | undefined
templateKey: string | undefined
}
@@ -566,14 +620,18 @@ export interface replayScannerLogicActions {
draftScannerFromGoalSuccess: (
goalDraft: DraftScannerResponseApi | null,
payload?: {
+ freeOnly: boolean
goal: string
+ goalFlow: boolean
monthlyCreditBudget: number | undefined
templateKey: string | undefined
}
) => {
goalDraft: DraftScannerResponseApi | null
payload?: {
+ freeOnly: boolean
goal: string
+ goalFlow: boolean
monthlyCreditBudget: number | undefined
templateKey: string | undefined
}
@@ -745,6 +803,9 @@ export interface replayScannerLogicActions {
setGoalDraftInput: (goal: string) => {
goal: string
}
+ setGoalSpendMode: (mode: GoalSpendMode) => {
+ mode: GoalSpendMode
+ }
setObservationBackfillFilter: (value: string | null) => {
value: string | null
}
@@ -855,6 +916,15 @@ export interface replayScannerLogicActions {
triggerOnDemandObservationSuccess: () => {
value: true
}
+ turnOffFreeOnly: () => {
+ value: true
+ }
+ turnOffFreeOnlyFailure: () => {
+ value: true
+ }
+ turnOffFreeOnlySuccess: (saved: ReplayScannerApi) => {
+ saved: ReplayScannerApi
+ }
turnOnSelfDriving: () => {
value: true
}
@@ -965,13 +1035,22 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
acceptTagSuggestion: (tag: string) => ({ tag }),
acceptAllTagSuggestions: true,
dismissTagSuggestions: true,
- draftScannerFromGoal: (goal: string, monthlyCreditBudget?: number, templateKey?: string) => ({
+ draftScannerFromGoal: (
+ goal: string,
+ monthlyCreditBudget?: number,
+ templateKey?: string,
+ freeOnly?: boolean
+ ) => ({
goal,
monthlyCreditBudget,
templateKey,
+ freeOnly: freeOnly ?? false,
+ // Read when the request starts, so a flag refresh while it runs cannot change what the result saves.
+ goalFlow: monthlyCreditBudget != null && goalFlowEnabled(),
}),
setGoalDraftInput: (goal: string) => ({ goal }),
setGoalBudgetInput: (budget: number | null) => ({ budget }),
+ setGoalSpendMode: (mode: GoalSpendMode) => ({ mode }),
loadObservations: (background = false) => ({ background }),
loadObservationsSuccess: (observations: ReplayObservationApi[], total: number) => ({ observations, total }),
loadObservationsFailure: true,
@@ -983,6 +1062,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
toggleEnabled: true,
toggleEnabledSuccess: (enabled: boolean) => ({ enabled }),
toggleEnabledFailure: true,
+ turnOffFreeOnly: true,
+ turnOffFreeOnlySuccess: (saved: ReplayScannerApi) => ({ saved }),
+ turnOffFreeOnlyFailure: true,
turnOnSelfDriving: true,
turnOnSelfDrivingSuccess: (scannerVersion: number, updatedAt: string) => ({ scannerVersion, updatedAt }),
scannerDashboardLinked: (dashboardId: number) => ({ dashboardId }),
@@ -1269,15 +1351,19 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
scannerSaved: () => '',
},
],
- // The monthly credit budget input on the goal-based creation flow. The default equals the free
- // monthly credits (FREE_TIER_MONTHLY_CREDITS in backend/billing.py), so a first scanner fits the
- // free tier and costs nothing unless the person raises it. Change both values together.
+ // The monthly credit budget input on the goal-based creation flow, used when the person sets a budget.
goalBudgetInput: [
- 2500 as number | null,
+ DEFAULT_GOAL_BUDGET as number | null,
{
setGoalBudgetInput: (_, { budget }) => budget,
},
],
+ goalSpendMode: [
+ 'free' as GoalSpendMode,
+ {
+ setGoalSpendMode: (_, { mode }) => mode,
+ },
+ ],
// A template pick replaces the drafted form, so its rationale no longer describes the config.
goalDraft: [
null as DraftScannerResponseApi | null,
@@ -1326,6 +1412,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// Keyed on the real save, not submitScannerSuccess — kea-forms fires that on the no-API advance path too.
scannerSaved: (_, { scanner }) => scanner,
toggleEnabledSuccess: (state, { enabled }) => (state ? { ...state, enabled } : state),
+ turnOffFreeOnlySuccess: (state, { saved }) => (state ? { ...state, ...freeOnlyFields(saved) } : state),
// Self-driving changes the prompt the model gets, so the backend bumps the version with it.
turnOnSelfDrivingSuccess: (state, { scannerVersion, updatedAt }) =>
state
@@ -1344,6 +1431,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
toggleEnabledFailure: () => false,
},
],
+ turningOffFreeOnly: [
+ false,
+ {
+ turnOffFreeOnly: () => true,
+ turnOffFreeOnlySuccess: () => false,
+ turnOffFreeOnlyFailure: () => false,
+ },
+ ],
turningOnSelfDriving: [
false,
{
@@ -2023,7 +2118,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
const consented = !!organizationLogic.values.currentOrganization?.is_ai_data_processing_approved
if (armedGoal && !hasFiltersPrefill && consented && !values.goalDraftLoading) {
actions.setGoalDraftInput(armedGoal)
- actions.draftScannerFromGoal(armedGoal, values.goalBudgetInput ?? undefined)
+ const spend = goalSpendChoice(
+ values.goalSpendMode,
+ values.goalBudgetInput,
+ visionQuotaLogic.findMounted()?.values.freeCreditsLeft ?? null
+ )
+ actions.draftScannerFromGoal(armedGoal, spend.budget, undefined, spend.mode === 'free')
}
return
}
@@ -2152,11 +2252,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
},
// Fires on request rather than result, so failed drafts still count as entering the AI path.
- draftScannerFromGoal: ({ goal, monthlyCreditBudget, templateKey }) => {
+ draftScannerFromGoal: ({ goal, monthlyCreditBudget, templateKey, freeOnly, goalFlow }) => {
posthog.capture('replay_vision_scanner_creation_started', {
creation_method: 'ai',
// Set when a goal starter card wrote the goal, so the funnel can split typed goals from one-click ones.
template_key: templateKey ?? null,
+ spend_mode: !goalFlow ? null : freeOnly ? 'free' : 'budget',
// The goal is customer text, so only its length is captured.
goal_length: goal.trim().length,
})
@@ -2198,6 +2299,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// one while the scanner saves the new one. Drop the card and let it rebuild.
actions.setExperimentContext(null)
}
+ // Solved dials mark a goal-flow draft. Free-only follows the request, because a draft whose costing failed has no dials.
+ const isGoalFlowDraft = goalDraft.sampling_mode != null || goalDraft.sampling_rate != null
+ const freeOnlyDraft = !!payload?.freeOnly && !!payload.goalFlow
const base = newScanner(null, teamLogic.values.currentTeam?.name)
actions.resetScanner(context ? prefillScannerForExperiment(base, context, asExperimentScanner) : base)
const draftQuery = goalDraft.query as RecordingsQuery | undefined
@@ -2234,9 +2338,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// The model the draft chose for the goal, and the credit cap set to the stated
// budget. credit_limit_enabled is UI-only form state, so turn it on alongside.
...(goalDraft.model ? { model: goalDraft.model } : {}),
- ...(goalDraft.credit_limit != null
- ? { credit_limit: goalDraft.credit_limit, credit_limit_enabled: true }
- : {}),
+ ...(freeOnlyDraft
+ ? { free_only: true, credit_limit: null, credit_limit_enabled: false }
+ : goalDraft.credit_limit != null
+ ? { credit_limit: goalDraft.credit_limit, credit_limit_enabled: true }
+ : {}),
// The experiment type carries the experiment. Without it, the experiment the goal
// named (or the one the wizard was entered from) stays legacy targeting.
experiment_targeting: asExperimentScanner
@@ -2246,10 +2352,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// Loads the experiment so the editor shows its name and variants, the same way it
// does for a scanner started from the experiment itself.
actions.rebuildExperimentContext()
- // Solved dials mark a goal-flow draft, which reviews on the overview; legacy drafts
- // open the details step. The goal flow is already on the overview (pushed on request),
- // so this only navigates the legacy path.
- const isGoalFlowDraft = goalDraft.sampling_mode != null || goalDraft.sampling_rate != null
+ // The goal flow is already on the overview, so only a legacy draft navigates, to the details step.
if (isGoalFlowDraft) {
// The form now carries the drafted filter, so count what it will actually watch.
actions.loadScannerEstimate()
@@ -2448,6 +2551,24 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
},
+ turnOffFreeOnly: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (props.id === 'new' || !values.scanner || !teamId) {
+ actions.turnOffFreeOnlyFailure()
+ return
+ }
+ try {
+ const saved = await visionScannersPartialUpdate(String(teamId), props.id, { free_only: false })
+ actions.setScannerValues(freeOnlyFields(saved))
+ actions.turnOffFreeOnlySuccess(saved)
+ refreshVisionQuota()
+ lemonToast.success('Free credits only turned off')
+ } catch (error: any) {
+ lemonToast.error(`Couldn't turn off free credits only${error.detail ? `: ${error.detail}` : ''}`)
+ actions.turnOffFreeOnlyFailure()
+ }
+ },
+
turnOnSelfDriving: async () => {
const teamId = teamLogic.values.currentTeamId
if (props.id === 'new' || !values.scanner || !teamId) {
diff --git a/products/replay_vision/frontend/replay_scanners/scannerCopy.ts b/products/replay_vision/frontend/replay_scanners/scannerCopy.ts
index bf5dceeafe1d..6ff8c9f2afd4 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerCopy.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerCopy.ts
@@ -1,4 +1,22 @@
/** Shared by every "Limit reached" badge so the surfaces tell one story. */
-export const LIMIT_REACHED_TOOLTIP =
+const LIMIT_REACHED_TOOLTIP =
'This scanner stopped scanning until its credit limit resets at the start of the next billing period. ' +
'Sessions skipped while capped are not scanned later.'
+
+const FREE_CREDITS_USED_TOOLTIP =
+ 'Paused until your free credits reset. Recordings until then are skipped. ' +
+ 'To keep scanning, turn off "Free credits only" on the scanner page.'
+
+type LimitFields =
+ | { free_only?: boolean; credit_limit?: number | null; limit_from_free_credits?: boolean }
+ | null
+ | undefined
+
+// The free credits stop a free-only scanner when it has no limit of its own, or when they leave less room than it.
+export function stoppedByFreeCredits(scanner: LimitFields): boolean {
+ return !!scanner?.free_only && (scanner.credit_limit == null || !!scanner.limit_from_free_credits)
+}
+
+export function limitReachedTooltip(scanner: LimitFields): string {
+ return stoppedByFreeCredits(scanner) ? FREE_CREDITS_USED_TOOLTIP : LIMIT_REACHED_TOOLTIP
+}
diff --git a/products/replay_vision/frontend/replay_scanners/scannerStatus.test.ts b/products/replay_vision/frontend/replay_scanners/scannerStatus.test.ts
index b2ac93aab56f..723b18b53fe4 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerStatus.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerStatus.test.ts
@@ -1,5 +1,7 @@
import { dayjs } from 'lib/dayjs'
+import { makeQuota } from '../utils/quotaTestUtils'
+import { stoppedByFreeCredits } from './scannerCopy'
import { ScannerStatusFields, scannerStatus, spendAgainstLimit } from './scannerStatus'
const NOW = dayjs('2026-05-12T12:00:00Z')
@@ -9,6 +11,8 @@ const HEALTHY: ScannerStatusFields = {
enabled: true,
sampling_rate: 1,
limit_reached: false,
+ credit_limit: null,
+ limit_from_free_credits: false,
sweep_throttle_factor: 1,
created_at: '2026-05-01T00:00:00Z',
last_swept_at: NOW.subtract(40, 'minute').toISOString(),
@@ -81,4 +85,53 @@ describe('scannerStatus', () => {
])('spend against a limit of %s with %s used', (credit_limit, credits_used_against_limit, expected) => {
expect(spendAgainstLimit({ credit_limit, credits_used_against_limit })).toEqual(expected)
})
+
+ test.each([
+ ['org free credits', { credit_limit: 10_000 }, { limit: 2_500, used: 600, usedPct: 24, freeCredits: true }],
+ [
+ 'org limit below the free credits',
+ { credit_limit: 1_000 },
+ { limit: 1_000, used: 600, usedPct: 60, freeCredits: true },
+ ],
+ ['uncapped org', { credit_limit: null }, { limit: 2_500, used: 600, usedPct: 24, freeCredits: true }],
+ ])('free-only spend against the %s', (_name, quotaOverrides, expected) => {
+ const quota = makeQuota({ credits_used: 600, ...quotaOverrides })
+ expect(
+ spendAgainstLimit({ credit_limit: null, credits_used_against_limit: 0, free_only: true }, quota)
+ ).toEqual(expected)
+ })
+
+ test.each([
+ ['an own limit blames that limit', { credit_limit: 500 }, false],
+ ['no own limit blames the free credits', { credit_limit: null }, true],
+ [
+ 'an own limit blames the free credits when they bind',
+ { credit_limit: 500, limit_from_free_credits: true },
+ true,
+ ],
+ ])('stopped free-only scanner with %s', (_name, overrides, expected) => {
+ const status = scannerStatus(
+ { ...HEALTHY, free_only: true, limit_reached: true, ...overrides },
+ { quotaExhausted: false, drought: null, now: NOW }
+ )
+ expect(status.kind === 'limit_reached' && stoppedByFreeCredits(status)).toBe(expected)
+ })
+
+ test.each([
+ ['free credits bind', true, 2_400, { limit: 2_500, used: 2_400, usedPct: 96, freeCredits: true }],
+ ['own limit binds', false, 300, { limit: 500, used: 300, usedPct: 60 }],
+ ])('free-only scanner with its own limit when the %s', (_name, fromFree, usedAgainstLimit, expected) => {
+ const quota = makeQuota({ credit_limit: 10_000, credits_used: 2_400 })
+ expect(
+ spendAgainstLimit(
+ {
+ credit_limit: 500,
+ credits_used_against_limit: usedAgainstLimit,
+ free_only: true,
+ limit_from_free_credits: fromFree,
+ },
+ quota
+ )
+ ).toEqual(expected)
+ })
})
diff --git a/products/replay_vision/frontend/replay_scanners/scannerStatus.ts b/products/replay_vision/frontend/replay_scanners/scannerStatus.ts
index 1c70e94cdf72..b22fe93c4835 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerStatus.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerStatus.ts
@@ -1,5 +1,6 @@
import { Dayjs, dayjs } from 'lib/dayjs'
+import type { VisionQuotaApi } from '../generated/api.schemas'
import type { ScanDrought } from './scanDrought'
import type { ReplayScanner } from './types'
@@ -13,7 +14,7 @@ const STARTING_MAX_AGE_MINUTES = 60
export type ScannerStatus =
| { kind: 'off'; reason: 'disabled' | 'no_sampling' }
- | { kind: 'limit_reached' }
+ | { kind: 'limit_reached'; free_only: boolean; credit_limit: number | null; limit_from_free_credits: boolean }
| { kind: 'quota_exhausted' }
| { kind: 'starting' }
| { kind: 'delayed'; lastCheckedAt: Dayjs }
@@ -23,7 +24,15 @@ export type ScannerStatus =
export type ScannerStatusFields = Pick<
ReplayScanner,
- 'enabled' | 'sampling_rate' | 'limit_reached' | 'sweep_throttle_factor' | 'created_at' | 'last_swept_at'
+ | 'enabled'
+ | 'sampling_rate'
+ | 'limit_reached'
+ | 'free_only'
+ | 'credit_limit'
+ | 'limit_from_free_credits'
+ | 'sweep_throttle_factor'
+ | 'created_at'
+ | 'last_swept_at'
>
/** The one status the scanner page leads with. Earlier checks win, so a scanner that is off never also reads as stopped. */
@@ -39,7 +48,12 @@ export function scannerStatus(
return { kind: 'off', reason: 'no_sampling' }
}
if (scanner.limit_reached) {
- return { kind: 'limit_reached' }
+ return {
+ kind: 'limit_reached',
+ free_only: !!scanner.free_only,
+ credit_limit: scanner.credit_limit ?? null,
+ limit_from_free_credits: !!scanner.limit_from_free_credits,
+ }
}
if (options.quotaExhausted) {
return { kind: 'quota_exhausted' }
@@ -72,15 +86,29 @@ export interface SpendAgainstLimit {
limit: number
used: number
usedPct: number
+ /** True when the limit is the organization's free credits, not the scanner's own. */
+ freeCredits?: boolean
}
export function spendAgainstLimit(
- scanner: Pick<ReplayScanner, 'credit_limit' | 'credits_used_against_limit'>
+ scanner: Pick<ReplayScanner, 'credit_limit' | 'credits_used_against_limit'> & {
+ free_only?: boolean
+ limit_from_free_credits?: boolean
+ },
+ quota: VisionQuotaApi | null = null
): SpendAgainstLimit | null {
+ const usedPct = (used: number, limit: number): number =>
+ limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0
const limit = scanner.credit_limit
+ // A free-only scanner draws on the organization's free credits when they leave less room than its own limit.
+ if (scanner.free_only && quota && (limit == null || scanner.limit_from_free_credits)) {
+ const freeLimit = Math.min(quota.free_monthly_credits, quota.credit_limit ?? Infinity)
+ const used = quota.credits_used
+ return { limit: freeLimit, used, usedPct: usedPct(used, freeLimit), freeCredits: true }
+ }
if (limit == null) {
return null
}
const used = scanner.credits_used_against_limit
- return { limit, used, usedPct: limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0 }
+ return { limit, used, usedPct: usedPct(used, limit) }
}
diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
index 18abef5e0586..a9e4d3a7138b 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
@@ -166,6 +166,7 @@ export function newScanner(templateKey?: string | null, teamName?: string | null
credit_limit: null,
// Materialized here so toggling the limit on and off compares equal to this baseline again.
credit_limit_enabled: false,
+ free_only: false,
// An unsaved scanner has no spend yet, so it can't have hit a limit it doesn't have.
credits_used_against_limit: 0,
limit_from_free_credits: false,
diff --git a/products/replay_vision/frontend/utils/quotaProjection.test.ts b/products/replay_vision/frontend/utils/quotaProjection.test.ts
index 3bfc8efdec90..b9ca8b4d094d 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.test.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.test.ts
@@ -1,6 +1,6 @@
import { dayjs } from 'lib/dayjs'
-import { daysUntilCapReached, hasBillableSpend, projectQuota, quotaUx } from './quotaProjection'
+import { daysUntilCapReached, freeCreditsCoverage, hasBillableSpend, projectQuota, quotaUx } from './quotaProjection'
import { makeQuota } from './quotaTestUtils'
describe('hasBillableSpend', () => {
@@ -122,6 +122,18 @@ describe('projectQuota', () => {
})
})
+describe('freeCreditsCoverage', () => {
+ it.each([
+ [2_500, 3_000, 'the first 3 weeks'],
+ [2_500, 5_000, 'the first 2 weeks'],
+ [2_500, 6_000, 'the first 12 days'],
+ [2_500, 75_000, 'the first day'],
+ [2_500, 1_000_000, 'the first day'],
+ ])('%s free credits at %s a month cover %s', (allowance, monthlyCredits, expected) => {
+ expect(freeCreditsCoverage(allowance, monthlyCredits)).toBe(expected)
+ })
+})
+
describe('daysUntilCapReached', () => {
it.each([
// 1,000 left of the 10,000 cap, burned at monthly/30 per day.
diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.ts
index a05c68eb4467..e5d77e536433 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.ts
@@ -59,6 +59,23 @@ export function hasBillableSpend(quota: VisionQuotaApi | null): boolean {
return billableCredits(quota.credit_limit, quota.free_monthly_credits) > 0
}
+/** What a free-only scanner can still spend this period; an org limit below the free credits lowers it. */
+export function freeCreditsLeft(quota: VisionQuotaApi | null): number | null {
+ if (!quota) {
+ return null
+ }
+ return Math.max(0, Math.min(quota.free_monthly_credits, quota.credit_limit ?? Infinity) - quota.credits_used)
+}
+
+/** How much of a month a monthly allowance covers at a monthly rate, for example "the first 3 weeks". */
+export function freeCreditsCoverage(allowance: number, monthlyCredits: number): string {
+ const days = Math.max(1, Math.floor((allowance / monthlyCredits) * ESTIMATE_MONTH_DAYS))
+ if (days >= 14) {
+ return `the first ${Math.floor(days / 7)} weeks`
+ }
+ return days === 1 ? 'the first day' : `the first ${days} days`
+}
+
/**
* True when the org's whole limit is the free allocation, so it is on the free plan rather than
* capped by choice. A zero limit is excluded: that is a deliberate spend cap, not a free plan.