: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
import { MakeLogicType, actions, afterMount, connect, kea, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { billingLogic } from 'lib/logic/billing/billingLogic'
import { teamLogic } from 'scenes/teamLogic'
import type { BillingType } from '~/types'
import { environmentVisionQuotaRetrieve } from '../generated/api'
import type { VisionQuotaApi } from '../generated/api.schemas'
import { billableCredits } from '../utils/credits'
import {
freeCreditsAllowance,
freeCreditsLeft,
hasBillableSpend,
isFreeAllocationOnly,
periodShareOfMonthlyRate,
} 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
freeCreditsAllowance: number | null
freeCreditsLeft: number | null
onFreePlan: boolean
quota: VisionQuotaApi | null
quotaLoading: boolean
showStartupCap: boolean
showStartupCapLine: boolean
showUsd: boolean
startupCapCredits: number | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visionQuotaLogicActions {
loadBilling: () => any // billingLogic
adjustProjectedMonthly: (delta: number) => {
delta: number
}
loadQuota: () => {
value: true
}
loadQuotaFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadQuotaSuccess: (
quota: VisionQuotaApi | null,
payload?: {
value: true
}
) => {
quota: VisionQuotaApi | null
payload?: {
value: true
}
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visionQuotaLogicMeta {
__keaTypeGenInternalSelectorTypes: {
startupCapCredits: (billing: BillingType | null) => number | null
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
freeCreditsAllowance: (quota: VisionQuotaApi | null) => number | null
freeCreditsLeft: (quota: VisionQuotaApi | null) => number | null
onFreePlan: (quota: VisionQuotaApi | null) => boolean
billedCredits: (displayQuota: VisionQuotaApi | null) => number
billedLimitCredits: (displayQuota: VisionQuotaApi | null) => number
}
}
export type visionQuotaLogicType = MakeLogicType<
visionQuotaLogicValues,
visionQuotaLogicActions,
Record<string, any>,
visionQuotaLogicMeta
>
export const visionQuotaLogic = kea<visionQuotaLogicType>([
path(['products', 'replay_vision', 'frontend', 'logics', 'visionQuotaLogic']),
connect(() => ({
actions: [billingLogic, ['loadBilling']],
values: [billingLogic, ['billing']],
})),
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(({ values }) => ({
quota: [
null as VisionQuotaApi | null,
{
loadQuota: async (_, breakpoint) => {
// Coalesce bursts of post-mutation refetches (e.g. toggling several scanners).
await breakpoint(50)
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
return values.quota
}
try {
return await environmentVisionQuotaRetrieve(String(teamId))
} catch {
// Keep the last-known snapshot — nulling it would silently drop the exhausted-quota guards.
return values.quota
}
},
},
],
})),
reducers({
quota: {
adjustProjectedMonthly: (state: VisionQuotaApi | null, { delta }: { delta: number }) =>
state
? {
...state,
// Meters project from the scanner rate, so the headline total and the rate move together.
scanners_monthly_credits: Math.max(0, state.scanners_monthly_credits + delta),
scanners_period_credits: Math.max(
0,
state.scanners_period_credits + periodShareOfMonthlyRate(state, delta)
),
projected_monthly_credits: Math.max(0, state.projected_monthly_credits + delta),
}
: state,
},
}),
selectors({
startupCapCredits: [(s) => [s.billing], (billing: BillingType | null) => startupCapCredits(billing)],
// Spend surfaces render this. Guards stay on `quota` so the display can never block what the backend allows.
displayQuota: [
(s) => [s.quota, s.startupCapCredits],
(quota: VisionQuotaApi | null, capCredits: number | null) => applyStartupCap(quota, capCredits),
],
// Single gate for the cap copy so the spend surfaces can't drift on when it shows.
showStartupCap: [(s) => [s.startupCapCredits], (capCredits: number | null) => capCredits !== null],
// Cost breakdowns already show "Monthly limit"; a cap line only adds information when the two differ.
showStartupCapLine: [
(s) => [s.startupCapCredits, s.displayQuota],
(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)],
freeCreditsAllowance: [
(s) => [s.quota],
(quota: VisionQuotaApi | null): number | null => freeCreditsAllowance(quota),
],
freeCreditsLeft: [(s) => [s.quota], (quota: VisionQuotaApi | null): number | null => freeCreditsLeft(quota)],
/** On the free plan: shapes copy, since running out of free credits isn't hitting a spend limit. */
onFreePlan: [(s) => [s.quota], (quota: VisionQuotaApi | null) => isFreeAllocationOnly(quota)],
// Billed figures come off `displayQuota` so a startup-capped org's dollars respect the cap.
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 }) => {
actions.loadQuota()
// billingLogic doesn't self-load; the ingestion banner needs billing on cold navigation.
actions.loadBilling()
}),
])
/** Refresh after any quota-affecting mutation — observes consume quota immediately (in-flight rows count). */
export function refreshVisionQuota(): void {
visionQuotaLogic.findMounted()?.actions.loadQuota()
}