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.

fix(inbox): keep the pr limit modal open when billing rejects a save (#82359)

posthog[bot]0b9975fd931f
diff --git a/frontend/src/scenes/billing/billingProductLogic.test.ts b/frontend/src/scenes/billing/billingProductLogic.test.ts
index ce7c70bfca8e..6095f6c774df 100644
--- a/frontend/src/scenes/billing/billingProductLogic.test.ts
+++ b/frontend/src/scenes/billing/billingProductLogic.test.ts
@@ -171,9 +171,10 @@ describe('billingProductLogic', () => {
'reportSurveySent',
'setSurveyID',
])
- // Enough to fire the loader's breakpoint(2000) but not the post-report
- // breakpoint(400), so the jsdom-unsupported scrollIntoView is never reached.
- await jest.advanceTimersByTimeAsync(2100)
+ // Run past the post-report breakpoint(400) so the scroll runs. The scene element
+ // is absent in jsdom, so this also guards that indexing it stays safe: without the
+ // optional-chain guard, scrollIntoView on the missing element throws a TypeError.
+ await jest.advanceTimersByTimeAsync(2500)
await expectation
expect(deactivateBody).toEqual({ products: 'product_analytics' })
diff --git a/frontend/src/scenes/billing/billingProductLogic.ts b/frontend/src/scenes/billing/billingProductLogic.ts
index b9b073acc6e6..108f1fbe8d76 100644
--- a/frontend/src/scenes/billing/billingProductLogic.ts
+++ b/frontend/src/scenes/billing/billingProductLogic.ts
@@ -1166,7 +1166,7 @@ export const billingProductLogic = kea<billingProductLogicType>([
if (!values.unsubscribeError && values.surveyID) {
actions.reportSurveySent(values.surveyID, values.surveyResponse)
await breakpoint(400)
- document.getElementsByClassName('Navigation3000__scene')[0].scrollIntoView()
+ document.getElementsByClassName('Navigation3000__scene')[0]?.scrollIntoView()
}
},
setScrollToProductKey: ({ scrollToProductKey }) => {
diff --git a/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts b/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
index fb07699d602f..02739f47c84a 100644
--- a/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
+++ b/products/signals/frontend/inbox/logics/inboxUsageLogic.test.ts
@@ -42,6 +42,42 @@ const mockUsageEndpoints = (
})
}
+// $0.01 per credit after a free first tier: 3 free PRs, then $15 per PR.
+const PRICED_INBOX_PRODUCT = {
+ type: 'inbox',
+ subscribed: true,
+ display_divisor: CREDITS_PER_PR,
+ current_usage: 3 * CREDITS_PER_PR,
+ tiers: [
+ { unit_amount_usd: '0', up_to: 3 * CREDITS_PER_PR },
+ { unit_amount_usd: '0.01', up_to: null },
+ ],
+}
+
+const mountPricedForSave = async (saveStatus: number): Promise<ReturnType<typeof inboxUsageLogic.build>> => {
+ useMocks({
+ get: {
+ '/api/billing': () => [200, { products: [PRICED_INBOX_PRODUCT] }],
+ '/api/projects/:team_id/signals/reports/refund-summary/': () => [
+ 200,
+ { period_billable_credits: 0, credited_credits: 0, credited_refund_count: 0, quota_limited: false },
+ ],
+ },
+ patch: {
+ '/api/billing': () =>
+ saveStatus === 200
+ ? [200, { products: [PRICED_INBOX_PRODUCT], custom_limits_usd: { inbox: 75 } }]
+ : [saveStatus, { attr: 'custom_limits_usd', detail: 'Rejected.' }],
+ },
+ })
+ featureFlagLogic.mount()
+ setRefundsFlag()
+ const logic = inboxUsageLogic()
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ return logic
+}
+
const setRefundsFlag = (): void => {
featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.SIGNALS_PR_REFUNDS], {
[FEATURE_FLAGS.SIGNALS_PR_REFUNDS]: true,
@@ -163,6 +199,33 @@ describe('inboxUsageLogic', () => {
expect(logic.values.quotaLimited).toBe(true)
})
+ // A rejected save that closes the modal reads as a saved limit while the agents stay paused.
+ it.each([
+ ['closes the modal and reloads the paused state when the save lands', 200, false, ['loadRefundSummary']],
+ ['keeps the modal open when billing rejects the save', 400, true, []],
+ ])('%s', async (_case, saveStatus, expectedModalOpen, expectedFollowUps) => {
+ logic = await mountPricedForSave(saveStatus)
+ logic.actions.openModal()
+ logic.actions.setLimitFormValue('prs', 8)
+
+ await expectLogic(logic, () => logic?.actions.submitLimitForm())
+ .toDispatchActions([...expectedFollowUps, 'submitLimitFormSuccess'])
+ .toFinishAllListeners()
+
+ expect(logic.values.isModalOpen).toBe(expectedModalOpen)
+ })
+
+ it('rejects a PR limit whose dollar cap is above the billing ceiling', async () => {
+ logic = await mountPricedForSave(200)
+ logic.actions.openModal()
+
+ logic.actions.setLimitFormValue('prs', 3336)
+ expect(logic.values.limitFormValidationErrors.prs).toBeUndefined()
+
+ logic.actions.setLimitFormValue('prs', 3337)
+ expect(logic.values.limitFormValidationErrors.prs).toBe('Maximum is 3,336 PRs')
+ })
+
// The org-keyed refunds flag resolves late on the client, so the client can fire the summary
// request while the server (re-checking the same flag) still returns 404. That mismatch must
// degrade to a null summary — falling back to billing's own usage — not bubble up as an
diff --git a/products/signals/frontend/inbox/logics/inboxUsageLogic.ts b/products/signals/frontend/inbox/logics/inboxUsageLogic.ts
index 98af7c0673ab..fb6016da7896 100644
--- a/products/signals/frontend/inbox/logics/inboxUsageLogic.ts
+++ b/products/signals/frontend/inbox/logics/inboxUsageLogic.ts
@@ -9,6 +9,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { Dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { getBillingLimitConfig } from 'scenes/billing/billingLimitConfig'
import { billingLogic } from 'scenes/billing/billingLogic'
import {
INBOX_PRODUCT_TYPE,
@@ -31,6 +32,8 @@ export type InboxUsageStatus = 'normal' | 'warning' | 'limit'
// Above this fraction of the limit we warn the user before they run out.
const WARNING_THRESHOLD = 0.8
+const MAX_LIMIT_PRS = 10000
+
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface inboxUsageLogicValues {
billing: BillingType | null // billingLogic
@@ -70,6 +73,7 @@ export interface inboxUsageLogicValues {
ValidationErrorType
>
limitPrs: number | null
+ maxPrs: number
percentage: number
pricePerPrUsd: number | null
product: BillingProductV2Type | null
@@ -93,6 +97,19 @@ export interface inboxUsageLogicActions {
updateBillingLimits: (limits: { [key: string]: number | null }) => {
[key: string]: number | null
} // billingLogic
+ updateBillingLimitsSuccess: (
+ billing: BillingType | null,
+ payload?:
+ | {
+ [key: string]: number | null
+ }
+ | undefined
+ ) => {
+ billing: BillingType | null
+ payload?: {
+ [key: string]: number | null
+ }
+ } // billingLogic
closeModal: () => {
value: true
}
@@ -201,6 +218,13 @@ export interface inboxUsageLogicMeta {
quotaLimited: (refundSummary: SignalReportRefundSummaryResponseApi | null) => boolean
spentUsd: (usedPrs: number, freePrs: number, pricePerPrUsd: number | null) => number | null
percentage: (usedPrs: number, limitPrs: number | null, freePrs: number) => number
+ maxPrs: (
+ billing: BillingType | null,
+ product: BillingProductV2Type | null,
+ customLimitUsd: number | null,
+ pricePerPrUsd: number | null,
+ freePrs: number
+ ) => number
resetDate: (billing: BillingType | null) => Dayjs | null
estimatedBudgetUsd: (
limitForm: {
@@ -237,7 +261,7 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
teamLogic,
['currentTeamId'],
],
- actions: [billingLogic, ['loadBilling', 'updateBillingLimits']],
+ actions: [billingLogic, ['loadBilling', 'updateBillingLimits', 'updateBillingLimitsSuccess']],
})),
actions({
openModal: true,
@@ -279,13 +303,14 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
{
openModal: () => true,
closeModal: () => false,
- submitLimitFormSuccess: () => false,
+ // The billing loader swallows a rejected save, so the form's own submit success fires either way.
+ updateBillingLimitsSuccess: () => false,
},
],
}),
// Defined before `selectors` so the `limitForm` values selector exists when
// `estimatedBudgetUsd` lists it as an input (kea builds in array order).
- forms(({ actions, values }) => ({
+ forms(({ values }) => ({
limitForm: {
defaults: { prs: null as number | null },
errors: ({ prs }) => ({
@@ -296,17 +321,17 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
? 'Enter a whole number'
: prs < values.freePrs
? `Minimum is ${values.freePrs} PRs (the free tier)`
- : prs > 10000
- ? 'Enter a smaller number'
+ : prs > values.maxPrs
+ ? `Maximum is ${values.maxPrs.toLocaleString()} PRs`
: undefined,
}),
- submit: ({ prs }) => {
+ submit: async ({ prs }) => {
const { product, pricePerPrUsd, freePrs } = values
if (!product || pricePerPrUsd == null || prs == null) {
return
}
const usd = Math.max(0, prs - freePrs) * pricePerPrUsd
- actions.updateBillingLimits({ [product.type]: usd })
+ await billingLogic.asyncActions.updateBillingLimits({ [product.type]: usd })
},
},
})),
@@ -484,6 +509,28 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
return Math.min(100, Math.round((usedPrs / denominator) * 100))
},
],
+ // The billing service rejects a dollar limit above its ceiling.
+ maxPrs: [
+ (s) => [s.billing, s.product, s.customLimitUsd, s.pricePerPrUsd, s.freePrs],
+ (
+ billing: null | import('~/types').BillingType,
+ product: BillingProductV2Type | null,
+ customLimitUsd: number | null,
+ pricePerPrUsd: number | null,
+ freePrs: number
+ ): number => {
+ if (!product || !pricePerPrUsd) {
+ return MAX_LIMIT_PRS
+ }
+ const { max } = getBillingLimitConfig({
+ billing,
+ product,
+ customLimitUsd,
+ billingLimitNextPeriod: null,
+ })
+ return Math.min(MAX_LIMIT_PRS, freePrs + Math.floor(max / pricePerPrUsd))
+ },
+ ],
resetDate: [
(s) => [s.billing],
(billing: null | import('~/types').BillingType): Dayjs | null =>
@@ -516,6 +563,8 @@ export const inboxUsageLogic = kea<inboxUsageLogicType>([
// the widget's PR and refund counts update in-session (mirrors the reportListLogic reconcile
// listener — a plain dismiss or resolve just makes this a cheap no-op reload).
[inboxBulkActionsLogic.actionTypes.reportStateChanged]: () => actions.loadRefundSummary(),
+ // A raised limit can lift the quota pause, and `quotaLimited` only comes from the summary.
+ updateBillingLimitsSuccess: () => actions.loadRefundSummary(),
})),
// Fires on mount and again when the org-group-keyed flag arrives after mount — a mount-time
// load alone silently skips the summary on pageloads where flags resolve late, leaving the