: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): redesign the replay vision usage tab (#93145)
Tue Haulundb6bd01755870
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 861218b8b45f..dccf4b17b355 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8285,9 +8285,9 @@ snapshots:scenes-app-replay-vision--summarizer-overview--light:hash: v1.k794b7964.099cc1596e288a869426dec004e0d3e6ae35de1ca2ec7f0264f775911010b0d9.eTbr9P9h5LFG5AtPxCE0tZn7Hxp4GvNnGI9zYmMI86oscenes-app-replay-vision--usage-tab--dark:- hash: v1.k794b7964.ad98efcf3b03420b327b36588d5c1c47c509446d50ab452de9c5859b5a530ea4.6Pn4bDGW95UO7bPpfjNrW0ToWQCQZXaLBy5qCAbOUOA+ hash: v1.k794b7964.9aa134e0143e1f059ee2e74c561f4bf72d3c7544a3c55f9074cc12aa7e6dc748.8olmwH0m-gjI2maBCyIaijGiHuxJa-VSX5OJ4X_Jfkwscenes-app-replay-vision--usage-tab--light:- hash: v1.k794b7964.ffd83813d408db75ccb39b74e28deae6710255f4d6807c2ea488c24236b16306.nkvTTvPdr-SB88WsAuWl0QvFP7yzMwqLjSsvW-0JjYg+ hash: v1.k794b7964.ddf3840ed0acb526be4621462a7475e33e5c7d58f0c92addc61796308743717f.cUngoOKhIwSqpS2Qe22HMpzvtPPT7eaHPrU7In5vNn4scenes-app-saved-insights--empty-state--dark:hash: v1.k794b7964.43545664c9133c8afd354be6a6ed8f808c35b381101325d9605114632fcdc0c9.l8w9uEOEmrH6Xl1kNd9ueRtg_51cJUSjWLdjWDM0Fkoscenes-app-saved-insights--empty-state--light:diff --git a/products/replay_vision/backend/api/quota.py b/products/replay_vision/backend/api/quota.pyindex 6feb1b8d0dc6..5551c3f1a088 100644--- a/products/replay_vision/backend/api/quota.py+++ b/products/replay_vision/backend/api/quota.py@@ -2,13 +2,14 @@ from uuid import UUIDfrom drf_spectacular.utils import extend_schema, extend_schema_serializerfrom rest_framework import serializers, viewsets+from rest_framework.decorators import actionfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin-from products.replay_vision.backend.quota import compute_quota_snapshot+from products.replay_vision.backend.quota import compute_quota_snapshot, daily_spend_series# `many=False` stops drf-spectacular wrapping the response as `VisionQuotaApi[]` for the `list` action.@@ -17,11 +18,31 @@ class VisionQuotaSerializer(serializers.Serializer):credit_limit = serializers.IntegerField(read_only=True,allow_null=True,- help_text="Credits the org may spend per billing period (1 credit = $0.01). Null when billing has synced the product with no spend limit: uncapped.",+ help_text=(+ "Credits the organization may spend per billing period (1 credit = $0.01). "+ "0 is a hard block: no observation can start. Null when billing has synced the product with no spend limit: uncapped."+ ),)credits_used = serializers.IntegerField(read_only=True,- help_text="Credits spent this period: succeeded observations from the receipt ledger plus reserved in-flight observations.",+ help_text=(+ "`credits_settled` plus `credits_reserved`: the organization's total draw on `credit_limit` this period, "+ "across every project."+ ),+ )+ credits_settled = serializers.IntegerField(+ read_only=True,+ help_text=(+ "Credits posted to the receipt ledger by succeeded observations and finished prompt-test sessions this period, "+ "across every project in the organization. Deleting an observation never refunds these."+ ),+ )+ credits_reserved = serializers.IntegerField(+ read_only=True,+ help_text=(+ "Credits held by in-flight observations and running prompt tests across every project in the organization. "+ "Released without charge when the work fails, settled into `credits_settled` when it succeeds."+ ),)remaining = serializers.IntegerField(read_only=True,@@ -51,6 +72,7 @@ class VisionQuotaSerializer(serializers.Serializer):read_only=True,help_text=("Credit-weighted sum of enabled scanners' projected observations/month across the organization. "+ "A capped scanner contributes at most what its own credit limit has left this period, folded back into a 30-day rate. ""A monthly rate: only the part falling in the days left of the period lands this period. ""Scanners without a computed estimate contribute 0."),@@ -71,13 +93,46 @@ class VisionQuotaSerializer(serializers.Serializer):)+class VisionSpendDaySerializer(serializers.Serializer):+ date = serializers.DateField(read_only=True, help_text="UTC calendar day.")+ credits = serializers.IntegerField(+ read_only=True,+ help_text="Credits settled by observations created on this day across every project in the organization; 0 when none.",+ )+++@extend_schema_serializer(many=False)+class VisionSpendSeriesSerializer(serializers.Serializer):+ period_start = serializers.DateTimeField(+ read_only=True,+ help_text="First moment of the current quota period (UTC).",+ )+ period_end = serializers.DateTimeField(+ read_only=True,+ help_text="First moment of the next quota period (UTC); the current period's exclusive upper bound.",+ )+ days = VisionSpendDaySerializer(+ many=True,+ read_only=True,+ help_text="One entry per UTC day from `period_start` through today, in order, zero-filled for days without spend.",+ )++class VisionQuotaViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "replay_scanner"# Custom viewsets must declare scopes or personal-API-key callers 403 silently.- scope_object_read_actions = ["list"]+ scope_object_read_actions = ["list", "spend_series"]permission_classes = [IsAuthenticated]@extend_schema(operation_id="environment_vision_quota_retrieve", responses={200: VisionQuotaSerializer})def list(self, request: Request, *args, **kwargs) -> Response:snapshot = compute_quota_snapshot(organization_id=UUID(self.organization_id))return Response(VisionQuotaSerializer(instance=snapshot).data)++ @extend_schema(+ operation_id="environment_vision_quota_spend_series_retrieve", responses={200: VisionSpendSeriesSerializer}+ )+ @action(detail=False, methods=["get"])+ def spend_series(self, request: Request, *args, **kwargs) -> Response:+ series = daily_spend_series(organization_id=UUID(self.organization_id))+ return Response(VisionSpendSeriesSerializer(instance=series).data)diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 0c49987c2043..ccea10cf555e 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -63,7 +63,11 @@ from products.replay_vision.backend.api.trigger import (check_team_in_flight_capacity,start_apply_scanner_workflow,)-from products.replay_vision.backend.billing import observation_credits_case, observation_credits_for_model+from products.replay_vision.backend.billing import (+ observation_credits_case,+ observation_credits_for_model,+ projected_monthly_credits,+)from products.replay_vision.backend.feedback_themes import cached_feedback_themesfrom products.replay_vision.backend.impact import (DEFAULT_IMPACT_WINDOW_DAYS,@@ -389,11 +393,22 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerialallow_null=True,help_text="Latest projected observations/month for this scanner. Null until first computed.",)+ estimated_at = serializers.DateTimeField(+ read_only=True,+ allow_null=True,+ help_text=(+ "When `estimated_monthly_observations` was last computed. Null means the estimate is being recomputed "+ "after a config change or has never run, so the stored number may be stale."+ ),+ )credits_per_observation = serializers.SerializerMethodField(help_text="Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`.",)estimated_monthly_credits = serializers.SerializerMethodField(- help_text="`estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.",+ help_text=(+ "`estimated_monthly_observations` priced at `credits_per_observation`, capped at `credit_limit` when one "+ "is set. Null until the estimate is first computed."+ ),)credits_this_month = serializers.SerializerMethodField(help_text=(@@ -466,6 +481,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"experiment_targeting","scanner_version","estimated_monthly_observations",+ "estimated_at","credits_per_observation","estimated_monthly_credits","credits_this_month",@@ -483,6 +499,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial"id","scanner_version","estimated_monthly_observations",+ "estimated_at","credits_per_observation","estimated_monthly_credits","credits_this_month",@@ -503,9 +520,7 @@ class ReplayScannerSerializer(TaggedItemSerializerMixin, UserAccessControlSerial@extend_schema_field(serializers.IntegerField(allow_null=True))def get_estimated_monthly_credits(self, scanner: ReplayScanner) -> int | None:- if scanner.estimated_monthly_observations is None:- return None- return scanner.estimated_monthly_observations * observation_credits_for_model(scanner.model)+ return projected_monthly_credits(scanner.model, scanner.estimated_monthly_observations, scanner.credit_limit)def _page_scanner_ids(self, scanner: ReplayScanner) -> list[UUID]:root = self.root@@ -1089,8 +1104,8 @@ class EstimateRequestSerializer(serializers.Serializer):required=False,help_text=("Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are "- "ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate "- "against all recordings."+ "ignored — the estimate scans a recent window (`window_days` in the response) and "+ "scales it to 30 days. Omit to estimate against all recordings."),))@@ -1187,18 +1202,20 @@ class EstimateResponseSerializer(serializers.Serializer):matched_sessions_in_window = serializers.IntegerField(help_text=(- "Distinct sessions matching the query within the 30-day lookback, after the sampling_mode quality "- "filter but before random sampling."+ "Distinct sessions matching the query within the scanned window (`window_days`), after the "+ "sampling_mode quality filter but before random sampling."),)window_days = serializers.IntegerField(help_text=(- "Lookback window the estimate is based on. Normally 30; smaller when the team has fewer days of recordings."+ "Days of recordings the estimate scanned before scaling to 30. Up to a week (shorter when the query's "+ "operand rules out sampling); smaller when the team has fewer days of recordings."),)estimated_observations_per_month = serializers.IntegerField(help_text=(- "Projected monthly observations: quality-filtered matched sessions scaled to 30 days, times sampling_rate."+ "Projected monthly observations: quality-filtered matched sessions scaled from `window_days` to 30 days, "+ "times sampling_rate."),)credits_per_observation = serializers.IntegerField(diff --git a/products/replay_vision/backend/billing.py b/products/replay_vision/backend/billing.pyindex 7896d955eebd..1e8ebc3167f7 100644--- a/products/replay_vision/backend/billing.py+++ b/products/replay_vision/backend/billing.py@@ -22,10 +22,7 @@ logger = structlog.get_logger(__name__)CREDITS_PER_DOLLAR = 100 # 1 credit = $0.01, matching ai_credits-# Google's list prices, tracked from GEMINI_PRICING_URL (standard tier, prompts <= 200k tokens).-GEMINI_PRICING_URL = "https://ai.google.dev/gemini-api/docs/pricing"--+# Google's list prices, tracked from https://ai.google.dev/gemini-api/docs/pricing (standard tier, prompts <= 200k tokens).GeminiTier = Literal["flash lite", "flash", "pro"]@@ -113,6 +110,18 @@ OBSERVATION_CREDITS_BY_MODEL: dict[str, int] = {_FALLBACK_CREDITS = max(OBSERVATION_CREDITS_BY_MODEL.values())+# Scanner estimates are a rate per this many days, whatever the billing period's length.+ESTIMATE_MONTH_DAYS = 30+++def projected_monthly_credits(model: str, estimated_observations: int | None, credit_limit: int | None) -> int | None:+ """A scanner's 30-day credit rate, capped at its own limit; None while no estimate exists."""+ if estimated_observations is None:+ return None+ credits = observation_credits_for_model(model) * estimated_observations+ return credits if credit_limit is None else min(credits, credit_limit)++def observation_credits_for_model(model: str) -> int:credits = OBSERVATION_CREDITS_BY_MODEL.get(model)if credits is None:diff --git a/products/replay_vision/backend/migrations/0087_replayscanner_estimate_attempted_at.py b/products/replay_vision/backend/migrations/0087_replayscanner_estimate_attempted_at.pynew file mode 100644index 000000000000..d552233e5a5b--- /dev/null+++ b/products/replay_vision/backend/migrations/0087_replayscanner_estimate_attempted_at.py@@ -0,0 +1,21 @@+# Generated by Django 5.2.17 on 2026-09-02 11:34++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("replay_vision", "0086_remove_visionactionrun_vision_action_and_more"),+ ]++ operations = [+ migrations.AddField(+ model_name="replayscanner",+ name="estimate_attempted_at",+ field=models.DateTimeField(+ blank=True,+ help_text="When an estimate was last attempted, success or failure. Backs off the refresher on scanners whose estimate query keeps failing.",+ null=True,+ ),+ ),+ ]diff --git a/products/replay_vision/backend/migrations/max_migration.txt b/products/replay_vision/backend/migrations/max_migration.txtindex 67556cc6ad17..d9e2a23a7d0e 100644--- a/products/replay_vision/backend/migrations/max_migration.txt+++ b/products/replay_vision/backend/migrations/max_migration.txt@@ -1 +1 @@-0086_remove_visionactionrun_vision_action_and_more+0087_replayscanner_estimate_attempted_atdiff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.pyindex eb246eb81d9b..9b169e5eaacf 100644--- a/products/replay_vision/backend/models/replay_scanner.py+++ b/products/replay_vision/backend/models/replay_scanner.py@@ -249,6 +249,11 @@ class ReplayScanner(UUIDModel):blank=True,help_text="When the estimate was last computed. Refreshed on config saves and by the sweep when stale.",)+ estimate_attempted_at = models.DateTimeField(+ null=True,+ blank=True,+ help_text="When an estimate was last attempted, success or failure. Backs off the refresher on scanners whose estimate query keeps failing.",+ )# Not "monthly": this resets with the org's billing period, which is only a calendar month# until billing syncs a real one. See quota.current_period_bounds.@@ -355,6 +360,7 @@ class ReplayScanner(UUIDModel):# Written by sweeps and the read meter through queryset updates; a stale full save must not clobber them._MACHINE_OWNED_FIELDS = (+ "estimate_attempted_at","last_swept_at","last_seen_session_id","deep_swept_through",@@ -400,8 +406,10 @@ class ReplayScanner(UUIDModel):self.scanner_version = old.scanner_version + 1extra_fields.append("scanner_version")if changed & self._ESTIMATE_FIELDS:+ # A config edit must not wait out a backoff the old config earned.self.estimated_at = None- extra_fields.append("estimated_at")+ self.estimate_attempted_at = None+ extra_fields.extend(["estimated_at", "estimate_attempted_at"])if track_enabled and not old.enabled and self.enabled:# Re-enabling restarts the sweep from now — don't backfill (and bill) the disabled gap.self.last_swept_at = initial_watermark()diff --git a/products/replay_vision/backend/queries/__init__.py b/products/replay_vision/backend/queries/__init__.pyindex a44d8735b6f9..e485e5d1dfb1 100644--- a/products/replay_vision/backend/queries/__init__.py+++ b/products/replay_vision/backend/queries/__init__.py@@ -9,6 +9,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import ()from products.replay_vision.backend.queries.scanner_volume_estimate import (DISABLED_ESTIMATE_STALE_AFTER,+ ESTIMATE_RETRY_BACKOFF,ESTIMATE_STALE_AFTER,PREVIEW_ESTIMATE_BUDGET,SAVE_ESTIMATE_BUDGET,@@ -25,6 +26,7 @@ __all__ = ["PREVIEW_ESTIMATE_BUDGET","SAVE_ESTIMATE_BUDGET","DISABLED_ESTIMATE_STALE_AFTER",+ "ESTIMATE_RETRY_BACKOFF","ESTIMATE_STALE_AFTER","MIN_SAMPLING_RATE","SAMPLE_RATE_PRECISION",diff --git a/products/replay_vision/backend/queries/scanner_volume_estimate.py b/products/replay_vision/backend/queries/scanner_volume_estimate.pyindex 153030a62d16..17fe96b7917a 100644--- a/products/replay_vision/backend/queries/scanner_volume_estimate.py+++ b/products/replay_vision/backend/queries/scanner_volume_estimate.py@@ -19,6 +19,7 @@ from posthog.exceptions import (from posthog.models import Team, Userfrom posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQuery+from products.replay_vision.backend.billing import ESTIMATE_MONTH_DAYSfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner, SamplingModefrom products.replay_vision.backend.queries.scanner_candidate_query import (eligibility_predicates,@@ -26,7 +27,7 @@ from products.replay_vision.backend.queries.scanner_candidate_query import ()# The estimate always projects to a calendar month.-ESTIMATE_WINDOW_DAYS = 30+ESTIMATE_WINDOW_DAYS = ESTIMATE_MONTH_DAYS# Fallback sample rate for events subqueries; matched counts are corrected back up._ESTIMATE_EVENTS_SAMPLE_FACTOR = 0.1_EXACT_ATTEMPT_BUDGET_FRACTION = 0.5@@ -48,6 +49,8 @@ class EstimateBudget:# Used when the operand rules out sampling, which makes the scan full price. None keeps one window# for both cases, which is what any estimate that gets persisted needs.unsampled_scan_window_days: int | None = None+ # Skips the exact attempt so the caller blocks for at most one query.+ sampled_only: bool = Falsedef window_days(self, *, unsampled: bool) -> int:if unsampled and self.unsampled_scan_window_days is not None:@@ -59,7 +62,7 @@ class EstimateBudget:BATCH_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=30, scan_window_days=7)# A save blocks the request, so it gets a tighter clock and fails soft. It still writes the persisted# number, so the window stays a whole week.-SAVE_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=10, scan_window_days=7)+SAVE_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=10, scan_window_days=7, sampled_only=True)# The editor's cost preview and Max both re-estimate freely and neither result is persisted, so where# sampling is unavailable they take an order-of-magnitude answer from a shorter window.PREVIEW_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=10, scan_window_days=7, unsampled_scan_window_days=2)@@ -68,6 +71,9 @@ PREVIEW_ESTIMATE_BUDGET = EstimateBudget(max_execution_seconds=10, scan_window_d# track data drift between edits (an edit nulls `estimated_at` and refreshes within one cycle), so a# slower clock trades projection freshness directly for ClickHouse reads.ESTIMATE_STALE_AFTER = dt.timedelta(hours=72)+# A scanner whose estimate query keeps failing waits this long between attempts, so it can't burn its+# full ClickHouse budget on every refresher tick.+ESTIMATE_RETRY_BACKOFF = dt.timedelta(hours=1)# Disabled scanners refresh on a slower clock still: fresh enough that re-enabling one puts a usable# number into the quota sum, without paying a full-price estimate for every parked scanner.DISABLED_ESTIMATE_STALE_AFTER = dt.timedelta(days=7)@@ -133,12 +139,16 @@ def estimate_scanner_session_volume()tag_queries(team_id=team.id, product=Product.REPLAY_VISION, feature=Feature.QUERY)- if not sampled_plan.sampled:+ if not sampled_plan.sampled or budget.sampled_only:# Nothing was sampled, so a fallback would rerun the identical query.return _execute_estimate_query(sampled_plan,team=team,- query_type="ReplayVisionScannerEstimateQuery",+ query_type=(+ "ReplayVisionScannerEstimateSampledQuery"+ if sampled_plan.sampled+ else "ReplayVisionScannerEstimateQuery"+ ),max_execution_seconds=budget.max_execution_seconds,scan_window_days=scan_window_days,ch_user=ch_user,@@ -206,6 +216,8 @@ def _plan_estimate_query(user=user,extra_having_predicates=extra_having,events_sample_factor=sample_factor,+ # Negative filters never sample, so they'd scan at full price; dropping them only over-counts.+ skip_negative_blocklists=True,)inner = list_query.get_query()# The inner query groups by session_id, so one row is one session; order is irrelevant to a count.@@ -290,6 +302,8 @@ def refresh_scanner_estimate(ch_user: ClickHouseUser = ClickHouseUser.APP,) -> None:"""Recompute and persist the scanner's projected monthly volume. Raises on failure; callers decide severity."""+ # An attempt is the query starting, not how it ends: a worker killed mid-query must still back off.+ ReplayScanner.objects.filter(pk=scanner.pk).update(estimate_attempted_at=timezone.now())# Scoped, not tag_queries: a bare tag on the worker thread would leak onto later queries and# charge other scanners' reads to this one in the meter. Previews stay untagged (no scanner yet).with tags_context(scanner_id=str(scanner.pk)):diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex 72ea4a83c719..8e78e42b01b3 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -1,20 +1,25 @@import jsonfrom collections import Counterfrom dataclasses import dataclass, replace-from datetime import UTC, datetime+from datetime import UTC, date, datetime, timedeltafrom uuid import UUIDfrom django.db.models import IntegerField, Sum, Value-from django.db.models.functions import Coalesce+from django.db.models.functions import Coalesce, TruncDayimport structlogfrom dateutil.relativedelta import relativedelta+from posthog.dataclasses import frozenfrom posthog.date_util import start_of_monthfrom posthog.models.organization import Organizationfrom posthog.settings.utils import get_from_env-from products.replay_vision.backend.billing import FREE_TIER_MONTHLY_CREDITS, observation_credits_for_model+from products.replay_vision.backend.billing import (+ ESTIMATE_MONTH_DAYS,+ FREE_TIER_MONTHLY_CREDITS,+ observation_credits_for_model,+)from products.replay_vision.backend.models.replay_observation import (IN_FLIGHT_STATUSES,ObservationStatus,@@ -89,11 +94,16 @@ class QuotaState:# None means no limit applies: an org billing synced with no spend limit, or a scanner with no cap set.credit_limit: int | None+ # `credits_settled + credits_reserved`; kept as a field because gates read only this one number.credits_used: intperiod_start: datetimeperiod_end: datetime# Display-only: the slice of `credit_limit` that never bills; see FREE_TIER_MONTHLY_CREDITS.free_monthly_credits: int = FREE_TIER_MONTHLY_CREDITS+ # Posted to the receipt ledger; deletes cannot refund it.+ credits_settled: int = 0+ # Held by in-flight observations and running prompt evaluations; released without a receipt on failure.+ credits_reserved: int = 0@propertydef remaining(self) -> int | None:@@ -170,15 +180,45 @@ def _as_utc(value: datetime) -> datetime:return value if value.tzinfo else value.replace(tzinfo=UTC)+def _roll_period_forward(start: datetime, end: datetime, now: datetime) -> BillingPeriod:+ """Advance a stale synced period along its own cadence until it contains `now`."""+ month_diff = (end.year - start.year) * 12 + end.month - start.month+ # Billing may close a period a second before the next one starts, so an end up to a day short+ # of the calendar boundary is still a whole-month period; the shortfall is carried along.+ for whole_months in (month_diff, month_diff + 1):+ if whole_months <= 0:+ continue+ shortfall = start + relativedelta(months=whole_months) - end+ if not timedelta(0) <= shortfall < timedelta(days=1):+ continue+ # Anniversary plans keep their day of month, so roll by calendar months from the original+ # start: re-anchoring on a February-clamped end would drift a day-31 plan.+ steps = 0+ while start + relativedelta(months=whole_months * (steps + 1)) - shortfall <= now:+ steps += 1+ return BillingPeriod(+ start=start + relativedelta(months=whole_months * steps),+ end=start + relativedelta(months=whole_months * (steps + 1)) - shortfall,+ )+ length = end - start+ elapsed = (now - start) // length+ start = start + elapsed * length+ return BillingPeriod(start=start, end=start + length)++def _current_period_bounds(organization: Organization | None, now: datetime) -> BillingPeriod:- """The org's active billing period when synced and current, else the calendar month containing `now`."""+ """The org's synced billing period rolled forward to contain `now`; the calendar month when unsynced.++ A billing sync that lags past the period's end must not snap the window to calendar months, or an+ anniversary-plan org would see its spend counted against a period boundary billing never uses.+ """billing_period = organization.current_billing_period if organization else Noneif billing_period:start = _as_utc(billing_period.start)end = _as_utc(billing_period.end)- # Gate before constructing so a malformed synced period falls back to the calendar month- if start <= now < end:- return BillingPeriod(start=start, end=end)+ # A malformed or not-yet-started period cannot be rolled, so it falls back to the calendar month.+ if start < end and start <= now:+ return _roll_period_forward(start, end, now)return _current_month_bounds(now)@@ -232,13 +272,12 @@ def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> dclass ScannerBudget(QuotaState):"""A scanner's own allowance, carrying what one more observation costs.- `credits_used` is the full draw: settled receipts plus live reservations. `settled_credits` is- only what has actually posted to the ledger. Defaults exist only to satisfy the dataclass- field-order rule, as `QuotaSnapshot` does; every constructor passes both.+ `credits_used` is the full draw: settled receipts plus live reservations, split as+ `credits_settled` and `credits_reserved`. The default exists only to satisfy the dataclass+ field-order rule, as `QuotaSnapshot` does; every constructor passes it."""credits_per_observation: int = 0- settled_credits: int = 0@propertydef blocked(self) -> bool:@@ -257,7 +296,7 @@ class ScannerBudget(QuotaState):A reservation can release without ever writing a receipt (a failed observation), so anirreversible reaction to a cap must not fire on a transient in-flight spike."""- return replace(self, credits_used=self.settled_credits).blocked+ return replace(self, credits_used=self.credits_settled).blockeddef _scanner_in_flight_credits(@@ -349,7 +388,8 @@ def compute_scanner_budgets(period_end=period.end,# A scanner outside this org or deleted mid-read has no model; pricing "" would log a warning.credits_per_observation=observation_credits_for_model(config[1]) if config else 0,- settled_credits=settled_credits,+ credits_settled=settled_credits,+ credits_reserved=reserved,)return result@@ -361,13 +401,31 @@ def compute_scanner_budget(scanner: ReplayScanner, period: BillingPeriod | Nonedef _sum_enabled_scanner_estimated_credits(organization_id: UUID, exclude_scanner_id: UUID | None = None) -> int:- """Projected monthly credit spend from the org's enabled scanners' cached estimates."""+ """Projected monthly credit spend of the org's enabled scanners' cached estimates.++ A capped scanner can only spend what its limit has left this period. Surfaces pro-rate this+ 30-day rate over the days left, so that headroom is folded back into a rate: the pro-rated+ share then lands on exactly the remaining cap, never past it.+ """scanners = ReplayScanner.objects.filter(team__organization_id=organization_id, enabled=True)if exclude_scanner_id is not None:scanners = scanners.exclude(pk=exclude_scanner_id)# Credit weighting happens in Python: the per-model price table lives in code, and orgs have few scanners.- rows = scanners.values_list("model", "estimated_monthly_observations")- return sum(observation_credits_for_model(model) * (estimate or 0) for model, estimate in rows)+ rows = list(scanners.values_list("id", "model", "estimated_monthly_observations", "credit_limit"))+ capped_ids = [scanner_id for scanner_id, _, _, credit_limit in rows if credit_limit is not None]+ budgets = compute_scanner_budgets(organization_id, capped_ids) if capped_ids else {}+ now = datetime.now(UTC)+ total = 0.0+ for scanner_id, model, estimate, _credit_limit in rows:+ rate = observation_credits_for_model(model) * (estimate or 0)+ budget = budgets.get(scanner_id)+ if budget is None or budget.remaining is None:+ total += rate+ continue+ days_left = max((budget.period_end - now).total_seconds() / 86400, 0)+ headroom_rate = budget.remaining * ESTIMATE_MONTH_DAYS / days_left if days_left > 0 else rate+ total += min(rate, headroom_rate)+ return round(total)def _sum_active_backfill_remaining_credits(organization_id: UUID) -> int:@@ -400,7 +458,12 @@ def _billing_synced_limit(organization: Organization | None) -> tuple[bool, intif limit is None:return True, Noneif isinstance(limit, (int, float)) and not isinstance(limit, bool):- return True, int(limit)+ if limit < 0:+ # A negative limit would read as permanently over; clamp to a hard block instead.+ logger.warning(+ "replay_vision.negative_billing_limit", organization_id=str(organization.id), limit=repr(limit)+ )+ return True, max(0, int(limit))# A malformed limit must fail toward the env cap, never toward uncapped.logger.warning("replay_vision.malformed_billing_limit", organization_id=str(organization.id), limit=repr(limit))return False, None@@ -447,7 +510,7 @@ def quota_state(organization_id: UUID) -> QuotaState:)in_flight = sum(observation_credits_for_model(model or "") * count for model, count in in_flight_models.items())# Prompt tests have no observation rows. Their unsettled sessions are committed spend too.- usage = consumed + in_flight + in_flight_evaluation_credits(organization_id)+ reserved = in_flight + in_flight_evaluation_credits(organization_id)synced, credit_limit = _billing_synced_limit(organization)if not synced:credit_limit = MONTHLY_CREDIT_QUOTA@@ -458,9 +521,11 @@ def quota_state(organization_id: UUID) -> QuotaState:credit_limit = override if credit_limit is None else min(credit_limit, override)return QuotaState(credit_limit=credit_limit,- credits_used=usage,+ credits_used=consumed + reserved,period_start=period.start,period_end=period.end,+ credits_settled=consumed,+ credits_reserved=reserved,)@@ -477,7 +542,51 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:period_start=state.period_start,period_end=state.period_end,free_monthly_credits=state.free_monthly_credits,+ credits_settled=state.credits_settled,+ credits_reserved=state.credits_reserved,projected_monthly_credits=projection.total,scanners_monthly_credits=projection.scanners_monthly_credits,backfills_committed_credits=projection.backfills_committed_credits,)+++@frozen+class DailySpend:+ date: date+ credits: int+++@frozen+class DailySpendSeries:+ """Settled credits per UTC day from the period start through today, zero-filled and in order."""++ period_start: datetime+ period_end: datetime+ days: tuple[DailySpend, ...]+++def daily_spend_series(organization_id: UUID) -> DailySpendSeries:+ now = datetime.now(UTC)+ organization = Organization.objects.filter(pk=organization_id).only("usage").first()+ # Same `now` as the window so the series can never straddle a period boundary.+ period = _current_period_bounds(organization, now)+ rows = (+ ReplayObservationUsage.objects.filter(+ organization_id=organization_id,+ observation_created_at__gte=period.start,+ observation_created_at__lt=period.end,+ )+ .annotate(day=TruncDay("observation_created_at", tzinfo=UTC))+ .values("day")+ .annotate(total=Coalesce(Sum("credits"), Value(0), output_field=IntegerField()))+ .order_by()+ .values_list("day", "total")+ )+ credits_by_day = {day.date(): total for day, total in rows}+ first_day = period.start.date()+ day_count = (now.date() - first_day).days + 1+ days = tuple(+ DailySpend(date=day, credits=credits_by_day.get(day, 0))+ for day in (first_day + timedelta(days=offset) for offset in range(day_count))+ )+ return DailySpendSeries(period_start=period.start, period_end=period.end, days=days)diff --git a/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py b/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.pyindex b4359970e15e..d013c655fcc0 100644--- a/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py+++ b/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py@@ -1,10 +1,15 @@-from django.db.models import F, Q+from django.db.models import Q+from django.db.models.functions import Coalescefrom django.utils import timezonefrom temporalio import activityfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner-from products.replay_vision.backend.queries import DISABLED_ESTIMATE_STALE_AFTER, ESTIMATE_STALE_AFTER+from products.replay_vision.backend.queries import (+ DISABLED_ESTIMATE_STALE_AFTER,+ ESTIMATE_RETRY_BACKOFF,+ ESTIMATE_STALE_AFTER,+)from products.replay_vision.backend.temporal.constants import ESTIMATES_MAX_PER_RUNfrom products.replay_vision.backend.temporal.decorators import track_activityfrom products.replay_vision.backend.temporal.estimates_types import RefreshScannerEstimateInputs@@ -25,9 +30,12 @@ def list_stale_scanner_estimates_activity() -> list[RefreshScannerEstimateInputs| Q(enabled=True, estimated_at__lt=now - ESTIMATE_STALE_AFTER)| Q(enabled=False, estimated_at__lt=now - DISABLED_ESTIMATE_STALE_AFTER))+ # A recent failed attempt is skipped, and a never-computed estimate sorts by that attempt rather+ # than unconditionally first, so one always-failing scanner can't hog the head of every batch.+ backoff = Q(estimate_attempted_at__isnull=True) | Q(estimate_attempted_at__lt=now - ESTIMATE_RETRY_BACKOFF)rows = (- ReplayScanner.objects.filter(stale)- .order_by("-enabled", F("estimated_at").asc(nulls_first=True))+ ReplayScanner.objects.filter(stale, backoff)+ .order_by("-enabled", Coalesce("estimated_at", "estimate_attempted_at").asc(nulls_first=True)).values_list("id", "team_id")[:ESTIMATES_MAX_PER_RUN])return [RefreshScannerEstimateInputs(scanner_id=scanner_id, team_id=team_id) for scanner_id, team_id in rows]diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pyindex 3b40d0be8af7..605b43ac8693 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -223,7 +223,7 @@ ESTIMATES_WORKFLOW_NAME = "replay-vision-refresh-scanner-estimates"ESTIMATES_WORKFLOW_ID = "replay-vision-estimate-refresher"ESTIMATES_SCHEDULE_ID = "replay-vision-estimate-refresher-schedule"-# Quarter-hourly checks against a 24h staleness target keep estimates at most ~24h15m old.+# Quarter-hourly so an estimate nulled by a config edit is recomputed soon; the staleness clocks live with the query.ESTIMATES_REFRESH_INTERVAL = dt.timedelta(minutes=15)# Covers the worst-case batch (MAX_PER_RUN / CONCURRENCY × the 60s activity timeout = 100 min) with margin;# overlap SKIP means a slow run absorbs later ticks instead of being cancelled mid-batch.diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 3cc6a225c521..13e7ea935f2b 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1229,12 +1229,30 @@ class TestScannerEstimatePersistence(_VisionAPITestCase):self.assertIsNone(resp.json()["estimated_monthly_observations"])def test_response_exposes_estimated_monthly_observations(self) -> None:+ scanner = self._create_scanner()+ estimated_at = timezone.now()+ ReplayScanner.objects.filter(pk=scanner.pk).update(estimated_monthly_observations=42, estimated_at=estimated_at)+ body = self.client.get(f"{self.scanners_url}{scanner.id}/").json()+ self.assertEqual(body["estimated_monthly_observations"], 42)+ self.assertEqual(body["estimated_at"], estimated_at.isoformat().replace("+00:00", "Z"))++ @parameterized.expand(+ [+ ("no_limit", None, None),+ ("limit_above_projection", 10_000, None),+ ("limit_below_projection", 100, 100),+ ]+ )+ def test_estimated_monthly_credits_clamp_to_the_scanner_credit_limit(+ self, _name: str, credit_limit: int | None, clamped_to: int | None+ ) -> None:scanner = self._create_scanner()ReplayScanner.objects.filter(pk=scanner.pk).update(- estimated_monthly_observations=42, estimated_at=timezone.now()+ estimated_monthly_observations=42, estimated_at=timezone.now(), credit_limit=credit_limit)- resp = self.client.get(f"{self.scanners_url}{scanner.id}/")- self.assertEqual(resp.json()["estimated_monthly_observations"], 42)+ body = self.client.get(f"{self.scanners_url}{scanner.id}/").json()+ expected = clamped_to if clamped_to is not None else 42 * observation_credits_for_model(scanner.model)+ self.assertEqual(body["estimated_monthly_credits"], expected)@parameterized.expand([@@ -3632,9 +3650,9 @@ class TestCurrentPeriodBounds(SimpleTestCase):(datetime(2026, 7, 10, tzinfo=UTC), datetime(2026, 8, 10, tzinfo=UTC)),),(- "stale_billing_period_falls_back_to_month",+ "stale_billing_period_rolls_forward_on_its_cadence",{"period": ["2026-05-10T00:00:00+00:00", "2026-06-10T00:00:00+00:00"]},- MONTH_BOUNDS,+ (datetime(2026, 7, 10, tzinfo=UTC), datetime(2026, 8, 10, tzinfo=UTC)),),("naive_timestamps_treated_as_utc",diff --git a/products/replay_vision/backend/tests/test_estimate_refresh.py b/products/replay_vision/backend/tests/test_estimate_refresh.pyindex 3005bb49e013..d4727f91430d 100644--- a/products/replay_vision/backend/tests/test_estimate_refresh.py+++ b/products/replay_vision/backend/tests/test_estimate_refresh.py@@ -23,12 +23,14 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner,from products.replay_vision.backend.queries import (DISABLED_ESTIMATE_STALE_AFTER,ESTIMATE_STALE_AFTER,+ SAVE_ESTIMATE_BUDGET,ScannerVolumeEstimate,project_monthly_observations,refresh_scanner_estimate,)from products.replay_vision.backend.queries.scanner_volume_estimate import (_ESTIMATE_EVENTS_SAMPLE_FACTOR,+ BATCH_ESTIMATE_BUDGET,estimate_scanner_session_volume,)from products.replay_vision.backend.temporal.activities.list_stale_scanner_estimates import (@@ -78,6 +80,12 @@ def _set_estimate(scanner: ReplayScanner, value: int, hours_ago: float) -> None:)+def _set_attempt(scanner: ReplayScanner, hours_ago: float) -> None:+ ReplayScanner.objects.filter(pk=scanner.pk).update(+ estimate_attempted_at=timezone.now() - dt.timedelta(hours=hours_ago)+ )++@pytest.mark.django_db@pytest.mark.parametrize("recordings_query, expect_sampled",@@ -118,33 +126,63 @@ _EVENT_FILTERED_AND_QUERY = RecordingsQuery(@pytest.mark.django_db@pytest.mark.parametrize(- "execute_outcomes, expected_matched, expected_sampled, expected_budgets",+ "budget, execute_outcomes, expected_matched, expected_sampled, expected_budgets, expected_query_types",[- ([MagicMock(results=[[5, None]])], 5, False, [15]),- ([ClickHouseQueryTimeOut(), MagicMock(results=[[5, None]])], 50, True, [15, 30]),- ([ClickHouseQueryMemoryLimitExceeded(), MagicMock(results=[[5, None]])], 50, True, [15, 30]),+ (+ BATCH_ESTIMATE_BUDGET,+ [MagicMock(results=[[5, None]])],+ 5,+ False,+ [15],+ ["ReplayVisionScannerEstimateExactQuery"],+ ),+ (+ BATCH_ESTIMATE_BUDGET,+ [ClickHouseQueryTimeOut(), MagicMock(results=[[5, None]])],+ 50,+ True,+ [15, 30],+ ["ReplayVisionScannerEstimateExactQuery", "ReplayVisionScannerEstimateSampledQuery"],+ ),+ (+ BATCH_ESTIMATE_BUDGET,+ [ClickHouseQueryMemoryLimitExceeded(), MagicMock(results=[[5, None]])],+ 50,+ True,+ [15, 30],+ ["ReplayVisionScannerEstimateExactQuery", "ReplayVisionScannerEstimateSampledQuery"],+ ),+ # A save blocks the request, so it skips the exact attempt and runs one sampled query.+ (+ SAVE_ESTIMATE_BUDGET,+ [MagicMock(results=[[5, None]])],+ 50,+ True,+ [10],+ ["ReplayVisionScannerEstimateSampledQuery"],+ ),],)def test_estimate_falls_back_to_sampling_only_when_the_exact_count_times_out(- execute_outcomes: list[Any], expected_matched: int, expected_sampled: bool, expected_budgets: list[int]+ budget: Any,+ execute_outcomes: list[Any],+ expected_matched: int,+ expected_sampled: bool,+ expected_budgets: list[int],+ expected_query_types: list[str],) -> None:scanner = _make_scanner()with patch("products.replay_vision.backend.queries.scanner_volume_estimate.execute_hogql_query",side_effect=execute_outcomes,) as mock_execute:- estimate = estimate_scanner_session_volume(team=scanner.team, query=_EVENT_FILTERED_AND_QUERY)+ estimate = estimate_scanner_session_volume(team=scanner.team, query=_EVENT_FILTERED_AND_QUERY, budget=budget)assert estimate.matched_sessions == expected_matchedassert estimate.sampled == expected_sampledsettings = [call.kwargs["settings"] for call in mock_execute.call_args_list]assert [s.max_execution_time for s in settings] == expected_budgetsassert all(s.timeout_overflow_mode == "throw" for s in settings)- query_types = [call.kwargs["query_type"] for call in mock_execute.call_args_list]- assert query_types == (- ["ReplayVisionScannerEstimateExactQuery", "ReplayVisionScannerEstimateSampledQuery"]- if expected_sampled- else ["ReplayVisionScannerEstimateExactQuery"]- )+ assert [call.kwargs["query_type"] for call in mock_execute.call_args_list] == expected_query_types@pytest.mark.django_db@@ -204,8 +242,11 @@ class TestRefreshScannerEstimate:scanner.refresh_from_db()assert scanner.estimated_monthly_observations == 30assert scanner.estimated_at is not None+ # The attempt is stamped when the query starts, so it never trails the success stamp.+ assert scanner.estimate_attempted_at is not None+ assert scanner.estimate_attempted_at <= scanner.estimated_at- def test_raises_and_leaves_fields_untouched_when_the_estimate_query_errors(self) -> None:+ def test_raises_and_stamps_only_the_attempt_when_the_estimate_query_errors(self) -> None:scanner = _make_scanner()with patch(_ESTIMATE_QUERY, side_effect=RuntimeError("clickhouse down")):with pytest.raises(RuntimeError, match="clickhouse down"):@@ -214,6 +255,7 @@ class TestRefreshScannerEstimate:scanner.refresh_from_db()assert scanner.estimated_monthly_observations is Noneassert scanner.estimated_at is None+ assert scanner.estimate_attempted_at is not Nonedef test_does_not_bump_scanner_version(self) -> None:scanner = _make_scanner()@@ -345,11 +387,17 @@ class TestListStaleScannerEstimatesActivity:# Disabled scanners run on the slower clock: stale for an enabled scanner, not for a disabled one.disabled_recent = _make_scanner(name="disabled-recent", enabled=False)_set_estimate(disabled_recent, 10, hours_ago=_STALE_HOURS + 24)+ # A failed attempt sorts a never-computed estimate by that attempt instead of at the head.+ failed_earlier = _make_scanner(name="failed-earlier")+ _set_attempt(failed_earlier, hours_ago=_STALE_HOURS + 12)+ # A recent failed attempt is skipped until the backoff has passed.+ failed_recently = _make_scanner(name="failed-recently")+ _set_attempt(failed_recently, hours_ago=0.1)entries = list_stale_scanner_estimates_activity()# Disabled scanners are included but sort behind enabled ones even when staler.- assert [e.scanner_id for e in entries] == [never.id, very_stale.id, stale.id, disabled.id]+ assert [e.scanner_id for e in entries] == [never.id, very_stale.id, failed_earlier.id, stale.id, disabled.id]assert entries[0].team_id == never.team_iddef test_caps_the_batch(self) -> None:diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.pyindex 799a7178256b..2de861edcf88 100644--- a/products/replay_vision/backend/tests/test_quota.py+++ b/products/replay_vision/backend/tests/test_quota.py@@ -1,6 +1,7 @@import uuidfrom datetime import UTC, datetime, timedelta+from freezegun import freeze_timefrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch@@ -26,6 +27,7 @@ from products.replay_vision.backend.quota import (MONTHLY_CREDIT_QUOTA,BillingPeriod,ScannerBudget,+ _current_period_bounds,_parse_org_credit_limit_overrides,compute_quota_snapshot,compute_scanner_budget,@@ -355,7 +357,7 @@ class TestComputeScannerBudget(_VisionQuotaTestCase):self._make_observation(status=ObservationStatus.RUNNING)budget = compute_scanner_budget(self.scanner)assert budget.credits_used == 30- assert budget.settled_credits == 15+ assert budget.credits_settled == 15def test_an_observation_settling_between_the_budget_reads_never_vanishes(self) -> None:# Reservations are read before receipts, so a settlement between the reads is seen by both@@ -491,7 +493,7 @@ class TestScannerBudgetBlocked(SimpleTestCase):period_start=datetime(2026, 8, 1, tzinfo=UTC),period_end=datetime(2026, 9, 1, tzinfo=UTC),credits_per_observation=15,- settled_credits=credits_used,+ credits_settled=credits_used,)assert budget.exhausted == expected_exhaustedassert budget.blocked == expected_blocked@@ -513,7 +515,7 @@ class TestScannerBudgetBlocked(SimpleTestCase):period_start=datetime(2026, 8, 1, tzinfo=UTC),period_end=datetime(2026, 9, 1, tzinfo=UTC),credits_per_observation=0,- settled_credits=credits_used,+ credits_settled=credits_used,)assert budget.exhausted == expected_exhaustedassert budget.blocked == expected_blocked@@ -528,7 +530,7 @@ class TestScannerBudgetBlocked(SimpleTestCase):def test_blocked_by_settled_spend_ignores_live_reservations(self,_name: str,- settled_credits: int,+ credits_settled: int,credits_used: int,expected_blocked: bool,expected_blocked_by_settled: bool,@@ -539,7 +541,7 @@ class TestScannerBudgetBlocked(SimpleTestCase):period_start=datetime(2026, 8, 1, tzinfo=UTC),period_end=datetime(2026, 9, 1, tzinfo=UTC),credits_per_observation=15,- settled_credits=settled_credits,+ credits_settled=credits_settled,)assert budget.blocked == expected_blockedassert budget.blocked_by_settled_spend == expected_blocked_by_settled@@ -624,7 +626,9 @@ class TestBillingSyncedQuota(_VisionQuotaTestCase):{"replay_vision_credits": {"limit": None, "usage": 0}},None,),- ("float_limit_honored", {"replay_vision_credits": {"limit": 42.0, "usage": 0}}, 42),+ ("float_limit_truncated", {"replay_vision_credits": {"limit": 42.9, "usage": 0}}, 42),+ # A negative limit would read as permanently over; it must clamp to a hard block, not fall back.+ ("negative_limit_clamped_to_zero", {"replay_vision_credits": {"limit": -5, "usage": 0}}, 0),("malformed_limit_falls_back_not_uncapped",{"replay_vision_credits": {"limit": "42", "usage": 0}},@@ -733,15 +737,43 @@ class TestBillingSyncedQuota(_VisionQuotaTestCase):assert snapshot.period_start == startassert snapshot.period_end == end- def test_stale_billing_period_falls_back_to_calendar_month(self) -> None:- now = datetime.now(UTC)- self.organization.usage = {- "period": [(now - timedelta(days=70)).isoformat(), (now - timedelta(days=40)).isoformat()]- }- self.organization.save()- snapshot = compute_quota_snapshot(organization_id=self.organization.id)- assert snapshot.period_start == start_of_month(now)- assert snapshot.period_end > now++class TestCurrentPeriodBounds(SimpleTestCase):+ @parameterized.expand(+ [+ ("current_period_kept", "2026-08-15", "2026-09-15", "2026-09-01", "2026-08-15", "2026-09-15"),+ # A lagging sync keeps the mid-month anniversary instead of snapping to the calendar month.+ ("stale_anniversary_rolls_by_month", "2026-08-15", "2026-09-15", "2026-09-20", "2026-09-15", "2026-10-15"),+ ("rolls_across_several_periods", "2026-08-15", "2026-09-15", "2026-12-01", "2026-11-15", "2026-12-15"),+ (+ "month_end_anniversary_keeps_its_day",+ "2026-01-31",+ "2026-02-28",+ "2026-04-05",+ "2026-03-31",+ "2026-04-30",+ ),+ ("yearly_plan_rolls_by_year", "2025-03-01", "2026-03-01", "2026-06-10", "2026-03-01", "2027-03-01"),+ # A period that is not a whole number of months rolls by its own length.+ ("fixed_length_rolls_by_length", "2026-08-01", "2026-08-31", "2026-09-05", "2026-08-31", "2026-09-30"),+ ("reversed_period_falls_back", "2026-09-15", "2026-08-15", "2026-09-20", "2026-09-01", "2026-10-01"),+ ("future_period_falls_back", "2026-10-15", "2026-11-15", "2026-09-20", "2026-09-01", "2026-10-01"),+ ]+ )+ def test_window_containing_now(+ self, _name: str, start: str, end: str, now: str, expected_start: str, expected_end: str+ ) -> None:+ organization = Organization(usage={"period": [f"{start}T00:00:00+00:00", f"{end}T00:00:00+00:00"]})+ period = _current_period_bounds(organization, datetime.fromisoformat(f"{now}T12:00:00+00:00"))+ assert period.start == datetime.fromisoformat(f"{expected_start}T00:00:00+00:00")+ assert period.end == datetime.fromisoformat(f"{expected_end}T00:00:00+00:00")++ def test_inclusive_period_end_still_rolls_by_month(self) -> None:+ # Billing closes a period a second before the next starts; the shortfall must not demote it to a fixed length.+ organization = Organization(usage={"period": ["2026-02-01T00:00:00+00:00", "2026-02-28T23:59:59+00:00"]})+ period = _current_period_bounds(organization, datetime.fromisoformat("2026-03-29T12:00:00+00:00"))+ assert period.start == datetime.fromisoformat("2026-03-01T00:00:00+00:00")+ assert period.end == datetime.fromisoformat("2026-03-31T23:59:59+00:00")class TestProjectedMonthlyObservations(_VisionQuotaTestCase):@@ -753,6 +785,7 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):enabled: bool = True,estimate: int | None = None,model: ScannerModel = ScannerModel.GEMINI_3_7_FLASH,+ credit_limit: int | None = None,) -> None:scanner = ReplayScanner.objects.create(team=team,@@ -761,6 +794,7 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):scanner_config={"prompt": "p"},model=model,enabled=enabled,+ credit_limit=credit_limit,)if estimate is not None:ReplayScanner.objects.filter(pk=scanner.pk).update(@@ -780,6 +814,14 @@ class TestProjectedMonthlyObservations(_VisionQuotaTestCase):snapshot = compute_quota_snapshot(organization_id=self.organization.id)assert snapshot.projected_monthly_credits == 0+ @freeze_time("2026-09-16T00:00:00Z")+ def test_a_capped_scanner_projects_at_most_its_remaining_limit(self) -> None:+ self._make_scanner(team=self.team, name="capped", estimate=100, credit_limit=200) # 1500 uncapped+ self._make_scanner(team=self.team, name="roomy", estimate=10, credit_limit=9000) # 150, under its cap+ snapshot = compute_quota_snapshot(organization_id=self.organization.id)+ # 15 of 30 days left: the 200 headroom pro-rated back to a 30-day rate is 400.+ assert snapshot.projected_monthly_credits == 400 + 150+def test_other_orgs_scanners_not_counted(self) -> None:other_org = Organization.objects.create(name="other-projection-org")other_team = Team.objects.create(organization=other_org, name="other-projection-team")@@ -799,6 +841,8 @@ class TestVisionQuotaEndpoint(_VisionQuotaTestCase):body = resp.json()assert body["credit_limit"] == MONTHLY_CREDIT_QUOTAassert body["credits_used"] == 0+ assert body["credits_settled"] == 0+ assert body["credits_reserved"] == 0assert body["remaining"] == MONTHLY_CREDIT_QUOTAassert body["exhausted"] is Falseassert body["projected_monthly_credits"] == 0@@ -813,13 +857,52 @@ class TestVisionQuotaEndpoint(_VisionQuotaTestCase):resp = self.client.get(self.quota_url)assert resp.json()["projected_monthly_credits"] == 120 * 15- def test_reflects_recent_succeeded_observations(self) -> None:+ def test_splits_settled_receipts_from_live_reservations(self) -> None:for _ in range(3):self._make_observation(status=ObservationStatus.SUCCEEDED, completed_at=timezone.now())+ self._make_observation(status=ObservationStatus.RUNNING)- resp = self.client.get(self.quota_url)- assert resp.json()["credits_used"] == 45- assert resp.json()["remaining"] == MONTHLY_CREDIT_QUOTA - 45+ body = self.client.get(self.quota_url).json()+ assert body["credits_settled"] == 45+ assert body["credits_reserved"] == 15+ assert body["credits_used"] == 60+ assert body["remaining"] == MONTHLY_CREDIT_QUOTA - 60+++class TestVisionSpendSeriesEndpoint(_VisionQuotaTestCase):+ @property+ def series_url(self) -> str:+ return f"/api/environments/{self.team.id}/vision/quota/spend_series/"++ def _receipt(self, created_at: str, credits: int, organization_id: uuid.UUID | None = None) -> None:+ ReplayObservationUsage.objects.create(+ observation_id=uuid.uuid4(),+ organization_id=organization_id or self.organization.id,+ team_id=self.team.id,+ observation_created_at=datetime.fromisoformat(created_at),+ model=ScannerModel.GEMINI_3_7_FLASH,+ credits=credits,+ )++ @freeze_time("2026-03-10T12:00:00Z")+ def test_zero_filled_daily_credits_from_period_start_through_today(self) -> None:+ self.organization.usage = {"period": ["2026-03-01T00:00:00+00:00", "2026-04-01T00:00:00+00:00"]}+ self.organization.save()+ self._receipt("2026-03-03T01:00:00+00:00", 15)+ self._receipt("2026-03-03T23:30:00+00:00", 5)+ self._receipt("2026-03-10T09:00:00+00:00", 2)+ # Previous period and another org: never in this series.+ self._receipt("2026-02-20T09:00:00+00:00", 99)+ other_org = Organization.objects.create(name="other-series-org")+ self._receipt("2026-03-03T09:00:00+00:00", 99, organization_id=other_org.id)++ resp = self.client.get(self.series_url)+ assert resp.status_code == 200, resp.json()+ body = resp.json()+ assert body["period_start"] == "2026-03-01T00:00:00Z"+ assert body["period_end"] == "2026-04-01T00:00:00Z"+ assert [d["date"] for d in body["days"]] == [f"2026-03-{day:02d}" for day in range(1, 11)]+ assert [d["credits"] for d in body["days"]] == [0, 0, 20, 0, 0, 0, 0, 0, 0, 2]@patch("products.replay_vision.backend.api.trigger.async_to_sync")diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex 18fbb1b727b3..4786d9c692da 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -684,12 +684,16 @@ export interface ObservationSearchResponseApi {export interface VisionQuotaApi {/**- * Credits the org may spend per billing period (1 credit = $0.01). Null when billing has synced the product with no spend limit: uncapped.+ * Credits the organization may spend per billing period (1 credit = $0.01). 0 is a hard block: no observation can start. Null when billing has synced the product with no spend limit: uncapped.* @nullable*/readonly credit_limit: number | null- /** Credits spent this period: succeeded observations from the receipt ledger plus reserved in-flight observations. */+ /** `credits_settled` plus `credits_reserved`: the organization's total draw on `credit_limit` this period, across every project. */readonly credits_used: number+ /** Credits posted to the receipt ledger by succeeded observations and finished prompt-test sessions this period, across every project in the organization. Deleting an observation never refunds these. */+ readonly credits_settled: number+ /** Credits held by in-flight observations and running prompt tests across every project in the organization. Released without charge when the work fails, settled into `credits_settled` when it succeeds. */+ readonly credits_reserved: number/*** `credit_limit - credits_used`, floored at 0. Null when uncapped.* @nullable@@ -703,7 +707,7 @@ export interface VisionQuotaApi {readonly period_end: string/** `scanners_monthly_credits` plus `backfills_committed_credits`. Kept as the single headline number; prefer the two components when pro-rating, since only the scanner half is a monthly rate. */readonly projected_monthly_credits: number- /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */+ /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A capped scanner contributes at most what its own credit limit has left this period, folded back into a 30-day rate. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */readonly scanners_monthly_credits: number/** Committed-but-unspent credits of the organization's active backfills. A one-off charge rather than a rate, so it lands in full regardless of how much of the period is left. */readonly backfills_committed_credits: number@@ -711,6 +715,22 @@ export interface VisionQuotaApi {readonly free_monthly_credits: number}+export interface VisionSpendDayApi {+ /** UTC calendar day. */+ readonly date: string+ /** Credits settled by observations created on this day across every project in the organization; 0 when none. */+ readonly credits: number+}++export interface VisionSpendSeriesApi {+ /** First moment of the current quota period (UTC). */+ readonly period_start: string+ /** First moment of the next quota period (UTC); the current period's exclusive upper bound. */+ readonly period_end: string+ /** One entry per UTC day from `period_start` through today, in order, zero-filled for days without spend. */+ readonly days: readonly VisionSpendDayApi[]+}+/*** * `focused` - Focused* * `balanced` - Balanced@@ -866,10 +886,15 @@ export interface ReplayScannerApi {* @nullable*/readonly estimated_monthly_observations: number | null+ /**+ * When `estimated_monthly_observations` was last computed. Null means the estimate is being recomputed after a config change or has never run, so the stored number may be stale.+ * @nullable+ */+ readonly estimated_at: string | null/** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */readonly credits_per_observation: number/**- * `estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.+ * `estimated_monthly_observations` priced at `credits_per_observation`, capped at `credit_limit` when one is set. Null until the estimate is first computed.* @nullable*/readonly estimated_monthly_credits: number | null@@ -979,10 +1004,15 @@ export interface PatchedReplayScannerApi {* @nullable*/readonly estimated_monthly_observations?: number | null+ /**+ * When `estimated_monthly_observations` was last computed. Null means the estimate is being recomputed after a config change or has never run, so the stored number may be stale.+ * @nullable+ */+ readonly estimated_at?: string | null/** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */readonly credits_per_observation?: number/**- * `estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.+ * `estimated_monthly_observations` priced at `credits_per_observation`, capped at `credit_limit` when one is set. Null until the estimate is first computed.* @nullable*/readonly estimated_monthly_credits?: number | null@@ -2014,7 +2044,7 @@ export interface DraftScannerResponseApi {* Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.*/export interface EstimateRequestApi {- /** Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate against all recordings. */+ /** Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate scans a recent window (`window_days` in the response) and scales it to 30 days. Omit to estimate against all recordings. */query?: unknown/*** 0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).@@ -2047,11 +2077,11 @@ export interface EstimateRequestApi {* Forward-looking volume and credit-cost estimate for a proposed scanner.*/export interface EstimateResponseApi {- /** Distinct sessions matching the query within the 30-day lookback, after the sampling_mode quality filter but before random sampling. */+ /** Distinct sessions matching the query within the scanned window (`window_days`), after the sampling_mode quality filter but before random sampling. */matched_sessions_in_window: number- /** Lookback window the estimate is based on. Normally 30; smaller when the team has fewer days of recordings. */+ /** Days of recordings the estimate scanned before scaling to 30. Up to a week (shorter when the query's operand rules out sampling); smaller when the team has fewer days of recordings. */window_days: number- /** Projected monthly observations: quality-filtered matched sessions scaled to 30 days, times sampling_rate. */+ /** Projected monthly observations: quality-filtered matched sessions scaled from `window_days` to 30 days, times sampling_rate. */estimated_observations_per_month: number/** Credits one observation costs at the proposed `model` (1 credit = $0.01). */credits_per_observation: numberdiff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.tsindex 9b3fcd4e4a0a..14e2a9876598 100644--- a/products/replay_vision/frontend/generated/api.ts+++ b/products/replay_vision/frontend/generated/api.ts@@ -70,6 +70,7 @@ import type {VisionScannersObservationsRetrieveParams,VisionScannersObservationsStatsRetrieveParams,VisionScannersPromptSuggestionsListParams,+ VisionSpendSeriesApi,} from './api.schemas'// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497@@ -475,6 +476,20 @@ export const environmentVisionQuotaRetrieve = async (})}+export const getEnvironmentVisionQuotaSpendSeriesRetrieveUrl = (projectId: string) => {+ return `/api/projects/${projectId}/vision/quota/spend_series/`+}++export const environmentVisionQuotaSpendSeriesRetrieve = async (+ projectId: string,+ options?: RequestInit+): Promise<VisionSpendSeriesApi> => {+ return apiMutator<VisionSpendSeriesApi>(getEnvironmentVisionQuotaSpendSeriesRetrieveUrl(projectId), {+ ...options,+ method: 'GET',+ })+}+export const getVisionScannersListUrl = (projectId: string, params?: VisionScannersListParams) => {const normalizedParams = new URLSearchParams()diff --git a/products/replay_vision/frontend/generated/api.zod.ts b/products/replay_vision/frontend/generated/api.zod.tsindex f587f3620e97..1654c337e123 100644--- a/products/replay_vision/frontend/generated/api.zod.ts+++ b/products/replay_vision/frontend/generated/api.zod.ts@@ -1142,7 +1142,7 @@ export const VisionScannersEstimateCreateBody = /* @__PURE__ */ zod.unknown().optional().describe(- 'Proposed `RecordingsQuery` for the candidate filter. `date_from`\/`date_to` are ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate against all recordings.'+ 'Proposed `RecordingsQuery` for the candidate filter. `date_from`\/`date_to` are ignored — the estimate scans a recent window (`window_days` in the response) and scales it to 30 days. Omit to estimate against all recordings.'),sampling_rate: zod.number()diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.tsindex 1294231e7206..971405025ed6 100644--- a/products/replay_vision/frontend/logics/visionQuotaLogic.ts+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.ts@@ -10,6 +10,7 @@ import { environmentVisionQuotaRetrieve } from '../generated/api'import type { VisionQuotaApi } from '../generated/api.schemas'import { billableCredits } from '../utils/credits'import { hasBillableSpend, isFreeAllocationOnly } from '../utils/quotaProjection'+import { currentQuotaScenario } from '../utils/quotaScenarios'import { applyStartupCap, startupCapCredits } from '../utils/startupCap'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -99,6 +100,10 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([loadQuota: async (_, breakpoint) => {// Coalesce bursts of post-mutation refetches (e.g. toggling several scanners).await breakpoint(50)+ const scenario = currentQuotaScenario()+ if (scenario) {+ return scenario.quota+ }const teamId = teamLogic.values.currentTeamIdif (!teamId) {return values.quota@@ -120,6 +125,8 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([state? {...state,+ // Meters project from the scanner rate, so the headline total and the rate move together.+ scanners_monthly_credits: Math.max(0, state.scanners_monthly_credits + delta),projected_monthly_credits: Math.max(0, state.projected_monthly_credits + delta),}: state,diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsxindex 679f11350834..bcc25ce6a5cb 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx@@ -64,6 +64,9 @@ const scanner = (overrides: Partial<ReplayScannerApi> = {}): ReplayScannerApi =>credits_this_month: 0,observations_this_month: 0,credits_per_observation: 1,+ estimated_monthly_observations: null,+ estimated_monthly_credits: null,+ estimated_at: null,user_access_level: 'editor',...overrides,}) as ReplayScannerApi@@ -78,6 +81,9 @@ const scanners = {name: 'Confused checkout',credits_this_month: 1250,observations_this_month: 1250,+ estimated_monthly_observations: 3100,+ estimated_monthly_credits: 3100,+ estimated_at: '2026-05-10T00:00:00Z',description: 'Flags sessions where the user hesitated at payment.',tags: ['checkout', 'core flows'],scanner_type: 'monitor',@@ -99,6 +105,9 @@ const scanners = {name: 'Session summary',credits_this_month: 5,observations_this_month: 5,+ estimated_monthly_observations: 40,+ estimated_monthly_credits: 40,+ estimated_at: '2026-05-10T00:00:00Z',scanner_type: 'summarizer',scanner_config: { prompt: 'Summarize this session.', length: 'medium' },sampling_rate: 0.05,@@ -110,6 +119,9 @@ const scanners = {credits_this_month: 320,observations_this_month: 160,credits_per_observation: 2,+ estimated_monthly_observations: 1000,+ estimated_monthly_credits: 2000,+ estimated_at: '2026-05-10T00:00:00Z',scanner_type: 'scorer',scanner_config: { prompt: 'Score this session.', scale: { min: 0, max: 10 } },sampling_rate: 1,@@ -138,10 +150,22 @@ const quota: VisionQuotaApi = {scanners_monthly_credits: 5200,backfills_committed_credits: 0,free_monthly_credits: 2500,+ credits_settled: 2400,+ credits_reserved: 0,period_start: '2026-05-01T00:00:00Z',period_end: '2026-06-01T00:00:00Z',}+// Settled ledger spend per UTC day of the mocked period, weekends dipping, summing to `quota.credits_used`.+const spendSeries = {+ period_start: quota.period_start,+ period_end: quota.period_end,+ days: [150, 190, 230, 260, 90, 80, 250, 280, 310, 120, 440].map((credits, i) => ({+ date: `2026-05-${String(i + 1).padStart(2, '0')}`,+ credits,+ })),+}+const summarizerScanner = scanners.results[2]const summarizerStats: ObservationStatsApi = {@@ -372,6 +396,7 @@ const meta: Meta = {'/api/projects/:team_id/vision/scanners/stats/': scannerStats,'/api/projects/:team_id/vision/scanners/creators/': { creators: [alice, bob] },'/api/projects/:team_id/vision/quota/': quota,+ '/api/projects/:team_id/vision/quota/spend_series/': spendSeries,'/api/projects/:team_id/vision/scanners/:id/': summarizerScanner,'/api/projects/:team_id/vision/scanners/:id/impact/': scannerImpact,'/api/projects/:team_id/vision/scanners/:id/observations/': observations,diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsxindex 0ba20c3dde68..21a5b6d1cc37 100644--- a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx@@ -192,11 +192,14 @@ export function QuotaMeter({label,size,className,+ limitLabel,}: {model: QuotaMeterModellabel: stringsize?: 'small' | 'medium'className?: string+ /** Caption under the limit marker; defaults to the bar's plain "Spend limit". */+ limitLabel?: string}): JSX.Element {const { projection, segments, periodEndPct } = modelconst [freeWidth, billedWidth, ...segmentWidths] = quotaMeterWidths(@@ -214,6 +217,7 @@ export function QuotaMeter({projected={segments}valueNow={periodEndPct}label={label}+ limitLabel={limitLabel}/><div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted"><QuotaMeterLegendItem barClass={QUOTA_METER_FREE_CLASS} width={freeWidth}>diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsxindex 8b6038603fad..0588aa0b25cc 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx@@ -189,6 +189,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {label={`Projected ${periodEndPct}% of the monthly spend limit by ${resetsOn ?? 'period end'}`}+ limitLabel={`Spend limit · ${formatCreditCount(cap)}`}/></div></Tooltip>diff --git a/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.tsx b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.tsxnew file mode 100644index 000000000000..32641ad71d1f--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/SpendTrajectoryChart.tsx@@ -0,0 +1,357 @@+import { memo } from 'react'++import { dayjs } from 'lib/dayjs'+import { clamp, compactNumber } from 'lib/utils/numbers'++import type { VisionQuotaApi } from '../../generated/api.schemas'+import { formatCreditCount, formatCreditNumber } from '../../utils/credits'+import type { SpendSeries } from '../visionUsageLogic'++const WIDTH = 640+const HEIGHT = 200+const PAD_LEFT = 34+const PAD_X = 8+const TOP = 34+const BASE = HEIGHT - 20+const LABEL_CLEARANCE = 12+const ABOVE = -6+const BELOW = 11++interface SpendTrajectoryChartProps {+ quota: VisionQuotaApi+ /** Settled credits per UTC day of the period, oldest first. */+ dailyCredits: SpendSeries+ /** Credits the period is projected to end on, already held at the limit where one applies. */+ projectedTotal: number+ /** When demand crosses the limit inside the period, the date the verdict computed for it. */+ capReachDate: dayjs.Dayjs | null+ /** Hex/token-resolved colour for the projection line, matching the verdict status. */+ statusVar: string+}++interface Point {+ x: number+ y: number+}++function pointsAttr(points: Point[]): string {+ return points.map((p) => `${Math.round(p.x * 10) / 10},${Math.round(p.y * 10) / 10}`).join(' ')+}++/** Labels live in HTML so they keep their font size while the SVG scales with the card. */+function Label({+ x,+ y,+ anchor = 'start',+ className = '',+ style,+ children,+}: {+ x: number+ y: number+ anchor?: 'start' | 'end' | 'middle'+ className?: string+ style?: React.CSSProperties+ children: React.ReactNode+}): JSX.Element {+ const translateX = anchor === 'end' ? '-100%' : anchor === 'middle' ? '-50%' : '0'+ return (+ <span+ className={`absolute text-xs leading-none whitespace-nowrap ${className}`}+ style={{+ left: `${(x / WIDTH) * 100}%`,+ top: `${(y / HEIGHT) * 100}%`,+ transform: `translate(${translateX}, -50%)`,+ ...style,+ }}+ >+ {children}+ </span>+ )+}++/**+ * Cumulative spend across the period against the limit: a solid line to today, a dashed projection+ * to period end, and a dashed line where the limit sits. Spend pauses at the limit, so the drawn+ * projection never exceeds it: when demand crosses, the line flattens at the crossing and the+ * crossing carries the date. Percentages stay off the chart.+ */+function SpendTrajectoryChartInner({+ quota,+ dailyCredits,+ projectedTotal,+ capReachDate,+ statusVar,+}: SpendTrajectoryChartProps): JSX.Element {+ // The ledger is bucketed by UTC day, so the axis is UTC too; a local axis would shift the curve by a day.+ const periodStart = dayjs.utc(quota.period_start)+ const periodEnd = dayjs.utc(quota.period_end)+ const periodDays = Math.max(periodEnd.diff(periodStart, 'day', true), 1)+ const todayDay = clamp(dayjs.utc().diff(periodStart, 'day', true), 0, periodDays)++ let runningTotal = 0+ const cumulative: { day: number; value: number }[] = []+ for (const entry of dailyCredits) {+ runningTotal += entry.credits+ // A day's bucket is complete at its end; today's is only as complete as the clock.+ const dayEnd = dayjs.utc(entry.date).diff(periodStart, 'day', true) + 1+ cumulative.push({ day: clamp(dayEnd, 0, todayDay), value: runningTotal })+ }+ // The ledger only holds settled spend, so reserved in-flight credits sit on top of today's point; the+ // quota total still wins when the series was fetched before the last receipts landed.+ const spentTotal = Math.max(runningTotal + quota.credits_reserved, quota.credits_used)+ if (cumulative.length > 0 && spentTotal > runningTotal) {+ cumulative[cumulative.length - 1] = { ...cumulative[cumulative.length - 1], value: spentTotal }+ }++ // A zero or missing limit draws no cap; spend stops at a real one, so the drawn end never+ // exceeds it and demand only decides the slope. Cumulative spend cannot go down, so it never dips below today either.+ const cap = quota.credit_limit !== null && quota.credit_limit > 0 ? quota.credit_limit : null+ const demand = Math.max(projectedTotal, spentTotal)+ const endValue = cap !== null ? Math.min(demand, cap) : demand+ // The free allocation gets its own quieter line, unless it IS the limit (the free plan).+ const freeCredits = quota.free_monthly_credits+ const drawFreeLine = freeCredits > 0 && (cap === null || freeCredits < cap)+ const maxValue = Math.max(cap ?? 0, endValue, spentTotal, drawFreeLine ? freeCredits : 0, 1)+ const xForDay = (day: number): number => PAD_LEFT + (day / periodDays) * (WIDTH - PAD_LEFT - PAD_X)+ const yForCredits = (credits: number): number => BASE - (credits / maxValue) * (BASE - TOP)++ const spentPoints: Point[] =+ cumulative.length > 0+ ? cumulative.map((c) => ({ x: xForDay(c.day), y: yForCredits(c.value) }))+ : [{ x: xForDay(todayDay), y: yForCredits(spentTotal) }]+ const origin: Point = { x: xForDay(0), y: yForCredits(0) }+ const today: Point = spentPoints[spentPoints.length - 1]+ // A day-old period leaves no width to draw a line in; a lone dot reads better than a vertical stroke.+ const drawSpentLine = today.x - origin.x >= 1.5+ const end: Point = { x: xForDay(periodDays), y: yForCredits(endValue) }++ // The crossing sits on the verdict's date, so the dot, its label and the tile all name the same day.+ const crossingDay = capReachDate ? capReachDate.diff(periodStart, 'day', true) : null+ const crossingDate = capReachDate?.format('MMM D')+ const crossing: Point | null =+ cap !== null && crossingDay !== null && spentTotal < cap && crossingDay > todayDay && crossingDay <= periodDays+ ? { x: xForDay(crossingDay), y: yForCredits(cap) }+ : null+ const pausedAtLimit = cap !== null && spentTotal >= cap++ // Round tick steps (1/2/2.5/5 per decade) so y labels land on friendly numbers.+ const rawStep = maxValue / 4+ const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)))+ const stepChoice = [1, 2, 2.5, 5, 10].find((m) => m * magnitude >= rawStep) ?? 10+ const yStep = stepChoice * magnitude+ const yTicks: number[] = []+ for (let v = yStep; v <= maxValue; v += yStep) {+ yTicks.push(v)+ }+ const xTicks: number[] = []+ for (let day = 7; day <= periodDays - 3; day += 7) {+ xTicks.push(day)+ }++ const dangerVar = 'var(--danger)'+ const mutedVar = 'var(--muted)'+ const projectionLabel = `${periodEnd.format('MMM D')} · ~${formatCreditNumber(endValue)}`+ const limitY = cap !== null ? yForCredits(cap) : null+ const freeY = drawFreeLine ? yForCredits(freeCredits) : null+ // Two dotted reference lines an em apart read as one; drop the free one when they nearly touch.+ const showFreeLine = freeY !== null && (limitY === null || Math.abs(freeY - limitY) >= LABEL_CLEARANCE)++ // Labels prefer sitting above their anchor; flip below when a reference line runs through that spot.+ const referenceYs = [limitY, freeY].filter((y): y is number => y !== null)+ const labelY = (anchorY: number): number => {+ const above = Math.max(anchorY + ABOVE, 10)+ if (+ referenceYs.every((y) => Math.abs(above - y) >= LABEL_CLEARANCE && Math.abs(anchorY - y) >= LABEL_CLEARANCE)+ ) {+ return above+ }+ return Math.min(anchorY + BELOW, BASE - 4)+ }+ // Today's label sits upper-left or lower-right; the left one is clearer, so it wins unless the point hugs the axis.+ const todayLabelLeft = today.x >= 60+ const todayLabelX = todayLabelLeft ? today.x - 9 : today.x + 9+ const belowY = Math.min(today.y + BELOW, BASE - 4)+ const rightSideY = referenceYs.every((y) => Math.abs(belowY - y) >= LABEL_CLEARANCE) ? belowY : today.y - 16+ const todayLabelY = todayLabelLeft ? labelY(today.y) : rightSideY+ const endLabelY = labelY(end.y)+ const crossingLabelRight = crossing !== null && crossing.x + 90 <= WIDTH - PAD_X++ const caption = crossing+ ? `Hits the limit around ${crossingDate}. Scanning pauses until ${periodEnd.format('MMM D')}.`+ : pausedAtLimit+ ? `Scanning is paused at the limit until ${periodEnd.format('MMM D')}.`+ : null++ return (+ <div className="flex flex-col gap-1">+ <div className="relative">+ <svg+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}+ className="block h-auto w-full"+ role="img"+ aria-label={`Cumulative spend this period: ${formatCreditCount(spentTotal)} so far, projected ${formatCreditCount(endValue)} by ${periodEnd.format('MMMM D')}${cap !== null ? `, limit ${formatCreditCount(cap)}` : ''}`}+ >+ {yTicks.map((v) => (+ <line+ key={v}+ x1={PAD_LEFT}+ y1={yForCredits(v)}+ x2={WIDTH - PAD_X}+ y2={yForCredits(v)}+ stroke="var(--border)"+ strokeWidth={0.5}+ opacity={0.6}+ />+ ))}+ <line x1={PAD_LEFT} y1={TOP - 14} x2={PAD_LEFT} y2={BASE} stroke="var(--border)" strokeWidth={1} />+ {xTicks.map((day) => (+ <line+ key={day}+ x1={xForDay(day)}+ y1={BASE}+ x2={xForDay(day)}+ y2={BASE + 3}+ stroke="var(--border)"+ strokeWidth={1}+ />+ ))}+ {limitY !== null && (+ <line+ x1={PAD_LEFT}+ y1={limitY}+ x2={WIDTH - PAD_X}+ y2={limitY}+ stroke={dangerVar}+ strokeWidth={1}+ strokeDasharray="2 3"+ />+ )}+ {showFreeLine && freeY !== null && (+ <line+ x1={PAD_LEFT}+ y1={freeY}+ x2={WIDTH - PAD_X}+ y2={freeY}+ stroke={mutedVar}+ strokeWidth={1}+ strokeDasharray="2 3"+ opacity={0.7}+ />+ )}+ <line x1={PAD_LEFT} y1={BASE} x2={WIDTH - PAD_X} y2={BASE} stroke="var(--border)" strokeWidth={1} />+ {drawSpentLine && (+ <>+ <polygon+ points={pointsAttr([origin, ...spentPoints, { x: today.x, y: BASE }])}+ fill="currentColor"+ opacity={0.06}+ />+ <polyline+ points={pointsAttr([origin, ...spentPoints])}+ fill="none"+ stroke="currentColor"+ strokeWidth={1.5}+ strokeLinecap="round"+ />+ </>+ )}+ {crossing ? (+ <>+ <polyline+ points={pointsAttr([today, crossing])}+ fill="none"+ stroke={dangerVar}+ strokeWidth={1.5}+ strokeDasharray="4 4"+ strokeLinecap="round"+ />+ <polyline+ points={pointsAttr([crossing, { x: end.x, y: crossing.y }])}+ fill="none"+ stroke={dangerVar}+ strokeWidth={1.5}+ strokeDasharray="2 5"+ strokeLinecap="round"+ opacity={0.7}+ />+ <circle cx={crossing.x} cy={crossing.y} r={3} fill={dangerVar} />+ </>+ ) : (+ <>+ <polyline+ points={pointsAttr([today, end])}+ fill="none"+ stroke={pausedAtLimit ? dangerVar : statusVar}+ strokeWidth={1.5}+ strokeDasharray="4 4"+ strokeLinecap="round"+ />+ <circle cx={end.x} cy={end.y} r={3} fill={pausedAtLimit ? dangerVar : statusVar} />+ </>+ )}+ <circle cx={today.x} cy={today.y} r={3} fill="currentColor" />+ </svg>+ <div className="absolute inset-0 pointer-events-none" aria-hidden>+ {yTicks.map((v) => (+ <Label key={v} x={PAD_LEFT - 4} y={yForCredits(v)} anchor="end" className="text-muted">+ {compactNumber(v)}+ </Label>+ ))}+ <Label x={PAD_LEFT - 4} y={BASE} anchor="end" className="text-muted">+ 0+ </Label>+ {xTicks.map((day) => (+ <Label key={day} x={xForDay(day)} y={HEIGHT - 8} anchor="middle" className="text-muted">+ {periodStart.add(day, 'day').format('MMM D')}+ </Label>+ ))}+ <Label x={PAD_LEFT} y={HEIGHT - 8} className="text-muted">+ {periodStart.format('MMM D')}+ </Label>+ <Label x={WIDTH - PAD_X} y={HEIGHT - 8} anchor="end" className="text-muted">+ {periodEnd.format('MMM D')}+ </Label>+ {limitY !== null && (+ <Label x={PAD_LEFT + 4} y={limitY - 8} className="font-semibold text-danger">+ Monthly limit · {formatCreditNumber(cap ?? 0)}+ </Label>+ )}+ {showFreeLine && freeY !== null && (+ <Label x={WIDTH - PAD_X} y={freeY + BELOW} anchor="end" className="font-semibold text-muted">+ Free credits · {formatCreditNumber(freeCredits)}+ </Label>+ )}+ {crossing && (+ <Label+ x={crossingLabelRight ? crossing.x + 8 : crossing.x - 8}+ y={crossing.y - 8}+ anchor={crossingLabelRight ? 'start' : 'end'}+ className="font-semibold text-danger"+ >+ Limit · {crossingDate}+ </Label>+ )}+ {!crossing && (+ <Label x={end.x - 8} y={endLabelY} anchor="end" className="font-semibold text-muted">+ {projectionLabel}+ </Label>+ )}+ <Label+ x={todayLabelX}+ y={todayLabelY}+ anchor={todayLabelLeft ? 'end' : 'start'}+ className="font-semibold"+ style={{ color: 'currentColor' }}+ >+ Today · {formatCreditNumber(spentTotal)}+ </Label>+ </div>+ </div>+ {caption && <p className="m-0 text-xs text-danger">{caption}</p>}+ </div>+ )+}++// Props are loader and selector outputs, so a scanner toggle re-rendering the tab need not redraw the chart.+export const SpendTrajectoryChart = memo(SpendTrajectoryChartInner)diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsxindex 8a4394c16bb6..5ad8dd15c816 100644--- a/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx@@ -1,64 +1,56 @@import { useActions, useValues } from 'kea'-import { useMemo } from 'react'-import { LemonSegmentedButton, LemonSwitch, LemonTable, Link, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonButton, LemonCard, LemonSwitch, Link, Spinner, Tooltip } from '@posthog/lemon-ui'-import { FEATURE_FLAGS } from 'lib/constants'import { LemonProgress } from 'lib/lemon-ui/LemonProgress'import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { LemonTable } from 'lib/lemon-ui/LemonTable'+import { pluralize } from 'lib/utils/strings'import { urls } from 'scenes/urls'-import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'-import { BaseMathType, ChartDisplayType, InsightLogicProps, PropertyFilterType, PropertyOperator } from '~/types'+import { ProductKey } from '~/queries/schema/schema-general'import { VisionDocsLink } from '../../components/DocsLink'import { CreditPriceNote } from '../../components/PricingLink'import { visionQuotaLogic } from '../../logics/visionQuotaLogic'import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'-import { creditsToUsd, formatCreditCount, formatCreditsMaybeUsd, formatCreditsRange } from '../../utils/credits'-import { exhaustionForecast, hasCreditLimit, projectQuota } from '../../utils/quotaProjection'+import {+ creditsToUsd,+ formatCreditCount,+ formatCreditNumber,+ formatCreditsMaybeUsd,+ formatCreditsRange,+} from '../../utils/credits'+import { verdictColorVar, verdictTextClass } from '../../utils/spendVerdict'import { STARTUP_CAP_EXPLANATION } from '../../utils/startupCap'-import { OBSERVATION_CREDITS_BY_MODEL, ReplayScanner, modelName, modelNamingVariant } from '../types'-import { SpendChartInterval, visionUsageLogic } from '../visionUsageLogic'-import { QuotaMeterBar } from './QuotaMeterBar'-import { VisionInsightChart } from './VisionInsightChart'+import { ReplayScanner } from '../types'+import { visionUsageLogic } from '../visionUsageLogic'+import { SpendTrajectoryChart } from './SpendTrajectoryChart'-const RECORDING_OBSERVED_EVENT = '$recording_observed'+const ORG_WIDE_NOTE = 'Spend and limits are shared by every project in the organization.'+const BILLING_URL = urls.organizationBilling([ProductKey.REPLAY_VISION])-const SPEND_CHART_INTERVAL_OPTIONS: { value: SpendChartInterval; label: string }[] = [- { value: 'day', label: 'Daily' },- { value: 'week', label: 'Weekly' },- { value: 'month', label: 'Monthly' },-]--const SPEND_CHART_DATE_FROM: Record<Exclude<SpendChartInterval, 'day'>, string> = {- week: '-90d',- month: '-365d',+function TilePlaceholder({ loading }: { loading: boolean }): JSX.Element {+ return <span className="text-2xl font-semibold">{loading ? <Spinner /> : '—'}</span>}-// Counted per model and priced in the formula: events predating the `credits` property would sum to zero.-const SPEND_CHART_MODEL_PRICES = Object.entries(OBSERVATION_CREDITS_BY_MODEL)-const SPEND_CHART_SERIES = SPEND_CHART_MODEL_PRICES.map(([model]) => ({- kind: NodeKind.EventsNode as const,- event: RECORDING_OBSERVED_EVENT,- math: BaseMathType.TotalCount,- properties: [- {- type: PropertyFilterType.Event as const,- key: 'model_used',- operator: PropertyOperator.Exact as const,- value: model,- },- ],-}))-const SPEND_CHART_CREDITS_FORMULA = SPEND_CHART_MODEL_PRICES.map(- ([, credits], index) => `${String.fromCharCode(65 + index)}*${credits}`-).join(' + ')-export function VisionUsageTab(): JSX.Element {- const { usageScanners, usageScannersLoading, spendChartInterval, togglingScannerIds } = useValues(visionUsageLogic)- const { setSpendChartInterval, toggleScannerEnabled } = useActions(visionUsageLogic)+ const {+ usageRows,+ usageScannersLoading,+ hiddenScannerCount,+ usageRowsTotalCredits,+ togglingScannerIds,+ spendSeries,+ spendSeriesLoading,+ spendSeriesFailed,+ verdict,+ resetsOn,+ daysToReset,+ projectedTotalCredits,+ projectedPctOfLimit,+ } = useValues(visionUsageLogic)+ const { toggleScannerEnabled, loadSpendSeries } = useActions(visionUsageLogic)const {displayQuota: quota,quotaLoading,@@ -67,67 +59,20 @@ export function VisionUsageTab(): JSX.Element {billedLimitCredits,showStartupCap,} = useValues(visionQuotaLogic)- const { featureFlags } = useValues(featureFlagLogic)- const namingVariant = modelNamingVariant(featureFlags[FEATURE_FLAGS.REPLAY_VISION_MODEL_TIER_NAMING_EXPERIMENT])-- const projection = projectQuota(quota)- const hasCap = hasCreditLimit(quota)- const forecastDate = quota- ? exhaustionForecast(quota.credits_used, quota.credit_limit, quota.period_start, quota.period_end)- : null- const spendTooltip =- quota && showUsd- ? `≈ ${creditsToUsd(billedCredits)} billed${hasCap ? ` of ${creditsToUsd(billedLimitCredits)}` : ''}.${- showStartupCap ? ` ${STARTUP_CAP_EXPLANATION}` : ''- }`- : undefined-- const rows = usageScanners.filter(- (s: ReplayScanner) => s.credits_this_month > 0 || (s.enabled && (s.estimated_monthly_credits ?? 0) > 0)- )- const hiddenCount = usageScanners.length - rows.length- const totalCredits = rows.reduce((sum: number, s: ReplayScanner) => sum + s.credits_this_month, 0)- // A $0 limit really blocks scanning, but as a bar denominator it deliberately counts as "no limit".- const creditLimit = hasCap && quota.credit_limit > 0 ? quota.credit_limit : null-- // The period window comes from the quota, so dispatching before it lands would abort the in-flight query- // and refetch. A failed load still resolves (the loader keeps the last snapshot) so this can't hang.- const quotaResolved = quota !== null || !quotaLoading-- // Memoized so re-renders can't churn the query; `tags.productKey` is required or the runner aborts.- const spendChartQuery = useMemo<InsightVizNode>(- () => ({- kind: NodeKind.InsightVizNode,- source: {- kind: NodeKind.TrendsQuery,- series: SPEND_CHART_SERIES,- trendsFilter: {- display: ChartDisplayType.ActionsLineGraph,- // Credits, not dollars: the free tier applies cumulatively per period, so no per-bucket- // conversion can chart billed dollars; those live in the tooltip beside the chart.- formulaNodes: [{ formula: SPEND_CHART_CREDITS_FORMULA, custom_name: 'Credits' }],- },- dateRange: {- date_from:- spendChartInterval === 'day'- ? (quota?.period_start ?? '-30d')- : SPEND_CHART_DATE_FROM[spendChartInterval],- date_to: null,- },- interval: spendChartInterval,- tags: { productKey: ProductKey.REPLAY_VISION },- },- }),- [quota?.period_start, spendChartInterval]- )- const spendChartInsightProps = useMemo<InsightLogicProps>(- () => ({- dashboardItemId: 'new-replay-vision-usage-spend-chart',- dataNodeCollectionId: 'replay-vision-usage',- }),- []- )+ const statusText = verdictTextClass(verdict.kind)+ const hasCap = verdict.hasCap+ const capDate =+ verdict.kind === 'danger' && verdict.projection.capReachDate+ ? verdict.projection.capReachDate.format('MMM D')+ : null+ const spendTooltip = quota+ ? `${ORG_WIDE_NOTE}${+ showUsd+ ? ` ≈ ${creditsToUsd(billedCredits)} billed${hasCap ? ` of ${creditsToUsd(billedLimitCredits)}` : ''}.`+ : ''+ }${showStartupCap ? ` ${STARTUP_CAP_EXPLANATION}` : ''}`+ : undefinedconst columns: LemonTableColumns<ReplayScanner> = [{@@ -159,161 +104,233 @@ export function VisionUsageTab(): JSX.Element {{title: 'Observations',key: 'observations_this_month',+ align: 'right',tooltip: 'Succeeded observations this billing period.',render: (_, scanner) => (- <span className="text-sm tabular-nums">{scanner.observations_this_month.toLocaleString()}</span>+ <div className="text-sm tabular-nums text-right whitespace-nowrap">+ {scanner.observations_this_month.toLocaleString()}+ </div>),},{- title: 'Price per observation',+ title: 'Price',key: 'credits_per_observation',+ align: 'right',render: (_, scanner) => (- <span className="text-sm whitespace-nowrap">- <span className="tabular-nums">- {scanner.credits_per_observation} credit{scanner.credits_per_observation === 1 ? '' : 's'}- </span>- <span className="text-muted"> · {modelName(scanner.model, namingVariant)}</span>- </span>+ <div className="text-sm text-secondary text-right whitespace-nowrap tabular-nums">+ {formatCreditCount(scanner.credits_per_observation)}/observation+ </div>),},{- title: 'Sampling',- key: 'sampling_rate',- tooltip: "Lower sampling scans fewer of the matching sessions. It's the main cost lever.",+ title: 'Spent this period',+ key: 'credits_this_month',+ align: 'right',render: (_, scanner) => (- <span className="text-sm tabular-nums">- {(scanner.sampling_rate * 100).toFixed(scanner.sampling_rate < 0.1 ? 2 : 1)}%- </span>+ <div className="text-sm tabular-nums text-right whitespace-nowrap">+ {formatCreditsMaybeUsd(scanner.credits_this_month, showUsd)}+ </div>),},{- title: 'Estimated monthly spend',- key: 'estimated_monthly_credits',- width: '20%',- tooltip:- "Based on the scanner's filters and sampling. The bar shows how much of the spend limit it would take up. Updates when the scanner is saved.",+ title: 'Share of spend',+ key: 'share',+ width: '18%',render: (_, scanner) => {- // The fleet projection skips disabled scanners, so an estimate here wouldn't add up to the meter.- if (!scanner.enabled || scanner.estimated_monthly_credits === null) {- return <span className="text-muted">—</span>- }- const estimatedCredits = scanner.estimated_monthly_credits- if (creditLimit === null) {- return (- <span className="text-sm tabular-nums">- ~{formatCreditsMaybeUsd(estimatedCredits, showUsd)}- </span>- )- }- const limitPct = (estimatedCredits / creditLimit) * 100- const limitPctLabel = limitPct > 0 && limitPct < 1 ? '< 1' : String(Math.round(limitPct))+ const sharePct =+ usageRowsTotalCredits > 0+ ? Math.round((scanner.credits_this_month / usageRowsTotalCredits) * 100)+ : 0return (- <div className="flex flex-col gap-1">- <span className="text-sm tabular-nums flex items-baseline justify-between gap-2">- ~{formatCreditsMaybeUsd(estimatedCredits, showUsd)}- <span className="text-muted">{limitPctLabel}% of spend limit</span>- </span>- <QuotaMeterBar- size="small"- usedPct={0}- projected={limitPct > 0 ? [{ pct: limitPct, barClass: 'bg-accent', striped: true }] : []}- valueNow={limitPct}- label={`Estimated ${limitPctLabel}% of the monthly spend limit`}- />+ <div className="flex items-center gap-2">+ <LemonProgress percent={sharePct} className="flex-1" />+ <span className="text-xs text-secondary tabular-nums w-8 text-right">{sharePct}%</span></div>)},},{- title: 'Spend this period',- key: 'credits_this_month',- width: '30%',- className: 'pl-6',- tooltip: 'How much of the total spend this billing period came from this scanner.',+ title: 'Projected monthly',+ key: 'estimated_monthly_credits',+ align: 'right',+ tooltip:+ "Credits per 30 days based on the scanner's filters and sampling. Updates when the scanner is saved.",render: (_, scanner) => {- const sharePct = totalCredits > 0 ? Math.round((scanner.credits_this_month / totalCredits) * 100) : 0+ if (!scanner.enabled || scanner.estimated_monthly_credits === null) {+ return <div className="text-secondary text-right">—</div>+ }+ const stale = !scanner.estimated_atreturn (- <div className="flex flex-col gap-1">- <span className="text-sm tabular-nums flex items-baseline justify-between gap-2">- {formatCreditsMaybeUsd(scanner.credits_this_month, showUsd)}- <span className="text-muted">{sharePct}%</span>- </span>- <LemonProgress percent={sharePct} />- </div>+ <Tooltip title={stale ? 'The estimate is being recomputed after a change.' : undefined}>+ <div className="text-sm tabular-nums text-secondary text-right whitespace-nowrap">+ ~{formatCreditCount(scanner.estimated_monthly_credits)}+ {stale ? ' (updating)' : ''}+ </div>+ </Tooltip>)},},]return (- <div className="flex flex-col gap-4">- <div className="bg-bg-light rounded p-4 flex flex-col InsightCard min-h-80 lg:h-80">- <div className="flex flex-wrap items-center justify-between gap-2 mb-1">- <h3 className="text-base font-semibold m-0">Spend over time</h3>- <div className="flex flex-wrap items-center gap-3">- {quota && (- <Tooltip title={spendTooltip}>- <span className="text-xs text-muted tabular-nums">- {hasCap- ? formatCreditsRange(quota.credits_used, quota.credit_limit ?? 0)- : formatCreditCount(quota.credits_used)}{' '}- this billing period- {projection.resetsOn ? `, resets ${projection.resetsOn}` : ''}- </span>- </Tooltip>+ <div className="@container flex flex-col gap-4">+ <div className="grid grid-cols-1 @md:grid-cols-2 @xl:grid-cols-4 gap-4">+ <LemonCard hoverEffect={false} className="p-4 flex flex-col gap-1" data-attr="vision-usage-tile-spent">+ <span className="text-muted text-xs font-medium uppercase">Spent</span>+ {quota ? (+ <Tooltip title={spendTooltip}>+ <span className="text-2xl font-semibold tabular-nums">+ {formatCreditNumber(quota.credits_used)}{' '}+ <span className="text-sm font-normal text-secondary">credits</span>+ </span>+ </Tooltip>+ ) : (+ <TilePlaceholder loading={quotaLoading} />+ )}+ {quota && showUsd && (+ <span className="text-xs text-secondary tabular-nums">+ ≈ {creditsToUsd(billedCredits)} billed+ </span>+ )}+ <span className="text-xs text-secondary">+ <CreditPriceNote dataAttr="vision-pricing-link-usage" />+ </span>+ </LemonCard>+ <LemonCard+ hoverEffect={false}+ className="p-4 flex flex-col gap-1"+ data-attr="vision-usage-tile-projected"+ >+ <span className="text-muted text-xs font-medium uppercase">+ Projected by {resetsOn ? resetsOn.format('MMM D') : 'period end'}+ </span>+ {quota && projectedTotalCredits !== null ? (+ <span className={`text-2xl font-semibold tabular-nums ${statusText}`}>+ {formatCreditNumber(projectedTotalCredits)}{' '}+ <span className="text-sm font-normal text-secondary">credits</span>+ </span>+ ) : (+ <TilePlaceholder loading={quotaLoading} />+ )}+ <span+ className={`text-xs tabular-nums ${verdict.kind === 'paused' || capDate ? 'text-danger' : 'text-secondary'}`}+ >+ {verdict.kind === 'paused'+ ? 'limit reached, scanning is paused'+ : capDate+ ? `hits the limit around ${capDate}`+ : projectedPctOfLimit !== null+ ? `${projectedPctOfLimit}% of limit`+ : 'no limit set'}+ </span>+ {(verdict.kind === 'paused' || capDate !== null) && (+ <span className="text-xs">+ <Link to={BILLING_URL}>Increase your spending limit</Link> to keep scanning.+ </span>+ )}+ </LemonCard>+ <LemonCard hoverEffect={false} className="p-4 flex flex-col gap-1" data-attr="vision-usage-tile-limit">+ <span className="text-muted text-xs font-medium uppercase">Monthly limit</span>+ {quota ? (+ <Tooltip title={ORG_WIDE_NOTE}>+ <span className="text-2xl font-semibold tabular-nums">+ {hasCap ? formatCreditNumber(quota.credit_limit ?? 0) : 'None set'}+ {hasCap && <span className="text-sm font-normal text-secondary"> credits</span>}+ </span>+ </Tooltip>+ ) : (+ <TilePlaceholder loading={quotaLoading} />+ )}+ <span className="text-xs text-secondary tabular-nums">+ {hasCap ? (+ <>+ {showUsd ? `≈ ${creditsToUsd(billedLimitCredits)} billed at most · ` : ''}+ <Link to={BILLING_URL}>change</Link>+ </>+ ) : (+ <>+ <Link to={BILLING_URL}>Set a spending limit</Link> to control spend.+ </>)}- <LemonSegmentedButton- size="small"- value={spendChartInterval}- onChange={(value) => setSpendChartInterval(value)}- options={SPEND_CHART_INTERVAL_OPTIONS}- />- </div>+ </span>+ </LemonCard>+ <LemonCard hoverEffect={false} className="p-4 flex flex-col gap-1" data-attr="vision-usage-tile-resets">+ <span className="text-muted text-xs font-medium uppercase">Resets in</span>+ <span className="text-2xl font-semibold tabular-nums">+ {daysToReset !== null ? pluralize(daysToReset, 'day') : '—'}+ </span>+ <span className="text-xs text-secondary">{resetsOn ? resetsOn.format('MMMM D') : ''}</span>+ </LemonCard>+ </div>++ <LemonCard hoverEffect={false} className="p-4 flex flex-col gap-2">+ <div className="flex flex-wrap items-baseline justify-between gap-2">+ <h3 className="text-base font-semibold m-0">Spend this period</h3>+ {quota && (+ <span className="text-xs text-secondary tabular-nums">+ {hasCap+ ? formatCreditsRange(quota.credits_used, quota.credit_limit ?? 0)+ : formatCreditCount(quota.credits_used)}+ {resetsOn ? ` · resets ${resetsOn.format('MMMM D')}` : ''}+ </span>+ )}</div>- <p className="text-muted text-xs mb-3">Across all scanners</p>- {quotaResolved ? (- <VisionInsightChart- query={spendChartQuery}- insightProps={spendChartInsightProps}- className="flex-1 flex flex-col min-h-0"- />+ {quota && spendSeries ? (+ spendSeries.length > 0 || quota.credits_used > 0 ? (+ <SpendTrajectoryChart+ quota={quota}+ dailyCredits={spendSeries}+ projectedTotal={projectedTotalCredits ?? quota.credits_used}+ capReachDate={verdict.projection.capReachDate}+ statusVar={verdictColorVar(verdict.kind)}+ />+ ) : (+ <div className="flex items-center justify-center h-40 text-sm text-secondary">+ Costs appear here once scanners produce observations.{' '}+ <VisionDocsLink page="quota-and-limits" dataAttr="vision-empty-docs-link-usage">+ Learn how credits and limits work+ </VisionDocsLink>+ </div>+ )) : (- <div className="flex-1 flex items-center justify-center">- <Spinner />+ <div className="flex items-center justify-center gap-2 h-40 text-sm text-secondary">+ {spendSeriesLoading || quotaLoading ? (+ <Spinner />+ ) : spendSeriesFailed ? (+ <>+ <span>Couldn't load spend data.</span>+ <LemonButton size="small" type="secondary" onClick={() => loadSpendSeries()}>+ Try again+ </LemonButton>+ </>+ ) : (+ <span>Spend data is unavailable.</span>+ )}</div>)}- </div>- {forecastDate && (- <div className="text-xs text-warning">- At the current pace, you'll reach your spend limit around {forecastDate}. Scanning pauses at the- limit until the period resets.- </div>- )}+ </LemonCard>+<LemonTablecolumns={columns}- dataSource={rows}+ dataSource={usageRows}loading={usageScannersLoading}rowKey={(scanner) => scanner.id}emptyState={- <>+ <div className="text-sm text-secondary">No spend this billing period yet. Costs appear here once scanners produce observations.{' '}- <VisionDocsLink page="quota-and-limits" dataAttr="vision-empty-docs-link-usage">+ <VisionDocsLink page="quota-and-limits" dataAttr="vision-empty-docs-link-usage-table">Learn how credits and limits work</VisionDocsLink>- </>+ </div>}footer={- hiddenCount > 0 ? (- <div className="px-3 py-2 text-xs text-muted">- {hiddenCount} scanner{hiddenCount === 1 ? '' : 's'} with no spend or estimate this billing- period+ hiddenScannerCount > 0 ? (+ <div className="px-3 py-2 text-xs text-secondary">+ {pluralize(hiddenScannerCount, 'scanner')} with no spend or estimate this billing period</div>) : undefined}/>- <div className="text-xs text-muted">- <CreditPriceNote dataAttr="vision-pricing-link-usage" />- </div></div>)}diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.tsindex 75de3d68c18e..b4c24de75dd4 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts@@ -600,7 +600,7 @@ export const replayScannersLogic = kea<replayScannersLogicType>([}const enabled = !scanner.enabledactions.toggleScannerEnabledStarted(id)- // The stored estimate is kept ≤24h fresh even while disabled, so the projection shift is known up front.+ // The refresher keeps the stored estimate fresh even while disabled, so the projection shift is known up front.const estimate = scanner.estimated_monthly_credits ?? 0const delta = enabled ? estimate : -estimatevisionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(delta)diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.tsindex 0fd585db2fbb..15439cd18ed8 100644--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts@@ -140,6 +140,7 @@ export function newScanner(templateKey?: string | null, teamName?: string | nullestimated_monthly_observations: null,feedback_themes: null,estimated_monthly_credits: null,+ estimated_at: null,// Seed price for the unsaved scanner; the server-computed value takes over after the first save.credits_per_observation: OBSERVATION_CREDITS_BY_MODEL[DEFAULT_MODEL],// An unsaved scanner has no object yet, so there's no effective access level for it —diff --git a/products/replay_vision/frontend/replay_scanners/visionUsageLogic.test.ts b/products/replay_vision/frontend/replay_scanners/visionUsageLogic.test.tsindex d82209f91aad..e2da88ae6286 100644--- a/products/replay_vision/frontend/replay_scanners/visionUsageLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/visionUsageLogic.test.ts@@ -5,6 +5,7 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { makeQuota } from '../utils/quotaTestUtils'import { ReplayScanner } from './types'import { visionUsageLogic } from './visionUsageLogic'@@ -35,13 +36,23 @@ function makeScanner(overrides: Partial<ReplayScanner> = {}): ReplayScanner {return { ...base, ...overrides } as ReplayScanner}+const PERIOD_A = '2026-05-01T00:00:00Z'+const PERIOD_A_END = '2026-06-01T00:00:00Z'+const PERIOD_B = '2026-06-01T00:00:00Z'+describe('visionUsageLogic', () => {let logic: ReturnType<typeof visionUsageLogic.build>+ let spendSeriesRequests = 0beforeEach(() => {+ spendSeriesRequests = 0useMocks({get: {'/api/projects/:team/vision/scanners/': { results: [makeScanner()], count: 1 },+ '/api/projects/:team/vision/quota/spend_series/': () => {+ spendSeriesRequests += 1+ return [200, { period_start: PERIOD_A, period_end: PERIOD_A_END, days: [] }]+ },},patch: {'/api/projects/:team/vision/scanners/:id/': () => [200, {}],@@ -96,4 +107,58 @@ describe('visionUsageLogic', () => {expect(lemonToast.error).toHaveBeenCalledWith('Failed to disable scanner: nope')})})++ describe('spend series', () => {+ it('loads once per billing period, not on every quota refetch', async () => {+ await expectLogic(logic).toFinishAllListeners()+ const quotaA = makeQuota({ period_start: PERIOD_A, period_end: PERIOD_A_END })++ await expectLogic(logic, () => {+ logic.actions.loadQuotaSuccess(quotaA)+ }).toFinishAllListeners()+ await expectLogic(logic, () => {+ logic.actions.loadQuotaSuccess({ ...quotaA, credits_used: 42 })+ }).toFinishAllListeners()+ expect(spendSeriesRequests).toBe(1)++ await expectLogic(logic, () => {+ logic.actions.loadQuotaSuccess(makeQuota({ period_start: PERIOD_B }))+ }).toFinishAllListeners()+ expect(spendSeriesRequests).toBe(2)+ })++ it('does not retry a failed period on the next quota refetch, but does on request', async () => {+ // Let the mount's successful load settle before swapping in the failing mock.+ await expectLogic(logic).toFinishAllListeners()+ logic.unmount()+ spendSeriesRequests = 0+ useMocks({+ get: {+ '/api/projects/:team/vision/quota/spend_series/': () => {+ spendSeriesRequests += 1+ return [500, { detail: 'boom' }]+ },+ },+ })+ logic = visionUsageLogic()+ logic.mount()+ await expectLogic(logic)+ .toFinishAllListeners()+ .toMatchValues({ spendSeries: null, spendSeriesFailed: true })+ const quotaA = makeQuota({ period_start: PERIOD_A, period_end: PERIOD_A_END })++ await expectLogic(logic, () => {+ logic.actions.loadQuotaSuccess(quotaA)+ }).toFinishAllListeners()+ await expectLogic(logic, () => {+ logic.actions.loadQuotaSuccess({ ...quotaA, credits_used: 7 })+ }).toFinishAllListeners()+ expect(spendSeriesRequests).toBe(1)++ await expectLogic(logic, () => {+ logic.actions.loadSpendSeries()+ }).toFinishAllListeners()+ expect(spendSeriesRequests).toBe(2)+ })+ })})diff --git a/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts b/products/replay_vision/frontend/replay_scanners/visionUsageLogic.tsindex 070a3e547fe0..264db578ce2c 100644--- a/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts@@ -1,30 +1,60 @@-import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { dayjs } from 'lib/dayjs'import { lemonToast } from 'lib/lemon-ui/LemonToast'import { teamLogic } from 'scenes/teamLogic'-import { IntervalType } from '~/types'--import { visionScannersList, visionScannersPartialUpdate } from '../generated/api'-import { refreshVisionQuota } from '../logics/visionQuotaLogic'+import {+ environmentVisionQuotaSpendSeriesRetrieve,+ visionScannersList,+ visionScannersPartialUpdate,+} from '../generated/api'+import type { VisionQuotaApi, VisionSpendSeriesApi } from '../generated/api.schemas'+import { refreshVisionQuota, visionQuotaLogic } from '../logics/visionQuotaLogic'+import { fleetContributions } from '../utils/quotaContributions'+import { hasCreditLimit } from '../utils/quotaProjection'+import { currentQuotaScenario } from '../utils/quotaScenarios'+import { type SpendVerdict, spendVerdict } from '../utils/spendVerdict'import type { ReplayScanner } from './types'-export type SpendChartInterval = Extract<IntervalType, 'day' | 'week' | 'month'>+/** Settled credit spend per UTC day of the current billing period, oldest first, zero-filled through today. */+export type SpendSeries = VisionSpendSeriesApi['days']interface visionUsageLogicValues {usageScanners: ReplayScanner[]usageScannersLoading: boolean- spendChartInterval: SpendChartIntervaltogglingScannerIds: string[]+ spendSeriesResponse: VisionSpendSeriesApi | null+ spendSeriesResponseLoading: boolean+ spendSeries: SpendSeries | null+ spendSeriesLoading: boolean+ spendSeriesFailed: boolean+ quota: VisionQuotaApi | null+ displayQuota: VisionQuotaApi | null+ onFreePlan: boolean+ verdict: SpendVerdict+ usageRows: ReplayScanner[]+ hiddenScannerCount: number+ usageRowsTotalCredits: number+ resetsOn: dayjs.Dayjs | null+ daysToReset: number | null+ projectedTotalCredits: number | null+ projectedPctOfLimit: number | null}interface visionUsageLogicActions {loadUsageScanners: () => { value: true }loadUsageScannersSuccess: (usageScanners: ReplayScanner[]) => { usageScanners: ReplayScanner[] }- setSpendChartInterval: (interval: SpendChartInterval) => { interval: SpendChartInterval }toggleScannerEnabled: (scanner: ReplayScanner) => { scanner: ReplayScanner }setScannerEnabled: (id: string, enabled: boolean) => { id: string; enabled: boolean }finishTogglingScanner: (id: string) => { id: string }+ loadSpendSeries: () => void+ loadSpendSeriesSuccess: (spendSeriesResponse: VisionSpendSeriesApi | null) => {+ spendSeriesResponse: VisionSpendSeriesApi | null+ }+ loadSpendSeriesFailure: (error: string) => { error: string }+ loadQuotaSuccess: (quota: VisionQuotaApi | null) => { quota: VisionQuotaApi | null }}export type visionUsageLogicType = MakeLogicType<visionUsageLogicValues, visionUsageLogicActions>@@ -35,14 +65,33 @@ export type visionUsageLogicType = MakeLogicType<visionUsageLogicValues, visionU// per-row enable toggle can update the list optimistically without a refetch.export const visionUsageLogic = kea<visionUsageLogicType>([path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'visionUsageLogic']),+ connect(() => ({+ values: [visionQuotaLogic, ['quota', 'displayQuota', 'onFreePlan']],+ actions: [visionQuotaLogic, ['loadQuotaSuccess']],+ })),actions({loadUsageScanners: true,loadUsageScannersSuccess: (usageScanners: ReplayScanner[]) => ({ usageScanners }),- setSpendChartInterval: (interval: SpendChartInterval) => ({ interval }),toggleScannerEnabled: (scanner: ReplayScanner) => ({ scanner }),setScannerEnabled: (id: string, enabled: boolean) => ({ id, enabled }),finishTogglingScanner: (id: string) => ({ id }),}),+ loaders(() => ({+ // The series names its own period, so it loads alongside the quota instead of waiting behind it.+ spendSeriesResponse: [+ null as VisionSpendSeriesApi | null,+ {+ loadSpendSeries: async (): Promise<VisionSpendSeriesApi | null> => {+ const scenario = currentQuotaScenario()+ if (scenario) {+ return scenario.dailySpend+ }+ const teamId = teamLogic.values.currentTeamId+ return teamId ? await environmentVisionQuotaSpendSeriesRetrieve(String(teamId)) : null+ },+ },+ ],+ })),reducers({usageScanners: [[] as ReplayScanner[],@@ -59,12 +108,6 @@ export const visionUsageLogic = kea<visionUsageLogicType>([loadUsageScannersSuccess: () => false,},],- spendChartInterval: [- 'day' as SpendChartInterval,- {- setSpendChartInterval: (_, { interval }) => interval,- },- ],togglingScannerIds: [[] as string[],{@@ -73,9 +116,81 @@ export const visionUsageLogic = kea<visionUsageLogicType>([finishTogglingScanner: (state, { id }) => state.filter((toggling) => toggling !== id),},],+ spendSeriesFailed: [+ false,+ {+ loadSpendSeries: () => false,+ loadSpendSeriesFailure: () => true,+ },+ ],+ }),+ selectors({+ spendSeries: [+ (s) => [s.spendSeriesResponse],+ (response: VisionSpendSeriesApi | null): SpendSeries | null => response?.days ?? null,+ ],+ spendSeriesLoading: [(s) => [s.spendSeriesResponseLoading], (loading: boolean): boolean => loading],+ verdict: [+ (s) => [s.displayQuota, s.onFreePlan],+ (quota: VisionQuotaApi | null, onFreePlan: boolean): SpendVerdict =>+ spendVerdict(quota, fleetContributions(quota), { onFreePlan }),+ ],+ // Rows that cost something this period or are set to: idle disabled scanners only add noise.+ usageRows: [+ (s) => [s.usageScanners],+ (usageScanners: ReplayScanner[]): ReplayScanner[] =>+ usageScanners.filter(+ (scanner) =>+ scanner.credits_this_month > 0 ||+ (scanner.enabled && (scanner.estimated_monthly_credits ?? 0) > 0)+ ),+ ],+ hiddenScannerCount: [+ (s) => [s.usageScanners, s.usageRows],+ (usageScanners: ReplayScanner[], usageRows: ReplayScanner[]): number =>+ usageScanners.length - usageRows.length,+ ],+ usageRowsTotalCredits: [+ (s) => [s.usageRows],+ (usageRows: ReplayScanner[]): number => usageRows.reduce((sum, s) => sum + s.credits_this_month, 0),+ ],+ resetsOn: [+ (s) => [s.displayQuota],+ // UTC, like the ledger's day buckets and the chart axis, so every surface names the same reset day.+ (quota: VisionQuotaApi | null): dayjs.Dayjs | null =>+ quota?.period_end ? dayjs.utc(quota.period_end) : null,+ ],+ daysToReset: [+ (s) => [s.resetsOn],+ (resetsOn: dayjs.Dayjs | null): number | null =>+ resetsOn ? Math.max(resetsOn.startOf('day').diff(dayjs.utc().startOf('day'), 'day'), 0) : null,+ ],+ // What the period will actually cost: spend stops at the limit, so demand past it is not billed.+ projectedTotalCredits: [+ (s) => [s.displayQuota, s.verdict],+ (quota: VisionQuotaApi | null, verdict: SpendVerdict): number | null => {+ const demand = verdict.projectedDemandCredits+ if (demand === null) {+ return null+ }+ return hasCreditLimit(quota) ? Math.min(demand, quota.credit_limit) : demand+ },+ ],+ projectedPctOfLimit: [+ (s) => [s.displayQuota, s.projectedTotalCredits],+ (quota: VisionQuotaApi | null, projectedTotalCredits: number | null): number | null =>+ hasCreditLimit(quota) && quota.credit_limit > 0 && projectedTotalCredits !== null+ ? Math.round((projectedTotalCredits / quota.credit_limit) * 100)+ : null,+ ],}),listeners(({ actions, values }) => ({loadUsageScanners: async () => {+ const scenario = currentQuotaScenario()+ if (scenario?.usageScanners) {+ actions.loadUsageScannersSuccess(scenario.usageScanners as unknown as ReplayScanner[])+ return+ }const teamId = teamLogic.values.currentTeamIdif (!teamId) {actions.loadUsageScannersSuccess([])@@ -88,7 +203,7 @@ export const visionUsageLogic = kea<visionUsageLogicType>([})actions.loadUsageScannersSuccess((response.results ?? []) as unknown as ReplayScanner[])} catch {- // Keep whatever list is already shown; the table's own empty/loaded state stays consistent.+ // Keep the list already shown; the table's own empty/loaded state stays consistent.actions.loadUsageScannersSuccess(values.usageScanners)}},@@ -112,8 +227,23 @@ export const visionUsageLogic = kea<visionUsageLogicType>([actions.finishTogglingScanner(scanner.id)}},+ // Quota refetches after scanner toggles keep the same period, and settled daily spend doesn't+ // move with them, so a loaded series is only refreshed when the period changes. A failed load+ // is not retried on every refetch either; the chart offers a retry instead.+ loadQuotaSuccess: ({ quota }) => {+ const loaded = values.spendSeriesResponse+ if (+ quota?.period_start &&+ loaded &&+ !values.spendSeriesLoading &&+ dayjs.utc(loaded.period_start).valueOf() !== dayjs.utc(quota.period_start).valueOf()+ ) {+ actions.loadSpendSeries()+ }+ },})),afterMount(({ actions }) => {actions.loadUsageScanners()+ actions.loadSpendSeries()}),])diff --git a/products/replay_vision/frontend/utils/credits.ts b/products/replay_vision/frontend/utils/credits.tsindex 42731c533223..cca72fd24705 100644--- a/products/replay_vision/frontend/utils/credits.ts+++ b/products/replay_vision/frontend/utils/credits.ts@@ -1,4 +1,4 @@-import { humanFriendlyCurrency } from 'lib/utils/numbers'+import { humanFriendlyCurrency, humanFriendlyNumber } from 'lib/utils/numbers'/** 1 credit = $0.01. Amounts arrive from the API as integer credits. Credits are the unit we bill, so credits are* what we show. The dollar anchor is reserved for the spend surfaces (the spend meter, the scanner list's@@ -17,10 +17,14 @@ export function billableCredits(credits: number, freeCredits: number): number {return Math.max(0, Math.round(credits) - Math.max(0, freeCredits))}+/** The bare number half of `formatCreditCount`, e.g. 1234.4 -> "1,234". */+export function formatCreditNumber(credits: number): string {+ return humanFriendlyNumber(credits, 0)+}+/** e.g. 500 -> "500 credits", 1 -> "1 credit". */export function formatCreditCount(credits: number): string {- const rounded = Math.round(credits)- return `${rounded.toLocaleString('en-US')} ${Math.abs(rounded) === 1 ? 'credit' : 'credits'}`+ return `${formatCreditNumber(credits)} ${Math.abs(Math.round(credits)) === 1 ? 'credit' : 'credits'}`}/** e.g. 500 -> "500 credits (≈ $5.00)", 1 -> "1 credit (≈ $0.01)". */diff --git a/products/replay_vision/frontend/utils/quotaContributions.test.ts b/products/replay_vision/frontend/utils/quotaContributions.test.tsindex b7a9ea743b5a..e5f997c1ec13 100644--- a/products/replay_vision/frontend/utils/quotaContributions.test.ts+++ b/products/replay_vision/frontend/utils/quotaContributions.test.ts@@ -10,9 +10,9 @@ const HALF_PERIOD_QUOTA: VisionQuotaApi = {projected_monthly_credits: 400,scanners_monthly_credits: 400,backfills_committed_credits: 0,- // Half the period is left, so a monthly rate lands at half value and a one-off lands whole.- period_start: '2026-05-01T00:00:00Z',- period_end: '2026-05-03T00:00:00Z',+ // 15 of 30 days are left, so a 30-day rate lands at half value and a one-off lands whole.+ period_start: '2026-04-17T00:00:00Z',+ period_end: '2026-05-17T00:00:00Z',} as VisionQuotaApiconst contribution = (overrides: Partial<QuotaContribution>): QuotaContribution => ({diff --git a/products/replay_vision/frontend/utils/quotaContributions.ts b/products/replay_vision/frontend/utils/quotaContributions.tsindex e762860afbfb..e8c0304d3393 100644--- a/products/replay_vision/frontend/utils/quotaContributions.ts+++ b/products/replay_vision/frontend/utils/quotaContributions.ts@@ -5,6 +5,7 @@ import {type QuotaProjection,type QuotaStatus,hasCreditLimit,+ projectDemandCredits,projectQuota,} from './quotaProjection'@@ -47,6 +48,12 @@ export interface QuotaMeterModel {segments: QuotaMeterSegmentModel[]/** Where the period lands counting every contribution; exceeds 100 on overshoot. */periodEndPct: number+ /** Projected period-end demand in credits, unclamped and unrounded by the percentage; null without a quota. */+ periodEndCredits: number | null+ /** Sum of the monthly-rate contributions, credits per 30 days. */+ rateTotal: number+ /** Sum of the one-off contributions, charged once. */+ oneOffTotal: numberhasCap: boolean}@@ -81,10 +88,10 @@ export function fleetContributions(quota: VisionQuotaApi | null): QuotaContributexport function buildQuotaMeter(quota: VisionQuotaApi | null, contributions: QuotaContribution[]): QuotaMeterModel {const hasCap = hasCreditLimit(quota)const cap = hasCap ? quota.credit_limit : 0- const rates = contributions.filter((c) => c.kind === 'monthly-rate')- const rateTotal = rates.reduce((sum, c) => sum + c.credits, 0)- // The contributions are the whole projection, so move `projectQuota` off the stored fleet rate onto them.- const projection = projectQuota(quota, rateTotal - (quota?.projected_monthly_credits ?? 0))+ const rateTotal = contributions.reduce((sum, c) => (c.kind === 'monthly-rate' ? sum + c.credits : sum), 0)+ const oneOffTotal = contributions.reduce((sum, c) => (c.kind === 'one-off' ? sum + c.credits : sum), 0)+ // The contributions are the whole projection, so the stored fleet rate is not consulted here.+ const projection = projectQuota(quota, { monthlyRateCredits: rateTotal, oneOffCredits: oneOffTotal })const asPct = (credits: number): number => (hasCap && cap > 0 ? (credits / cap) * 100 : 0)const segments = contributions.map((c) => ({@@ -98,11 +105,12 @@ export function buildQuotaMeter(quota: VisionQuotaApi | null, contributions: Quoc.kind === 'one-off'? asPct(c.credits): rateTotal > 0- ? (projection.projectedPct * c.credits) / rateTotal+ ? ((projection.projectedPct - asPct(oneOffTotal)) * c.credits) / rateTotal: 0,}))- const periodEndPct = Math.round(projection.usedPct + segments.reduce((sum, s) => sum + s.pct, 0))+ const periodEndPctExact = projection.usedPct + segments.reduce((sum, s) => sum + s.pct, 0)+ const periodEndPct = Math.round(periodEndPctExact)// One verdict, from the same total the bar draws. Deriving it per card produced a headline that// could read green beside a bar sitting past the limit marker.const status: QuotaStatus =@@ -122,6 +130,11 @@ export function buildQuotaMeter(quota: VisionQuotaApi | null, contributions: Quo: segment),periodEndPct,+ periodEndCredits: quota+ ? Math.round(projectDemandCredits(quota, { monthlyRateCredits: rateTotal, oneOffCredits: oneOffTotal }))+ : null,+ rateTotal,+ oneOffTotal,hasCap,}}diff --git a/products/replay_vision/frontend/utils/quotaProjection.test.ts b/products/replay_vision/frontend/utils/quotaProjection.test.tsindex 5fe0f98a59be..3bfc8efdec90 100644--- a/products/replay_vision/frontend/utils/quotaProjection.test.ts+++ b/products/replay_vision/frontend/utils/quotaProjection.test.ts@@ -1,4 +1,6 @@-import { daysUntilCapReached, exhaustionForecast, hasBillableSpend, projectQuota, quotaUx } from './quotaProjection'+import { dayjs } from 'lib/dayjs'++import { daysUntilCapReached, hasBillableSpend, projectQuota, quotaUx } from './quotaProjection'import { makeQuota } from './quotaTestUtils'describe('hasBillableSpend', () => {@@ -33,7 +35,7 @@ describe('projectQuota', () => {it('safe when the fleet rate projects well under the cap', () => {// 3,000/month fleet → 100/day → ends at 3,000 of 10,000.- const proj = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }))+ const proj = projectQuota(makeQuota({ credits_used: 1_000, scanners_monthly_credits: 3_000 }))expect(proj.status).toBe('safe')})@@ -45,13 +47,28 @@ describe('projectQuota', () => {it('warning when the fleet projection crosses the warn threshold but stays under cap', () => {// 3,000 used + 9,000/month fleet → 300/day × 20 days → ends at 9,000 (90% of cap).- const proj = projectQuota(makeQuota({ credits_used: 3_000, projected_monthly_credits: 9_000 }))+ const proj = projectQuota(makeQuota({ credits_used: 3_000, scanners_monthly_credits: 9_000 }))expect(proj.status).toBe('warning')})+ it('counts one-off credits against headroom before the rate', () => {+ // 5,000 used + 4,000 committed leaves 1,000 for a 100/day rate: 10 days, not 50.+ const proj = projectQuota(makeQuota({ credits_used: 5_000, scanners_monthly_credits: 3_000 }), {+ oneOffCredits: 4_000,+ })+ expect(proj.capReachDate?.diff(dayjs(), 'day', true)).toBeCloseTo(10, 0)+ expect(proj.status).toBe('danger')+ })++ it('reaches the cap today when one-offs alone overshoot it', () => {+ const proj = projectQuota(makeQuota({ credits_used: 5_000 }), { oneOffCredits: 6_000 })+ expect(proj.capReachDate?.diff(dayjs(), 'minute')).toBe(0)+ expect(proj.status).toBe('danger')+ })+it('danger when projected to exhaust before period end', () => {// 9,000 used + 100/day → cap reached in 10 days, 20 days left in the period.- const proj = projectQuota(makeQuota({ credits_used: 9_000, projected_monthly_credits: 3_000 }))+ const proj = projectQuota(makeQuota({ credits_used: 9_000, scanners_monthly_credits: 3_000 }))expect(proj.status).toBe('danger')expect(proj.capReachDate).not.toBeNull()})@@ -72,16 +89,18 @@ describe('projectQuota', () => {})it('a positive scanner delta raises the projection on top of the fleet sum', () => {- const base = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }))- const withDelta = projectQuota(makeQuota({ credits_used: 1_000, projected_monthly_credits: 3_000 }), 6_000)+ const base = projectQuota(makeQuota({ credits_used: 1_000, scanners_monthly_credits: 3_000 }))+ const withDelta = projectQuota(makeQuota({ credits_used: 1_000, scanners_monthly_credits: 3_000 }), {+ monthlyRateCredits: 9_000,+ })expect(withDelta.projectedPct).toBeGreaterThan(base.projectedPct)})it('a negative scanner delta lowers the projection and clamps at zero', () => {// 2,000/month over a 30-day period × 20 remaining days = ~1,333 of the 10,000 cap.- const lowered = projectQuota(makeQuota({ projected_monthly_credits: 3_000 }), -1_000)+ const lowered = projectQuota(makeQuota({ scanners_monthly_credits: 3_000 }), { monthlyRateCredits: 2_000 })expect(lowered.projectedPct).toBeCloseTo(13.33, 1)- const clamped = projectQuota(makeQuota({ projected_monthly_credits: 3_000 }), -9_000)+ const clamped = projectQuota(makeQuota({ scanners_monthly_credits: 3_000 }), { monthlyRateCredits: -6_000 })expect(clamped.projectedPct).toBe(0)})@@ -98,7 +117,7 @@ describe('projectQuota', () => {it('reports unclamped percentages on overshoot', () => {// 8,000 used + 30,000/month × 20 days = 20,000 more → 280% of the 10,000 cap.- const proj = projectQuota(makeQuota({ credits_used: 8_000, projected_monthly_credits: 30_000 }))+ const proj = projectQuota(makeQuota({ credits_used: 8_000, scanners_monthly_credits: 30_000 }))expect(proj.projectedPct).toBeCloseTo(200, 0)})})@@ -106,9 +125,9 @@ describe('projectQuota', () => {describe('daysUntilCapReached', () => {it.each([// 1,000 left of the 10,000 cap, burned at monthly/30 per day.- ['inside the window', { credits_used: 9_000, projected_monthly_credits: 15_000 }, 2],- ['further out than the window', { credits_used: 9_000, projected_monthly_credits: 3_000 }, null],- ['already exhausted', { credits_used: 9_000, projected_monthly_credits: 15_000, exhausted: true }, null],+ ['inside the window', { credits_used: 9_000, scanners_monthly_credits: 15_000 }, 2],+ ['further out than the window', { credits_used: 9_000, scanners_monthly_credits: 3_000 }, null],+ ['already exhausted', { credits_used: 9_000, scanners_monthly_credits: 15_000, exhausted: true }, null],['no fleet spend, so the cap is never reached', { credits_used: 9_000 }, null],])('%s', (_name, overrides, expected) => {const days = daysUntilCapReached(projectQuota(makeQuota(overrides)))@@ -164,30 +183,3 @@ describe('quotaUx', () => {expect(quotaUx(makeQuota({ credits_used: 1_000, remaining: 9_000 }))).toEqual({})})})--describe('exhaustionForecast', () => {- // Frozen 10 days into a July 1-31 period.- beforeEach(() => {- jest.useFakeTimers().setSystemTime(new Date('2026-07-11T00:00:00Z'))- })- afterEach(() => {- jest.useRealTimers()- })-- const PERIOD_START = '2026-07-01T00:00:00Z'- const PERIOD_END = '2026-07-31T00:00:00Z'-- it.each([- ['uncapped', 5_000, null],- ['no spend yet', 0, 10_000],- ['already at the limit', 10_000, 10_000],- ['burn too slow to hit the limit this period', 1_000, 10_000],- ])('returns null when %s', (_name, creditsUsed, creditLimit) => {- expect(exhaustionForecast(creditsUsed, creditLimit, PERIOD_START, PERIOD_END)).toBeNull()- })-- it('extrapolates the burn rate to the exhaustion date', () => {- // 5,000 of 10,000 spent in 10 days: the other half runs out 10 days from now.- expect(exhaustionForecast(5_000, 10_000, PERIOD_START, PERIOD_END)).toBe('Jul 21')- })-})diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.tsindex 600ce6f585d5..a05c68eb4467 100644--- a/products/replay_vision/frontend/utils/quotaProjection.ts+++ b/products/replay_vision/frontend/utils/quotaProjection.ts@@ -7,6 +7,9 @@ export const QUOTA_WARN_THRESHOLD = 0.85export const IMMINENT_CAP_DAYS = 3+/** Scanner estimates are a rate per 30 days (backend `ESTIMATE_WINDOW_DAYS`), not per billing period. */+export const ESTIMATE_MONTH_DAYS = 30+export type QuotaStatus = 'safe' | 'warning' | 'danger'export const QUOTA_STATUS_STYLES: Record<QuotaStatus, { bar: string; text: string }> = {@@ -68,44 +71,49 @@ export function isFreeAllocationOnly(quota: VisionQuotaApi | null): boolean {return billableCredits(quota.credit_limit, quota.free_monthly_credits) === 0}-/**- * Project credit spend to period end from the enabled fleet's summed per-scanner estimates.- * `scannerProjectedMonthlyCreditsDelta` adjusts the fleet sum for a scanner being edited:- * its proposed monthly credit estimate minus the stored contribution already in the sum.- */-export function projectQuota(- quota: VisionQuotaApi | null,- scannerProjectedMonthlyCreditsDelta: number = 0-): QuotaProjection {+export interface ProjectionInputs {+ /** Fleet rate in credits per 30 days; defaults to the quota's stored `scanners_monthly_credits`. */+ monthlyRateCredits?: number+ /** Charged once (backfills), so they count toward the cap-reach date but not the rate. */+ oneOffCredits?: number+}++/** Credits the period ends on: spend so far, the rate pro-rated over the days left, and the one-offs. Unclamped. */+export function projectDemandCredits(quota: VisionQuotaApi, inputs: ProjectionInputs = {}): number {+ const daysRemaining = Math.max(dayjs.utc(quota.period_end).diff(dayjs(), 'day', true), 0)+ const rate = Math.max(inputs.monthlyRateCredits ?? quota.scanners_monthly_credits, 0) / ESTIMATE_MONTH_DAYS+ return quota.credits_used + rate * daysRemaining + Math.max(inputs.oneOffCredits ?? 0, 0)+}++/** Project credit spend to period end from a fleet rate and the one-offs already committed. */+export function projectQuota(quota: VisionQuotaApi | null, inputs: ProjectionInputs = {}): QuotaProjection {if (!hasCreditLimit(quota)) {return EMPTY}const now = dayjs()const used = quota.credits_usedconst cap = quota.credit_limit+ const periodEnd = dayjs.utc(quota.period_end)+ const resetsOn = periodEnd.format('MMMM D')if (cap === 0) {// A $0 spend limit blocks everything; there is no ratio to project against.- return {- ...EMPTY,- status: 'danger',- exhausted: quota.exhausted,- usedPct: 100,- resetsOn: quota.period_end ? dayjs(quota.period_end).format('MMMM D') : null,- }+ return { ...EMPTY, status: 'danger', exhausted: quota.exhausted, usedPct: 100, resetsOn }}- const periodStart = quota.period_start ? dayjs(quota.period_start) : null- const periodEnd = quota.period_end ? dayjs(quota.period_end) : null- const periodLengthDays = periodStart && periodEnd ? Math.max(periodEnd.diff(periodStart, 'day', true), 1) : 30- const daysRemaining = periodEnd ? Math.max(periodEnd.diff(now, 'day', true), 0) : 0- const resetsOn = periodEnd ? periodEnd.format('MMMM D') : null-- const projectedMonthly = Math.max(quota.projected_monthly_credits + scannerProjectedMonthlyCreditsDelta, 0)- const combinedDailyRate = projectedMonthly / periodLengthDays- const projectedAdditional = combinedDailyRate * daysRemaining+ const oneOffCredits = Math.max(inputs.oneOffCredits ?? 0, 0)+ const combinedDailyRate =+ Math.max(inputs.monthlyRateCredits ?? quota.scanners_monthly_credits, 0) / ESTIMATE_MONTH_DAYS+ const projectedAdditional = projectDemandCredits(quota, inputs) - usedconst projectedPeriodEndRatio = (used + projectedAdditional) / cap- const capReachDate = combinedDailyRate > 0 && used < cap ? now.add((cap - used) / combinedDailyRate, 'day') : null- const capReachInPeriod = !!(capReachDate && periodEnd && capReachDate.isBefore(periodEnd))+ const committed = used + oneOffCredits+ // One-offs are charged as soon as they run, so they eat headroom before the rate does.+ const capReachDate =+ used < cap && committed >= cap+ ? now+ : combinedDailyRate > 0 && committed < cap+ ? now.add((cap - committed) / combinedDailyRate, 'day')+ : null+ const capReachInPeriod = !!capReachDate && !capReachDate.isAfter(periodEnd)// `used >= cap` without `exhausted`: a display clamp (startup cap) lowered the limit below spend,// so the backend isn't blocking yet. Being over the limit must not read quieter than approaching it.@@ -164,7 +172,7 @@ export function quotaBannerState(if (!hasCreditLimit(quota)) {return { kind: null }}- const resetsOn = dayjs(quota.period_end).format('MMMM D')+ const resetsOn = dayjs.utc(quota.period_end).format('MMMM D')if (quota.exhausted) {return { kind: 'exhausted', resetsOn, quota }}@@ -173,26 +181,3 @@ export function quotaBannerState(}return { kind: null }}--/** "You'll hit your limit around Jul 24": null when uncapped, unused, exhausted, or safely within budget. */-export function exhaustionForecast(- creditsUsed: number,- creditLimit: number | null,- periodStart: string,- periodEnd: string-): string | null {- if (creditLimit === null || creditsUsed <= 0 || creditsUsed >= creditLimit) {- return null- }- const elapsedMs = Date.now() - dayjs(periodStart).valueOf()- if (elapsedMs <= 0) {- return null- }- const burnPerMs = creditsUsed / elapsedMs- const msToLimit = (creditLimit - creditsUsed) / burnPerMs- const exhaustAt = dayjs(Date.now() + msToLimit)- if (exhaustAt.isAfter(dayjs(periodEnd))) {- return null- }- return exhaustAt.format('MMM D')-}diff --git a/products/replay_vision/frontend/utils/quotaScenarios.ts b/products/replay_vision/frontend/utils/quotaScenarios.tsnew file mode 100644index 000000000000..602c8999bd6b--- /dev/null+++ b/products/replay_vision/frontend/utils/quotaScenarios.ts@@ -0,0 +1,241 @@+import { dayjs } from 'lib/dayjs'++import type { VisionQuotaApi, VisionSpendSeriesApi } from '../generated/api.schemas'++/**+ * Dev-only fake states for every spend surface, driven by `?vision_quota_scenario=<key>`.+ * Lets the quota card, landing page, and usage tab render each state of the spend UI with+ * realistic data, without contorting billing or burning credits. Never active in production+ * builds; the overrides are display-only and the backend still enforces the real quota.+ */++export interface QuotaScenario {+ key: string+ quota: VisionQuotaApi | null+ /** Per-scanner rows for the usage tab; null keeps the real rows. */+ usageScanners: FakeUsageScanner[] | null+ /** Settled credits per UTC day from the period start to today; null keeps the real series request. */+ dailySpend: VisionSpendSeriesApi+}++export interface FakeUsageScanner {+ id: string+ name: string+ enabled: boolean+ credits_this_month: number+ observations_this_month: number+ credits_per_observation: number+ sampling_rate: number+ estimated_monthly_credits: number | null+ estimated_at: string | null+ model: string+}++const SCENARIO_PARAM = 'vision_quota_scenario'++// Hoisted so the production bundle keeps no live path into the fixtures below.+const SCENARIOS_ENABLED = process.env.NODE_ENV !== 'production'++// Scenarios run 18 days into a 30-day period, so the chart has a real spend history to draw+// regardless of today's date.+const SCENARIO_DAYS_ELAPSED = 18++function buildQuota(overrides: Partial<VisionQuotaApi>): VisionQuotaApi {+ const periodStart = dayjs.utc().subtract(SCENARIO_DAYS_ELAPSED, 'day').startOf('day')+ const base = {+ credit_limit: 5000,+ credits_used: 1850,+ remaining: 3150,+ exhausted: false,+ period_start: periodStart.toISOString(),+ period_end: periodStart.add(30, 'day').toISOString(),+ projected_monthly_credits: 2400,+ scanners_monthly_credits: 2100,+ backfills_committed_credits: 300,+ free_monthly_credits: 500,+ credits_settled: 1850,+ credits_reserved: 0,+ }+ return { ...base, ...overrides } as VisionQuotaApi+}++const FAKE_SCANNERS: FakeUsageScanner[] = [+ {+ id: 'scenario-checkout',+ name: 'Checkout errors',+ enabled: true,+ credits_this_month: 820,+ observations_this_month: 410,+ credits_per_observation: 2,+ sampling_rate: 0.25,+ estimated_monthly_credits: 700,+ estimated_at: '2026-01-01T00:00:00Z',+ model: 'standard',+ },+ {+ id: 'scenario-rage',+ name: 'Rage click detector',+ enabled: true,+ credits_this_month: 520,+ observations_this_month: 260,+ credits_per_observation: 2,+ sampling_rate: 0.1,+ estimated_monthly_credits: 900,+ estimated_at: '2026-01-01T00:00:00Z',+ model: 'standard',+ },+ {+ id: 'scenario-signup',+ name: 'Signup friction',+ enabled: true,+ credits_this_month: 510,+ observations_this_month: 255,+ credits_per_observation: 2,+ sampling_rate: 0.05,+ estimated_monthly_credits: 500,+ estimated_at: null,+ model: 'standard',+ },+]++/** Scale a scanner's period spend and monthly estimate together, so the table sums match the quota's fleet rate. */+function scaleScanners(spendFactor: number, estimateFactor: number): FakeUsageScanner[] {+ return FAKE_SCANNERS.map((s) => ({+ ...s,+ credits_this_month: Math.round(s.credits_this_month * spendFactor),+ estimated_monthly_credits:+ s.estimated_monthly_credits === null ? null : Math.round(s.estimated_monthly_credits * estimateFactor),+ }))+}++/**+ * A believable daily burn landing on `total`: gently accelerating, dipping on weekends, with+ * deterministic noise (sine-based, so every render draws the same series).+ */+function rampSpend(total: number): VisionSpendSeriesApi {+ const days = SCENARIO_DAYS_ELAPSED+ const start = dayjs.utc().subtract(SCENARIO_DAYS_ELAPSED, 'day').startOf('day')+ const weights = Array.from({ length: days }, (_, i) => {+ const weekday = start.add(i, 'day').day()+ const weekendDip = weekday === 0 || weekday === 6 ? 0.45 : 1+ const growth = 1 + (1.2 * i) / Math.max(days - 1, 1)+ const noise = 1 + 0.35 * Math.sin(i * 12.9898) * Math.sin(i * 78.233)+ return weekendDip * growth * Math.max(noise, 0.2)+ })+ const weightTotal = weights.reduce((sum, w) => sum + w, 0)+ const daily = weights.map((w) => Math.round((total * w) / weightTotal))+ // Per-day rounding drifts off `total`; settle the difference on the last day so the sum is exact.+ daily[daily.length - 1] += total - daily.reduce((sum, v) => sum + v, 0)+ return {+ period_start: start.toISOString(),+ period_end: start.add(30, 'day').toISOString(),+ days: daily.map((credits, i) => ({ date: start.add(i, 'day').format('YYYY-MM-DD'), credits })),+ }+}++const SCENARIOS: Record<string, () => Omit<QuotaScenario, 'key'>> = {+ 'on-track': () => ({+ quota: buildQuota({}),+ usageScanners: FAKE_SCANNERS,+ dailySpend: rampSpend(1850),+ }),+ 'nearing-limit': () => ({+ quota: buildQuota({+ credits_used: 2600,+ remaining: 2400,+ projected_monthly_credits: 4400,+ scanners_monthly_credits: 4100,+ }),+ usageScanners: scaleScanners(1.4, 4100 / 2100),+ dailySpend: rampSpend(2600),+ }),+ 'limit-soon': () => ({+ quota: buildQuota({+ credits_used: 3900,+ remaining: 1100,+ projected_monthly_credits: 7800,+ scanners_monthly_credits: 7500,+ }),+ usageScanners: scaleScanners(2.1, 7500 / 2100),+ dailySpend: rampSpend(3900),+ }),+ paused: () => ({+ quota: buildQuota({ credits_used: 5000, remaining: 0, exhausted: true }),+ usageScanners: scaleScanners(2.7, 7500 / 2100),+ dailySpend: rampSpend(5000),+ }),+ 'free-plan': () => ({+ quota: buildQuota({+ credit_limit: 500,+ credits_used: 260,+ remaining: 240,+ projected_monthly_credits: 420,+ scanners_monthly_credits: 420,+ backfills_committed_credits: 0,+ free_monthly_credits: 500,+ }),+ usageScanners: scaleScanners(1 / 7, 420 / 2100),+ dailySpend: rampSpend(260),+ }),+ 'free-paused': () => ({+ quota: buildQuota({+ credit_limit: 500,+ credits_used: 500,+ remaining: 0,+ exhausted: true,+ free_monthly_credits: 500,+ }),+ usageScanners: scaleScanners(1 / 4, 420 / 2100),+ dailySpend: rampSpend(500),+ }),+ 'zero-limit': () => ({+ quota: buildQuota({+ credit_limit: 0,+ credits_used: 0,+ remaining: 0,+ exhausted: true,+ projected_monthly_credits: 0,+ scanners_monthly_credits: 0,+ backfills_committed_credits: 0,+ }),+ usageScanners: FAKE_SCANNERS.map((s) => ({ ...s, credits_this_month: 0, observations_this_month: 0 })),+ dailySpend: rampSpend(0),+ }),+ 'no-limit': () => ({+ quota: buildQuota({ credit_limit: null, remaining: null }),+ usageScanners: FAKE_SCANNERS,+ dailySpend: rampSpend(1850),+ }),+ empty: () => ({+ quota: buildQuota({+ credits_used: 0,+ remaining: 5000,+ projected_monthly_credits: 0,+ scanners_monthly_credits: 0,+ backfills_committed_credits: 0,+ }),+ usageScanners: [],+ dailySpend: rampSpend(0),+ }),+}++function scenarioParam(name: string): string | null {+ try {+ return new URLSearchParams(window.location.search).get(name)+ } catch {+ return null+ }+}++/** The active scenario, or null when none is requested (the normal case, and always in production). */+export function currentQuotaScenario(): QuotaScenario | null {+ if (!SCENARIOS_ENABLED) {+ return null+ }+ const key = scenarioParam(SCENARIO_PARAM)+ const build = key && Object.hasOwn(SCENARIOS, key) ? SCENARIOS[key] : null+ if (!key || !build) {+ return null+ }+ return { key, ...build() }+}diff --git a/products/replay_vision/frontend/utils/quotaTestUtils.ts b/products/replay_vision/frontend/utils/quotaTestUtils.tsindex 453dcdfed557..4996e31cbe00 100644--- a/products/replay_vision/frontend/utils/quotaTestUtils.ts+++ b/products/replay_vision/frontend/utils/quotaTestUtils.ts@@ -7,6 +7,8 @@ export function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaAreturn {credit_limit: 10_000,credits_used: 0,+ credits_settled: 0,+ credits_reserved: 0,remaining: 10_000,exhausted: false,projected_monthly_credits: 0,diff --git a/products/replay_vision/frontend/utils/spendVerdict.test.ts b/products/replay_vision/frontend/utils/spendVerdict.test.tsnew file mode 100644index 000000000000..5a4802d9eae9--- /dev/null+++ b/products/replay_vision/frontend/utils/spendVerdict.test.ts@@ -0,0 +1,85 @@+import { fleetContributions } from './quotaContributions'+import { makeQuota } from './quotaTestUtils'+import { type SpendVerdictKind, spendVerdict } from './spendVerdict'++describe('spendVerdict', () => {+ // 20 of 30 period days remain, so a monthly rate lands at 2/3 of its value.+ test.each<[string, Parameters<typeof makeQuota>[0] | null, boolean, SpendVerdictKind, string]>([+ [+ 'uncapped org',+ { credit_limit: null, remaining: null, scanners_monthly_credits: 3000 },+ false,+ 'uncapped',+ 'No spend limit',+ ],+ ['low spend and projection', { credits_used: 1000, scanners_monthly_credits: 1500 }, false, 'safe', 'On track'],+ [+ 'projection at 85% of the limit',+ { credits_used: 5000, scanners_monthly_credits: 5250 },+ false,+ 'warning',+ 'Nearing limit',+ ],+ [+ 'backend exhausted',+ { credits_used: 10_000, remaining: 0, exhausted: true },+ false,+ 'paused',+ 'Limit reached',+ ],+ [+ 'exhausted on the free plan',+ { credit_limit: 2500, credits_used: 2500, remaining: 0, exhausted: true },+ true,+ 'paused',+ 'Out of free credits',+ ],+ // The startup cap can clamp the displayed limit below spend while the backend still allows scanning.+ [+ 'over the displayed limit, not exhausted',+ { credits_used: 11_000, exhausted: false },+ false,+ 'danger',+ 'Over limit',+ ],+ ])('%s', (_name, overrides, onFreePlan, expectedKind, expectedPill) => {+ const quota = overrides === null ? null : makeQuota(overrides)+ const verdict = spendVerdict(quota, fleetContributions(quota), { onFreePlan })+ expect(verdict.kind).toBe(expectedKind)+ expect(verdict.pillLabel).toBe(expectedPill)+ })++ // Credits are projected before any percentage is rounded, so headlines move in credits, not in 1% of the limit.+ it.each<[string, Parameters<typeof makeQuota>[0], number]>([+ // 20 of 30 days left: 1,500/30 * 20 = 1,000 on top of spend.+ ['capped, mid-period', { credits_used: 1_234, scanners_monthly_credits: 1_500 }, 2_234],+ ['capped, over the limit', { credits_used: 6_000, scanners_monthly_credits: 12_000 }, 14_000],+ [+ 'uncapped',+ { credit_limit: null, remaining: null, credits_used: 400, scanners_monthly_credits: 3_000 },+ 2_400,+ ],+ ['with a backfill commitment', { credits_used: 100, backfills_committed_credits: 250 }, 350],+ ])('projects demand in credits: %s', (_name, overrides, expected) => {+ const quota = makeQuota(overrides)+ expect(spendVerdict(quota, fleetContributions(quota), { onFreePlan: false }).projectedDemandCredits).toBe(+ expected+ )+ })++ it('dates the cap from committed one-offs when they alone overshoot it', () => {+ const quota = makeQuota({ credits_used: 5_000, backfills_committed_credits: 6_000 })+ const verdict = spendVerdict(quota, fleetContributions(quota), { onFreePlan: false })+ expect(verdict.kind).toBe('danger')+ expect(verdict.pillLabel).toMatch(/^Limit by /)+ })++ it('pins the bar at 100 while the headline keeps the real overshoot', () => {+ const quota = makeQuota({ credits_used: 6000, scanners_monthly_credits: 12_000 })+ const verdict = spendVerdict(quota, fleetContributions(quota), { onFreePlan: false })+ expect(verdict.kind).toBe('danger')+ expect(verdict.pillLabel).toMatch(/^Limit by /)+ expect(verdict.spentPct + verdict.projectedPct).toBeLessThanOrEqual(100)+ expect(verdict.periodEndPct).toBeGreaterThan(100)+ })+})diff --git a/products/replay_vision/frontend/utils/spendVerdict.ts b/products/replay_vision/frontend/utils/spendVerdict.tsnew file mode 100644index 000000000000..ac7bb45b1764--- /dev/null+++ b/products/replay_vision/frontend/utils/spendVerdict.ts@@ -0,0 +1,134 @@+import type { VisionQuotaApi } from '../generated/api.schemas'+import { formatCreditCount } from './credits'+import { type QuotaContribution, buildQuotaMeter } from './quotaContributions'+import { QUOTA_STATUS_STYLES, type QuotaProjection } from './quotaProjection'++export type SpendVerdictKind = 'safe' | 'warning' | 'danger' | 'paused' | 'uncapped'++export interface SpendVerdict {+ kind: SpendVerdictKind+ /** Short label for the status pill, e.g. "On track" or "Limit by Sep 21". */+ pillLabel: string+ /** One sentence stating the projection; the pill and the bar repeat it, never contradict it. */+ sentence: string+ /** Actual spend as a share of the limit, clamped to 0..100. */+ spentPct: number+ /** Projected additional spend as a share of the limit, clamped so spent + projected <= 100. */+ projectedPct: number+ /** Projected period-end share of the limit, unclamped (e.g. 124 when overshooting). */+ periodEndPct: number+ /** Projected period-end demand in credits, unclamped; null without a quota snapshot. */+ projectedDemandCredits: number | null+ projection: QuotaProjection+ hasCap: boolean+}++const TEXT_CLASS: Record<SpendVerdictKind, string> = {+ safe: QUOTA_STATUS_STYLES.safe.text,+ warning: QUOTA_STATUS_STYLES.warning.text,+ danger: QUOTA_STATUS_STYLES.danger.text,+ paused: QUOTA_STATUS_STYLES.danger.text,+ uncapped: 'text-secondary',+}++const COLOR_VAR: Record<SpendVerdictKind, string> = {+ safe: 'var(--success)',+ warning: 'var(--warning)',+ danger: 'var(--danger)',+ paused: 'var(--danger)',+ uncapped: 'var(--muted)',+}++/** Text colour class for a verdict, for headline numbers and captions. */+export function verdictTextClass(kind: SpendVerdictKind): string {+ return TEXT_CLASS[kind]+}++/** CSS colour variable for a verdict, for SVG marks that cannot take a class. */+export function verdictColorVar(kind: SpendVerdictKind): string {+ return COLOR_VAR[kind]+}++interface SpendVerdictOptions {+ /** Free-plan orgs run out of free credits; everyone else hits a spend limit they chose. */+ onFreePlan: boolean+ /** Subject plus verb, e.g. "Everything running is" or "Enabled scanners are". */+ subject?: string+}++/**+ * The one verdict a spend surface renders: pill, sentence, and bar widths from a single computation,+ * so a pill can never disagree with the bar beside it. Composition of the projection stays in the+ * contributions; this only decides how the total reads.+ */+export function spendVerdict(+ quota: VisionQuotaApi | null,+ contributions: QuotaContribution[],+ { onFreePlan, subject = 'Enabled scanners are' }: SpendVerdictOptions+): SpendVerdict {+ const model = buildQuotaMeter(quota, contributions)+ const { projection, periodEndPct, hasCap } = model+ const resetsOn = projection.resetsOn ?? 'period end'+ const limitNoun = onFreePlan ? 'free credits' : 'monthly spend limit'++ const spentPct = Math.min(Math.max(projection.usedPct, 0), 100)+ const projectedPct = Math.min(Math.max(periodEndPct, spentPct), 100) - spentPct++ const projectedDemandCredits = model.periodEndCredits+ const base = { spentPct, projectedPct, periodEndPct, projectedDemandCredits, projection, hasCap }++ if (!hasCap) {+ const { rateTotal: monthly, oneOffTotal: oneOffs } = model+ return {+ ...base,+ kind: 'uncapped',+ pillLabel: 'No spend limit',+ sentence: `${subject} projected to use ~${formatCreditCount(monthly)}/month${oneOffs > 0 ? ` plus ${formatCreditCount(oneOffs)} of backfills` : ''}.`,+ spentPct: 0,+ projectedPct: 0,+ }+ }++ if (projection.exhausted) {+ return {+ ...base,+ kind: 'paused',+ pillLabel: onFreePlan ? 'Out of free credits' : 'Limit reached',+ sentence: onFreePlan+ ? `Scanning is paused until ${resetsOn}: the free credits are used up.`+ : `Scanning is paused until ${resetsOn}: the monthly spend limit is reached.`,+ spentPct: 100,+ projectedPct: 0,+ }+ }++ // Over the displayed limit without the backend blocking (the startup cap clamps the display+ // below billing's limit): state the overshoot without claiming scanning is paused.+ if (projection.usedPct >= 100) {+ return {+ ...base,+ kind: 'danger',+ pillLabel: 'Over limit',+ sentence: `Spend has exceeded the ${limitNoun} for this period.`,+ }+ }++ if (model.status === 'danger') {+ const capDate = projection.capReachDate ? projection.capReachDate.format('MMM D') : null+ return {+ ...base,+ kind: 'danger',+ pillLabel: capDate ? `Limit by ${capDate}` : 'Over limit',+ sentence: capDate+ ? `${subject} on track to ${onFreePlan ? 'use up the free credits' : 'hit the monthly spend limit'} around ${capDate}.`+ : `${subject} projected to exceed the ${limitNoun} by ${resetsOn}.`,+ }+ }++ return {+ ...base,+ kind: model.status === 'warning' ? 'warning' : 'safe',+ pillLabel: model.status === 'warning' ? 'Nearing limit' : 'On track',+ sentence: `${subject} projected to use ${periodEndPct}% of the ${limitNoun} by ${resetsOn}.`,+ }+}diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yamlindex 4cb5b35b5cec..3a534d1161b8 100644--- a/products/replay_vision/mcp/tools.yaml+++ b/products/replay_vision/mcp/tools.yaml@@ -17,6 +17,9 @@ ui_apps:item_name_field: identity_label: observationtools:+ environment-vision-quota-spend-series-retrieve:+ operation: environment_vision_quota_spend_series_retrieve+ enabled: falsevision-alerts-create:operation: vision_alerts_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2d651d4d880a..e439b8b89b29 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -32504,7 +32504,7 @@ export namespace Schemas {* Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.*/export interface EstimateRequest {- /** Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate against all recordings. */+ /** Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate scans a recent window (`window_days` in the response) and scales it to 30 days. Omit to estimate against all recordings. */query?: unknown;/*** 0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).@@ -32537,11 +32537,11 @@ export namespace Schemas {* Forward-looking volume and credit-cost estimate for a proposed scanner.*/export interface EstimateResponse {- /** Distinct sessions matching the query within the 30-day lookback, after the sampling_mode quality filter but before random sampling. */+ /** Distinct sessions matching the query within the scanned window (`window_days`), after the sampling_mode quality filter but before random sampling. */matched_sessions_in_window: number;- /** Lookback window the estimate is based on. Normally 30; smaller when the team has fewer days of recordings. */+ /** Days of recordings the estimate scanned before scaling to 30. Up to a week (shorter when the query's operand rules out sampling); smaller when the team has fewer days of recordings. */window_days: number;- /** Projected monthly observations: quality-filtered matched sessions scaled to 30 days, times sampling_rate. */+ /** Projected monthly observations: quality-filtered matched sessions scaled from `window_days` to 30 days, times sampling_rate. */estimated_observations_per_month: number;/** Credits one observation costs at the proposed `model` (1 credit = $0.01). */credits_per_observation: number;@@ -55721,10 +55721,15 @@ export namespace Schemas {* @nullable*/readonly estimated_monthly_observations: number | null;+ /**+ * When `estimated_monthly_observations` was last computed. Null means the estimate is being recomputed after a config change or has never run, so the stored number may be stale.+ * @nullable+ */+ readonly estimated_at: string | null;/** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */readonly credits_per_observation: number;/**- * `estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.+ * `estimated_monthly_observations` priced at `credits_per_observation`, capped at `credit_limit` when one is set. Null until the estimate is first computed.* @nullable*/readonly estimated_monthly_credits: number | null;@@ -65587,10 +65592,15 @@ export namespace Schemas {* @nullable*/readonly estimated_monthly_observations?: number | null;+ /**+ * When `estimated_monthly_observations` was last computed. Null means the estimate is being recomputed after a config change or has never run, so the stored number may be stale.+ * @nullable+ */+ readonly estimated_at?: string | null;/** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */readonly credits_per_observation?: number;/**- * `estimated_monthly_observations` priced at `credits_per_observation`. Null until the estimate is first computed.+ * `estimated_monthly_observations` priced at `credits_per_observation`, capped at `credit_limit` when one is set. Null until the estimate is first computed.* @nullable*/readonly estimated_monthly_credits?: number | null;@@ -86608,12 +86618,16 @@ export namespace Schemas {export interface VisionQuota {/**- * Credits the org may spend per billing period (1 credit = $0.01). Null when billing has synced the product with no spend limit: uncapped.+ * Credits the organization may spend per billing period (1 credit = $0.01). 0 is a hard block: no observation can start. Null when billing has synced the product with no spend limit: uncapped.* @nullable*/readonly credit_limit: number | null;- /** Credits spent this period: succeeded observations from the receipt ledger plus reserved in-flight observations. */+ /** `credits_settled` plus `credits_reserved`: the organization's total draw on `credit_limit` this period, across every project. */readonly credits_used: number;+ /** Credits posted to the receipt ledger by succeeded observations and finished prompt-test sessions this period, across every project in the organization. Deleting an observation never refunds these. */+ readonly credits_settled: number;+ /** Credits held by in-flight observations and running prompt tests across every project in the organization. Released without charge when the work fails, settled into `credits_settled` when it succeeds. */+ readonly credits_reserved: number;/*** `credit_limit - credits_used`, floored at 0. Null when uncapped.* @nullable@@ -86627,7 +86641,7 @@ export namespace Schemas {readonly period_end: string;/** `scanners_monthly_credits` plus `backfills_committed_credits`. Kept as the single headline number; prefer the two components when pro-rating, since only the scanner half is a monthly rate. */readonly projected_monthly_credits: number;- /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */+ /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A capped scanner contributes at most what its own credit limit has left this period, folded back into a 30-day rate. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */readonly scanners_monthly_credits: number;/** Committed-but-unspent credits of the organization's active backfills. A one-off charge rather than a rate, so it lands in full regardless of how much of the period is left. */readonly backfills_committed_credits: number;@@ -86635,6 +86649,22 @@ export namespace Schemas {readonly free_monthly_credits: number;}+ export interface VisionSpendDay {+ /** UTC calendar day. */+ readonly date: string;+ /** Credits settled by observations created on this day across every project in the organization; 0 when none. */+ readonly credits: number;+ }++ export interface VisionSpendSeries {+ /** First moment of the current quota period (UTC). */+ readonly period_start: string;+ /** First moment of the next quota period (UTC); the current period's exclusive upper bound. */+ readonly period_end: string;+ /** One entry per UTC day from `period_start` through today, in order, zero-filled for days without spend. */+ readonly days: readonly VisionSpendDay[];+ }+export interface WarehouseConnection {/** Connection host — the warehouse name is the SNI subdomain, e.g. my-warehouse.dw.us.postwh.com */host: string;diff --git a/services/mcp/src/generated/replay_vision/api.ts b/services/mcp/src/generated/replay_vision/api.tsindex 799981c5d998..48e39a8f74ba 100644--- a/services/mcp/src/generated/replay_vision/api.ts+++ b/services/mcp/src/generated/replay_vision/api.ts@@ -976,7 +976,7 @@ export const VisionScannersEstimateCreateBody = () => zod.unknown().optional().describe(- 'Proposed `RecordingsQuery` for the candidate filter. `date_from`\/`date_to` are ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate against all recordings.'+ 'Proposed `RecordingsQuery` for the candidate filter. `date_from`\/`date_to` are ignored — the estimate scans a recent window (`window_days` in the response) and scales it to 30 days. Omit to estimate against all recordings.'),sampling_rate: zod.number()diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.jsonindex 5f5a6f4436b2..fdeaceda4b1b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/vision-scanners-estimate-create.json@@ -44,7 +44,7 @@"type": "string"},"query": {- "description": "Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate always uses a fixed 30-day lookback. Omit to estimate against all recordings."+ "description": "Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate scans a recent window (`window_days` in the response) and scales it to 30 days. Omit to estimate against all recordings."},"sampling_mode": {"default": "comprehensive",