: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(inbox): add a usage section (#65526)
Joshua Snyder54c1d0b40acf
diff --git a/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx b/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsxindex 5080640cc682..59f3091e0310 100644--- a/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx+++ b/frontend/src/scenes/inbox/components/shell/AgentSetupColumn.tsx@@ -18,6 +18,7 @@ import { ScoutsFleetSection } from '../config/scouts/ScoutsFleetSection'import { SignalSourcesPanel } from '../config/SignalSourcesPanel'import { SlackNotificationsSection } from '../config/SlackNotificationsSection'import { AgentSetupModalKey, agentSetupModalLogic } from './agentSetupModalLogic'+import { InboxUsageWidget } from './InboxUsageWidget'type WidgetTone = 'todo' | 'done' | 'neutral'/** Visual weight reflecting how important / frequently edited a part of the setup is. */@@ -329,6 +330,9 @@ export function AgentSetupColumn({ layout }: { layout: 'rail' | 'stacked' }): JS<NotificationsWidget /><McpServersWidget /></SetupSection>+ <SetupSection title="Usage">+ <InboxUsageWidget />+ </SetupSection><SetupModal /></div>)diff --git a/frontend/src/scenes/inbox/components/shell/InboxUsageWidget.tsx b/frontend/src/scenes/inbox/components/shell/InboxUsageWidget.tsxnew file mode 100644index 000000000000..7217f8afaa29--- /dev/null+++ b/frontend/src/scenes/inbox/components/shell/InboxUsageWidget.tsx@@ -0,0 +1,199 @@+import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'++import { LemonButton, LemonInput, LemonModal, LemonSkeleton, LemonTag } from '@posthog/lemon-ui'+import { Progress } from '@posthog/quill'++import { BillingUpgradeCTA } from 'lib/components/BillingUpgradeCTA'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { currencyFormatter } from 'scenes/billing/billing-utils'+import { billingProductLogic } from 'scenes/billing/billingProductLogic'+import { paymentEntryLogic } from 'scenes/billing/paymentEntryLogic'++import { BillingProductV2Type } from '~/types'++import { InboxUsageStatus, inboxUsageLogic } from '../../logics/inboxUsageLogic'++const PROGRESS_VARIANT: Record<InboxUsageStatus, 'info' | 'warning' | 'destructive'> = {+ normal: 'info',+ warning: 'warning',+ limit: 'destructive',+}++const CARD_CLASS = 'flex flex-col gap-2 rounded border border-primary bg-surface-primary px-2.5 py-2'++function UsageCardSkeleton(): JSX.Element {+ return (+ <div className={CARD_CLASS}>+ <LemonSkeleton className="h-3 w-24" />+ <LemonSkeleton className="h-2 w-full" />+ <div className="flex items-center justify-between">+ <LemonSkeleton className="h-3 w-28" />+ <LemonSkeleton className="h-3 w-16" />+ </div>+ </div>+ )+}++/**+ * Runs the standard billing upgrade in place — same flow the billing page uses. The Stripe payment+ * modal is mounted globally (GlobalModals), so on click a returning customer is subscribed+ * immediately and a new one gets the card modal; either way billing reloads and this widget flips+ * to the editable subscribed state.+ */+function UpgradeButton({ product }: { product: BillingProductV2Type }): JSX.Element {+ const { billingProductLoading } = useValues(billingProductLogic({ product }))+ const { startPaymentEntryFlow } = useActions(paymentEntryLogic)++ return (+ <BillingUpgradeCTA+ type="primary"+ size="small"+ fullWidth+ center+ disableClientSideRouting+ loading={!!billingProductLoading}+ onClick={() => startPaymentEntryFlow(product, window.location.pathname + window.location.search)}+ >+ Upgrade to raise limit+ </BillingUpgradeCTA>+ )+}++function EditLimitModal(): JSX.Element {+ const { isModalOpen, freePrs, pricePerPrUsd, estimatedBudgetUsd, limitForm, isLimitFormSubmitting } =+ useValues(inboxUsageLogic)+ const { closeModal, submitLimitForm } = useActions(inboxUsageLogic)++ const billablePrs = Math.max(0, (limitForm.prs ?? 0) - freePrs)++ return (+ <LemonModal+ isOpen={isModalOpen}+ onClose={closeModal}+ title="PR limit"+ description="How many pull requests agents can open each month before pausing."+ width={460}+ footer={+ <>+ <LemonButton type="secondary" onClick={closeModal}>+ Cancel+ </LemonButton>+ <LemonButton type="primary" onClick={submitLimitForm} loading={isLimitFormSubmitting}>+ Save+ </LemonButton>+ </>+ }+ >+ <Form logic={inboxUsageLogic} formKey="limitForm" className="flex flex-col gap-3">+ <LemonField name="prs" label="Monthly limit (PRs)">+ <LemonInput type="number" min={0} step={1} autoFocus />+ </LemonField>+ <div className="flex flex-col gap-2 text-xs">+ {freePrs > 0 && pricePerPrUsd != null && (+ <span className="text-secondary">+ The first {freePrs} PRs each month are free, then {currencyFormatter(pricePerPrUsd)} per PR.+ </span>+ )}+ {estimatedBudgetUsd != null && pricePerPrUsd != null && (+ <div className="flex flex-col gap-0.5 rounded bg-surface-secondary px-2 py-1.5">+ <div className="flex items-center justify-between">+ <span className="text-default">Estimated monthly budget</span>+ <span className="font-semibold text-default tabular-nums">+ {currencyFormatter(estimatedBudgetUsd)}+ </span>+ </div>+ <span className="text-tertiary">+ {billablePrs > 0+ ? `${billablePrs} billable PRs × ${currencyFormatter(pricePerPrUsd)}`+ : 'Within the free tier'}+ </span>+ </div>+ )}+ </div>+ </Form>+ </LemonModal>+ )+}++/**+ * Compact PR-usage meter for the inbox agents rail: a progress bar, `X / Y PRs created` on the+ * left, `Resets <date>` on the right. On a paid plan the limit is editable (and the edit affordance+ * escalates to "Increase limit" at the cap); on the free plan it shows an in-place upgrade instead.+ * Renders nothing until billing has loaded and the inbox product is present.+ */+export function InboxUsageWidget(): JSX.Element | null {+ const {+ product,+ isLoading,+ isSubscribed,+ canAccessBilling,+ usedPrsDisplay,+ limitPrs,+ percentage,+ status,+ resetDate,+ } = useValues(inboxUsageLogic)+ const { openModal } = useActions(inboxUsageLogic)++ if (isLoading) {+ return <UsageCardSkeleton />+ }+ if (!product) {+ return null+ }++ // Only org admins/owners can change billing (canAccessBilling) — others get a read-only view with a hint.+ return (+ <>+ <div className={CARD_CLASS}>+ <div className="flex items-center justify-between gap-1.5">+ <span className="text-[13px] font-semibold text-default">Pull requests</span>+ {!isSubscribed ? (+ <LemonTag type="muted" size="small">+ Free plan+ </LemonTag>+ ) : canAccessBilling && status !== 'limit' ? (+ <button+ type="button"+ onClick={openModal}+ className="text-xs text-link hover:underline cursor-pointer bg-transparent border-0 p-0"+ >+ Edit+ </button>+ ) : null}+ </div>+ <Progress value={percentage} variant={PROGRESS_VARIANT[status]} />+ <div className="flex items-center justify-between gap-2 text-xs">+ <span className="text-secondary tabular-nums">+ <span className="font-medium text-default">{usedPrsDisplay}</span>+ {limitPrs != null ? ` / ${limitPrs}` : ''} PRs created+ </span>+ {resetDate && (+ <span className="text-tertiary tabular-nums">Resets {resetDate.format('MMM D')}</span>+ )}+ </div>+ {canAccessBilling ? (+ !isSubscribed ? (+ <UpgradeButton product={product} />+ ) : (+ status === 'limit' && (+ <LemonButton type="primary" size="small" fullWidth center onClick={openModal}>+ Increase limit+ </LemonButton>+ )+ )+ ) : (+ (!isSubscribed || status === 'limit') && (+ <span className="text-xs text-muted">+ {isSubscribed+ ? 'Contact an organization admin to raise the limit.'+ : 'Contact an organization admin to upgrade.'}+ </span>+ )+ )}+ </div>+ {canAccessBilling && <EditLimitModal />}+ </>+ )+}diff --git a/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts b/frontend/src/scenes/inbox/logics/inboxUsageLogic.tsnew file mode 100644index 000000000000..1d418571cfa1--- /dev/null+++ b/frontend/src/scenes/inbox/logics/inboxUsageLogic.ts@@ -0,0 +1,205 @@+import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { forms } from 'kea-forms'++import { Dayjs } from 'lib/dayjs'+import { calculateFreeTier } from 'scenes/billing/billing-utils'+import { billingLogic } from 'scenes/billing/billingLogic'++import { BillingProductV2Type } from '~/types'++import type { inboxUsageLogicType } from './inboxUsageLogicType'++// The inbox/signals billing product type (a flat per-PR credit charge). This is the identifier+// billing uses everywhere — it's also the key into `custom_limits_usd` — so we match on it rather+// than `usage_key` (the product reports usage under `signals_credits`).+const INBOX_PRODUCT_TYPE = 'inbox'++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++/** Marginal USD price of a single credit, from the first paid tier (falling back to the product+ * unit price). Used with `creditsPerPr` to derive the per-PR price without hardcoding anything. */+function perCreditUsd(product: BillingProductV2Type): number | null {+ const paidTier = product.tiers?.find((tier) => parseFloat(tier.unit_amount_usd) > 0)+ if (paidTier) {+ return parseFloat(paidTier.unit_amount_usd)+ }+ return product.unit_amount_usd ? parseFloat(product.unit_amount_usd) : null+}++/**+ * Drives the PR-usage widget in the inbox agents rail. Reads the inbox/signals billing product and+ * surfaces usage, limit, and reset date in PRs (the product bills in credits; `display_divisor`+ * converts credits → PRs). Editing the limit writes a USD spend cap to `custom_limits_usd`, the+ * same mechanism the billing page uses.+ */+export const inboxUsageLogic = kea<inboxUsageLogicType>([+ path(['scenes', 'inbox', 'logics', 'inboxUsageLogic']),+ connect(() => ({+ values: [billingLogic, ['billing', 'billingLoading', 'canAccessBilling']],+ actions: [billingLogic, ['loadBilling', 'updateBillingLimits']],+ })),+ actions({+ openModal: true,+ closeModal: true,+ }),+ reducers({+ isModalOpen: [+ false,+ {+ openModal: () => true,+ closeModal: () => false,+ submitLimitFormSuccess: () => 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 }) => ({+ limitForm: {+ defaults: { prs: null as number | null },+ errors: ({ prs }) => ({+ prs:+ prs == null+ ? 'Enter a number of PRs'+ : !Number.isInteger(prs) || prs < 0+ ? 'Enter a whole number'+ : prs < values.freePrs+ ? `Minimum is ${values.freePrs} PRs (the free tier)`+ : prs > 10000+ ? 'Enter a smaller number'+ : undefined,+ }),+ submit: ({ 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 })+ },+ },+ })),+ selectors({+ product: [+ (s) => [s.billing],+ (billing): BillingProductV2Type | null =>+ billing?.products?.find((p) => p.type === INBOX_PRODUCT_TYPE) ?? null,+ ],+ isLoading: [+ (s) => [s.billing, s.billingLoading],+ (billing, billingLoading): boolean => billing === null && billingLoading,+ ],+ // Free plan can't raise the limit past the free allocation — the widget points to+ // billing to upgrade instead of editing a limit.+ isSubscribed: [(s) => [s.product], (product): boolean => !!product?.subscribed],+ // Credits per PR — the API's credits → PR divisor. Null means we can't safely show PRs.+ creditsPerPr: [+ (s) => [s.product],+ (product): number | null =>+ product?.display_divisor && product.display_divisor > 0 ? product.display_divisor : null,+ ],+ pricePerPrUsd: [+ (s) => [s.product, s.creditsPerPr],+ (product, creditsPerPr): number | null => {+ if (!product || !creditsPerPr) {+ return null+ }+ const perCredit = perCreditUsd(product)+ return perCredit != null ? perCredit * creditsPerPr : null+ },+ ],+ freePrs: [+ (s) => [s.product, s.creditsPerPr],+ (product, creditsPerPr): number =>+ product && creditsPerPr ? Math.round(calculateFreeTier(product) / creditsPerPr) : 0,+ ],+ usedPrs: [+ (s) => [s.product, s.creditsPerPr],+ (product, creditsPerPr): number =>+ product && creditsPerPr ? Math.round((product.current_usage ?? 0) / creditsPerPr) : 0,+ ],+ customLimitUsd: [+ (s) => [s.billing, s.product],+ (billing, product): number | null => {+ if (!product) {+ return null+ }+ const limit = billing?.custom_limits_usd?.[product.type]+ return limit === 0 || limit ? Number(limit) : null+ },+ ],+ // The effective monthly PR cap: a user-set custom limit takes precedence, otherwise the+ // product's own usage_limit (credits). Null means uncapped.+ limitPrs: [+ (s) => [s.product, s.creditsPerPr, s.customLimitUsd, s.pricePerPrUsd, s.freePrs],+ (product, creditsPerPr, customLimitUsd, pricePerPrUsd, freePrs): number | null => {+ if (!product || !creditsPerPr) {+ return null+ }+ if (customLimitUsd != null && pricePerPrUsd) {+ return freePrs + Math.round(customLimitUsd / pricePerPrUsd)+ }+ if (product.usage_limit != null) {+ return Math.round(product.usage_limit / creditsPerPr)+ }+ return null+ },+ ],+ percentage: [+ (s) => [s.usedPrs, s.limitPrs, s.freePrs],+ (usedPrs, limitPrs, freePrs): number => {+ const denominator = limitPrs ?? (freePrs || null)+ if (!denominator) {+ return 0+ }+ return Math.min(100, Math.round((usedPrs / denominator) * 100))+ },+ ],+ status: [+ (s) => [s.usedPrs, s.limitPrs],+ (usedPrs, limitPrs): InboxUsageStatus => {+ if (limitPrs == null) {+ return 'normal'+ }+ if (usedPrs >= limitPrs) {+ return 'limit'+ }+ if (usedPrs / limitPrs >= WARNING_THRESHOLD) {+ return 'warning'+ }+ return 'normal'+ },+ ],+ // Displayed usage caps at the limit — we never show "53 / 50" when usage runs over.+ usedPrsDisplay: [+ (s) => [s.usedPrs, s.limitPrs],+ (usedPrs, limitPrs): number => (limitPrs != null ? Math.min(usedPrs, limitPrs) : usedPrs),+ ],+ resetDate: [(s) => [s.billing], (billing): Dayjs | null => billing?.billing_period?.current_period_end ?? null],+ // USD spend cap implied by the limit currently typed into the modal. Drives the live budget.+ estimatedBudgetUsd: [+ (s) => [s.limitForm, s.pricePerPrUsd, s.freePrs],+ (limitForm, pricePerPrUsd, freePrs): number | null => {+ const prs = limitForm?.prs+ if (pricePerPrUsd == null || prs == null || Number.isNaN(prs)) {+ return null+ }+ return Math.max(0, prs - freePrs) * pricePerPrUsd+ },+ ],+ }),+ listeners(({ actions, values }) => ({+ openModal: () => {+ // Seed the field with the current limit (or the free allowance when uncapped).+ actions.setLimitFormValue('prs', values.limitPrs ?? values.freePrs)+ },+ })),+ afterMount(({ actions, values }) => {+ if (!values.billing) {+ actions.loadBilling()+ }+ }),+])