: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 and see per-scanner credit limits (#75155)
Arno Hillen77630cbe6979
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2ab7ca8f657b..0d335d4ab2ac 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7247,9 +7247,9 @@ snapshots:scenes-app-replay-vision--scanner-editor-configure-tier-names--light:hash: v1.k794b7964.ce4949dd405f5c3f649603d9ef8c456fdbdb54bba316315da99de61381ed2adb.JE7suDQnoBdS-7uamAnvAQ49DzNNiyKXg8gh2HkeSOwscenes-app-replay-vision--scanner-editor-triggers--dark:- hash: v1.k794b7964.d5d7349cee24b107e7cc4026a11b525ebd8eaf0d58fcca76f476e4d9abe4df54.yxuHswihy4WM4sunFIL7bUKgJglMPmRmRRwtuavRnE0+ hash: v1.k794b7964.166ce138029235c749dec3b1bbf09b8af7d666dbb92375a7a2d8ed66fdfa7202.E5gIuCZqduv6Qz3_AuMRkF-HknnZvESW26W30tPAQucscenes-app-replay-vision--scanner-editor-triggers--light:- hash: v1.k794b7964.74abe036edeb6479f4f8015cdc003465003e089c1a6a8b862a791afa1f8e907c.gblC39OvMrIptBQV0S2EtSws7fnFcD0H-QN75vG5t3U+ hash: v1.k794b7964.63b3d2d922a2dd471ee37bc48cbb18ec68cd9385d460de48d0e265d3017578ab.LZVA-vMEtsHiEFWOc5CgkwG7ZLl9BCj_JD9g36f8nwQscenes-app-replay-vision--scanner-observations--dark:hash: v1.k794b7964.836bbeb03dc8a6a02c7489875920b0e0098cc696580490eb7163b36eb8e835f3.r_NXe4vOXdXkB7NxFQuoq9N4a3BlD6DMwP5HHCX4c70scenes-app-replay-vision--scanner-observations--light:diff --git a/products/replay_vision/README.md b/products/replay_vision/README.mdindex f3dae5ebb16a..9e5983c8e694 100644--- a/products/replay_vision/README.md+++ b/products/replay_vision/README.md@@ -25,6 +25,7 @@ A finding can also be turned into a PostHog Task once (the observation remembersUsage (receipts + in-flight rows + in-flight prompt tests) counts against the organization's credit limit for the current billing period, falling back to the calendar month when billing hasn't synced the product.Per-scanner volume estimates are credit-weighted and summed into a projected-spend prognosis shown at configuration time.Scheduled observations over budget are skipped; on-demand ones are rejected.+A scanner can also carry its own optional `credit_limit` for the same period, so one broad scanner cannot drain the whole organization budget. A scanner that reaches its limit stops scanning until the period resets, stays enabled, and does not go back for the sessions it skipped.## Scenes and tabsdiff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 6251cc795a15..e34420fece43 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -1,5 +1,6 @@import jsonfrom typing import Any, NoReturn, cast+from uuid import UUIDfrom django.db import IntegrityErrorfrom django.db.models import CharField, Count, F, IntegerField, OuterRef, Q, QuerySet, Subquery, Sum, Value@@ -80,7 +81,9 @@ from products.replay_vision.backend.queries import (refresh_scanner_estimate,)from products.replay_vision.backend.quota import (+ ScannerBudget,ScannerSpend,+ compute_scanner_budgets,credits_used_by_scanner,current_period_bounds,spend_projection,@@ -275,6 +278,18 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Moderequired=False,help_text="Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).",)+ credit_limit = serializers.IntegerField(+ required=False,+ allow_null=True,+ min_value=1,+ # int4 bound: DRF never runs full_clean, so an over-int4 value would 500 in Postgres, not 400.+ max_value=2147483647,+ help_text=(+ "Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level "+ "cap. When reached, this scanner stops scanning until the period resets. It stays enabled and "+ "does not scan the sessions it skipped."+ ),+ )provider = serializers.ChoiceField(choices=ScannerProvider.choices,required=False,@@ -317,6 +332,21 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modeobservations_this_month = serializers.SerializerMethodField(help_text="Succeeded observations this scanner produced in the current billing period.",)+ credits_used_against_limit = serializers.SerializerMethodField(+ help_text=(+ "Credits counted against `credit_limit` for the current billing period: settled receipts plus "+ "in-flight observations and running prompt tests, priced from their frozen snapshot model. This "+ "is what the limit gate measures, so it includes work still in progress. It is not the same as "+ "`credits_this_month`, which counts only succeeded observations."+ ),+ )+ limit_reached = serializers.SerializerMethodField(+ help_text=(+ "Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is "+ "set and the budget left cannot cover one more observation, which is the same test the scanner's "+ "enforcement gates apply. Always false when no limit is set."+ ),+ )last_swept_at = serializers.DateTimeField(read_only=True,help_text="Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery.",@@ -355,6 +385,7 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode"query","sampling_rate","sampling_mode",+ "credit_limit","provider","model","enabled",@@ -366,6 +397,8 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode"estimated_monthly_credits","credits_this_month","observations_this_month",+ "credits_used_against_limit",+ "limit_reached","last_swept_at","created_at","created_by",@@ -381,6 +414,8 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode"estimated_monthly_credits","credits_this_month","observations_this_month",+ "credits_used_against_limit",+ "limit_reached","last_swept_at","created_at","created_by",@@ -399,17 +434,41 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modereturn Nonereturn scanner.estimated_monthly_observations * observation_credits_for_model(scanner.model)+ def _page_scanner_ids(self, scanner: ReplayScanner) -> list[UUID]:+ root = self.root+ instance = root.instance if isinstance(root, serializers.ListSerializer) else None+ return [s.id for s in instance] if instance is not None else [scanner.id]+def _scanner_spend(self, scanner: ReplayScanner) -> ScannerSpend:# The context dict is shared across the list's children, so the page's totals are computed once.totals = self.context.get("_scanner_credits_used")if totals is None:- root = self.root- instance = root.instance if isinstance(root, serializers.ListSerializer) else None- scanner_ids = [s.id for s in instance] if instance is not None else [scanner.id]- totals = credits_used_by_scanner(self.context["get_team"]().organization_id, scanner_ids)+ totals = credits_used_by_scanner(+ self.context["get_team"]().organization_id, self._page_scanner_ids(scanner)+ )self.context["_scanner_credits_used"] = totalsreturn totals.get(scanner.id, ScannerSpend(0, 0))+ def _scanner_budget(self, scanner: ReplayScanner) -> ScannerBudget:+ """The limit-facing figure. Separate from `_scanner_spend` on purpose: that one is the displayed+ spend read from observation rows, this one is the delete-proof ledger draw the cap is enforced on."""+ budgets = self.context.get("_scanner_budgets")+ if budgets is None:+ budgets = compute_scanner_budgets(+ self.context["get_team"]().organization_id, self._page_scanner_ids(scanner)+ )+ self.context["_scanner_budgets"] = budgets+ # Indexed, not `.get(default)` like `_scanner_spend`: a missing entry means the page id list didn't+ # cover this scanner, and defaulting a limit figure to zero would report a blocked scanner as fine.+ # Displayed spend can safely fall back to zero; this cannot.+ try:+ return budgets[scanner.id]+ except KeyError:+ raise KeyError(+ f"Scanner {scanner.id} missing from the page's budget batch; the serializer ran outside "+ f"the list context that precomputes _page_scanner_ids"+ ) from None+@extend_schema_field(serializers.IntegerField())def get_credits_this_month(self, scanner: ReplayScanner) -> int:return self._scanner_spend(scanner).credits@@ -418,6 +477,17 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modedef get_observations_this_month(self, scanner: ReplayScanner) -> int:return self._scanner_spend(scanner).observations+ @extend_schema_field(serializers.IntegerField())+ def get_credits_used_against_limit(self, scanner: ReplayScanner) -> int:+ return self._scanner_budget(scanner).credits_used++ @extend_schema_field(serializers.BooleanField())+ def get_limit_reached(self, scanner: ReplayScanner) -> bool:+ # `blocked`, not `exhausted`: the enforcement gates admit an observation only when its full cost+ # fits, so a scanner with under one observation of headroom is already stopped. Reporting+ # `exhausted` here would tell the user a blocked scanner is fine.+ return self._scanner_budget(scanner).blocked+def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:# Surface the (team_id, name) uniqueness as a 400 instead of letting the DB raise 500.name = attrs.get("name")diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 661ec36ba277..787b6eaf1de0 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -4,7 +4,9 @@ from typing import Anyfrom posthog.test.base import APIBaseTest, ClickhouseTestMixinfrom unittest.mock import MagicMock, patch+from django.db import connectionfrom django.test import SimpleTestCase, override_settings+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom parameterized import parameterized@@ -15,6 +17,7 @@ from posthog.models.utils import generate_random_token_personal, hash_key_value,from posthog.redis import get_clientfrom posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary+from products.replay_vision.backend.api.scanners import ReplayScannerSerializerfrom products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_apply_scanner_workflowfrom products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.digest import SCANNER_DIGEST_RRULE@@ -418,6 +421,18 @@ class TestReplayScannerViewSet(_VisionAPITestCase):)self.assertEqual(resp.status_code, 200, resp.json())+ def test_patching_the_credit_limit_persists_and_rejects_zero(self) -> None:+ scanner = self._create_scanner()+ url = f"{self.scanners_url}{scanner.id}/"++ resp = self.client.patch(url, data={"credit_limit": 500}, format="json")+ self.assertEqual(resp.status_code, 200, resp.json())+ scanner.refresh_from_db()+ self.assertEqual(scanner.credit_limit, 500)++ resp = self.client.patch(url, data={"credit_limit": 0}, format="json")+ self.assertEqual(resp.status_code, 400, resp.json())+def test_create_accepts_valid_query(self) -> None:resp = self.client.post(self.scanners_url,@@ -3049,6 +3064,90 @@ class TestScannerSpend(_VisionAPITestCase):self.assertEqual(resp.status_code, 200, resp.json())self.assertEqual(self._credits_by_name(resp.json())["spender"], observation_credits_for_model(spender.model))+ def _spend_against_limit(self, scanner: ReplayScanner, session_id: str) -> None:+ """Ledger spend, which is what the limit is enforced on. `_succeeded_observation` deliberately+ writes no receipt, because it seeds the displayed column, which reads observation rows."""+ observation = self._succeeded_observation(scanner, session_id)+ ReplayObservationUsage.objects.create(+ observation_id=observation.id,+ organization_id=self.team.organization_id,+ team_id=self.team.pk,+ scanner_id=scanner.id,+ observation_created_at=observation.created_at,+ model=scanner.model,+ credits=observation_credits_for_model(scanner.model),+ )++ def test_limit_reached_is_reported_per_scanner(self) -> None:+ scanner = self._create_scanner()+ cost = observation_credits_for_model(scanner.model)+ ReplayScanner.objects.filter(pk=scanner.pk).update(credit_limit=cost)++ resp = self.client.get(f"{self.scanners_url}{scanner.id}/")+ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertIs(resp.json()["limit_reached"], False)++ self._spend_against_limit(scanner, "over-limit")++ resp = self.client.get(f"{self.scanners_url}{scanner.id}/")+ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertIs(resp.json()["limit_reached"], True)+ self.assertEqual(resp.json()["credits_used_against_limit"], cost)++ def test_limit_fields_are_per_row_on_the_list_endpoint(self) -> None:+ # The page's budgets are computed once and cached on the shared serializer context, so a lookup+ # keyed on the wrong scanner would give every row the first row's answer.+ capped = self._create_scanner(name="capped")+ self._create_scanner(name="uncapped")+ cost = observation_credits_for_model(capped.model)+ ReplayScanner.objects.filter(pk=capped.pk).update(credit_limit=cost)+ self._spend_against_limit(capped, "capped-spend")++ resp = self.client.get(self.scanners_url)+ self.assertEqual(resp.status_code, 200, resp.json())+ by_name = {row["name"]: row for row in resp.json()["results"]}+ self.assertIs(by_name["capped"]["limit_reached"], True)+ self.assertIs(by_name["uncapped"]["limit_reached"], False)+ self.assertEqual(by_name["capped"]["credits_used_against_limit"], cost)+ self.assertEqual(by_name["uncapped"]["credits_used_against_limit"], 0)++ def test_limit_below_one_observation_reports_reached_before_any_spend(self) -> None:+ # `limit_reached` answers "can this scanner run again", not "has it spent its limit". A cap+ # smaller than one observation blocks the scanner immediately, and the UI must say so.+ scanner = self._create_scanner()+ ReplayScanner.objects.filter(pk=scanner.pk).update(+ credit_limit=observation_credits_for_model(scanner.model) - 1+ )++ resp = self.client.get(f"{self.scanners_url}{scanner.id}/")+ self.assertEqual(resp.status_code, 200, resp.json())+ self.assertIs(resp.json()["limit_reached"], True)+ self.assertEqual(resp.json()["credits_used_against_limit"], 0)++ def test_list_endpoint_query_count_does_not_scale_with_page_size(self) -> None:+ # Both spend figures are computed once per page and cached on the shared serializer context.+ # Asserting the count rather than matching SQL text keeps this from breaking on a query refactor+ # that preserves the property, and from passing on an N+1 that happens to be shaped differently.+ one = self._create_scanner(name="scanner-0")+ ReplayScanner.objects.filter(pk=one.pk).update(credit_limit=10_000)+ self._spend_against_limit(one, "seed-0")+ with CaptureQueriesContext(connection) as single_page:+ self.assertEqual(self.client.get(self.scanners_url).status_code, 200)++ for i in range(1, 5):+ extra = self._create_scanner(name=f"scanner-{i}")+ ReplayScanner.objects.filter(pk=extra.pk).update(credit_limit=10_000)+ self._spend_against_limit(extra, f"seed-{i}")+ with CaptureQueriesContext(connection) as five_page:+ self.assertEqual(self.client.get(self.scanners_url).status_code, 200)++ # Only the spend sources are asserted. Other parts of the endpoint may legitimately do per-row+ # work, and matching on table name survives a query refactor that keeps the property.+ def spend_queries(ctx: CaptureQueriesContext) -> int:+ return len([q for q in ctx.captured_queries if "replay_vision_replayobservation" in q["sql"]])++ self.assertEqual(spend_queries(five_page), spend_queries(single_page))+class TestCurrentPeriodBounds(SimpleTestCase):NOW = datetime(2026, 7, 15, 12, 0, tzinfo=UTC)@@ -3080,6 +3179,25 @@ class TestCurrentPeriodBounds(SimpleTestCase):self.assertEqual(_current_period_bounds(organization, self.NOW), BillingPeriod(*expected))+class TestScannerCreditLimitValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("null_is_allowed", None, True),+ ("one_is_allowed", 1, True),+ ("large_is_allowed", 1_000_000, True),+ ("int4_max_is_allowed", 2_147_483_647, True),+ ("zero_is_rejected", 0, False),+ ("negative_is_rejected", -1, False),+ ("over_int4_is_rejected", 2_147_483_648, False),+ ]+ )+ def test_credit_limit_bounds(self, _name: str, limit: int | None, expected_valid: bool) -> None:+ serializer = ReplayScannerSerializer(data={"credit_limit": limit}, partial=True)+ self.assertIs(serializer.is_valid(), expected_valid)+ if not expected_valid:+ self.assertIn("credit_limit", serializer.errors)++@patch("products.replay_vision.backend.api.trigger.async_to_sync")@patch("products.replay_vision.backend.api.trigger.sync_connect")class TestInlineScanAction(_VisionAPITestCase):diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 1183061d9570..7490fb0ad6ef 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -845,6 +845,13 @@ export interface ReplayScannerApi {* * `balanced` - Balanced* * `comprehensive` - Comprehensive */sampling_mode?: SamplingModeEnumApi+ /**+ * Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped.+ * @minimum 1+ * @maximum 2147483647+ * @nullable+ */+ credit_limit?: number | null/** LLM provider. v1 is Google-only.** * `google` - Google */@@ -879,6 +886,10 @@ export interface ReplayScannerApi {readonly credits_this_month: number/** Succeeded observations this scanner produced in the current billing period. */readonly observations_this_month: number+ /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations and running prompt tests, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. */+ readonly credits_used_against_limit: number+ /** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */+ readonly limit_reached: boolean/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at: stringreadonly created_at: string@@ -941,6 +952,13 @@ export interface PatchedReplayScannerApi {* * `balanced` - Balanced* * `comprehensive` - Comprehensive */sampling_mode?: SamplingModeEnumApi+ /**+ * Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped.+ * @minimum 1+ * @maximum 2147483647+ * @nullable+ */+ credit_limit?: number | null/** LLM provider. v1 is Google-only.** * `google` - Google */@@ -975,6 +993,10 @@ export interface PatchedReplayScannerApi {readonly credits_this_month?: number/** Succeeded observations this scanner produced in the current billing period. */readonly observations_this_month?: number+ /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations and running prompt tests, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. */+ readonly credits_used_against_limit?: number+ /** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */+ readonly limit_reached?: boolean/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at?: stringreadonly created_at?: stringdiff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex 6fb97f7db97f..f6ffe3524044 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -412,6 +412,8 @@ export const visionScannersCreateBodyDescriptionMax = 1000export const visionScannersCreateBodySamplingRateMin = 0export const visionScannersCreateBodySamplingRateMax = 1+export const visionScannersCreateBodyCreditLimitMax = 2147483647+export const visionScannersCreateBodyExperimentTargetingOneVariantKeysItemMax = 400export const visionScannersCreateBodyExperimentTargetingOneVariantKeysMax = 50@@ -461,6 +463,14 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.describe('Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive'),+ credit_limit: zod+ .number()+ .min(1)+ .max(visionScannersCreateBodyCreditLimitMax)+ .nullish()+ .describe(+ "Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."+ ),provider: zod.enum(['google']).describe('\* `google` - Google')@@ -522,6 +532,8 @@ export const visionScannersPartialUpdateBodyDescriptionMax = 1000export const visionScannersPartialUpdateBodySamplingRateMin = 0export const visionScannersPartialUpdateBodySamplingRateMax = 1+export const visionScannersPartialUpdateBodyCreditLimitMax = 2147483647+export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysItemMax = 400export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysMax = 50@@ -574,6 +586,14 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.describe('Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive'),+ credit_limit: zod+ .number()+ .min(1)+ .max(visionScannersPartialUpdateBodyCreditLimitMax)+ .nullish()+ .describe(+ "Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."+ ),provider: zod.enum(['google']).describe('\* `google` - Google')diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsxindex 2cd1bb1703ba..c96e2318f9fd 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { IconSparkles } from '@posthog/icons'-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'@@ -28,6 +28,7 @@ import { ScannerRunTab } from './components/ScannerRunTab'import { VisionActionsTab } from './components/VisionActionsTab'import { replayScannerLogic } from './replayScannerLogic'import { ReplayScannerTab, replayScannerSceneLogic } from './replayScannerSceneLogic'+import { LIMIT_REACHED_TOOLTIP } from './scannerCopy'export const scene: SceneExport = {component: ReplayScannerSceneComponent,@@ -56,6 +57,13 @@ export function ReplayScannerSceneComponent(): JSX.Element {<SceneContent><SceneTitleSectionname={scanner.name || 'Untitled scanner'}+ nameSuffix={+ scanner.limit_reached ? (+ <Tooltip title={LIMIT_REACHED_TOOLTIP}>+ <LemonTag type="danger">Limit reached</LemonTag>+ </Tooltip>+ ) : undefined+ }description={scanner.description}resourceType={{ type: 'replay_vision' }}actions={diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex b3b85d0af25c..64cb8672f62b 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -11,8 +11,10 @@ import {LemonSwitch,LemonTable,LemonTabs,+ LemonTag,Link,Spinner,+ Tooltip,} from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'@@ -40,6 +42,7 @@ import { creditsToUsd, formatCreditCount } from '../utils/credits'import { VisionMetrics } from './components/VisionMetrics'import { VisionUsageTab } from './components/VisionUsageTab'import { type ScannersSorting, SCANNERS_PAGE_SIZE, replayScannersLogic } from './replayScannersLogic'+import { LIMIT_REACHED_TOOLTIP } from './scannerCopy'import { ENABLED_OPTIONS, EnabledFilter, SCANNER_TYPE_OPTIONS, ScannerType, ReplayScanner } from './types'const HedgehogXRay = pngHoggie(xRayPng)@@ -169,6 +172,11 @@ export function ReplayScannersScene(): JSX.Element {<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>),sorter: true,diff --git a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsxindex dd8c2b998c1b..d1a7847b706a 100644--- a/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ScannerEditorScene.tsx@@ -100,7 +100,10 @@ export function ScannerEditorSceneComponent(): JSX.Element {self_driving: false,configure: showScannerErrors && !!(scannerValidationErrors?.name || scannerValidationErrors?.scanner_config),triggers:- showScannerErrors && (scannerValidationErrors?.sampling_rate != null || durationValidationError != null),+ showScannerErrors &&+ (scannerValidationErrors?.sampling_rate != null ||+ scannerValidationErrors?.credit_limit != null ||+ durationValidationError != null),}// Validate the current step and move on: submit routes to the next visible step on success.diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsxindex c02659db8457..3617cbed8353 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerBackfillsTab.tsx@@ -20,6 +20,7 @@ import { VisionDocsLink } from '../../components/DocsLink'import type { BackfillStatusEnumApi, ReplayScannerBackfillApi } from '../../generated/api.schemas'import { formatCreditCount, formatCredits } from '../../utils/credits'import { backfillsLogic, isBackfillActive } from '../backfillsLogic'+import { replayScannerLogic } from '../replayScannerLogic'import { ReplayScannerTab } from '../replayScannerSceneLogic'import type { ScannerCreatedBy } from '../types'import { BackfillCostEstimate } from './BackfillCostEstimate'@@ -70,9 +71,25 @@ export function ScannerBackfillsTab({ scannerId }: { scannerId: string }): JSX.EwindowDateTo,} = useValues(logic)const { requestEstimate, createBackfill, cancelBackfill, resumeBackfill, setWindowRange } = useActions(logic)+ const { scanner } = useValues(replayScannerLogic({ id: scannerId }))const activeBackfill = backfills.find(isBackfillActive)+ // A capped or disabled scanner holds its running backfill without changing the row's status, so+ // the row itself has to say why nothing is progressing.+ const runningHold = scanner?.limit_reached+ ? {+ label: "Waiting on the scanner's credit limit",+ tooltip:+ 'The backfill is on hold and resumes when the credit limit resets at the start of the next billing period.',+ }+ : scanner && !scanner.enabled+ ? {+ label: 'Waiting on the scanner to be enabled',+ tooltip: 'The backfill is on hold and resumes when the scanner is enabled again.',+ }+ : null+const estimateWindow = (dateFrom: string | null, dateTo: string | null): void => {setWindowRange(dateFrom, dateTo)requestEstimate(resolveWindowBound(dateFrom, dayjs().subtract(30, 'day')), resolveWindowBound(dateTo, dayjs()))@@ -117,9 +134,16 @@ export function ScannerBackfillsTab({ scannerId }: { scannerId: string }): JSX.Etitle: 'Status',key: 'status',render: (_, backfill) => (- <LemonTag type={BACKFILL_STATUS_TAG[backfill.status].type}>- {BACKFILL_STATUS_TAG[backfill.status].label}- </LemonTag>+ <div className="flex items-center gap-1 flex-wrap">+ <LemonTag type={BACKFILL_STATUS_TAG[backfill.status].type}>+ {BACKFILL_STATUS_TAG[backfill.status].label}+ </LemonTag>+ {backfill.status === 'running' && runningHold && (+ <Tooltip title={runningHold.tooltip}>+ <LemonTag type="warning">{runningHold.label}</LemonTag>+ </Tooltip>+ )}+ </div>),},{diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsxnew file mode 100644index 000000000000..e78d4c11b659--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerCreditLimit.tsx@@ -0,0 +1,98 @@+import { useActions, useValues } from 'kea'++import { LemonCard, LemonInput, 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 { MAX_CREDIT_LIMIT } from '../types'++interface ScannerCreditLimitProps {+ scannerId: string+}++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++ return (+ <LemonField name="credit_limit">+ {() => (+ <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>+ <div className="text-xs text-muted">+ Cap what this scanner spends in a billing period, on top of your organization's limit.+ </div>+ </div>+ <LemonSwitch+ checked={isOn}+ onChange={(checked) =>+ setScannerValues({+ credit_limit_enabled: checked,+ credit_limit: checked ? seedValue : null,+ })+ }+ data-attr="vision-scanner-credit-limit-toggle"+ />+ </div>+ {isOn && (+ <>+ <div className="flex items-center gap-4">+ <div className="w-40">+ <LemonInput+ type="number"+ value={limit ?? undefined}+ onChange={(v) =>+ // The toggle is materialized on edit too, so clearing a loaded limit blocks the save.+ setScannerValues({+ credit_limit_enabled: true,+ credit_limit:+ v == null || !Number.isFinite(v)+ ? null+ : Math.max(1, Math.round(v)),+ })+ }+ min={1}+ max={MAX_CREDIT_LIMIT}+ step={1}+ suffix={<span>credits</span>}+ />+ </div>+ <span className="text-sm text-muted">+ {limit != null && `≈ ${creditsToUsd(limit)} per period`}+ {limit != 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.+ </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.+ </div>+ )+ )}+ <div className="text-xs text-muted">+ When this scanner reaches its limit, it stops scanning until the next billing period. It+ stays enabled, but sessions it skipped this period aren't scanned later, even after you+ raise the limit.+ </div>+ </>+ )}+ </LemonCard>+ )}+ </LemonField>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsxindex 585b24356141..ef111c7a15a9 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerOverview.tsx@@ -7,6 +7,7 @@ import { BarChart } from '@posthog/quill-charts'import { useChartConfig, useChartTheme } from 'lib/charts/hooks'import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { creditsToUsd, formatCreditsRange } from '../../utils/credits'import { replayScannerLogic } from '../replayScannerLogic'import { scannerOverviewLogic } from '../scannerOverviewLogic'import { ScannerType } from '../types'@@ -312,6 +313,38 @@ function ClassifierOverview({ scannerId }: { scannerId: string }): JSX.Element |)}+function CreditLimitOverview({ scannerId }: { scannerId: string }): JSX.Element | null {+ const { creditLimitStats } = useValues(scannerOverviewLogic({ scannerId }))+ if (!creditLimitStats) {+ return null+ }+ const { used, limit, usedPct, limitReached } = creditLimitStats+ return (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <div className="min-w-0">+ <OverviewPanel+ title="Spend against limit"+ subtitle={limitReached ? <LemonTag type="danger">Limit reached</LemonTag> : `${usedPct}%`}+ fill+ >+ <LemonProgress percent={usedPct} strokeColor={limitReached ? 'var(--danger)' : undefined} />+ <div className="text-sm tabular-nums">+ {formatCreditsRange(used, limit)} (≈ {creditsToUsd(limit)} per period)+ </div>+ {limitReached && (+ // The tag can appear below 100%: a scanner stops as soon as what's left can't cover a whole+ // scan, so the copy has to explain that rather than claim the budget is fully spent.+ <div className="text-xs text-muted">+ What's left won't cover another scan, so this scanner has stopped until its limit resets at+ the start of the next billing period. Sessions skipped while capped are not scanned later.+ </div>+ )}+ </OverviewPanel>+ </div>+ </div>+ )+}+function ScorerOverview({ scannerId }: { scannerId: string }): JSX.Element {const { scorerSummary, scorerHistogram, hasActiveOverviewFilters, overviewStatsApiLoading } = useValues(scannerOverviewLogic({ scannerId })@@ -454,6 +487,7 @@ export function ScannerOverview({ scannerId }: { scannerId: string }): JSX.Eleme<div className="flex flex-col gap-4"><ScannerOverviewFilters scannerId={scannerId} />{body}+ <CreditLimitOverview scannerId={scannerId} /></div>)}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsxindex 0511c11476bb..6815e0fcfecf 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx@@ -33,6 +33,7 @@ import { PropertyFilterType, RecordingUniversalFilters, UniversalFiltersGroup }import { clampDurationFilter, durationFilterError, MAX_ACTIVE_LABEL } from '../durationBounds'import { replayScannerLogic } from '../replayScannerLogic'import { SAMPLING_MODE_OPTIONS, SamplingMode } from '../types'+import { ScannerCreditLimit } from './ScannerCreditLimit'import { ScannerQuotaForecast } from './ScannerQuotaForecast'// Mirrors the recordings list taxonomy, including suggested filters so the search bar surfaces them.@@ -340,6 +341,8 @@ export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Eleme}}</LemonField>+ <ScannerCreditLimit scannerId={scannerId} />+<ScannerQuotaForecast scannerId={scannerId} /></div>)diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex cf4b2188d209..f3195531bdeb 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -296,6 +296,18 @@ describe('replayScannerLogic', () => {expect(logic.values.hasUnsavedChanges).toBe(true)})+ it('restores an on-but-empty credit limit across a remount, so the save stays blocked', async () => {+ logic.actions.setScannerValues({ credit_limit_enabled: true, credit_limit: null })+ logic.unmount()+ logic = replayScannerLogic({ id: 'new' })+ logic.mount()+ 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',+ })+ })+it.each([['scannerSaved', () => logic.actions.scannerSaved(logic.values.scanner!)],['startFromTemplate', () => logic.actions.startFromTemplate(null)],@@ -422,6 +434,26 @@ describe('replayScannerLogic', () => {setup: () => logic.actions.setScannerValues({ sampling_rate: 0 }),expectedErrors: { sampling_rate: expect.any(String) },},+ {+ name: 'flags a zero credit limit, which would silently stop the scanner forever',+ setup: () => logic.actions.setScannerValues({ credit_limit: 0 }),+ expectedErrors: { credit_limit: expect.any(String) },+ },+ {+ name: 'flags a negative credit limit',+ setup: () => logic.actions.setScannerValues({ credit_limit: -10 }),+ expectedErrors: { credit_limit: expect.any(String) },+ },+ {+ name: 'flags a credit limit above the API int4 bound, which the server would reject',+ setup: () => logic.actions.setScannerValues({ credit_limit: 2147483648 }),+ expectedErrors: { credit_limit: expect.any(String) },+ },+ {+ name: 'flags the limit toggled on but left empty, so it cannot silently save as unlimited',+ setup: () => logic.actions.setScannerValues({ credit_limit_enabled: true, credit_limit: null }),+ expectedErrors: { credit_limit: expect.any(String) },+ },{name: 'flags scorer scale when min >= max',setup: () => {@@ -522,6 +554,141 @@ describe('replayScannerLogic', () => {isScannerValid: true,})})++ // 2147483647 is the API's int4 bound, the highest value the server accepts.+ it.each([null, 1, 500, 2147483647])(+ 'accepts a credit limit of %p, including the unlimited default',+ async (limit) => {+ logic.actions.setScannerValues({ credit_limit: limit })+ await expectLogic(logic).toMatchValues({+ scannerValidationErrors: expect.objectContaining({ credit_limit: undefined }),+ })+ }+ )+ })++ describe('creditLimitState', () => {+ const estimate = (perMonth: number | null, perObservation = 15): void => {+ logic.actions.loadScannerEstimateSuccess({+ estimated_credits_per_month: perMonth,+ credits_per_observation: perObservation,+ } as any)+ }++ it('decodes null as limit off', async () => {+ logic.actions.setScannerValues({ credit_limit: null })+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({ limit: null, isOn: false }),+ })+ })++ it('keeps the toggle on while the amount is still empty, which blocks the save', async () => {+ logic.actions.setScannerValues({ credit_limit_enabled: true, credit_limit: null })+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({ limit: null, isOn: true }),+ })+ })++ it('derives the toggle for scanners that never carried the form-only field', async () => {+ // API-loaded scanners have no credit_limit_enabled; a set limit must still present as on.+ logic.actions.setScannerValues({ credit_limit_enabled: undefined, credit_limit: 250 })+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({ limit: 250, isOn: true }),+ })+ })++ it('seeds the field with double the forecast when one exists', async () => {+ estimate(100)+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({ seedValue: 200 }),+ })+ })++ it('seeds at least one credit for a tiny but non-zero forecast', async () => {+ estimate(0.3)+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({ seedValue: 1 }),+ })+ })++ it.each([+ ['no estimate', null],+ ['a zero estimate, which must not seed a 1-credit cap', 0],+ ])('leaves the field empty with %s', async (_name, perMonth) => {+ estimate(perMonth as number | null)+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({ seedValue: null }),+ })+ })++ 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 })+ await expectLogic(logic).toMatchValues({+ creditLimitState: expect.objectContaining({+ limit: 10,+ isOn: true,+ isBelowEstimate: true,+ cannotAffordOneScan: true,+ }),+ })+ })+ })++ describe('credit limit on a loaded scanner', () => {+ // API scanners never carry the form-only credit_limit_enabled field.+ const loadedScanner = {+ id: 'limited-1',+ name: 'Limited scanner',+ enabled: true,+ scanner_type: 'monitor',+ scanner_config: { prompt: 'Anything odd?' },+ sampling_rate: 1,+ credit_limit: 500,+ }+ let editLogic: ReturnType<typeof replayScannerLogic.build>++ beforeEach(() => {+ useMocks({+ get: { '/api/projects/:team/vision/scanners/:id/': () => [200, loadedScanner] },+ })+ editLogic = replayScannerLogic({ id: 'limited-1' })+ editLogic.mount()+ })++ afterEach(() => {+ editLogic?.unmount()+ })++ it('blocks the save when the amount is cleared, instead of silently saving as unlimited', async () => {+ await expectLogic(editLogic, () => editLogic.actions.loadScanner()).toFinishAllListeners()+ expect(editLogic.values.scanner.credit_limit_enabled).toBe(true)+ // A bare amount clear, without the toggle write the editor card sends alongside it.+ editLogic.actions.setScannerValues({ credit_limit: null })+ 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',+ }),+ })+ })++ it('strips the form-only toggle from the update payload', async () => {+ let patchedBody: any+ useMocks({+ patch: {+ '/api/projects/:team/vision/scanners/:id/': async ({ request }: { request: Request }) => {+ patchedBody = await request.json()+ return [200, loadedScanner]+ },+ },+ })+ await expectLogic(editLogic, () => editLogic.actions.loadScanner()).toFinishAllListeners()+ editLogic.actions.setScannerValues({ credit_limit_enabled: true, credit_limit: 100 })+ await expectLogic(editLogic, () => editLogic.actions.submitScanner()).toDispatchActions(['scannerSaved'])+ expect(patchedBody.credit_limit).toBe(100)+ expect(patchedBody).not.toHaveProperty('credit_limit_enabled')+ })})describe('buildObservationListParams', () => {diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.tsindex a5c81b366f0a..cd13fe1ccf35 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -78,7 +78,9 @@ import type { ObservationStatusStats } from './scannerStats'import { availableTagsFromStats, daysFromDateRange, deriveObservationStatusStats } from './scannerStats'import { findScannerTemplate, newScanner } from './scannerTemplates'import {+ MAX_CREDIT_LIMIT,ScannerConfig,+ ScannerFormValues,ScannerType,ReplayScanner,scannerFromApi,@@ -256,6 +258,22 @@ export function buildObservationListParams(return params}+// Multiplier applied to the forecast when seeding a fresh limit, so a limit set from the suggestion+// doesn't bind on ordinary month-to-month variance.+const CREDIT_LIMIT_SEED_HEADROOM = 2++export interface CreditLimitState {+ /** The limit in credits, or null when the field is empty or the limit is off. */+ limit: number | null+ isOn: boolean+ estimatedMonthly: number | null+ creditsPerObservation: number | null+ isBelowEstimate: boolean+ cannotAffordOneScan: boolean+ /** What to put in the field when the user switches the limit on; null leaves it empty. */+ seedValue: number | null+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface replayScannerLogicValues {affectedCohort: {@@ -266,6 +284,7 @@ export interface replayScannerLogicValues {chartDateFrom: string | nullchartDateTo: string | nullcopyingAllObservations: boolean+ creditLimitState: CreditLimitStatedurationValidationError: string | nullestimateRequestVersion: numberexperimentContext: ExperimentScannerContext | null@@ -295,15 +314,15 @@ export interface replayScannerLogicValues {observationsSort: ObservationsSorting | nullobservationsTotal: numberonDemandObservationSuccessCount: number- originalScanner: ReplayScanner | null+ originalScanner: ScannerFormValues | nullpollUntil: numberretryingObservationIds: string[]savingCohortTag: string | null- scanner: ReplayScanner+ scanner: ScannerFormValuesscannerAllErrors: Record<string, any>scannerChanged: booleanscannerDraftSavedAt: number | null- scannerErrors: DeepPartialMap<ReplayScanner, ValidationErrorType>+ scannerErrors: DeepPartialMap<ScannerFormValues, ValidationErrorType>scannerEstimate: EstimateResponseApi | nullscannerEstimateError: string | nullscannerEstimateLoading: boolean@@ -312,7 +331,7 @@ export interface replayScannerLogicValues {scannerManualErrors: Record<string, any>scannerTouched: booleanscannerTouches: Record<string, boolean>- scannerValidationErrors: DeepPartialMap<ReplayScanner, ValidationErrorType>+ scannerValidationErrors: DeepPartialMap<ScannerFormValues, ValidationErrorType>showScannerErrors: booleansidePanelContext: SidePanelSceneContext | nullsubmitIntent: 'advance' | 'save'@@ -385,8 +404,8 @@ export interface replayScannerLogicActions {loadScannerFailure: () => {value: true}- loadScannerSuccess: (scanner: ReplayScanner) => {- scanner: ReplayScanner+ loadScannerSuccess: (scanner: ScannerFormValues) => {+ scanner: ScannerFormValues}loadTagSuggestions: () => anyloadTagSuggestionsFailure: (@@ -409,8 +428,8 @@ export interface replayScannerLogicActions {requestScannerEstimate: () => {value: true}- resetScanner: (values?: ReplayScanner) => {- values?: ReplayScanner+ resetScanner: (values?: ScannerFormValues) => {+ values?: ScannerFormValues}restoreObservationsTableState: (state: {backfillId: string | null@@ -473,8 +492,8 @@ export interface replayScannerLogicActions {tag: string | undefined}}- scannerSaved: (scanner: ReplayScanner) => {- scanner: ReplayScanner+ scannerSaved: (scanner: ScannerFormValues) => {+ scanner: ScannerFormValues}setChartDateRange: (dateFrom: string | null,@@ -540,8 +559,8 @@ export interface replayScannerLogicActions {name: FieldNamevalue: any}- setScannerValues: (values: DeepPartial<ReplayScanner>) => {- values: DeepPartial<ReplayScanner>+ setScannerValues: (values: DeepPartial<ScannerFormValues>) => {+ values: DeepPartial<ScannerFormValues>}setSubmitIntent: (intent: 'advance' | 'save') => {intent: 'advance' | 'save'@@ -559,11 +578,11 @@ export interface replayScannerLogicActions {error: Errorerrors: Record<string, any>}- submitScannerRequest: (scanner: ReplayScanner) => {- scanner: ReplayScanner+ submitScannerRequest: (scanner: ScannerFormValues) => {+ scanner: ScannerFormValues}- submitScannerSuccess: (scanner: ReplayScanner) => {- scanner: ReplayScanner+ submitScannerSuccess: (scanner: ScannerFormValues) => {+ scanner: ScannerFormValues}toggleEnabled: () => {value: true@@ -597,8 +616,8 @@ export interface replayScannerLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {isNew: (id: string) => boolean- durationValidationError: (scanner: ReplayScanner) => string | null- hasUnsavedChanges: (scanner: ReplayScanner, originalScanner: ReplayScanner | null) => boolean+ durationValidationError: (scanner: ScannerFormValues) => string | null+ hasUnsavedChanges: (scanner: ScannerFormValues, originalScanner: ScannerFormValues | null) => booleanhasObservationsInFlight: (observationStatsApi: ObservationStatsApi | null) => booleanhasActiveObservationFilters: (observationStatusFilter: ObservationStatusEnumApi[],@@ -624,11 +643,12 @@ export interface replayScannerLogicMeta {observationDateTo: string | null,observationBackfillFilter: string | null,observationsSort: ObservationsSorting | null,- scanner: ReplayScanner+ scanner: ScannerFormValues) => Record<string, number | string>availableTags: (observationStatsApi: ObservationStatsApi | null) => string[]observationStats: (observationStatsApi: ObservationStatsApi | null) => ObservationStatusStats- sidePanelContext: (scanner: ReplayScanner, isNew: boolean) => SidePanelSceneContext | null+ sidePanelContext: (scanner: ScannerFormValues, isNew: boolean) => SidePanelSceneContext | null+ creditLimitState: (scanner: ScannerFormValues, scannerEstimate: EstimateResponseApi | null) => CreditLimitState}}@@ -646,7 +666,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([actions({loadScanner: true,- loadScannerSuccess: (scanner: ReplayScanner) => ({ scanner }),+ loadScannerSuccess: (scanner: ScannerFormValues) => ({ scanner }),loadScannerFailure: true,setExperimentContext: (context: ExperimentScannerContext | null) => ({ context }),saveAffectedCohort: (tag?: string) => ({ tag }),@@ -656,7 +676,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([setScannerDraftSavedAt: (savedAt: number | null) => ({ savedAt }),setSubmitIntent: (intent: 'save' | 'advance') => ({ intent }),// Fired only after an actual API write, unlike submitScannerSuccess (which the advance path emits too).- scannerSaved: (scanner: ReplayScanner) => ({ scanner }),+ scannerSaved: (scanner: ScannerFormValues) => ({ scanner }),appendClassifierTags: (tags: string[]) => ({ tags }),acceptTagSuggestion: (tag: string) => ({ tag }),acceptAllTagSuggestions: true,@@ -715,7 +735,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([forms(({ props, values, actions }) => ({scanner: {defaults: newScanner(props.id === 'new' ? currentTemplateKey() : null),- errors: (scanner: ReplayScanner) => {+ errors: (scanner: ScannerFormValues) => {+ // API-loaded scanners never carry the UI-only toggle, so fall back to whether a limit is set.+ const creditLimitEnabled = scanner.credit_limit_enabled ?? scanner.credit_limit != nullconst configErrors: Record<string, string | undefined> = {}if (!scanner.scanner_config?.prompt?.trim()) {configErrors.prompt = 'Prompt is required'@@ -749,10 +771,20 @@ export const replayScannerLogic = kea<replayScannerLogicType>([scanner.sampling_rate > 0 && scanner.sampling_rate <= 1? undefined: 'Sampling rate must be between 0% and 100%',+ 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'+ : 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()}`,scanner_config: Object.keys(configErrors).length > 0 ? configErrors : undefined,}},- submit: async (scanner: ReplayScanner) => {+ submit: async (scanner: ScannerFormValues) => {// Advance to the next visible step instead of persisting, when the footer asked to (intent// 'advance') or a new scanner submitted mid-wizard via Enter on any non-final step.const steps = scannerEditorSceneLogic.findMounted()?.values.visibleSteps ?? SCANNER_EDITOR_STEPS@@ -767,7 +799,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([if (!teamId) {return}- const body = scanner.query == null ? omitQuery(scanner) : scanner+ // credit_limit_enabled is UI-only form state; the API payload carries only credit_limit itself.+ const { credit_limit_enabled: _creditLimitEnabled, ...apiScanner } = scanner+ const body = apiScanner.query == null ? omitQuery(apiScanner) : apiScannertry {if (props.id === 'new') {const response = await visionScannersCreate(String(teamId), scannerToApiBody(body))@@ -880,7 +914,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([},],originalScanner: [- null as ReplayScanner | null,+ null as ScannerFormValues | null,{loadScannerSuccess: (_, { scanner }) => scanner,// Keyed on the real save, not submitScannerSuccess — kea-forms fires that on the no-API advance path too.@@ -1264,6 +1298,33 @@ export const replayScannerLogic = kea<replayScannerLogicType>([: null},],+ // The toggle lives in the UI-only `credit_limit_enabled` field; scanners straight from the API+ // 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 => {+ const limit = typeof scanner?.credit_limit === 'number' ? scanner.credit_limit : null+ const estimatedMonthly = estimate?.estimated_credits_per_month ?? null+ const creditsPerObservation = estimate?.credits_per_observation ?? null+ return {+ limit,+ isOn: scanner?.credit_limit_enabled ?? limit !== null,+ estimatedMonthly,+ 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+ // the moment it is saved.+ cannotAffordOneScan:+ limit !== null && creditsPerObservation !== null && limit < creditsPerObservation,+ // 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))+ : null,+ }+ },+ ],}),listeners(({ actions, props, values, cache }) => {@@ -1390,7 +1451,10 @@ export const replayScannerLogic = kea<replayScannerLogicType>([}try {const response = await visionScannersRetrieve(String(teamId), props.id)- actions.loadScannerSuccess(scannerFromApi(response))+ const scanner = scannerFromApi(response)+ // The API never carries the UI-only toggle; materialize it so clearing a loaded limit+ // still blocks the save instead of silently saving as unlimited.+ actions.loadScannerSuccess({ ...scanner, credit_limit_enabled: scanner.credit_limit != null })} catch (error: any) {lemonToast.error(`Failed to load scanner${error.detail ? `: ${error.detail}` : ''}`)actions.loadScannerFailure()@@ -1418,7 +1482,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([...current,scanner_type: scannerType,scanner_config: defaultConfigForType(scannerType),- } as ReplayScanner)+ } as ScannerFormValues)persistDraft()},diff --git a/products/replay_vision/frontend/replay_scanners/scannerCopy.ts b/products/replay_vision/frontend/replay_scanners/scannerCopy.tsnew file mode 100644index 000000000000..bf5dceeafe1d--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerCopy.ts@@ -0,0 +1,4 @@+/** Shared by every "Limit reached" badge so the surfaces tell one story. */+export 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.'diff --git a/products/replay_vision/frontend/replay_scanners/scannerDraft.test.ts b/products/replay_vision/frontend/replay_scanners/scannerDraft.test.tsindex 62fedaa047ae..c5bca456dcc3 100644--- a/products/replay_vision/frontend/replay_scanners/scannerDraft.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerDraft.test.ts@@ -32,4 +32,25 @@ describe('scannerDraft', () => {localStorage.setItem(STORAGE_KEY, typeof tampered === 'string' ? tampered : JSON.stringify(tampered))expect(readScannerDraft(readTeamId)?.scanner.name ?? null).toBe(expectRestored ? 'Drafted scanner' : null)})++ it('keeps the credit limit toggle on across the round trip while the amount is still empty', () => {+ const scanner = { ...newScanner(null), credit_limit_enabled: true, credit_limit: null }+ writeScannerDraft(1, scanner)+ const restored = readScannerDraft(1)?.scanner+ expect(restored?.credit_limit_enabled).toBe(true)+ expect(restored?.credit_limit).toBeNull()+ })++ it('restores a concrete credit limit as-is', () => {+ const scanner = { ...newScanner(null), credit_limit: 500 }+ writeScannerDraft(1, scanner)+ expect(readScannerDraft(1)?.scanner.credit_limit).toBe(500)+ })++ it('still restores an old draft carrying the retired empty-but-enabled marker', () => {+ writeScannerDraft(1, { ...newScanner(null), name: 'Old draft' })+ const stored = JSON.parse(localStorage.getItem(STORAGE_KEY)!)+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ ...stored, creditLimitEmptyButEnabled: true }))+ expect(readScannerDraft(1)?.scanner.name).toBe('Old draft')+ })})diff --git a/products/replay_vision/frontend/replay_scanners/scannerDraft.ts b/products/replay_vision/frontend/replay_scanners/scannerDraft.tsindex f498caa74fcf..44543d111ccf 100644--- a/products/replay_vision/frontend/replay_scanners/scannerDraft.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerDraft.ts@@ -1,4 +1,4 @@-import { ReplayScanner } from './types'+import { ScannerFormValues } from './types'const DRAFT_STORAGE_KEY = 'replay-vision.new-scanner-draft'const DRAFT_VERSION = 1@@ -8,17 +8,22 @@ interface StoredScannerDraft {version: numberteamId: numbersavedAt: number- scanner: ReplayScanner+ scanner: ScannerFormValues}export interface ScannerDraft {- scanner: ReplayScanner+ scanner: ScannerFormValuessavedAt: number}-export function writeScannerDraft(teamId: number, scanner: ReplayScanner): number | null {+export function writeScannerDraft(teamId: number, scanner: ScannerFormValues): number | null {const savedAt = Date.now()- const draft: StoredScannerDraft = { version: DRAFT_VERSION, teamId, savedAt, scanner }+ const draft: StoredScannerDraft = {+ version: DRAFT_VERSION,+ teamId,+ savedAt,+ scanner,+ }try {localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(draft))return savedAtdiff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.tsindex 8877014f9e15..9120c5d5901d 100644--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.test.ts@@ -5,7 +5,19 @@ import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'-import { scannerEditorSceneLogic } from './scannerEditorSceneLogic'+import { firstErroredScannerStep, scannerEditorSceneLogic } from './scannerEditorSceneLogic'++describe('firstErroredScannerStep', () => {+ it.each([+ ['name error lands on configure', { name: 'Required' }, 'configure'],+ ['config error lands on configure', { scanner_config: { prompt: 'Required' } }, 'configure'],+ ['sampling error lands on triggers', { sampling_rate: 'Out of range' }, 'triggers'],+ ['credit limit error lands on triggers', { credit_limit: 'Enter a credit amount' }, 'triggers'],+ ['no errors maps nowhere', {}, null],+ ])('%s', (_label, errors, expected) => {+ expect(firstErroredScannerStep(errors)).toBe(expected)+ })+})describe('scannerEditorSceneLogic', () => {let logic: ReturnType<typeof scannerEditorSceneLogic.build>diff --git a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.tsindex 8e7ec61773db..9afc9dee69f5 100644--- a/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerEditorSceneLogic.ts@@ -19,11 +19,12 @@ export function firstErroredScannerStep(errors: {name?: unknownscanner_config?: unknownsampling_rate?: unknown+ credit_limit?: unknown}): ScannerEditorStep | null {if (errors.name || errors.scanner_config) {return 'configure'}- if (errors.sampling_rate) {+ if (errors.sampling_rate || errors.credit_limit) {return 'triggers'}return nulldiff --git a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.tsindex 65f3fc914b6c..09937ca8b884 100644--- a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.test.ts@@ -110,6 +110,40 @@ describe('scannerOverviewLogic', () => {expect(logic.values.hasActiveOverviewFilters).toBe(false)})+ describe('creditLimitStats', () => {+ it('is null when the scanner has no limit, so callers render no panel instead of "0% of 0"', async () => {+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.creditLimitStats).toBeNull()+ })++ it.each([+ { used: 200, limit: 1000, expectedPct: 20, expectedReached: false },+ { used: 1000, limit: 1000, expectedPct: 100, expectedReached: true },+ { used: 1200, limit: 1000, expectedPct: 100, expectedReached: true },+ // The server reports reached as soon as what's left can't cover one more scan, so this+ // must come from the API and not be re-derived from usedPct.+ { used: 990, limit: 1000, expectedPct: 99, expectedReached: true },+ ])(+ 'derives usedPct $expectedPct and limitReached $expectedReached from used=$used, limit=$limit',+ async ({ used, limit, expectedPct, expectedReached }) => {+ await expectLogic(logic, () =>+ logic.actions.loadScannerSuccess({+ ...logic.values.scanner,+ credit_limit: limit,+ credits_used_against_limit: used,+ limit_reached: expectedReached,+ })+ ).toFinishAllListeners()+ expect(logic.values.creditLimitStats).toEqual({+ limit,+ used,+ usedPct: expectedPct,+ limitReached: expectedReached,+ })+ }+ )+ })+describe('observationsDrilldownSearchParams', () => {const day = (overrides: object = {}): Parameters<typeof observationsDrilldownSearchParams>[0] => ({day: '2026-05-04',diff --git a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.tsindex 0bf2b6050525..e55e1caded7a 100644--- a/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerOverviewLogic.ts@@ -45,6 +45,7 @@ import {deriveSummarizerFacetStats,} from './scannerStats'import type { ReplayScanner, ScannerType } from './types'+import type { ScannerFormValues } from './types'export interface ScannerOverviewLogicProps {scannerId: string@@ -52,6 +53,13 @@ export interface ScannerOverviewLogicProps {const DEFAULT_DATE_FROM = '-14d'+export interface CreditLimitStats {+ limit: number+ used: number+ usedPct: number+ limitReached: boolean+}+/** The bucket size of the Overview charts; the drill-down only knows how to map day buckets onto the Observations tab. */export const OVERVIEW_CHART_INTERVAL: IntervalType = 'day'@@ -86,10 +94,11 @@ export function observationsDrilldownSearchParams(options: {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scannerOverviewLogicValues {- scanner: ReplayScanner // replayScannerLogic+ scanner: ScannerFormValues // replayScannerLogicavailableTags: string[]classifierTagStats: ClassifierTagStatscoverageStats: CoverageStats+ creditLimitStats: CreditLimitStats | nullhasActiveOverviewFilters: booleanmonitorStats: MonitorStatsoverviewDateFrom: string | null@@ -107,8 +116,8 @@ export interface scannerOverviewLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface scannerOverviewLogicActions {- loadScannerSuccess: (scanner: ReplayScanner) => {- scanner: ReplayScanner+ loadScannerSuccess: (scanner: ScannerFormValues) => {+ scanner: ScannerFormValues} // replayScannerLogicclearOverviewFilters: () => {value: true@@ -176,6 +185,7 @@ export interface scannerOverviewLogicMeta {scorerHistogram: (overviewStatsApi: ObservationStatsApi | null) => ScorerHistogram | nullsummarizerFacetStats: (overviewStatsApi: ObservationStatsApi | null) => SummarizerFacetStatscoverageStats: (overviewStatsApi: ObservationStatsApi | null) => CoverageStats+ creditLimitStats: (scanner: ScannerFormValues) => CreditLimitStats | null}}@@ -304,6 +314,25 @@ export const scannerOverviewLogic = kea<scannerOverviewLogicType>([(s) => [s.overviewStatsApi],(stats: ObservationStatsApi | null): CoverageStats => deriveCoverageStats(stats),],+ // Null when the scanner has no limit set, so callers can render nothing rather than a "0% of 0" panel.+ creditLimitStats: [+ (s) => [s.scanner],+ (scanner: ReplayScanner): CreditLimitStats | null => {+ const limit = scanner.credit_limit+ 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,+ // Comes from the API, not from usedPct: a scanner stops as soon as what's left can't+ // cover another scan, so this can be true below 100%.+ limitReached: !!scanner.limit_reached,+ }+ },+ ],}),loaders(({ props, values }) => ({diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.tsindex 9acfaeb098e3..7a3bd796a8a8 100644--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts@@ -5,7 +5,7 @@ import { NodeKind } from '~/queries/schema/schema-general'import type {ClassifierScannerConfig,MonitorScannerConfig,- ReplayScanner,+ ScannerFormValues,ScorerScannerConfig,SummarizerScannerConfig,} from './types'@@ -120,7 +120,7 @@ export function findScannerTemplate(key: string | undefined): ScannerTemplate |return defaultScannerTemplates.find((t) => t.key === key)}-export function newScanner(templateKey?: string | null): ReplayScanner {+export function newScanner(templateKey?: string | null): ScannerFormValues {const base = {id: 'new',enabled: true,@@ -145,6 +145,12 @@ export function newScanner(templateKey?: string | null): ReplayScanner {user_access_level: null,credits_this_month: 0,observations_this_month: 0,+ credit_limit: null,+ // Materialized here so toggling the limit on and off compares equal to this baseline again.+ credit_limit_enabled: 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_reached: false,} as constconst template = findScannerTemplate(templateKey ?? undefined)@@ -156,7 +162,7 @@ export function newScanner(templateKey?: string | null): ReplayScanner {scanner_type: template.scanner_type,// Cloned so an in-place form mutation can never corrupt the module-level template.scanner_config: structuredClone(template.scanner_config),- } as ReplayScanner+ } as ScannerFormValues}return {...base,diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex 8d1ddecd64b6..c5543e2e5822 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -403,7 +403,7 @@ export type BaseReplayScanner = Omit<ReplayScannerApi,'scanner_type' | 'scanner_config' | 'query' | 'created_by' | 'user_access_level'> &- Required<Pick<ReplayScannerApi, 'sampling_rate' | 'enabled' | 'emits_signals' | 'provider'>> & {+ Required<Pick<ReplayScannerApi, 'sampling_rate' | 'enabled' | 'emits_signals' | 'provider' | 'credit_limit'>> & {query: RecordingsQuery | nullcreated_by: ScannerCreatedBy | nullsampling_mode: SamplingMode@@ -432,6 +432,13 @@ export interface ScorerScanner extends BaseReplayScanner {export type ReplayScanner = MonitorScanner | SummarizerScanner | ClassifierScanner | ScorerScanner+// The editor form's values: the API scanner plus UI-only state that is stripped before every API write.+// `credit_limit_enabled` keeps "limit toggle on, amount still empty" representable so it can block the save.+export type ScannerFormValues = ReplayScanner & { credit_limit_enabled?: boolean }++// Mirrors the API's int4 bound on credit_limit (visionScannersCreateBodyCreditLimitMax in generated/api.zod.ts).+export const MAX_CREDIT_LIMIT = 2147483647+/** Narrow a snapshot's untyped scanner_config at one boundary; pair with the snapshot's scanner_type to pick the variant. */export function configFromSnapshot(snapshot: { scanner_config?: unknown } | null | undefined): ScannerConfig | null {const config = snapshot?.scanner_configdiff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 05f1baf8d794..323b4b57b0ac 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -326,14 +326,16 @@ tools:scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call`vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to checkthe org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation- itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Creating a- scanner also creates its built-in daily digest: an enabled vision action with no delivery targets that- synthesizes the scanner's observations once a day and spends credits of its own, on top of the observations.- Disable or delete it with `vision-actions-update` / `vision-actions-delete` if you don't want it. To get- notified about what the scanner finds (a Slack alert or a summary on another schedule), create a further- vision action bound to it with `vision-actions-create`. For a scanner scoped to one experiment's exposed- sessions, load the `scanning-experiments-with-replay-vision` skill first — it derives the query from the- experiment's exposure criteria.+ itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Set+ `credit_limit` to cap what this one scanner can spend per billing period, so it cannot starve the org's+ other scanners. The scanner stops scanning once the credits left cannot cover another observation, and+ resumes when the period resets. Creating a scanner also creates its built-in daily digest: an enabled vision+ action with no delivery targets that synthesizes the scanner's observations once a day and spends credits of+ its own, on top of the observations. Disable or delete it with `vision-actions-update` /+ `vision-actions-delete` if you don't want it. To get notified about what the scanner finds (a Slack alert or+ a summary on another schedule), create a further vision action bound to it with `vision-actions-create`. For+ a scanner scoped to one experiment's exposed sessions, load the `scanning-experiments-with-replay-vision`+ skill first — it derives the query from the experiment's exposure criteria.exclude_params:- id- scanner_versiondiff --git a/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md b/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.mdindex b3696865a5ec..692d0c2acf3e 100644--- a/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md+++ b/products/replay_vision/skills/creating-replay-vision-scanners/SKILL.md@@ -121,6 +121,10 @@ Then decide on `rest_of_period` against `remaining`:one resets. Mid-period a scanner can fit in `remaining` and still blow the next period's budget.- If the org is already `exhausted`, say so. A new enabled scanner won't produce anything until the budgetresets: its scheduled observations are silently skipped, and on-demand scans are rejected outright.+- If the estimate is a large fraction of `remaining` but the user still wants the scanner, offer a+ per-scanner cap: set `credit_limit` on create so this scanner can only ever spend that many credits per+ billing period. It stops scanning once the credits left can't cover another observation, then resumes+ when the period resets. Sessions it skipped while capped are not scanned later.Confirmation here is a conversation step, not an API capability — surface the trade-off and let the userchoose. When the projected volume is clearly small relative to the budget, you don't need to ask.diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 42c8204e5534..d546ec62d93c 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -10587,7 +10587,7 @@}},"vision-scanners-create": {- "description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, always with facet embeddings for search) — and fill `scanner_config` to match: all types need a `prompt`; monitors optionally set `allow_inconclusive`; classifiers also need `tags` (and optionally `multi_label`, `allow_freeform_tags`); scorers also need `scale`; summarizers optionally set `length`. Unknown `scanner_config` keys are rejected. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_mode` is a quality pre-filter over matched sessions (`focused` / `balanced` / `comprehensive`, default `comprehensive`) and `sampling_rate` is a 0..1 random downsample applied after it (default 1.0). `model` chooses the LLM and sets the credit price of every observation. Names must be unique within the team. Before creating a broad scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Creating a scanner also creates its built-in daily digest: an enabled vision action with no delivery targets that synthesizes the scanner's observations once a day and spends credits of its own, on top of the observations. Disable or delete it with `vision-actions-update` / `vision-actions-delete` if you don't want it. To get notified about what the scanner finds (a Slack alert or a summary on another schedule), create a further vision action bound to it with `vision-actions-create`. For a scanner scoped to one experiment's exposed sessions, load the `scanning-experiments-with-replay-vision` skill first — it derives the query from the experiment's exposure criteria.",+ "description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, always with facet embeddings for search) — and fill `scanner_config` to match: all types need a `prompt`; monitors optionally set `allow_inconclusive`; classifiers also need `tags` (and optionally `multi_label`, `allow_freeform_tags`); scorers also need `scale`; summarizers optionally set `length`. Unknown `scanner_config` keys are rejected. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_mode` is a quality pre-filter over matched sessions (`focused` / `balanced` / `comprehensive`, default `comprehensive`) and `sampling_rate` is a 0..1 random downsample applied after it (default 1.0). `model` chooses the LLM and sets the credit price of every observation. Names must be unique within the team. Before creating a broad scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Set `credit_limit` to cap what this one scanner can spend per billing period, so it cannot starve the org's other scanners. The scanner stops scanning once the credits left cannot cover another observation, and resumes when the period resets. Creating a scanner also creates its built-in daily digest: an enabled vision action with no delivery targets that synthesizes the scanner's observations once a day and spends credits of its own, on top of the observations. Disable or delete it with `vision-actions-update` / `vision-actions-delete` if you don't want it. To get notified about what the scanner finds (a Slack alert or a summary on another schedule), create a further vision action bound to it with `vision-actions-create`. For a scanner scoped to one experiment's exposed sessions, load the `scanning-experiments-with-replay-vision` skill first — it derives the query from the experiment's exposure criteria.","category": "Replay vision","feature": "replay_vision","summary": "Create replay vision scanner",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 74d0a5834519..8696b7e32051 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -11201,7 +11201,7 @@}},"vision-scanners-create": {- "description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, always with facet embeddings for search) — and fill `scanner_config` to match: all types need a `prompt`; monitors optionally set `allow_inconclusive`; classifiers also need `tags` (and optionally `multi_label`, `allow_freeform_tags`); scorers also need `scale`; summarizers optionally set `length`. Unknown `scanner_config` keys are rejected. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_mode` is a quality pre-filter over matched sessions (`focused` / `balanced` / `comprehensive`, default `comprehensive`) and `sampling_rate` is a 0..1 random downsample applied after it (default 1.0). `model` chooses the LLM and sets the credit price of every observation. Names must be unique within the team. Before creating a broad scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Creating a scanner also creates its built-in daily digest: an enabled vision action with no delivery targets that synthesizes the scanner's observations once a day and spends credits of its own, on top of the observations. Disable or delete it with `vision-actions-update` / `vision-actions-delete` if you don't want it. To get notified about what the scanner finds (a Slack alert or a summary on another schedule), create a further vision action bound to it with `vision-actions-create`. For a scanner scoped to one experiment's exposed sessions, load the `scanning-experiments-with-replay-vision` skill first — it derives the query from the experiment's exposure criteria.",+ "description": "Create a replay vision scanner. Pick a `scanner_type` — `monitor` (open-ended observations), `classifier` (assign a tag from a fixed label set), `scorer` (numeric rubric), or `summarizer` (free-text summary, always with facet embeddings for search) — and fill `scanner_config` to match: all types need a `prompt`; monitors optionally set `allow_inconclusive`; classifiers also need `tags` (and optionally `multi_label`, `allow_freeform_tags`); scorers also need `scale`; summarizers optionally set `length`. Unknown `scanner_config` keys are rejected. `query` is a `RecordingsQuery` shape that defines which sessions the scanner watches — `date_from` and `date_to` are ignored (the schedule controls time). `sampling_mode` is a quality pre-filter over matched sessions (`focused` / `balanced` / `comprehensive`, default `comprehensive`) and `sampling_rate` is a 0..1 random downsample applied after it (default 1.0). `model` chooses the LLM and sets the credit price of every observation. Names must be unique within the team. Before creating a broad scanner (a permissive `query`, loose `sampling_mode`, and/or high `sampling_rate`), first call `vision-scanners-estimate-create` to project its monthly credit spend and `vision-quota-retrieve` to check the org's remaining budget — an enabled scanner sweeps matching recordings every 5 minutes, and creation itself does not check quota, so a too-broad scanner can exhaust the budget on its first sweeps. Set `credit_limit` to cap what this one scanner can spend per billing period, so it cannot starve the org's other scanners. The scanner stops scanning once the credits left cannot cover another observation, and resumes when the period resets. Creating a scanner also creates its built-in daily digest: an enabled vision action with no delivery targets that synthesizes the scanner's observations once a day and spends credits of its own, on top of the observations. Disable or delete it with `vision-actions-update` / `vision-actions-delete` if you don't want it. To get notified about what the scanner finds (a Slack alert or a summary on another schedule), create a further vision action bound to it with `vision-actions-create`. For a scanner scoped to one experiment's exposed sessions, load the `scanning-experiments-with-replay-vision` skill first — it derives the query from the experiment's exposure criteria.","category": "Replay vision","feature": "replay_vision","summary": "Create replay vision scanner",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d4c4eb20ce75..02d04d16895f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -49564,6 +49564,13 @@ export namespace Schemas {* * `balanced` - Balanced* * `comprehensive` - Comprehensive */sampling_mode?: SamplingModeEnum;+ /**+ * Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped.+ * @minimum 1+ * @maximum 2147483647+ * @nullable+ */+ credit_limit?: number | null;/** LLM provider. v1 is Google-only.** * `google` - Google */@@ -49598,6 +49605,10 @@ export namespace Schemas {readonly credits_this_month: number;/** Succeeded observations this scanner produced in the current billing period. */readonly observations_this_month: number;+ /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations and running prompt tests, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. */+ readonly credits_used_against_limit: number;+ /** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */+ readonly limit_reached: boolean;/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at: string;readonly created_at: string;@@ -58762,6 +58773,13 @@ export namespace Schemas {* * `balanced` - Balanced* * `comprehensive` - Comprehensive */sampling_mode?: SamplingModeEnum;+ /**+ * Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped.+ * @minimum 1+ * @maximum 2147483647+ * @nullable+ */+ credit_limit?: number | null;/** LLM provider. v1 is Google-only.** * `google` - Google */@@ -58796,6 +58814,10 @@ export namespace Schemas {readonly credits_this_month?: number;/** Succeeded observations this scanner produced in the current billing period. */readonly observations_this_month?: number;+ /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations and running prompt tests, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. */+ readonly credits_used_against_limit?: number;+ /** Whether this scanner has stopped because of its own credit limit. True when `credit_limit` is set and the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set. */+ readonly limit_reached?: boolean;/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at?: string;readonly created_at?: string;diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 19dbf659406b..181315e1087d 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -673,6 +673,8 @@ export const visionScannersCreateBodyDescriptionMax = 1000export const visionScannersCreateBodySamplingRateMin = 0export const visionScannersCreateBodySamplingRateMax = 1+export const visionScannersCreateBodyCreditLimitMax = 2147483647+export const visionScannersCreateBodyExperimentTargetingOneVariantKeysItemMax = 400export const visionScannersCreateBodyExperimentTargetingOneVariantKeysMax = 50@@ -722,6 +724,14 @@ export const VisionScannersCreateBody = /* @__PURE__ */ zod.describe('Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive'),+ credit_limit: zod+ .number()+ .min(1)+ .max(visionScannersCreateBodyCreditLimitMax)+ .nullish()+ .describe(+ "Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."+ ),provider: zod.enum(['google']).describe('\* `google` - Google')@@ -804,6 +814,8 @@ export const visionScannersPartialUpdateBodyDescriptionMax = 1000export const visionScannersPartialUpdateBodySamplingRateMin = 0export const visionScannersPartialUpdateBodySamplingRateMax = 1+export const visionScannersPartialUpdateBodyCreditLimitMax = 2147483647+export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysItemMax = 400export const visionScannersPartialUpdateBodyExperimentTargetingOneVariantKeysMax = 50@@ -856,6 +868,14 @@ export const VisionScannersPartialUpdateBody = /* @__PURE__ */ zod.describe('Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).\n\n\* `focused` - Focused\n\* `balanced` - Balanced\n\* `comprehensive` - Comprehensive'),+ credit_limit: zod+ .number()+ .min(1)+ .max(visionScannersPartialUpdateBodyCreditLimitMax)+ .nullish()+ .describe(+ "Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."+ ),provider: zod.enum(['google']).describe('\* `google` - Google')diff --git a/services/mcp/src/tools/generated/replay_vision.ts b/services/mcp/src/tools/generated/replay_vision.tsindex fc6c2cd7aa0b..8073258aaf96 100644--- a/services/mcp/src/tools/generated/replay_vision.ts+++ b/services/mcp/src/tools/generated/replay_vision.ts@@ -439,6 +439,9 @@ const visionScannersCreate = (): ToolBase<typeof VisionScannersCreateSchema, Schif (params.sampling_mode !== undefined) {body['sampling_mode'] = params.sampling_mode}+ if (params.credit_limit !== undefined) {+ body['credit_limit'] = params.credit_limit+ }if (params.provider !== undefined) {body['provider'] = params.provider}@@ -880,6 +883,9 @@ const visionScannersUpdate = (): ToolBase<typeof VisionScannersUpdateSchema, Schif (params.sampling_mode !== undefined) {body['sampling_mode'] = params.sampling_mode}+ if (params.credit_limit !== undefined) {+ body['credit_limit'] = params.credit_limit+ }if (params.provider !== undefined) {body['provider'] = params.provider}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.jsonindex 6038f4177504..a91eaef37ee6 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-create.json@@ -2,6 +2,19 @@"$schema": "https://json-schema.org/draft/2020-12/schema","description": "A Replay Vision scanner: its type, targeting query, and AI configuration.","properties": {+ "credit_limit": {+ "anyOf": [+ {+ "maximum": 2147483647,+ "minimum": 1,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."+ },"description": {"description": "Free-form description shown in the scanner management UI.","maxLength": 1000,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.jsonindex 26487c51ed73..940f58646ab1 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-update.json@@ -1,6 +1,19 @@{"$schema": "https://json-schema.org/draft/2020-12/schema","properties": {+ "credit_limit": {+ "anyOf": [+ {+ "maximum": 2147483647,+ "minimum": 1,+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped."+ },"description": {"description": "Free-form description shown in the scanner management UI.","maxLength": 1000,