:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): animate the quota meter and update it optimistically (#63140)
Tue Haulunda17c643d55a2
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9cde4a437ca9..fa83271eb493 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -3392,6 +3392,9 @@ importers:'@types/react':specifier: 18.3.27version: 18.3.27+ clsx:+ specifier: '*'+ version: 2.1.1fast-deep-equal:specifier: '*'version: 3.1.3diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 1e6c7a8ee4d1..50e7c51b0f02 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -5,6 +5,7 @@ from django.conf import settingsfrom django.db import IntegrityErrorfrom django.db.models import CharField, Count, F, Q, QuerySet, Valuefrom django.db.models.functions import Coalesce, NullIf+from django.utils import timezoneimport structlogimport django_filters@@ -50,6 +51,7 @@ from products.replay_vision.backend.models.replay_scanner import ()from products.replay_vision.backend.queries import (ESTIMATE_INTERACTIVE_MAX_EXECUTION_SECONDS,+ ESTIMATE_STALE_AFTER,estimate_scanner_session_volume,project_monthly_observations,refresh_scanner_estimate,@@ -278,12 +280,17 @@ class ReplayScannerSerializer(serializers.ModelSerializer):return scannerdef update(self, instance: ReplayScanner, validated_data: dict[str, Any]) -> ReplayScanner:+ was_enabled = instance.enabledtry:scanner = super().update(instance, validated_data)except IntegrityError as e:self._reraise_unique_name_violation(e)- # Model save clears `estimated_at` when volume inputs change; refresh eagerly for the editor.- if scanner.estimated_at is None:+ # Model save clears `estimated_at` when volume inputs change. Re-enables only refresh inline when+ # the background refresher has fallen behind, so a stale number never enters the quota sum.+ needs_refresh = scanner.estimated_at is None or (+ scanner.enabled and not was_enabled and timezone.now() - scanner.estimated_at >= ESTIMATE_STALE_AFTER+ )+ if needs_refresh:_refresh_estimate_fail_soft(scanner)return scannerdiff --git a/products/replay_vision/backend/models/replay_scanner.py b/products/replay_vision/backend/models/replay_scanner.pyindex 8b345f4af190..ae2879695979 100644--- a/products/replay_vision/backend/models/replay_scanner.py+++ b/products/replay_vision/backend/models/replay_scanner.py@@ -114,19 +114,13 @@ class ReplayScanner(UUIDModel):update_fields = kwargs.get("update_fields")if update_fields is not None:relevant = [f for f in self._VERSION_TRACKED_FIELDS if f in update_fields]- track_enabled = "enabled" in update_fieldselse:relevant = list(self._VERSION_TRACKED_FIELDS)- track_enabled = True- if self.pk and (relevant or track_enabled):+ if self.pk and relevant:# SELECT FOR UPDATE so concurrent saves can't both bump scanner_version from the same baseline.with transaction.atomic():old = (- type(self)- .objects.select_for_update()- .filter(pk=self.pk)- .only("scanner_version", "enabled", *relevant)- .first()+ type(self).objects.select_for_update().filter(pk=self.pk).only("scanner_version", *relevant).first())if old is not None:changed = {f for f in relevant if getattr(old, f) != getattr(self, f)}@@ -134,9 +128,7 @@ class ReplayScanner(UUIDModel):if changed:self.scanner_version = old.scanner_version + 1extra_fields.append("scanner_version")- # Re-enabling resurfaces a possibly long-stale estimate in the quota sum, so it invalidates too.- reenabled = track_enabled and self.enabled and not old.enabled- if (changed & self._ESTIMATE_FIELDS) or reenabled:+ if changed & self._ESTIMATE_FIELDS:self.estimated_at = Noneextra_fields.append("estimated_at")if update_fields is not None and extra_fields:diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex 82af33a3cd65..c4148c392017 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -8,12 +8,13 @@ from django.db.models.functions import Coalescefrom dateutil.relativedelta import relativedeltafrom posthog.date_util import start_of_month+from posthog.settings.utils import get_from_envfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservationfrom products.replay_vision.backend.models.replay_quota_grant import ReplayQuotaGrantfrom products.replay_vision.backend.models.replay_scanner import ReplayScanner-MONTHLY_OBSERVATION_QUOTA = 3000+MONTHLY_OBSERVATION_QUOTA = get_from_env("REPLAY_VISION_MONTHLY_OBSERVATION_QUOTA", 3000, type_cast=int)# In-flight rows count against the quota so concurrent on-demand triggers can't all race past the gate before any complete._COUNTED_STATUSES = (ObservationStatus.SUCCEEDED, ObservationStatus.PENDING, ObservationStatus.RUNNING)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 aced0d3f764e..5bba37e1638c 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@@ -13,13 +13,15 @@ from products.replay_vision.backend.temporal.estimates_types import RefreshScann@activity.defn@track_activity()def list_stale_scanner_estimates_activity() -> list[RefreshScannerEstimateInputs]:- """Enabled scanners whose persisted estimate is missing or past the staleness window, oldest first."""+ """Scanners whose persisted estimate is missing or past the staleness window.++ Disabled scanners are refreshed too so re-enabling one puts an accurate number straight into the+ quota sum. Enabled scanners come first so they can't starve behind a backlog of disabled ones.+ """cutoff = timezone.now() - ESTIMATE_STALE_AFTERrows = (- ReplayScanner.objects.filter(enabled=True)- .filter(Q(estimated_at__isnull=True) | Q(estimated_at__lt=cutoff))- # Never-estimated scanners first, then the longest-stale, so a backlog drains fairly across runs.- .order_by(F("estimated_at").asc(nulls_first=True))+ ReplayScanner.objects.filter(Q(estimated_at__isnull=True) | Q(estimated_at__lt=cutoff))+ .order_by("-enabled", F("estimated_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/activities/refresh_scanner_estimate.py b/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.pyindex 7f81da4f9eda..c3718163e240 100644--- a/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py+++ b/products/replay_vision/backend/temporal/activities/refresh_scanner_estimate.py@@ -12,11 +12,7 @@ from products.replay_vision.backend.temporal.estimates_types import RefreshScann@track_activity()def refresh_scanner_estimate_activity(inputs: RefreshScannerEstimateInputs) -> bool:"""Recompute the scanner's persisted estimate; the staleness re-check makes it idempotent against an interactive save racing the batch."""- scanner = (- ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id, enabled=True)- .select_related("team")- .first()- )+ scanner = ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id).select_related("team").first()if scanner is None:return Falseif scanner.estimated_at is not None and timezone.now() - scanner.estimated_at < ESTIMATE_STALE_AFTER:diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex fccd08cd2c24..c7eb96b4c0c8 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -637,17 +637,25 @@ class TestScannerEstimatePersistence(_VisionAPITestCase):self.assertEqual(resp.status_code, 200, resp.json())self.assertEqual(self.mock_refresh_estimate.called, expect_refresh)- def test_reenabling_refreshes_a_stale_estimate(self) -> None:+ @parameterized.expand(+ [+ ("fresh_estimate_skips_inline_refresh", timedelta(hours=1), False),+ ("stale_estimate_refreshes_inline", timedelta(days=2), True),+ ]+ )+ def test_reenabling_refreshes_inline_only_when_stale(+ self, _name: str, estimate_age: timedelta, expect_refresh: bool+ ) -> None:scanner = self._create_scanner(enabled=False)ReplayScanner.objects.filter(pk=scanner.pk).update(- estimated_monthly_observations=10, estimated_at=timezone.now() - timedelta(days=30)+ estimated_monthly_observations=10, estimated_at=timezone.now() - estimate_age)self.mock_refresh_estimate.reset_mock()resp = self.client.patch(f"{self.scanners_url}{scanner.id}/", data={"enabled": True}, format="json")self.assertEqual(resp.status_code, 200, resp.json())- self.mock_refresh_estimate.assert_called_once()+ self.assertEqual(self.mock_refresh_estimate.called, expect_refresh)def test_update_backfills_a_never_computed_estimate(self) -> None:scanner = self._create_scanner()diff --git a/products/replay_vision/backend/tests/test_estimate_refresh.py b/products/replay_vision/backend/tests/test_estimate_refresh.pyindex e1031bc7ffc4..227079e598f3 100644--- a/products/replay_vision/backend/tests/test_estimate_refresh.py+++ b/products/replay_vision/backend/tests/test_estimate_refresh.py@@ -154,14 +154,14 @@ class TestEstimateInvalidationOnSave:assert scanner.estimated_monthly_observations == 10@pytest.mark.parametrize(- "initial_enabled, new_enabled, expect_stale",+ "initial_enabled, new_enabled",[- (False, True, True), # re-enable resurfaces the estimate in the quota sum → refresh needed- (True, False, False), # disabling keeps the last estimate for display- (True, True, False), # no transition+ (False, True), # the refresher keeps disabled scanners fresh, so re-enabling needs no invalidation+ (True, False),+ (True, True),],)- def test_enabled_transitions(self, initial_enabled: bool, new_enabled: bool, expect_stale: bool) -> None:+ def test_enabled_transitions_keep_the_estimate(self, initial_enabled: bool, new_enabled: bool) -> None:scanner = _make_scanner(enabled=initial_enabled)_set_estimate(scanner, 10, hours_ago=1)scanner.refresh_from_db()@@ -170,7 +170,7 @@ class TestEstimateInvalidationOnSave:scanner.save(update_fields=["enabled"])scanner.refresh_from_db()- assert (scanner.estimated_at is None) == expect_stale+ assert scanner.estimated_at is not None@pytest.mark.django_db(transaction=True)@@ -181,12 +181,11 @@ class TestRefreshScannerEstimateActivity:(True, None, True), # never computed → refresh(True, 25, True), # stale → refresh(True, 1, False), # fresh → no-op- (False, 25, False), # disabled → no-op+ (False, 25, True), # disabled scanners refresh too, so re-enabling uses an accurate number+ (False, 1, False), # fresh → no-op regardless of enabled],)- def test_gates_on_enabled_and_staleness(- self, enabled: bool, estimated_hours_ago: int | None, expect_refresh: bool- ) -> None:+ def test_gates_on_staleness(self, enabled: bool, estimated_hours_ago: int | None, expect_refresh: bool) -> None:scanner = _make_scanner(enabled=enabled)if estimated_hours_ago is not None:_set_estimate(scanner, 10, hours_ago=estimated_hours_ago)@@ -218,7 +217,7 @@ class TestRefreshScannerEstimateActivity:@pytest.mark.django_db(transaction=True)class TestListStaleScannerEstimatesActivity:- def test_returns_stale_enabled_scanners_oldest_first(self) -> None:+ def test_returns_stale_scanners_enabled_first_then_oldest(self) -> None:never = _make_scanner(name="never-estimated")stale = _make_scanner(name="stale")_set_estimate(stale, 10, hours_ago=48)@@ -227,11 +226,12 @@ class TestListStaleScannerEstimatesActivity:fresh = _make_scanner(name="fresh")_set_estimate(fresh, 10, hours_ago=1)disabled = _make_scanner(name="disabled", enabled=False)- _set_estimate(disabled, 10, hours_ago=48)+ _set_estimate(disabled, 10, hours_ago=96)entries = list_stale_scanner_estimates_activity()- assert [e.scanner_id for e in entries] == [never.id, very_stale.id, stale.id]+ # 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 entries[0].team_id == never.team_iddef test_caps_the_batch(self) -> None:diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.test.tsnew file mode 100644index 000000000000..39e2aa5cff95--- /dev/null+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts@@ -0,0 +1,57 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import { makeQuota } from '../utils/quotaTestUtils'+import { visionQuotaLogic } from './visionQuotaLogic'++const quota = makeQuota({+ monthly_quota: 1000,+ usage_this_month: 100,+ remaining: 900,+ projected_monthly_observations: 500,+})++describe('visionQuotaLogic', () => {+ let logic: ReturnType<typeof visionQuotaLogic.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team/vision/quota/': quota,+ },+ })+ initKeaTests()+ logic = visionQuotaLogic()+ logic.mount()+ })++ afterEach(() => {+ logic?.unmount()+ })++ it('adjustProjectedMonthly shifts the loaded projection and clamps at zero', async () => {+ await expectLogic(logic).toDispatchActions(['loadQuotaSuccess'])++ logic.actions.adjustProjectedMonthly(250)+ expect(logic.values.quota?.projected_monthly_observations).toBe(750)++ logic.actions.adjustProjectedMonthly(-10_000)+ expect(logic.values.quota?.projected_monthly_observations).toBe(0)+ })++ it('adjustProjectedMonthly is a no-op before the quota has loaded', () => {+ logic.actions.adjustProjectedMonthly(250)+ expect(logic.values.quota).toBeNull()+ })++ it('loadQuota overwrites any optimistic adjustment with the server value', async () => {+ await expectLogic(logic).toDispatchActions(['loadQuotaSuccess'])+ logic.actions.adjustProjectedMonthly(250)++ await expectLogic(logic, () => logic.actions.loadQuota()).toDispatchActions(['loadQuotaSuccess'])++ expect(logic.values.quota?.projected_monthly_observations).toBe(500)+ })+})diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.tsindex 34291013bab5..bad08b4a668b 100644--- a/products/replay_vision/frontend/logics/visionQuotaLogic.ts+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.ts@@ -1,4 +1,4 @@-import { afterMount, kea, path } from 'kea'+import { actions, afterMount, kea, path, reducers } from 'kea'import { loaders } from 'kea-loaders'import { teamLogic } from 'scenes/teamLogic'@@ -10,11 +10,20 @@ import type { visionQuotaLogicType } from './visionQuotaLogicType'export const visionQuotaLogic = kea<visionQuotaLogicType>([path(['products', 'replay_vision', 'frontend', 'logics', 'visionQuotaLogic']),+ actions({+ // Declared here so the action stays zero-arg despite the loader's `breakpoint` parameter.+ loadQuota: true,+ // Optimistic shift of the fleet projection (e.g. ±scanner estimate on toggle); loadQuota reconciles.+ adjustProjectedMonthly: (delta: number) => ({ delta }),+ }),+loaders({quota: [null as VisionQuotaApi | null,{- loadQuota: async () => {+ loadQuota: async (_, breakpoint) => {+ // Coalesce bursts of post-mutation refetches (e.g. toggling several scanners).+ await breakpoint(50)const teamId = teamLogic.values.currentTeamIdif (!teamId) {return null@@ -29,6 +38,18 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([],}),+ reducers({+ quota: {+ adjustProjectedMonthly: (state: VisionQuotaApi | null, { delta }: { delta: number }) =>+ state+ ? {+ ...state,+ projected_monthly_observations: Math.max(0, state.projected_monthly_observations + delta),+ }+ : state,+ },+ }),+afterMount(({ actions }) => {actions.loadQuota()}),diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.scss b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.scssnew file mode 100644index 000000000000..dd1e665e9563--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.scss@@ -0,0 +1,34 @@+// Shifting by exactly one integer tile keeps the loop pixel-exact, so the wrap-around is seamless.+@keyframes QuotaMeterBar__stripes {+ from {+ background-position: 0 0;+ }++ to {+ background-position: 16px 0;+ }+}++.QuotaMeterBar__stripes {+ // Quarter-tile stops at 135° in a 16px square tile ≈ the same stripe density as a+ // repeating-linear-gradient with 4px/8px stops, but tiles seamlessly under animation.+ background-image: linear-gradient(+ 135deg,+ rgb(255 255 255 / 25%) 25%,+ transparent 25%,+ transparent 50%,+ rgb(255 255 255 / 25%) 50%,+ rgb(255 255 255 / 25%) 75%,+ transparent 75%,+ transparent+ );+ background-size: 16px 16px;+}++.QuotaMeterBar__stripes--animated {+ animation: QuotaMeterBar__stripes 2s linear infinite;++ @media (prefers-reduced-motion: reduce) {+ animation: none;+ }+}diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.tsnew file mode 100644index 000000000000..e3808309750a--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts@@ -0,0 +1,21 @@+import { clampSegmentWidths } from './QuotaMeterBar'++describe('clampSegmentWidths', () => {+ it('passes widths through when they fit', () => {+ expect(clampSegmentWidths([40, 20, 10])).toEqual([40, 20, 10])+ })++ it('truncates the overflowing segment and zeroes the rest', () => {+ expect(clampSegmentWidths([60, 30, 50])).toEqual([60, 30, 10])+ expect(clampSegmentWidths([80, 120, 50])).toEqual([80, 20, 0])+ })++ it('zeroes later segments when the bar is already saturated', () => {+ expect(clampSegmentWidths([100, 30, 10])).toEqual([100, 0, 0])+ expect(clampSegmentWidths([150, 30])).toEqual([100, 0])+ })++ it('floors negative widths at zero without consuming headroom', () => {+ expect(clampSegmentWidths([-10, 50])).toEqual([0, 50])+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsxnew file mode 100644index 000000000000..5537da6fb956--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx@@ -0,0 +1,85 @@+import './QuotaMeterBar.scss'++import clsx from 'clsx'+import type { ReactNode } from 'react'++export interface QuotaMeterSegment {+ /** Width as a percentage of the cap; may exceed the bar — segments are clamped cumulatively. */+ pct: number+ /** Background class, e.g. `bg-success` / `bg-warning` / `bg-danger` / `bg-accent`. */+ barClass: string+ /** Overlay the animated stripe pattern. */+ striped?: boolean+}++interface QuotaMeterBarProps {+ /** Solid segment: actual usage as a percentage of the cap. */+ usedPct: number+ /** Striped/solid projection segments, rendered in order after the used segment. */+ projected: QuotaMeterSegment[]+ valueNow: number+ label: string+ className?: string+}++/** Segment widths fill left to right; later segments absorb overflow past 100%. */+export function clampSegmentWidths(pcts: number[]): number[] {+ let headroom = 100+ return pcts.map((pct) => {+ const width = Math.max(Math.min(pct, headroom), 0)+ headroom -= width+ return width+ })+}++/** Quota meter: solid used segment plus projection segments; later segments absorb overflow past 100%. */+export function QuotaMeterBar({ usedPct, projected, valueNow, label, className }: QuotaMeterBarProps): JSX.Element {+ const widths = clampSegmentWidths([usedPct, ...projected.map((segment) => segment.pct)])+ return (+ <div+ className={clsx('flex h-3 rounded overflow-hidden bg-fill-tertiary', className)}+ role="meter"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={Math.min(Math.round(valueNow), 100)}+ aria-label={label}+ >+ <div className="bg-muted transition-[width] duration-500 ease-out" style={{ width: `${widths[0]}%` }} />+ {projected.map(({ barClass, striped }, index) => (+ <div+ key={index}+ className={clsx(+ 'transition-[width,background-color] duration-500 ease-out',+ striped && 'QuotaMeterBar__stripes QuotaMeterBar__stripes--animated',+ barClass+ )}+ style={{ width: `${widths[index + 1]}%` }}+ />+ ))}+ </div>+ )+}++/** Legend entry with a chip matching a bar segment. */+export function QuotaMeterLegendItem({+ barClass,+ striped,+ children,+}: {+ barClass?: string+ striped?: boolean+ children: ReactNode+}): JSX.Element {+ return (+ <div className="flex items-center gap-1">+ <span+ className={clsx(+ 'inline-block w-2.5 h-2.5 rounded-sm',+ striped && 'QuotaMeterBar__stripes',+ barClass ?? 'bg-muted'+ )}+ />+ {children}+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsxnew file mode 100644index 000000000000..e00ab4eea87d--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx@@ -0,0 +1,18 @@+import type { QuotaProjection } from '../../utils/quotaProjection'++/** Red warning when the quota is exhausted or projected to overshoot; renders nothing otherwise. */+export function QuotaStatusLine({ projection }: { projection: QuotaProjection }): JSX.Element | null {+ if (projection.exhausted) {+ return <span className="text-danger">Quota exhausted</span>+ }+ if (projection.status !== 'danger') {+ return null+ }+ return projection.capReachDate ? (+ <span className="text-danger">+ Quota projected to run out on <strong>{projection.capReachDate.format('MMMM D')}</strong>+ </span>+ ) : (+ <span className="text-danger">Projected to exceed the monthly quota</span>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsxindex dc414237fa9a..e5728214085c 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx@@ -3,19 +3,15 @@ import { useValues } from 'kea'import { Spinner, Tooltip } from '@posthog/lemon-ui'import { visionQuotaLogic } from '../../logics/visionQuotaLogic'-import { type QuotaStatus, projectQuota } from '../../utils/quotaProjection'+import { QUOTA_STATUS_STYLES, type QuotaStatus, projectQuota, splitProjectedPct } from '../../utils/quotaProjection'import { replayScannerLogic } from '../replayScannerLogic'+import { QuotaMeterBar, QuotaMeterLegendItem } from './QuotaMeterBar'+import { QuotaStatusLine } from './QuotaStatusLine'interface Props {scannerId: string}-const STATUS_STYLES: Record<QuotaStatus, { bar: string; text: string }> = {- safe: { bar: 'bg-success', text: 'text-success' },- warning: { bar: 'bg-warning', text: 'text-warning' },- danger: { bar: 'bg-danger', text: 'text-danger' },-}-export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {const { scanner, scannerEstimate, scannerEstimateLoading, scannerEstimateError } = useValues(replayScannerLogic({ id: scannerId })@@ -32,21 +28,21 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {const used = quota?.usage_this_month ?? 0const cap = quota?.monthly_quota ?? 0- // The fleet sum already contains this scanner's stored estimate when it's enabled, so only the- // delta between the proposed config and that stored contribution is added on top.+ // The fleet sum already contains this scanner's stored estimate when it's enabled. Deriving the+ // delta from the clamped `othersMonthly` keeps the projection and the bar split consistent even+ // when a stale stored estimate exceeds the reported fleet sum.const storedContribution = scanner.enabled ? (scanner.estimated_monthly_observations ?? 0) : 0- const projection = projectQuota(quota, projected !== null ? projected - storedContribution : 0)- const { status, capReachDate, projectedPeriodEndRatio, resetsOn, daysRemaining, combinedDailyRate } = projection+ const fleetMonthly = quota?.projected_monthly_observations ?? 0+ const othersMonthly = Math.max(fleetMonthly - storedContribution, 0)+ const projection = projectQuota(quota, projected !== null ? othersMonthly + projected - fleetMonthly : 0)+ const { status, percentLabel, resetsOn, usedPct, projectedPct } = projectionconst effectiveStatus: QuotaStatus = projected === null ? 'safe' : status- const styles = STATUS_STYLES[effectiveStatus]- const percentLabel = hasCap ? Math.round(projectedPeriodEndRatio * 100) : 0+ const styles = QUOTA_STATUS_STYLES[effectiveStatus]- const usedPct = hasCap ? Math.min((used / cap) * 100, 100) : 0- const additionalUsagePct =- hasCap && projected !== null ? Math.min((combinedDailyRate * daysRemaining * 100) / cap, 100 - usedPct) : 0+ const { thisScannerPct, othersPct } = splitProjectedPct(projectedPct, projected ?? 0, othersMonthly)- const renderBreakdown = (): JSX.Element => (+ const breakdown = (<div className="text-xs space-y-0.5"><div>Used this month: <strong>{used.toLocaleString()}</strong>@@ -54,6 +50,9 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {<div>Projected from this scanner: <strong>~{(projected ?? 0).toLocaleString()}/month</strong></div>+ <div>+ Projected from other scanners: <strong>~{othersMonthly.toLocaleString()}/month</strong>+ </div><div>Monthly quota: <strong>{cap.toLocaleString()}</strong></div>@@ -61,31 +60,12 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {</div>)- const renderStatusLine = (): JSX.Element | string => {- if (effectiveStatus === 'danger') {- if (capReachDate) {- return (- <span className="text-danger">- You'll run out of observations on <strong>{capReachDate.format('MMMM D')}</strong> at this rate.- </span>- )- }- return <span className="text-danger">Projected to exceed your monthly cap.</span>- }- return (- <>- Based on <strong>{scannerEstimate?.matched_sessions_in_window.toLocaleString() ?? 0}</strong> matching- recordings in the last {scannerEstimate?.window_days ?? 0} days.- </>- )- }-return (<div className="border rounded p-3 bg-bg-light space-y-2"><div className="flex items-baseline justify-between gap-3"><div className="text-xs font-medium uppercase tracking-wide text-muted">Estimated impact</div>{hasCap && projected !== null && (- <Tooltip title={renderBreakdown()}>+ <Tooltip title={breakdown}><span className={`text-xs tabular-nums ${styles.text}`}>{percentLabel}%{' '}<span className="text-muted font-normal">by {resetsOn ?? 'period end'}</span>@@ -111,51 +91,33 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {<div className="text-sm text-muted">—</div>)}{hasCap && (- <span className="text-xs text-muted tabular-nums">- {used.toLocaleString()} / {cap.toLocaleString()}+ <span className="text-xs tabular-nums">+ <QuotaStatusLine projection={projection} /></span>)}</div>{hasCap && projected !== null && (<>- <Tooltip title={renderBreakdown()}>- <div- className="flex h-3 rounded overflow-hidden bg-fill-tertiary"- role="meter"- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={percentLabel}- aria-label={`Projected ${percentLabel}% of monthly observation quota by ${+ <Tooltip title={breakdown}>+ <QuotaMeterBar+ usedPct={usedPct}+ projected={[+ { pct: othersPct, barClass: 'bg-accent' },+ { pct: thisScannerPct, barClass: styles.bar, striped: true },+ ]}+ valueNow={percentLabel}+ label={`Projected ${percentLabel}% of monthly observation quota by ${resetsOn ?? 'period end'}`}- >- <div className="bg-muted" style={{ width: `${usedPct}%` }} />- <div- className={styles.bar}- style={{- width: `${additionalUsagePct}%`,- backgroundImage:- 'repeating-linear-gradient(135deg, rgba(255,255,255,0.25) 0, rgba(255,255,255,0.25) 4px, transparent 4px, transparent 8px)',- }}- />- </div>+ /></Tooltip><div className="flex items-center gap-3 text-xs text-muted">- <div className="flex items-center gap-1">- <span className="inline-block w-2.5 h-2.5 rounded-sm bg-muted" />- Used- </div>- <div className="flex items-center gap-1">- <span- className={`inline-block w-2.5 h-2.5 rounded-sm ${styles.bar}`}- style={{- backgroundImage:- 'repeating-linear-gradient(135deg, rgba(255,255,255,0.25) 0, rgba(255,255,255,0.25) 2px, transparent 2px, transparent 4px)',- }}- />- Projected from this scanner- </div>+ <QuotaMeterLegendItem>Used</QuotaMeterLegendItem>+ <QuotaMeterLegendItem barClass="bg-accent">Projected (other scanners)</QuotaMeterLegendItem>+ <QuotaMeterLegendItem barClass={styles.bar} striped>+ Projected (this scanner)+ </QuotaMeterLegendItem></div></>)}@@ -169,7 +131,10 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {<Spinner /> Estimating from your filters…</div>) : scannerEstimate ? (- <div className="text-xs text-muted">{renderStatusLine()}</div>+ <div className="text-xs text-muted">+ Based on <strong>{scannerEstimate.matched_sessions_in_window.toLocaleString()}</strong> matching+ recordings in the last {scannerEstimate.window_days} days.+ </div>) : scannerEstimateError ? (<div className="text-xs text-danger">Couldn't estimate impact: {scannerEstimateError}</div>) : (diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsxindex 04824039fa8a..06e6e7292aaf 100644--- a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx@@ -9,9 +9,11 @@ import { InsightVizNode, NodeKind, ProductKey, TrendsQuery } from '~/queries/schimport { BaseMathType, ChartDisplayType } from '~/types'import { visionQuotaLogic } from '../../logics/visionQuotaLogic'-import { projectQuota } from '../../utils/quotaProjection'+import { QUOTA_STATUS_STYLES, projectQuota } from '../../utils/quotaProjection'import { replayScannersLogic } from '../replayScannersLogic'import { SCANNER_TYPE_OPTIONS, SCANNER_TYPE_TAG_TYPE, scannerTypeLabel } from '../types'+import { QuotaMeterBar, QuotaMeterLegendItem } from './QuotaMeterBar'+import { QuotaStatusLine } from './QuotaStatusLine'const RECORDING_OBSERVED_EVENT = '$recording_observed'const COLLECTION_ID = 'replay-vision-list-observations'@@ -22,13 +24,9 @@ export function VisionMetrics(): JSX.Element {const { quota } = useValues(visionQuotaLogic)const projection = projectQuota(quota)- const { resetsOn, status, daysRemaining, combinedDailyRate } = projection- const used = quota?.usage_this_month ?? 0- const cap = quota?.monthly_quota ?? 0- const hasCap = cap > 0- const usedPct = hasCap ? Math.min((used / cap) * 100, 100) : 0- const additionalUsagePct = hasCap ? Math.min((combinedDailyRate * daysRemaining * 100) / cap, 100 - usedPct) : 0- const projectedBarColor = status === 'danger' ? 'bg-danger' : status === 'warning' ? 'bg-warning' : 'bg-success'+ const { resetsOn, status, percentLabel, usedPct, projectedPct } = projection+ const hasCap = (quota?.monthly_quota ?? 0) > 0+ const styles = QUOTA_STATUS_STYLES[status]// `tags.productKey` is required for ClickHouse query tagging; without it the runner aborts.const chartSource: TrendsQuery = {@@ -97,7 +95,15 @@ export function VisionMetrics(): JSX.Element {</div></div><div className="flex-1 bg-bg-light border rounded p-4 flex flex-col">- <div className="text-muted text-xs font-medium uppercase mb-2">Observations this month</div>+ <div className="flex items-baseline justify-between gap-3 mb-2">+ <div className="text-muted text-xs font-medium uppercase">Observations this month</div>+ {hasCap && (+ <span className={`text-xs tabular-nums ${styles.text}`}>+ {percentLabel}%{' '}+ <span className="text-muted font-normal">by {resetsOn ?? 'period end'}</span>+ </span>+ )}+ </div>{quota ? (<><div className="text-3xl font-semibold tabular-nums">@@ -126,46 +132,21 @@ export function VisionMetrics(): JSX.Element {</div>}>- <div- className="flex h-3 rounded overflow-hidden bg-fill-tertiary mt-2"- role="meter"- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={Math.round(usedPct + additionalUsagePct)}- aria-label={`${Math.round(usedPct + additionalUsagePct)}% of monthly observation quota`}- >- <div className="bg-muted" style={{ width: `${usedPct}%` }} />- <div- className={projectedBarColor}- style={{- width: `${additionalUsagePct}%`,- backgroundImage:- 'repeating-linear-gradient(135deg, rgba(255,255,255,0.25) 0, rgba(255,255,255,0.25) 4px, transparent 4px, transparent 8px)',- }}- />- </div>+ <QuotaMeterBar+ className="mt-2"+ usedPct={usedPct}+ projected={[{ pct: projectedPct, barClass: styles.bar, striped: true }]}+ valueNow={percentLabel}+ label={`Projected ${percentLabel}% of monthly observation quota`}+ /></Tooltip><div className="flex items-center gap-3 text-xs text-muted mt-1.5">- <div className="flex items-center gap-1">- <span className="inline-block w-2 h-2 rounded-sm bg-muted" />- Used- </div>- <div className="flex items-center gap-1">- <span- className={`inline-block w-2 h-2 rounded-sm ${projectedBarColor}`}- style={{- backgroundImage:- 'repeating-linear-gradient(135deg, rgba(255,255,255,0.25) 0, rgba(255,255,255,0.25) 2px, transparent 2px, transparent 4px)',- }}- />+ <QuotaMeterLegendItem>Used</QuotaMeterLegendItem>+ <QuotaMeterLegendItem barClass={styles.bar} striped>Projected- </div>- <span className="ml-auto text-muted">- {quota.exhausted ? (- <span className="text-danger">Quota exhausted</span>- ) : (- `${quota.remaining.toLocaleString()} remaining`- )}+ </QuotaMeterLegendItem>+ <span className="ml-auto">+ <QuotaStatusLine projection={projection} /></span></div></>diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.tsindex 02abc4b66293..1e5b574cd80f 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts@@ -4,6 +4,8 @@ import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'+import { visionQuotaLogic } from '../logics/visionQuotaLogic'+import { makeQuota as makeQuotaFixture } from '../utils/quotaTestUtils'import {buildScannerListParams,replayScannersLogic,@@ -12,6 +14,13 @@ import {} from './replayScannersLogic'import { ScannerConfig, ScannerType, ReplayScanner } from './types'+const quotaFixture = makeQuotaFixture({+ monthly_quota: 1000,+ usage_this_month: 100,+ remaining: 900,+ projected_monthly_observations: 500,+})+function defaultConfigForType(scannerType: ScannerType): ScannerConfig {if (scannerType === 'summarizer') {return { prompt: 'Summarize this session.', length: 'medium' }@@ -60,6 +69,9 @@ describe('replayScannersLogic', () => {patch: {'/api/projects/:team/vision/scanners/:id/': () => [200, {}],},+ delete: {+ '/api/projects/:team/vision/scanners/:id/': () => [204, null],+ },})initKeaTests()logic = replayScannersLogic()@@ -304,6 +316,61 @@ describe('replayScannersLogic', () => {togglingIds: [],})})++ it('toggle shifts the quota projection optimistically by the stored estimate', async () => {+ const quotaLogic = visionQuotaLogic()+ quotaLogic.mount()+ quotaLogic.actions.loadQuotaSuccess(quotaFixture)+ logic.actions.loadScannersSuccess(+ [makeScanner({ id: 'a', enabled: true, estimated_monthly_observations: 200 })],+ 1+ )++ logic.actions.toggleScannerEnabled('a') // disabling → subtract the stored estimate++ expect(quotaLogic.values.quota?.projected_monthly_observations).toBe(300)+ quotaLogic.unmount()+ })++ it('delete shifts the quota projection optimistically for enabled scanners only', async () => {+ const quotaLogic = visionQuotaLogic()+ quotaLogic.mount()+ quotaLogic.actions.loadQuotaSuccess(quotaFixture)+ logic.actions.loadScannersSuccess(+ [+ makeScanner({ id: 'a', enabled: true, estimated_monthly_observations: 200 }),+ makeScanner({ id: 'b', name: 'other', enabled: false, estimated_monthly_observations: 999 }),+ ],+ 2+ )++ logic.actions.deleteScanner('b') // disabled — contributes nothing to the sum+ expect(quotaLogic.values.quota?.projected_monthly_observations).toBe(500)++ logic.actions.deleteScanner('a')+ expect(quotaLogic.values.quota?.projected_monthly_observations).toBe(300)+ quotaLogic.unmount()+ })++ it('a failed delete reverts the optimistic projection shift', async () => {+ useMocks({+ // The quota GET must be mocked: `toFinishAllListeners` waits out the quota loader too.+ get: { '/api/projects/:team/vision/quota/': quotaFixture },+ delete: { '/api/projects/:team/vision/scanners/:id/': () => [500, {}] },+ })+ const quotaLogic = visionQuotaLogic()+ quotaLogic.mount()+ quotaLogic.actions.loadQuotaSuccess(quotaFixture)+ logic.actions.loadScannersSuccess(+ [makeScanner({ id: 'a', enabled: true, estimated_monthly_observations: 200 })],+ 1+ )++ await expectLogic(logic, () => logic.actions.deleteScanner('a')).toFinishAllListeners()++ expect(quotaLogic.values.quota?.projected_monthly_observations).toBe(500)+ quotaLogic.unmount()+ })})it('setChartDateRange updates the chart date range', async () => {diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.tsindex 616487ca8d91..030fadfc414a 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts@@ -286,11 +286,16 @@ export const replayScannersLogic = kea<replayScannersLogicType>([if (!teamId) {return}+ // Deleting an enabled scanner removes its known contribution from the fleet sum — exact, so apply it now.+ const scanner = values.scanners.find((s) => s.id === id)+ const delta = scanner?.enabled ? -(scanner.estimated_monthly_observations ?? 0) : 0+ visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(delta)try {await visionScannersDestroy(String(teamId), id)actions.deleteScannerSuccess(id)lemonToast.success('Scanner deleted')} catch (error: any) {+ visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(-delta)lemonToast.error(`Failed to delete scanner${error.detail ? `: ${error.detail}` : ''}`)}},@@ -346,12 +351,17 @@ export const replayScannersLogic = kea<replayScannersLogicType>([actions.revertScannerEnabled(id)return}+ // The stored estimate is kept ≤24h fresh even while disabled, so the projection shift is known up front.+ const estimate = scanner.estimated_monthly_observations ?? 0+ const delta = scanner.enabled ? estimate : -estimate+ visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(delta)try {await visionScannersPartialUpdate(String(teamId), id, { enabled: scanner.enabled })actions.toggleScannerEnabledDone(id)} catch (error: any) {const verb = scanner.enabled ? 'enable' : 'disable'lemonToast.error(`Failed to ${verb} scanner${error.detail ? `: ${error.detail}` : ''}`)+ visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(-delta)actions.revertScannerEnabled(id)}},diff --git a/products/replay_vision/frontend/utils/quotaProjection.test.ts b/products/replay_vision/frontend/utils/quotaProjection.test.tsindex 133ade0be048..026c9ae36d1d 100644--- a/products/replay_vision/frontend/utils/quotaProjection.test.ts+++ b/products/replay_vision/frontend/utils/quotaProjection.test.ts@@ -1,39 +1,23 @@-import { dayjs } from 'lib/dayjs'--import type { VisionQuotaApi } from '../generated/api.schemas'-import { QUOTA_WARN_THRESHOLD, projectQuota, quotaUx } from './quotaProjection'--function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaApi {- const now = dayjs()- return {- monthly_quota: 10_000,- usage_this_month: 0,- remaining: 10_000,- exhausted: false,- projected_monthly_observations: 0,- period_start: now.subtract(10, 'day').toISOString(),- period_end: now.add(20, 'day').toISOString(),- ...overrides,- } as VisionQuotaApi-}+import { projectQuota, quotaUx, splitProjectedPct } from './quotaProjection'+import { makeQuota } from './quotaTestUtils'describe('projectQuota', () => {it('returns the empty projection when quota is null or unbounded', () => {- expect(projectQuota(null)).toMatchObject({ status: 'safe', daysRemaining: 0 })- expect(projectQuota(makeQuota({ monthly_quota: 0 }))).toMatchObject({ status: 'safe', combinedDailyRate: 0 })+ expect(projectQuota(null)).toMatchObject({ status: 'safe', usedPct: 0, projectedPct: 0 })+ expect(projectQuota(makeQuota({ monthly_quota: 0 }))).toMatchObject({ status: 'safe', percentLabel: 0 })})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({ usage_this_month: 1_000, projected_monthly_observations: 3_000 }))expect(proj.status).toBe('safe')- expect(proj.projectedPeriodEndRatio).toBeLessThan(QUOTA_WARN_THRESHOLD)+ expect(proj.percentLabel).toBe(30)})it('zero fleet rate projects flat usage to period end', () => {const proj = projectQuota(makeQuota({ usage_this_month: 4_000 }))- expect(proj.combinedDailyRate).toBe(0)- expect(proj.projectedPeriodEndRatio).toBeCloseTo(0.4)+ expect(proj.projectedPct).toBe(0)+ expect(proj.percentLabel).toBe(40)expect(proj.capReachDate).toBeNull()})@@ -41,21 +25,20 @@ describe('projectQuota', () => {// 3,000 used + 9,000/month fleet → 300/day × 20 days → ends at 9,000 (90% of cap).const proj = projectQuota(makeQuota({ usage_this_month: 3_000, projected_monthly_observations: 9_000 }))expect(proj.status).toBe('warning')- expect(proj.projectedPeriodEndRatio).toBeGreaterThanOrEqual(QUOTA_WARN_THRESHOLD)- expect(proj.capReachInPeriod).toBe(false)+ expect(proj.percentLabel).toBe(90)})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({ usage_this_month: 9_000, projected_monthly_observations: 3_000 }))expect(proj.status).toBe('danger')- expect(proj.capReachInPeriod).toBe(true)expect(proj.capReachDate).not.toBeNull()})it('danger when explicitly exhausted regardless of the fleet rate', () => {const proj = projectQuota(makeQuota({ usage_this_month: 10_000, remaining: 0, exhausted: true }))expect(proj.status).toBe('danger')+ expect(proj.exhausted).toBe(true)})it('a positive scanner delta raises the projection on top of the fleet sum', () => {@@ -64,15 +47,37 @@ describe('projectQuota', () => {makeQuota({ usage_this_month: 1_000, projected_monthly_observations: 3_000 }),6_000)- expect(withDelta.combinedDailyRate).toBeGreaterThan(base.combinedDailyRate)- expect(withDelta.projectedPeriodEndRatio).toBeGreaterThan(base.projectedPeriodEndRatio)+ expect(withDelta.projectedPct).toBeGreaterThan(base.projectedPct)+ expect(withDelta.percentLabel).toBeGreaterThan(base.percentLabel)})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_observations: 3_000 }), -1_000)- expect(lowered.combinedDailyRate).toBeCloseTo(2_000 / 30)+ expect(lowered.projectedPct).toBeCloseTo(13.33, 1)const clamped = projectQuota(makeQuota({ projected_monthly_observations: 3_000 }), -9_000)- expect(clamped.combinedDailyRate).toBe(0)+ expect(clamped.projectedPct).toBe(0)+ })++ 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({ usage_this_month: 8_000, projected_monthly_observations: 30_000 }))+ expect(proj.percentLabel).toBe(280)+ expect(proj.projectedPct).toBeCloseTo(200, 0)+ })+})++describe('splitProjectedPct', () => {+ it('apportions by monthly volume', () => {+ expect(splitProjectedPct(30, 100, 200)).toEqual({ thisScannerPct: 10, othersPct: 20 })+ })++ it('gives everything to this scanner when the fleet is empty', () => {+ expect(splitProjectedPct(30, 100, 0)).toEqual({ thisScannerPct: 30, othersPct: 0 })+ })++ it('defaults the share to zero (no division by zero) when both volumes are zero', () => {+ expect(splitProjectedPct(30, 0, 0)).toEqual({ thisScannerPct: 0, othersPct: 30 })})})diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.tsindex f813e2abb90a..066b259b6f0b 100644--- a/products/replay_vision/frontend/utils/quotaProjection.ts+++ b/products/replay_vision/frontend/utils/quotaProjection.ts@@ -6,24 +6,33 @@ export const QUOTA_WARN_THRESHOLD = 0.85export type QuotaStatus = 'safe' | 'warning' | 'danger'+export const QUOTA_STATUS_STYLES: Record<QuotaStatus, { bar: string; text: string }> = {+ safe: { bar: 'bg-success', text: 'text-success' },+ warning: { bar: 'bg-warning', text: 'text-warning' },+ danger: { bar: 'bg-danger', text: 'text-danger' },+}+export interface QuotaProjection {status: QuotaStatus+ exhausted: booleancapReachDate: dayjs.Dayjs | null- capReachInPeriod: boolean- projectedPeriodEndRatio: number+ /** Projected period-end usage as a rounded percentage of the cap; exceeds 100 on overshoot. */+ percentLabel: numberresetsOn: string | null- daysRemaining: number- combinedDailyRate: number+ /** Actual usage as a percentage of the cap; `QuotaMeterBar` clamps for display. */+ usedPct: number+ /** Projected additional usage as a percentage of the cap, unclamped. */+ projectedPct: number}const EMPTY: QuotaProjection = {status: 'safe',+ exhausted: false,capReachDate: null,- capReachInPeriod: false,- projectedPeriodEndRatio: 0,+ percentLabel: 0,resetsOn: null,- daysRemaining: 0,- combinedDailyRate: 0,+ usedPct: 0,+ projectedPct: 0,}/**@@ -46,8 +55,9 @@ export function projectQuota(quota: VisionQuotaApi | null, scannerProjectedMonthconst projectedMonthly = Math.max(quota.projected_monthly_observations + scannerProjectedMonthlyDelta, 0)const combinedDailyRate = projectedMonthly / periodLengthDays+ const projectedAdditional = combinedDailyRate * daysRemaining- const projectedPeriodEndRatio = (used + combinedDailyRate * daysRemaining) / cap+ const projectedPeriodEndRatio = (used + projectedAdditional) / capconst capReachDate = combinedDailyRate > 0 && used < cap ? now.add((cap - used) / combinedDailyRate, 'day') : nullconst capReachInPeriod = !!(capReachDate && periodEnd && capReachDate.isBefore(periodEnd))@@ -60,15 +70,27 @@ export function projectQuota(quota: VisionQuotaApi | null, scannerProjectedMonthreturn {status,+ exhausted: quota.exhausted,capReachDate,- capReachInPeriod,- projectedPeriodEndRatio,+ percentLabel: Math.round(projectedPeriodEndRatio * 100),resetsOn,- daysRemaining,- combinedDailyRate,+ usedPct: (used / cap) * 100,+ projectedPct: (projectedAdditional / cap) * 100,}}+/** Apportion a projected percentage between this scanner and the rest of the fleet by monthly volume. */+export function splitProjectedPct(+ projectedPct: number,+ thisScannerMonthly: number,+ othersMonthly: number+): { thisScannerPct: number; othersPct: number } {+ const combined = thisScannerMonthly + othersMonthly+ const thisScannerPct = combined > 0 ? (projectedPct * thisScannerMonthly) / combined : 0+ // Exact complement so the two segments always sum to the full projection.+ return { thisScannerPct, othersPct: projectedPct - thisScannerPct }+}+/*** Disabled-reason / tooltip for scan triggers based on the monthly observation quota.* Assumes block-only overage policy; revisit when `usage_based` lands so we don't disable on metered orgs.diff --git a/products/replay_vision/frontend/utils/quotaTestUtils.ts b/products/replay_vision/frontend/utils/quotaTestUtils.tsnew file mode 100644index 000000000000..2123c443daae--- /dev/null+++ b/products/replay_vision/frontend/utils/quotaTestUtils.ts@@ -0,0 +1,17 @@+import type { VisionQuotaApi } from '../generated/api.schemas'++/** Test-only `VisionQuotaApi` builder: a 10,000 cap with 20 of 30 period days remaining. */+export function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaApi {+ const now = new Date()+ const daysFromNow = (days: number): string => new Date(now.getTime() + days * 24 * 3600 * 1000).toISOString()+ return {+ monthly_quota: 10_000,+ usage_this_month: 0,+ remaining: 10_000,+ exhausted: false,+ projected_monthly_observations: 0,+ period_start: daysFromNow(-10),+ period_end: daysFromNow(20),+ ...overrides,+ }+}diff --git a/products/replay_vision/package.json b/products/replay_vision/package.jsonindex 18adb7b6f4dd..e053e598ee48 100644--- a/products/replay_vision/package.json+++ b/products/replay_vision/package.json@@ -18,6 +18,7 @@"@posthog/lemon-ui": "*","@storybook/react": "catalog:","@types/react": "*",+ "clsx": "*","fast-deep-equal": "*","react": "*","typescript": "*"