Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-vision): billed-dollar spend labels, free tier surfacing, and lower quota fallback (#76120)

Tue Haulund77ac5223bdca
diff --git a/products/replay_vision/backend/api/quota.py b/products/replay_vision/backend/api/quota.py
index 78cd800af8a5..1a8cced85fc5 100644
--- a/products/replay_vision/backend/api/quota.py
+++ b/products/replay_vision/backend/api/quota.py
@@ -48,6 +48,13 @@ class VisionQuotaSerializer(serializers.Serializer):
"Scanners without a computed estimate contribute 0."
),
)
+ free_monthly_credits = serializers.IntegerField(
+ read_only=True,
+ help_text=(
+ "Credits per period included for free. Already counted inside `credit_limit`; "
+ "only credits beyond this number are billed."
+ ),
+ )
class VisionQuotaViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
diff --git a/products/replay_vision/backend/billing.py b/products/replay_vision/backend/billing.py
index 600082f427be..bc8c0d62f75a 100644
--- a/products/replay_vision/backend/billing.py
+++ b/products/replay_vision/backend/billing.py
@@ -83,6 +83,11 @@ AVG_OUTPUT_TOKENS_PER_OBSERVATION = 200
# (rasterizing, video cache storage, retries) plus margin.
TARGET_MARGIN = 3.75
+# Mirrors the free plan's `free_allocation` in the billing service (billing/constants/plans/replay_vision).
+# Billing bakes it into the synced credit limit (the $ limit converts to credits on top of the free tier),
+# so this constant is display-only: it lets the UI report billed dollars as credits beyond the free tier.
+FREE_TIER_MONTHLY_CREDITS = 2500
+
def suggested_observation_credits(info: GeminiModelInfo, margin: float = TARGET_MARGIN) -> int:
"""Suggested credits per observation for a model, derived from its token prices and a target margin."""
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index 7e0cb24805d1..f471d680ace0 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -13,7 +13,7 @@ from posthog.date_util import start_of_month
from posthog.models.organization import Organization
from posthog.settings.utils import get_from_env
-from products.replay_vision.backend.billing import observation_credits_for_model
+from products.replay_vision.backend.billing import FREE_TIER_MONTHLY_CREDITS, observation_credits_for_model
from products.replay_vision.backend.models.replay_observation import (
IN_FLIGHT_STATUSES,
ObservationStatus,
@@ -24,8 +24,10 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner
logger = structlog.get_logger(__name__)
-# Fallback monthly credit cap for orgs billing has never synced (self-hosted, pre-launch beta).
-MONTHLY_CREDIT_QUOTA = get_from_env("REPLAY_VISION_MONTHLY_CREDIT_QUOTA", 15000, type_cast=int)
+# Fallback monthly credit cap for orgs billing has never synced (self-hosted, sync gaps, malformed
+# limits). Matches the free plan's allocation so an unsynced org is never better off than a synced
+# free-tier org; self-hosted deployments raise it via the env var.
+MONTHLY_CREDIT_QUOTA = get_from_env("REPLAY_VISION_MONTHLY_CREDIT_QUOTA", FREE_TIER_MONTHLY_CREDITS, type_cast=int)
# Billing's usage_key for this product; see ee/billing/quota_limiting.QuotaResource.REPLAY_VISION_CREDITS.
USAGE_KEY = "replay_vision_credits"
@@ -42,6 +44,8 @@ class QuotaSnapshot:
period_end: datetime
# Credit-weighted sum of enabled scanners' persisted estimates across the org; uncomputed estimates count 0.
projected_monthly_credits: int
+ # Display-only: the slice of `credit_limit` that never bills; see FREE_TIER_MONTHLY_CREDITS.
+ free_monthly_credits: int = FREE_TIER_MONTHLY_CREDITS
@property
def remaining(self) -> int | None:
diff --git a/products/replay_vision/backend/tests/test_quota.py b/products/replay_vision/backend/tests/test_quota.py
index ef01b0b0e30d..bdfb2e167ee7 100644
--- a/products/replay_vision/backend/tests/test_quota.py
+++ b/products/replay_vision/backend/tests/test_quota.py
@@ -376,6 +376,7 @@ class TestVisionQuotaEndpoint(_VisionQuotaTestCase):
assert body["remaining"] == MONTHLY_CREDIT_QUOTA
assert body["exhausted"] is False
assert body["projected_monthly_credits"] == 0
+ assert body["free_monthly_credits"] == 2500
assert "period_start" in body
assert "period_end" in body
diff --git a/products/replay_vision/frontend/components/NoBillingLimitNote.tsx b/products/replay_vision/frontend/components/NoBillingLimitNote.tsx
new file mode 100644
index 000000000000..988bb6e7d4ec
--- /dev/null
+++ b/products/replay_vision/frontend/components/NoBillingLimitNote.tsx
@@ -0,0 +1,32 @@
+import { Link } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+
+import { formatCreditCount } from '../utils/credits'
+
+interface Props {
+ /** Projected monthly credits across every enabled scanner. */
+ projectedCredits: number
+}
+
+/**
+ * Uncapped orgs get no meter and no exhaustion guard, so the spend surfaces stand in for both:
+ * the projection on its own line, then the same status-plus-way-out shape as `QuotaExhaustedNote`.
+ */
+export function NoBillingLimitNote({ projectedCredits }: Props): JSX.Element {
+ return (
+ <div className="space-y-1 text-xs text-muted">
+ <div>Enabled scanners are projected to use ~{formatCreditCount(projectedCredits)}/month.</div>
+ {/* One colour throughout, so the link is underlined instead of accented to stay discoverable. */}
+ <div className="text-danger">
+ No billing limit set. Spend is uncapped.{' '}
+ <Link className="text-danger underline" to={urls.organizationBilling([ProductKey.REPLAY_VISION])}>
+ Set a billing limit
+ </Link>{' '}
+ to control costs.
+ </div>
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/components/QuotaExhaustedNote.tsx b/products/replay_vision/frontend/components/QuotaExhaustedNote.tsx
new file mode 100644
index 000000000000..b4d7a4397f1a
--- /dev/null
+++ b/products/replay_vision/frontend/components/QuotaExhaustedNote.tsx
@@ -0,0 +1,29 @@
+import { Link } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+
+interface Props {
+ /** Free-plan orgs have no limit to raise; they need billing in the first place. */
+ onFreePlan: boolean
+}
+
+/**
+ * Status and the way out in one line, shown once scanning has stopped.
+ * Replaces `QuotaStatusLine` in that state rather than sitting under it.
+ */
+export function QuotaExhaustedNote({ onFreePlan }: Props): JSX.Element {
+ const [status, linkText, suffix] = onFreePlan
+ ? ['Free credits used up.', 'Add billing', 'to keep scanning.']
+ : ['Spend limit reached.', 'Raise your billing limit', 'to resume scanning.']
+ return (
+ <div className="text-xs text-danger">
+ {status}{' '}
+ <Link className="text-danger underline" to={urls.organizationBilling([ProductKey.REPLAY_VISION])}>
+ {linkText}
+ </Link>{' '}
+ {suffix}
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 255efe7dce24..470343ef1392 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -708,6 +708,8 @@ export interface VisionQuotaApi {
readonly period_end: string
/** Credit-weighted sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */
readonly projected_monthly_credits: number
+ /** Credits per period included for free. Already counted inside `credit_limit`; only credits beyond this number are billed. */
+ readonly free_monthly_credits: number
}
/**
diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts
index bbeab5f22c2c..144c59f0bb19 100644
--- a/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts
+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.test.ts
@@ -86,6 +86,24 @@ describe('visionQuotaLogic', () => {
expect(logic.values.showStartupCapLine).toBe(false)
})
+ it('derives billing display values from the quota, paid vs free-allocation-only', async () => {
+ await expectLogic(logic).toDispatchActions(['loadQuotaSuccess'])
+
+ // Paid org: 4,000 used against a 10,000 limit with a 2,500 free tier.
+ logic.actions.loadQuotaSuccess(makeQuota({ credits_used: 4000, remaining: 6000 }))
+ expect(logic.values.showUsd).toBe(true)
+ expect(logic.values.onFreePlan).toBe(false)
+ expect(logic.values.billedCredits).toBe(1500)
+ expect(logic.values.billedLimitCredits).toBe(7500)
+
+ // Free-allocation-only org: the whole limit is the free tier, so nothing bills.
+ logic.actions.loadQuotaSuccess(makeQuota({ credit_limit: 2500, credits_used: 1000, remaining: 1500 }))
+ expect(logic.values.showUsd).toBe(false)
+ expect(logic.values.onFreePlan).toBe(true)
+ expect(logic.values.billedCredits).toBe(0)
+ expect(logic.values.billedLimitCredits).toBe(0)
+ })
+
it('loadQuota overwrites any optimistic adjustment with the server value', async () => {
await expectLogic(logic).toDispatchActions(['loadQuotaSuccess'])
logic.actions.adjustProjectedMonthly(250)
diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
index e7732279edfb..1294231e7206 100644
--- a/products/replay_vision/frontend/logics/visionQuotaLogic.ts
+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
@@ -8,16 +8,22 @@ import type { BillingType } from '~/types'
import { environmentVisionQuotaRetrieve } from '../generated/api'
import type { VisionQuotaApi } from '../generated/api.schemas'
+import { billableCredits } from '../utils/credits'
+import { hasBillableSpend, isFreeAllocationOnly } from '../utils/quotaProjection'
import { applyStartupCap, startupCapCredits } from '../utils/startupCap'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visionQuotaLogicValues {
billing: BillingType | null // billingLogic
+ billedCredits: number
+ billedLimitCredits: number
displayQuota: VisionQuotaApi | null
+ onFreePlan: boolean
quota: VisionQuotaApi | null
quotaLoading: boolean
showStartupCap: boolean
showStartupCapLine: boolean
+ showUsd: boolean
startupCapCredits: number | null
}
@@ -57,6 +63,10 @@ export interface visionQuotaLogicMeta {
displayQuota: (quota: VisionQuotaApi | null, startupCapCredits: number | null) => VisionQuotaApi | null
showStartupCap: (startupCapCredits: number | null) => boolean
showStartupCapLine: (startupCapCredits: number | null, displayQuota: VisionQuotaApi | null) => boolean
+ showUsd: (quota: VisionQuotaApi | null) => boolean
+ onFreePlan: (quota: VisionQuotaApi | null) => boolean
+ billedCredits: (displayQuota: VisionQuotaApi | null) => number
+ billedLimitCredits: (displayQuota: VisionQuotaApi | null) => number
}
}
@@ -131,6 +141,21 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([
(capCredits: number | null, quota: VisionQuotaApi | null) =>
capCredits !== null && quota !== null && quota.credit_limit !== capCredits,
],
+ /** Whether spend converts to a bill, so the `≈ $` anchors are worth showing. */
+ showUsd: [(s) => [s.quota], (quota: VisionQuotaApi | null) => hasBillableSpend(quota)],
+ /** On the free plan: shapes copy, since running out of free credits isn't hitting a spend limit. */
+ onFreePlan: [(s) => [s.quota], (quota: VisionQuotaApi | null) => isFreeAllocationOnly(quota)],
+ // Billed figures come off `displayQuota` so a startup-capped org's dollars respect the cap.
+ billedCredits: [
+ (s) => [s.displayQuota],
+ (quota: VisionQuotaApi | null) =>
+ quota ? billableCredits(quota.credits_used, quota.free_monthly_credits) : 0,
+ ],
+ billedLimitCredits: [
+ (s) => [s.displayQuota],
+ (quota: VisionQuotaApi | null) =>
+ quota ? billableCredits(quota.credit_limit ?? 0, quota.free_monthly_credits) : 0,
+ ],
}),
afterMount(({ actions }) => {
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
index 46818f60b52d..28dcdad8f66f 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
@@ -159,7 +159,7 @@ export function ReplayScannerSceneComponent(): JSX.Element {
// Assumes block-only overage policy; revisit when `usage_based` ships so we don't scare metered orgs.
function QuotaBanner(): JSX.Element | null {
- const { quota } = useValues(visionQuotaLogic)
+ const { quota, onFreePlan } = useValues(visionQuotaLogic)
const state = quotaBannerState(quota)
if (!state.kind) {
return null
@@ -167,8 +167,12 @@ function QuotaBanner(): JSX.Element | null {
return (
<LemonBanner type="warning">
{state.kind === 'exhausted'
- ? `Monthly spend limit reached: ${formatCreditsRange(state.quota.credits_used, state.quota.credit_limit ?? 0)}. New observations are paused until ${state.resetsOn}.`
- : `You've used ${formatCreditsRange(state.quota.credits_used, state.quota.credit_limit ?? 0)} this month. New observations will pause once you hit the limit. Resets ${state.resetsOn}.`}
+ ? `${
+ onFreePlan ? 'Free credits used up' : 'Monthly spend limit reached'
+ }: ${formatCreditsRange(state.quota.credits_used, state.quota.credit_limit ?? 0)}. New observations are paused until ${state.resetsOn}.`
+ : onFreePlan
+ ? `You've used ${Math.round(state.quota.credits_used).toLocaleString('en-US')} of your ${Math.round(state.quota.credit_limit ?? 0).toLocaleString('en-US')} free credits this month. New observations will pause once they run out. Resets ${state.resetsOn}.`
+ : `You've used ${formatCreditsRange(state.quota.credits_used, state.quota.credit_limit ?? 0)} this month. New observations will pause once you hit the limit. Resets ${state.resetsOn}.`}
</LemonBanner>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
index 9b29c05824bf..e4d3886c462b 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.stories.tsx
@@ -106,6 +106,7 @@ const quota: VisionQuotaApi = {
remaining: 7600,
exhausted: false,
projected_monthly_credits: 5200,
+ free_monthly_credits: 2500,
period_start: '2026-05-01T00:00:00Z',
period_end: '2026-06-01T00:00:00Z',
}
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
index ec0500b1d26b..99ca2325f808 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
@@ -38,6 +38,7 @@ import { FilterPill } from '../components/FilterPill'
import { IngestionLimitBanner } from '../components/IngestionLimitBanner'
import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'
import { ScannerTypeBadge } from '../components/ScannerTypeBadge'
+import { visionQuotaLogic } from '../logics/visionQuotaLogic'
import { getReplayVisionDeleteDisabledReason, getReplayVisionEditDisabledReason } from '../utils/accessControl'
import { creditsToUsd, formatCreditCount } from '../utils/credits'
import { VisionMetrics } from './components/VisionMetrics'
@@ -136,6 +137,7 @@ export function ReplayScannersScene(): JSX.Element {
const { searchParams } = useValues(router)
const { featureFlags, receivedFeatureFlags } = useValues(featureFlagLogic)
const { featureFlagsTimedOut } = useValues(appLogic)
+ const { showUsd } = useValues(visionQuotaLogic)
if (!featureFlags[FEATURE_FLAGS.REPLAY_VISION]) {
// Flags load asynchronously, so wait for them before deciding the page doesn't exist.
@@ -206,7 +208,7 @@ export function ReplayScannersScene(): JSX.Element {
render: (_, scanner) => (
<div className="text-sm tabular-nums">
<div>{formatCreditCount(scanner.credits_this_month)}</div>
- <div className="text-muted text-xs">≈ {creditsToUsd(scanner.credits_this_month)}</div>
+ {showUsd && <div className="text-muted text-xs">≈ {creditsToUsd(scanner.credits_this_month)}</div>}
</div>
),
sorter: true,
diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.scss b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.scss
index dd1e665e9563..b88280a824e6 100644
--- a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.scss
+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.scss
@@ -32,3 +32,14 @@
animation: none;
}
}
+
+// Free credits are still spend, so they stay in the same neutral family as the billed segment,
+// just lighter. Keeping the bar monochrome leaves green/amber/red to mean status, nothing else.
+.QuotaMeterBar__free {
+ background-color: var(--color-neutral-cool-300);
+
+ // The light-mode neutral disappears against a dark track.
+ [theme='dark'] & {
+ background-color: var(--color-neutral-cool-600);
+ }
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts
index e3808309750a..109579d025a4 100644
--- a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.test.ts
@@ -1,21 +1,33 @@
-import { clampSegmentWidths } from './QuotaMeterBar'
+import { clampSegmentWidths, quotaMeterWidths } from './QuotaMeterBar'
-describe('clampSegmentWidths', () => {
- it('passes widths through when they fit', () => {
- expect(clampSegmentWidths([40, 20, 10])).toEqual([40, 20, 10])
- })
+describe('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('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('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])
+ })
})
- it('floors negative widths at zero without consuming headroom', () => {
- expect(clampSegmentWidths([-10, 50])).toEqual([0, 50])
+ describe('quotaMeterWidths', () => {
+ it.each([
+ ['free slice within spend', 50, 20, [30], [20, 30, 30]],
+ ['free slice clamped to spend so the free chip cannot outsize actual usage', 30, 80, [10], [30, 0, 10]],
+ ['negative free slice floored at zero', 40, -5, [10], [0, 40, 10]],
+ ])('%s', (_name, usedPct, usedFreePct, projected, expected) => {
+ expect(quotaMeterWidths(usedPct, usedFreePct, projected)).toEqual(expected)
+ })
})
})
diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx
index 5537da6fb956..b5db096c91b0 100644
--- a/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaMeterBar.tsx
@@ -12,9 +12,14 @@ export interface QuotaMeterSegment {
striped?: boolean
}
+/** Shading for the non-billable slice of spend, so free credits don't read as money spent. */
+export const QUOTA_METER_FREE_CLASS = 'QuotaMeterBar__free'
+
interface QuotaMeterBarProps {
/** Solid segment: actual usage as a percentage of the cap. */
usedPct: number
+ /** Portion of `usedPct` that was covered by free credits; shaded separately, ahead of the billed remainder. */
+ usedFreePct?: number
/** Striped/solid projection segments, rendered in order after the used segment. */
projected: QuotaMeterSegment[]
valueNow: number
@@ -32,9 +37,27 @@ export function clampSegmentWidths(pcts: number[]): number[] {
})
}
+/** Widths for `[free, billed, ...projected]`, with the free slice clamped inside the used slice. The bar and its
+ * legends both derive widths from this, so a legend chip can never outlive its segment. */
+export function quotaMeterWidths(usedPct: number, usedFreePct: number, projectedPcts: number[]): number[] {
+ const freePct = Math.max(Math.min(usedFreePct, usedPct), 0)
+ return clampSegmentWidths([freePct, usedPct - freePct, ...projectedPcts])
+}
+
/** 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)])
+export function QuotaMeterBar({
+ usedPct,
+ usedFreePct = 0,
+ projected,
+ valueNow,
+ label,
+ className,
+}: QuotaMeterBarProps): JSX.Element {
+ const widths = quotaMeterWidths(
+ usedPct,
+ usedFreePct,
+ projected.map((segment) => segment.pct)
+ )
return (
<div
className={clsx('flex h-3 rounded overflow-hidden bg-fill-tertiary', className)}
@@ -44,7 +67,11 @@ export function QuotaMeterBar({ usedPct, projected, valueNow, label, className }
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]}%` }} />
+ <div
+ className={clsx('transition-[width] duration-500 ease-out', QUOTA_METER_FREE_CLASS)}
+ style={{ width: `${widths[0]}%` }}
+ />
+ <div className="bg-muted transition-[width] duration-500 ease-out" style={{ width: `${widths[1]}%` }} />
{projected.map(({ barClass, striped }, index) => (
<div
key={index}
@@ -53,23 +80,29 @@ export function QuotaMeterBar({ usedPct, projected, valueNow, label, className }
striped && 'QuotaMeterBar__stripes QuotaMeterBar__stripes--animated',
barClass
)}
- style={{ width: `${widths[index + 1]}%` }}
+ style={{ width: `${widths[index + 2]}%` }}
/>
))}
</div>
)
}
-/** Legend entry with a chip matching a bar segment. */
+/** Legend entry with a chip matching a bar segment. Renders nothing when its segment has no width. */
export function QuotaMeterLegendItem({
barClass,
striped,
+ width,
children,
}: {
barClass?: string
striped?: boolean
+ /** Clamped width of the matching segment; omit for entries that are always shown. */
+ width?: number
children: ReactNode
-}): JSX.Element {
+}): JSX.Element | null {
+ if (width !== undefined && width <= 0) {
+ return null
+ }
return (
<div className="flex items-center gap-1">
<span
diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.test.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.test.tsx
index d8d3df542474..4503b91f501f 100644
--- a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.test.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.test.tsx
@@ -12,6 +12,7 @@ const base: QuotaProjection = {
percentLabel: 0,
resetsOn: null,
usedPct: 0,
+ usedFreePct: 0,
projectedPct: 0,
}
@@ -36,7 +37,7 @@ describe('QuotaStatusLine', () => {
text: 'July 21',
},
])('$name', ({ projection, text }) => {
- const { container } = render(<QuotaStatusLine projection={projection} />)
+ const { container } = render(<QuotaStatusLine projection={projection} onFreePlan={false} />)
if (text === null) {
expect(container.textContent).toBe('')
diff --git a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx
index 4a297f602f21..caefec6208ca 100644
--- a/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/QuotaStatusLine.tsx
@@ -1,9 +1,20 @@
import type { QuotaProjection } from '../../utils/quotaProjection'
-/** Red warning when the spend limit is exhausted, exceeded, or projected to overshoot; renders nothing otherwise. */
-export function QuotaStatusLine({ projection }: { projection: QuotaProjection }): JSX.Element | null {
+interface Props {
+ projection: QuotaProjection
+ /** Free-plan orgs run out of credits; everyone else hits a spend limit they chose. */
+ onFreePlan: boolean
+}
+
+/** Red warning when the allocation is exhausted or projected to overshoot; renders nothing otherwise. */
+export function QuotaStatusLine({ projection, onFreePlan }: Props): JSX.Element | null {
+ const message = statusMessage(projection, onFreePlan)
+ return message ? <span className="text-danger">{message}</span> : null
+}
+
+function statusMessage(projection: QuotaProjection, onFreePlan: boolean): JSX.Element | string | null {
if (projection.exhausted) {
- return <span className="text-danger">Spend limit reached</span>
+ return onFreePlan ? 'Free credits used up' : 'Spend limit reached'
}
if (projection.status !== 'danger') {
return null
@@ -11,13 +22,15 @@ export function QuotaStatusLine({ projection }: { projection: QuotaProjection })
// Over the displayed limit but not backend-exhausted (the startup cap before billing clamps):
// "exceeded" states the spend fact without claiming scanning is paused.
if (projection.usedPct >= 100) {
- return <span className="text-danger">Monthly spend limit exceeded</span>
+ return onFreePlan ? 'Free credits used up' : 'Monthly spend limit exceeded'
+ }
+ if (projection.capReachDate) {
+ const date = <strong>{projection.capReachDate.format('MMMM D')}</strong>
+ return onFreePlan ? (
+ <>Free credits projected to run out on {date}</>
+ ) : (
+ <>Spend limit projected to be reached on {date}</>
+ )
}
- return projection.capReachDate ? (
- <span className="text-danger">
- Spend limit projected to be reached on <strong>{projection.capReachDate.format('MMMM D')}</strong>
- </span>
- ) : (
- <span className="text-danger">Projected to exceed the monthly spend limit</span>
- )
+ return onFreePlan ? 'Projected to use up the free credits' : 'Projected to exceed the monthly spend limit'
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
index 616a412d80a6..f5ab51e71ba7 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
@@ -30,8 +30,9 @@ import { BooleanTag } from '../../components/BooleanTag'
import { CardHeader } from '../../components/CardHeader'
import { LabeledRow } from '../../components/LabeledRow'
import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
+import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
-import { formatCredits } from '../../utils/credits'
+import { formatCreditsMaybeUsd } from '../../utils/credits'
import { promptUnchangedSince } from '../../utils/labelStats'
import { replayScannerLogic } from '../replayScannerLogic'
import { MODEL_OPTIONS, ReplayScanner, SAMPLING_MODE_OPTIONS, ScannerType } from '../types'
@@ -243,6 +244,7 @@ function PromptVersionHistory({ scanner }: { scanner: ReplayScanner }): JSX.Elem
export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }): JSX.Element {
const { observationStats, togglingEnabled } = useValues(replayScannerLogic({ id: scanner.id }))
+ const { showUsd } = useValues(visionQuotaLogic)
const { toggleEnabled } = useActions(replayScannerLogic({ id: scanner.id }))
const samplingPercent = Math.round((scanner.sampling_rate ?? 0) * 1000) / 10
// Read every filter dimension (events, actions, properties, console logs, …), not just top-level properties.
@@ -385,7 +387,7 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
<LabeledRow label="Estimated monthly cost">
{scanner.estimated_monthly_credits != null ? (
<span className="tabular-nums">
- {formatCredits(scanner.estimated_monthly_credits)}{' '}
+ {formatCreditsMaybeUsd(scanner.estimated_monthly_credits, showUsd)}{' '}
<span className="text-muted">
· {(scanner.estimated_monthly_observations ?? 0).toLocaleString()} observations
</span>
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
index 749919a23291..4b19ecf1d091 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
@@ -4,6 +4,8 @@ import { LemonCard, Spinner, Tooltip } from '@posthog/lemon-ui'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
+import { NoBillingLimitNote } from '../../components/NoBillingLimitNote'
+import { QuotaExhaustedNote } from '../../components/QuotaExhaustedNote'
import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
import { creditsToUsd, formatCreditCount } from '../../utils/credits'
import {
@@ -14,7 +16,7 @@ import {
splitProjectedPct,
} from '../../utils/quotaProjection'
import { replayScannerLogic } from '../replayScannerLogic'
-import { QuotaMeterBar, QuotaMeterLegendItem } from './QuotaMeterBar'
+import { QUOTA_METER_FREE_CLASS, QuotaMeterBar, QuotaMeterLegendItem, quotaMeterWidths } from './QuotaMeterBar'
import { QuotaStatusLine } from './QuotaStatusLine'
interface Props {
@@ -25,7 +27,13 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
const { scanner, scannerEstimate, scannerEstimateLoading, scannerEstimateError } = useValues(
replayScannerLogic({ id: scannerId })
)
- const { displayQuota: quota, startupCapCredits, showStartupCapLine } = useValues(visionQuotaLogic)
+ const {
+ displayQuota: quota,
+ showUsd,
+ onFreePlan,
+ startupCapCredits,
+ showStartupCapLine,
+ } = useValues(visionQuotaLogic)
if (!scanner) {
return null
@@ -47,12 +55,16 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
// projectQuota wants a delta off the stored fleet total, so compute the new fleet total (others + this) and pass the difference.
const newFleetMonthly = projectedCredits !== null ? othersMonthly + projectedCredits : fleetMonthly
const projection = projectQuota(quota, newFleetMonthly - fleetMonthly)
- const { status, percentLabel, resetsOn, usedPct, projectedPct } = projection
+ const { status, percentLabel, resetsOn, usedPct, usedFreePct, projectedPct } = projection
const effectiveStatus: QuotaStatus = projectedCredits === null ? 'safe' : status
const styles = QUOTA_STATUS_STYLES[effectiveStatus]
const { thisScannerPct, othersPct } = splitProjectedPct(projectedPct, projectedCredits ?? 0, othersMonthly)
+ const [freeWidth, billedWidth, othersWidth, thisWidth] = quotaMeterWidths(usedPct, usedFreePct, [
+ othersPct,
+ thisScannerPct,
+ ])
const breakdown = (
<div className="text-xs space-y-0.5">
@@ -100,8 +112,9 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
~{formatCreditCount(projectedCredits)}
<span className="text-sm font-normal text-muted">/month</span>{' '}
<span className="text-sm font-normal text-muted">
- (≈ {creditsToUsd(projectedCredits)}) · {(projectedObservations ?? 0).toLocaleString()}{' '}
- observations at {formatCreditCount(scannerEstimate?.credits_per_observation ?? 0)} each
+ {showUsd ? `(≈ ${creditsToUsd(projectedCredits)}) · ` : ''}
+ {(projectedObservations ?? 0).toLocaleString()} observations at{' '}
+ {formatCreditCount(scannerEstimate?.credits_per_observation ?? 0)} each
</span>
</span>
{scannerEstimateLoading && (
@@ -113,18 +126,32 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
) : (
<div className="text-sm text-muted">—</div>
)}
- {hasCap && (
+ {/* The exhausted note below carries this status, so don't say it twice. */}
+ {hasCap && !projection.exhausted && (
<span className="text-xs tabular-nums">
- <QuotaStatusLine projection={projection} />
+ <QuotaStatusLine projection={projection} onFreePlan={onFreePlan} />
</span>
)}
</div>
+ {/* `hasCap` is also false while quota is still loading, so require a resolved snapshot before
+ telling anyone their billing limit is missing. */}
+ {quota !== null && !hasCap && projectedCredits !== null && (
+ <Tooltip title={breakdown}>
+ <div>
+ <NoBillingLimitNote projectedCredits={newFleetMonthly} />
+ </div>
+ </Tooltip>
+ )}
+
+ {hasCap && projection.exhausted && <QuotaExhaustedNote onFreePlan={onFreePlan} />}
+
{hasCap && projectedCredits !== null && (
<>
<Tooltip title={breakdown}>
<QuotaMeterBar
usedPct={usedPct}
+ usedFreePct={usedFreePct}
projected={[
{ pct: othersPct, barClass: 'bg-accent' },
{ pct: thisScannerPct, barClass: styles.bar, striped: true },
@@ -136,9 +163,16 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {
/>
</Tooltip>
<div className="flex items-center gap-3 text-xs text-muted">
- <QuotaMeterLegendItem>Spent</QuotaMeterLegendItem>
- <QuotaMeterLegendItem barClass="bg-accent">Projected (other scanners)</QuotaMeterLegendItem>
- <QuotaMeterLegendItem barClass={styles.bar} striped>
+ <QuotaMeterLegendItem barClass={QUOTA_METER_FREE_CLASS} width={freeWidth}>
+ Free
+ </QuotaMeterLegendItem>
+ <QuotaMeterLegendItem width={billedWidth}>
+ {freeWidth > 0 ? 'Billed' : 'Spent'}
+ </QuotaMeterLegendItem>
+ <QuotaMeterLegendItem barClass="bg-accent" width={othersWidth}>
+ Projected (other scanners)
+ </QuotaMeterLegendItem>
+ <QuotaMeterLegendItem barClass={styles.bar} striped width={thisWidth}>
Projected (this scanner)
</QuotaMeterLegendItem>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
index 461a12185f0a..e016a428c603 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
@@ -9,6 +9,8 @@ import { urls } from 'scenes/urls'
import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'
import { BaseMathType, ChartDisplayType, InsightLogicProps } from '~/types'
+import { NoBillingLimitNote } from '../../components/NoBillingLimitNote'
+import { QuotaExhaustedNote } from '../../components/QuotaExhaustedNote'
import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
import { creditsToUsd, formatCreditCount } from '../../utils/credits'
@@ -16,7 +18,7 @@ import { QUOTA_STATUS_STYLES, hasCreditLimit, projectQuota } from '../../utils/q
import { STARTUP_CAP_EXPLANATION } from '../../utils/startupCap'
import { replayScannersLogic } from '../replayScannersLogic'
import { SCANNER_TYPE_OPTIONS } from '../types'
-import { QuotaMeterBar, QuotaMeterLegendItem } from './QuotaMeterBar'
+import { QUOTA_METER_FREE_CLASS, QuotaMeterBar, QuotaMeterLegendItem, quotaMeterWidths } from './QuotaMeterBar'
import { QuotaStatusLine } from './QuotaStatusLine'
import { VisionInsightChart } from './VisionInsightChart'
@@ -29,14 +31,19 @@ export function VisionMetrics(): JSX.Element {
const {
displayQuota: quota,
quotaLoading,
+ showUsd,
+ onFreePlan,
+ billedCredits,
+ billedLimitCredits,
startupCapCredits,
showStartupCap,
showStartupCapLine,
} = useValues(visionQuotaLogic)
const projection = projectQuota(quota)
- const { resetsOn, status, percentLabel, usedPct, projectedPct } = projection
+ const { resetsOn, status, percentLabel, usedPct, usedFreePct, projectedPct } = projection
const hasCap = hasCreditLimit(quota)
+ const [freeWidth, billedWidth, projectedWidth] = quotaMeterWidths(usedPct, usedFreePct, [projectedPct])
const styles = QUOTA_STATUS_STYLES[status]
// Memoized so a re-render (e.g. stats/quota arriving) can't churn the query and abort an in-flight load.
@@ -133,10 +140,12 @@ export function VisionMetrics(): JSX.Element {
</span>
)}
</div>
- <div className="text-muted text-sm tabular-nums">
- ≈ {creditsToUsd(quota.credits_used)}
- {hasCap ? ` / ${creditsToUsd(quota.credit_limit ?? 0)}` : ''}
- </div>
+ {showUsd && (
+ <div className="text-muted text-sm tabular-nums">
+ ≈ {creditsToUsd(billedCredits)} billed
+ {hasCap ? ` / ${creditsToUsd(billedLimitCredits)} limit` : ''}
+ </div>
+ )}
{hasCap ? (
<>
<Tooltip
@@ -171,26 +180,38 @@ export function VisionMetrics(): JSX.Element {
<QuotaMeterBar
className="mt-2"
usedPct={usedPct}
+ usedFreePct={usedFreePct}
projected={[{ pct: projectedPct, barClass: styles.bar, striped: true }]}
valueNow={percentLabel}
label={`Projected ${percentLabel}% of the monthly spend limit`}
/>
</Tooltip>
<div className="flex items-center gap-3 text-xs text-muted mt-1.5">
- <QuotaMeterLegendItem>Spent</QuotaMeterLegendItem>
- <QuotaMeterLegendItem barClass={styles.bar} striped>
+ <QuotaMeterLegendItem barClass={QUOTA_METER_FREE_CLASS} width={freeWidth}>
+ Free
+ </QuotaMeterLegendItem>
+ <QuotaMeterLegendItem width={billedWidth}>
+ {freeWidth > 0 ? 'Billed' : 'Spent'}
+ </QuotaMeterLegendItem>
+ <QuotaMeterLegendItem barClass={styles.bar} striped width={projectedWidth}>
Projected
</QuotaMeterLegendItem>
- <span className="ml-auto">
- <QuotaStatusLine projection={projection} />
- </span>
+ {/* The exhausted note below carries this status, so don't say it twice. */}
+ {!projection.exhausted && (
+ <span className="ml-auto">
+ <QuotaStatusLine projection={projection} onFreePlan={onFreePlan} />
+ </span>
+ )}
</div>
+ {projection.exhausted && (
+ <div className="mt-1.5">
+ <QuotaExhaustedNote onFreePlan={onFreePlan} />
+ </div>
+ )}
</>
) : (
- <div className="text-xs text-muted mt-2">
- No spend limit set: projected ~{formatCreditCount(quota.projected_monthly_credits)}
- /month from enabled scanners. Set a billing limit in your billing settings to cap
- spend.
+ <div className="mt-2">
+ <NoBillingLimitNote projectedCredits={quota.projected_monthly_credits} />
</div>
)}
{showStartupCap && (
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx
index b01a5680541f..1befd9b82cf9 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { useMemo } from 'react'
-import { LemonSegmentedButton, LemonTable, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+import { LemonSegmentedButton, LemonTable, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
@@ -11,7 +11,7 @@ import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-ge
import { BaseMathType, ChartDisplayType, InsightLogicProps, PropertyFilterType, PropertyOperator } from '~/types'
import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
-import { creditsToUsd, formatCreditCount, formatCredits, formatCreditsRange } from '../../utils/credits'
+import { creditsToUsd, formatCreditCount, formatCreditsMaybeUsd, formatCreditsRange } from '../../utils/credits'
import { exhaustionForecast, hasCreditLimit, projectQuota } from '../../utils/quotaProjection'
import { STARTUP_CAP_EXPLANATION } from '../../utils/startupCap'
import { OBSERVATION_CREDITS_BY_MODEL, ReplayScanner, modelName } from '../types'
@@ -46,14 +46,21 @@ const SPEND_CHART_SERIES = SPEND_CHART_MODEL_PRICES.map(([model]) => ({
},
],
}))
-const SPEND_CHART_FORMULA = `(${SPEND_CHART_MODEL_PRICES.map(
+const SPEND_CHART_CREDITS_FORMULA = SPEND_CHART_MODEL_PRICES.map(
([, credits], index) => `${String.fromCharCode(65 + index)}*${credits}`
-).join(' + ')}) / 100`
+).join(' + ')
export function VisionUsageTab(): JSX.Element {
const { usageScanners, usageScannersLoading, spendChartInterval } = useValues(visionUsageLogic)
const { setSpendChartInterval } = useActions(visionUsageLogic)
- const { displayQuota: quota, showStartupCap } = useValues(visionQuotaLogic)
+ const {
+ displayQuota: quota,
+ quotaLoading,
+ showUsd,
+ billedCredits,
+ billedLimitCredits,
+ showStartupCap,
+ } = useValues(visionQuotaLogic)
const projection = projectQuota(quota)
const hasCap = hasCreditLimit(quota)
@@ -61,10 +68,21 @@ export function VisionUsageTab(): JSX.Element {
? 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 spenders = usageScanners.filter((s: ReplayScanner) => s.credits_this_month > 0)
const zeroSpendCount = usageScanners.length - spenders.length
const totalCredits = spenders.reduce((sum: number, s: ReplayScanner) => sum + s.credits_this_month, 0)
+ // 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>(
() => ({
@@ -74,9 +92,9 @@ export function VisionUsageTab(): JSX.Element {
series: SPEND_CHART_SERIES,
trendsFilter: {
display: ChartDisplayType.ActionsLineGraph,
- // The /100 charts dollars (1 credit = $0.01).
- formulaNodes: [{ formula: SPEND_CHART_FORMULA, custom_name: 'Spend' }],
- aggregationAxisPrefix: '$',
+ // 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:
@@ -152,7 +170,7 @@ export function VisionUsageTab(): JSX.Element {
return (
<div className="flex flex-col gap-1">
<span className="text-sm tabular-nums flex items-baseline justify-between gap-2">
- {formatCredits(scanner.credits_this_month)}
+ {formatCreditsMaybeUsd(scanner.credits_this_month, showUsd)}
<span className="text-muted">{sharePct}%</span>
</span>
<LemonProgress percent={sharePct} />
@@ -169,11 +187,7 @@ export function VisionUsageTab(): JSX.Element {
<h3 className="text-base font-semibold m-0">Spend over time</h3>
<div className="flex items-center gap-3">
{quota && (
- <Tooltip
- title={`≈ ${creditsToUsd(quota.credits_used)}${
- hasCap ? ` of ${creditsToUsd(quota.credit_limit ?? 0)}` : ''
- }${showStartupCap ? `. ${STARTUP_CAP_EXPLANATION}` : ''}`}
- >
+ <Tooltip title={spendTooltip}>
<span className="text-xs text-muted tabular-nums">
{hasCap
? formatCreditsRange(quota.credits_used, quota.credit_limit ?? 0)
@@ -192,11 +206,17 @@ export function VisionUsageTab(): JSX.Element {
</div>
</div>
<p className="text-muted text-xs mb-3">Across all scanners</p>
- <VisionInsightChart
- query={spendChartQuery}
- insightProps={spendChartInsightProps}
- className="flex-1 flex flex-col min-h-0"
- />
+ {quotaResolved ? (
+ <VisionInsightChart
+ query={spendChartQuery}
+ insightProps={spendChartInsightProps}
+ className="flex-1 flex flex-col min-h-0"
+ />
+ ) : (
+ <div className="flex-1 flex items-center justify-center">
+ <Spinner />
+ </div>
+ )}
</div>
{forecastDate && (
<div className="text-xs text-warning">
diff --git a/products/replay_vision/frontend/utils/credits.test.ts b/products/replay_vision/frontend/utils/credits.test.ts
index 304ba547aad7..b13ecee481c0 100644
--- a/products/replay_vision/frontend/utils/credits.test.ts
+++ b/products/replay_vision/frontend/utils/credits.test.ts
@@ -1,4 +1,4 @@
-import { creditsToUsd, formatCreditCount, formatCredits, formatCreditsRange } from './credits'
+import { billableCredits, creditsToUsd, formatCreditCount, formatCredits, formatCreditsRange } from './credits'
describe('credits formatting', () => {
it.each([
@@ -35,4 +35,13 @@ describe('credits formatting', () => {
])('formatCreditsRange(%p, %p) -> %p', (used, total, expected) => {
expect(formatCreditsRange(used, total)).toBe(expected)
})
+
+ it.each([
+ ['nothing bills below the free allocation', 800, 2500, 0],
+ ['nothing bills exactly at it', 2500, 2500, 0],
+ ['only the overage bills', 3100, 2500, 600],
+ ['a free allocation larger than spend bills nothing', 2800, 3000, 0],
+ ])('billableCredits: %s', (_name, credits, freeCredits, expected) => {
+ expect(billableCredits(credits, freeCredits)).toBe(expected)
+ })
})
diff --git a/products/replay_vision/frontend/utils/credits.ts b/products/replay_vision/frontend/utils/credits.ts
index a92eb67c9326..fdab15c36b9d 100644
--- a/products/replay_vision/frontend/utils/credits.ts
+++ b/products/replay_vision/frontend/utils/credits.ts
@@ -12,6 +12,11 @@ export function creditsToUsd(credits: number): string {
return humanFriendlyCurrency(Math.round(credits) / CREDITS_PER_DOLLAR)
}
+/** Credits that actually bill once the free allocation is spent, e.g. (3000, 2500) -> 500. */
+export function billableCredits(credits: number, freeCredits: number): number {
+ return Math.max(0, Math.round(credits) - Math.max(0, freeCredits))
+}
+
/** e.g. 500 -> "500 credits", 1 -> "1 credit". */
export function formatCreditCount(credits: number): string {
const rounded = Math.round(credits)
@@ -23,6 +28,11 @@ export function formatCredits(credits: number): string {
return `${formatCreditCount(credits)} (≈ ${creditsToUsd(credits)})`
}
+/** `formatCredits` for orgs that can be billed, `formatCreditCount` for orgs whose spend is all free. */
+export function formatCreditsMaybeUsd(credits: number, showUsd: boolean): string {
+ return showUsd ? formatCredits(credits) : formatCreditCount(credits)
+}
+
/** A "used of limit" pair that names the unit once, e.g. (1200, 5000) -> "1,200 of 5,000 credits". */
export function formatCreditsRange(used: number, total: number): string {
return `${Math.round(used).toLocaleString('en-US')} of ${formatCreditCount(total)}`
diff --git a/products/replay_vision/frontend/utils/quotaProjection.test.ts b/products/replay_vision/frontend/utils/quotaProjection.test.ts
index 1ade6fcf1bc7..aa0ca732aaf8 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.test.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.test.ts
@@ -1,6 +1,22 @@
-import { exhaustionForecast, projectQuota, quotaUx, splitProjectedPct } from './quotaProjection'
+import { exhaustionForecast, hasBillableSpend, projectQuota, quotaUx, splitProjectedPct } from './quotaProjection'
import { makeQuota } from './quotaTestUtils'
+describe('hasBillableSpend', () => {
+ it.each([
+ ['null quota keeps the dollars rather than flickering', null, true],
+ ['uncapped org is metered', makeQuota({ credit_limit: null, remaining: null }), true],
+ [
+ 'limit is entirely the free allocation',
+ makeQuota({ credit_limit: 2_500, free_monthly_credits: 2_500 }),
+ false,
+ ],
+ ['limit exceeds the free allocation', makeQuota({ credit_limit: 7_500, free_monthly_credits: 2_500 }), true],
+ ['zero limit cannot bill', makeQuota({ credit_limit: 0, free_monthly_credits: 2_500 }), false],
+ ])('%s', (_name, quota, expected) => {
+ expect(hasBillableSpend(quota)).toBe(expected)
+ })
+})
+
describe('projectQuota', () => {
it('returns the empty projection when quota is null or uncapped', () => {
expect(projectQuota(null)).toMatchObject({ status: 'safe', usedPct: 0, projectedPct: 0 })
@@ -75,6 +91,17 @@ describe('projectQuota', () => {
expect(clamped.projectedPct).toBe(0)
})
+ it.each([
+ // Cap 10,000 with a 2,500 free allocation.
+ ['all spend still inside the free tier', 1_000, 10, 10],
+ ['free portion caps at the allocation', 4_000, 40, 25],
+ ['nothing spent, nothing free', 0, 0, 0],
+ ])('usedFreePct: %s', (_name, creditsUsed, expectedUsedPct, expectedFreePct) => {
+ const proj = projectQuota(makeQuota({ credits_used: creditsUsed }))
+ expect(proj.usedPct).toBe(expectedUsedPct)
+ expect(proj.usedFreePct).toBe(expectedFreePct)
+ })
+
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 }))
@@ -120,6 +147,26 @@ describe('quotaUx', () => {
expect(ux.tooltip).toContain('1,500 credits left')
})
+ // A deliberate $0 cap is not a free plan, so it keeps the spend-limit wording.
+ it('keeps spend-limit wording for a zero limit', () => {
+ const ux = quotaUx(makeQuota({ credit_limit: 0, remaining: 0, exhausted: true }))
+ expect(ux.disabledReason).toMatch(/spend limit reached/i)
+ })
+
+ it('tells a free-tier org its credits ran out, not that it hit a spend limit', () => {
+ const ux = quotaUx(
+ makeQuota({
+ credit_limit: 2_500,
+ free_monthly_credits: 2_500,
+ credits_used: 2_500,
+ remaining: 0,
+ exhausted: true,
+ })
+ )
+ expect(ux.disabledReason).toMatch(/free Replay vision credits/i)
+ expect(ux.disabledReason).not.toMatch(/spend limit/i)
+ })
+
it('returns nothing while usage is well under the threshold', () => {
expect(quotaUx(makeQuota({ credits_used: 1_000, remaining: 9_000 }))).toEqual({})
})
diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.ts
index 64bf93739b09..be620c985a4f 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.ts
@@ -1,7 +1,7 @@
import { dayjs } from 'lib/dayjs'
import type { VisionQuotaApi } from '../generated/api.schemas'
-import { formatCreditCount } from './credits'
+import { billableCredits, formatCreditCount } from './credits'
export const QUOTA_WARN_THRESHOLD = 0.85
@@ -22,6 +22,8 @@ export interface QuotaProjection {
resetsOn: string | null
/** Actual spend as a percentage of the limit; `QuotaMeterBar` clamps for display. */
usedPct: number
+ /** The slice of `usedPct` covered by non-billable credits, so the meter can shade it separately. */
+ usedFreePct: number
/** Projected additional spend as a percentage of the limit, unclamped. */
projectedPct: number
}
@@ -33,6 +35,7 @@ const EMPTY: QuotaProjection = {
percentLabel: 0,
resetsOn: null,
usedPct: 0,
+ usedFreePct: 0,
projectedPct: 0,
}
@@ -42,6 +45,30 @@ export function hasCreditLimit(quota: VisionQuotaApi | null): quota is VisionQuo
return !!quota && quota.credit_limit !== null
}
+/**
+ * True when spending credits can actually produce a bill, so the `≈ $` conversions mean something.
+ * An org whose whole limit is the free allocation can never be charged — it just stops scanning at the cap —
+ * so those surfaces speak in credits only. Unknown quota keeps the dollars rather than flickering them away.
+ */
+export function hasBillableSpend(quota: VisionQuotaApi | null): boolean {
+ if (!hasCreditLimit(quota)) {
+ return true
+ }
+ return billableCredits(quota.credit_limit, quota.free_monthly_credits) > 0
+}
+
+/**
+ * True when the org's whole limit is the free allocation, so it is on the free plan rather than
+ * capped by choice. A zero limit is excluded: that is a deliberate spend cap, not a free plan.
+ * Drives copy, where "you ran out of free credits" and "you hit your limit" are different messages.
+ */
+export function isFreeAllocationOnly(quota: VisionQuotaApi | null): boolean {
+ if (!hasCreditLimit(quota) || quota.credit_limit <= 0) {
+ return false
+ }
+ 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:
@@ -98,6 +125,7 @@ export function projectQuota(
percentLabel: Math.round(projectedPeriodEndRatio * 100),
resetsOn,
usedPct: (used / cap) * 100,
+ usedFreePct: (Math.min(used, quota.free_monthly_credits) / cap) * 100,
projectedPct: (projectedAdditional / cap) * 100,
}
}
@@ -124,7 +152,11 @@ export function quotaUx(quota: VisionQuotaApi | null): { disabledReason?: string
return {}
}
if (state.kind === 'exhausted') {
- return { disabledReason: `Monthly Replay vision spend limit reached. Resets ${state.resetsOn}.` }
+ return {
+ disabledReason: isFreeAllocationOnly(quota)
+ ? `You've used all your free Replay vision credits. Resets ${state.resetsOn}.`
+ : `Monthly Replay vision spend limit reached. Resets ${state.resetsOn}.`,
+ }
}
return {
tooltip: `${formatCreditCount(state.quota.remaining ?? 0)} left this month (resets ${state.resetsOn})`,
diff --git a/products/replay_vision/frontend/utils/quotaTestUtils.ts b/products/replay_vision/frontend/utils/quotaTestUtils.ts
index ac043c918b0b..d5583fea5d41 100644
--- a/products/replay_vision/frontend/utils/quotaTestUtils.ts
+++ b/products/replay_vision/frontend/utils/quotaTestUtils.ts
@@ -10,6 +10,7 @@ export function makeQuota(overrides: Partial<VisionQuotaApi> = {}): VisionQuotaA
remaining: 10_000,
exhausted: false,
projected_monthly_credits: 0,
+ free_monthly_credits: 2500,
period_start: daysFromNow(-10),
period_end: daysFromNow(20),
...overrides,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 11c3d75e277b..8b411e44ab5b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -72989,6 +72989,8 @@ export namespace Schemas {
readonly period_end: string;
/** Credit-weighted sum of enabled scanners' projected observations/month across the organization. Scanners without a computed estimate contribute 0. */
readonly projected_monthly_credits: number;
+ /** Credits per period included for free. Already counted inside `credit_limit`; only credits beyond this number are billed. */
+ readonly free_monthly_credits: number;
}
export interface WarehouseConnection {