Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai-billing): bring back the Max plan and cap free users at $5/mo (#7515)

Will Hutchinson9e5ab16ac3a6
diff --git a/apps/docs/account/billing.mdx b/apps/docs/account/billing.mdx
index 32ce7552a0..36f908eb29 100644
--- a/apps/docs/account/billing.mdx
+++ b/apps/docs/account/billing.mdx
@@ -1,31 +1,34 @@
---
title: "Billing & Plans"
icon: "credit-card"
-description: "Macro's Guest access and Premium subscriptions, how AI usage is included, and how to manage your subscription."
+description: "Macro's Guest access and Premium and Max subscriptions, how AI usage is included, and how to manage your subscription."
---
-Join a workspace as a Guest for free. Macro offers one paid plan for new subscriptions, priced per person. The price is the same whether you're solo or on a team.
+Join a workspace as a Guest for free. Macro has two paid plans, priced per person. The price is the same whether you're solo or on a team.
-| | Guest | Premium |
-| --- | --- | --- |
-| Price | \$0 | \$40 / month |
-| AI agent | Fast model only | All models |
-| AI usage included each month | Limited | \$40 |
-| Beyond included AI | — | Credits or usage billing |
-| Storage | 5 GB | 1 TB |
+| | Guest | Premium | Max |
+| --- | --- | --- | --- |
+| Price | \$0 | \$40 / month | \$200 / month |
+| AI agent | Fast model only | All models | All models |
+| AI usage included each month | \$5 | \$15 | \$150 |
+| Beyond included AI | Upgrade to continue | Credits or usage billing | Credits or usage billing |
+| Storage | 5 GB | 1 TB | 1 TB |
-Paid teams require a paid seat for every member. Free teams can include unpaid members. New paid seats use Premium. Max is unavailable for new purchases and upgrades. Existing Max seats keep their plan and can move to Premium from **Settings → Team**. Moving a seat is prorated for the rest of the billing period. Your current plan is shown in **Settings → Billing**, with an **Upgrade** button if you have Guest access and a **Switch to Premium** option if you're on Max.
+Paid teams require a paid seat for every member; free teams can include unpaid members. Each seat has its own plan: a team can mix Premium and Max seats, and team admins choose the plan for every member from the **Seat plan** menu next to their name in **Settings → Team**. Moving a seat is prorated for the rest of the billing period. Your current plan is shown in **Settings → Billing**, with **Upgrade now** and **Get Max** buttons if you have Guest access, an **Upgrade to Max** button on Premium, and a **Switch to Premium** option on Max (on a team, these move only your own seat).
## AI usage
-Premium includes \$40 of AI each month, measured at Macro's usage rates. Existing Max seats keep their \$200 allowance. Each AI request draws on that amount based on the model and the tokens it used, so the heavy models go further into it: Opus 5 uses about 2.5×, and Fable 5.1 and GPT-6 Astra about 5×, what Sonnet 5 does for the same conversation (the model picker shows the multiplier). On a team, every seat keeps its own allowance: unused usage on one seat doesn't move to another. Prepaid credits and usage billing are shared across the team and managed by the team owner.
+Every plan includes a monthly amount of AI usage measured at the provider's list price: Guest access includes \$5, Premium \$15, and Max \$150. Each AI request draws on that amount based on the model and the tokens it used, so the heavy models go further into it: Opus 5 uses about 2.5×, and Fable 5.1 and GPT-6 Astra about 5×, what Sonnet 5 does for the same conversation (the model picker shows the multiplier). On a team, every seat keeps its own allowance: unused usage on one seat doesn't move to another. Prepaid credits and usage billing are shared across the team and managed by the team owner.
+
+With Guest access the included amount is a hard cap: once it's used, AI requests pause until the next calendar month or until you upgrade. Paid plans can keep going with credits or usage billing, both priced at list price plus 25%.
**Settings → Billing** shows how much of this period's included AI you've used, when it resets, your credit balance, and your usage billing settings. Included usage resets at the start of each billing period; it doesn't roll over.
-When the included amount is used up, AI requests pause until one of these applies:
+When a paid plan's included amount is used up, AI requests pause until one of these applies:
- **Credits** — prepaid AI usage you buy in \$10, \$25, \$50, or \$100 packs. Credits are applied after your included amount, never expire, and carry over between periods.
- **Usage billing** — turn it on to bill AI beyond your included amount and credits to your card in \$10 increments, up to a monthly limit you choose. If a charge fails, usage billing pauses until you update your payment method and turn it back on.
+- **Upgrading to Max** — ten times the included usage for that seat. Upgrades take effect immediately and are prorated for the rest of the period. On a team, move the heavy users' seats to Max from **Settings → Team** and leave the rest on Premium.
On a team, the team owner buys credits and controls usage billing for everyone; members see the team's position but not the controls.
diff --git a/apps/docs/product/agents.mdx b/apps/docs/product/agents.mdx
index f9ec0e5ae9..45df1c901c 100644
--- a/apps/docs/product/agents.mdx
+++ b/apps/docs/product/agents.mdx
@@ -77,7 +77,7 @@ Agents can run on a schedule. An automation is a saved prompt that runs on its o
A model picker sits in the chat input. You can choose a model per chat depending on how difficult you deem the question. Your choice is remembered for that chat and carried forward when you start a new one from the composer.
-With Guest access you can only use Haiku, the fast model. Premium and existing Max subscriptions unlock the rest, including Opus 5, Fable 5.1 (Anthropic's most capable model), and GPT-6 Astra (OpenAI's). Heavier models draw down your included AI faster, and the picker shows by how much: Opus uses about 2.5×, and Fable and Astra about 5×, what Sonnet does for the same conversation.
+With Guest access you can only use Haiku, the fast model. Every paid plan (Premium and Max) unlocks the rest, including Opus 5, Fable 5.1 (Anthropic's most capable model), and GPT-6 Astra (OpenAI's). Heavier models draw down your included AI faster, and the picker shows by how much: Opus uses about 2.5×, and Fable and Astra about 5×, what Sonnet does for the same conversation.
<Frame>
![The model picker, showing the available models](/images/model_options.png)
diff --git a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx
index 9e0da181f3..bcd4fa2f85 100644
--- a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx
+++ b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx
@@ -1,9 +1,8 @@
import { AiUsageControls, AiUsageMeter } from '@app/features/settings/AiUsage';
-// import { useAnalytics } from '@app/lib/analytics/analytics-context';
-// import { toast } from '@core/component/Toast/Toast';
+import { useAnalytics } from '@app/lib/analytics/analytics-context';
+import { toast } from '@core/component/Toast/Toast';
import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
-import { useAiBillingSummaryQuery } from '@queries/auth';
-// import { useChangePlanMutation } from '@queries/auth';
+import { useAiBillingSummaryQuery, useChangePlanMutation } from '@queries/auth';
import type { AiDenyCode } from '@service-auth/ai-billing-types';
import { useNavigate } from '@solidjs/router';
import { Button, Dialog, Surface } from '@ui';
@@ -11,6 +10,7 @@ import { Show, Suspense } from 'solid-js';
const TITLES: Record<AiDenyCode, string> = {
ai_allowance_exhausted: "You've used this month's included AI",
+ ai_free_allowance_exhausted: "You've used this month's free AI",
ai_overage_limit_reached: "You've hit your AI spending limit",
ai_overage_payment_failed: 'Your last AI usage charge failed',
};
@@ -18,19 +18,21 @@ const TITLES: Record<AiDenyCode, string> = {
/**
* Shown when the backend refuses an AI request with a billing code. Offers the
* payer the same controls as Billing settings, right where they were blocked.
+ * Free users have no controls; they are pointed at an upgrade instead.
*/
export function AiUsageLimitDialog() {
const { usageLimitOpen, usageLimitCode, hideUsageLimit } =
useAiUsageLimitState();
- // const analytics = useAnalytics();
+ const analytics = useAnalytics();
const navigate = useNavigate();
const summary = useAiBillingSummaryQuery({ enabled: usageLimitOpen });
- // const changePlan = useChangePlanMutation();
+ const changePlan = useChangePlanMutation();
- const title = () => TITLES[usageLimitCode() ?? 'ai_allowance_exhausted'];
+ const code = () => usageLimitCode() ?? 'ai_allowance_exhausted';
+ const title = () => TITLES[code()];
+ const free = () => code() === 'ai_free_allowance_exhausted';
const returnUrl = () => `${window.location.origin}/app/settings/billing`;
- /*
const upgradeToMax = async () => {
try {
await changePlan.mutateAsync({ plan: 'max' });
@@ -42,7 +44,6 @@ export function AiUsageLimitDialog() {
toast.failure("Couldn't upgrade. Please try again from Billing.");
}
};
- */
return (
<Dialog
@@ -56,8 +57,14 @@ export function AiUsageLimitDialog() {
<div class="flex flex-col gap-1">
<h2 class="text-xl font-semibold text-ink">{title()}</h2>
<p class="text-sm text-ink-extra-muted">
- Your plan includes AI each month, measured at provider cost. Add
- credits or turn on usage billing to keep going.
+ <Show
+ when={!free()}
+ fallback="Guest access includes a fixed amount of AI each month, measured at provider cost. Upgrade to keep going now and unlock every model."
+ >
+ Your plan includes AI each month, measured at provider cost. Add
+ credits or turn on usage billing to keep going, or move to Max
+ for a larger included amount.
+ </Show>
</p>
</div>
@@ -68,12 +75,14 @@ export function AiUsageLimitDialog() {
{(snapshot) => (
<div class="flex flex-col gap-4 rounded-lg bg-active p-4">
<AiUsageMeter snapshot={snapshot()} />
- <div class="border-t border-t-edge-muted pt-4">
- <AiUsageControls
- snapshot={snapshot()}
- returnUrl={returnUrl()}
- />
- </div>
+ <Show when={snapshot().tier !== 'free'}>
+ <div class="border-t border-t-edge-muted pt-4">
+ <AiUsageControls
+ snapshot={snapshot()}
+ returnUrl={returnUrl()}
+ />
+ </div>
+ </Show>
</div>
)}
</Show>
@@ -100,8 +109,19 @@ export function AiUsageLimitDialog() {
>
Dismiss
</Button>
- {/*
<Suspense fallback={null}>
+ <Show when={summary.isSuccess && summary.data.tier === 'free'}>
+ <Button
+ variant="strong"
+ class="px-3 py-1.5"
+ onClick={() => {
+ hideUsageLimit();
+ navigate('/app/settings/billing');
+ }}
+ >
+ Upgrade
+ </Button>
+ </Show>
<Show
when={
summary.isSuccess &&
@@ -111,7 +131,7 @@ export function AiUsageLimitDialog() {
>
<Button
variant="strong"
- class="rounded-full px-3 py-1.5"
+ class="px-3 py-1.5"
disabled={changePlan.isPending}
onClick={() => void upgradeToMax()}
>
@@ -119,7 +139,6 @@ export function AiUsageLimitDialog() {
</Button>
</Show>
</Suspense>
- */}
</div>
</div>
</section>
diff --git a/apps/web/src/features/paywall/plans.test.ts b/apps/web/src/features/paywall/plans.test.ts
index 1f7f8ce4a4..88bbe5bd15 100644
--- a/apps/web/src/features/paywall/plans.test.ts
+++ b/apps/web/src/features/paywall/plans.test.ts
@@ -1,13 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { PLAN_BY_TIER, PLANS } from './plans';
+import { PLAN_BY_TIER, PLANS, planFeatures } from './plans';
describe('plan catalogs', () => {
- it('offers Guest access and Premium during onboarding', () => {
- expect(PLANS.map((plan) => plan.tier)).toEqual(['free', 'premium']);
+ it('lists Guest, Premium and Max, cheapest first', () => {
+ expect(PLANS.map((plan) => plan.tier)).toEqual(['free', 'premium', 'max']);
expect(PLAN_BY_TIER.free.name).toBe('Guest');
- });
-
- it('retains Max for current-plan display', () => {
expect(PLAN_BY_TIER.max).toEqual({
tier: 'max',
name: 'Max',
@@ -15,4 +12,27 @@ describe('plan catalogs', () => {
highlighted: false,
});
});
+
+ it('reads every allowance, including the free cap, from the catalog', () => {
+ const [included, , beyond] = planFeatures(true, {
+ free: 500,
+ premium: 1_500,
+ max: 15_000,
+ });
+ expect(included.values).toEqual({
+ free: '$5 / mo at cost',
+ premium: '$15 / mo at cost',
+ max: '$150 / mo at cost',
+ });
+ expect(beyond.values.free).toBe('Upgrade to continue');
+ // Unknown until the catalog loads.
+ expect(planFeatures(true).at(0)?.values.free).toBe('—');
+ });
+
+ it('hides the usage rows without AI usage billing', () => {
+ expect(planFeatures(false).map((row) => row.label)).toEqual([
+ 'AI Agent',
+ 'Storage',
+ ]);
+ });
});
diff --git a/apps/web/src/features/paywall/plans.ts b/apps/web/src/features/paywall/plans.ts
index 4378074ea4..220423c36c 100644
--- a/apps/web/src/features/paywall/plans.ts
+++ b/apps/web/src/features/paywall/plans.ts
@@ -54,7 +54,7 @@ const MAX_PLAN = {
export const PLANS = [
FREE_PLAN,
PREMIUM_PLAN,
- // MAX_PLAN,
+ MAX_PLAN,
] as const satisfies Plan[];
export const PLAN_BY_TIER: Record<PlanTier, Plan> = {
@@ -70,7 +70,10 @@ interface PlanFeature {
aiUsageBilling?: boolean;
}
-/** The allowance row; amounts come from the plan catalog, "—" until it loads. */
+/**
+ * The allowance row; amounts come from the plan catalog, "—" until it loads.
+ * Free's amount is its monthly hard cap.
+ */
function includedAiRow(includedAi: IncludedAiCentsByTier): PlanFeature {
const perMonth = (tier: PlanTier) => {
const amount = formatIncludedAi(includedAi[tier]);
@@ -80,7 +83,7 @@ function includedAiRow(includedAi: IncludedAiCentsByTier): PlanFeature {
label: 'AI usage included',
aiUsageBilling: true,
values: {
- free: 'Limited',
+ free: perMonth('free'),
premium: perMonth('premium'),
max: perMonth('max'),
},
@@ -100,7 +103,7 @@ const PLAN_FEATURE_ROWS: PlanFeature[] = [
label: 'Beyond included',
aiUsageBilling: true,
values: {
- free: '—',
+ free: 'Upgrade to continue',
premium: 'Credits or usage billing',
max: 'Credits or usage billing',
},
diff --git a/apps/web/src/features/settings/AiUsage.test.tsx b/apps/web/src/features/settings/AiUsage.test.tsx
index d14f5dfde7..5314d5604e 100644
--- a/apps/web/src/features/settings/AiUsage.test.tsx
+++ b/apps/web/src/features/settings/AiUsage.test.tsx
@@ -49,4 +49,28 @@ describe('AiUsageMeter', () => {
expect(screen.getByText(/Usage billing this period/)).toBeTruthy();
expect(screen.queryByText(/Team credits:/)).toBeNull();
});
+
+ it('shows free users only their monthly cap and the upgrade prompt', () => {
+ render(() => (
+ <AiUsageMeter
+ snapshot={{
+ ...snapshot(1),
+ tier: 'free',
+ included_cents: 500,
+ used_cents: 500,
+ credit_balance_cents: 0,
+ overage_enabled: false,
+ overage_limit_cents: 0,
+ overage_charged_cents: 0,
+ remaining_cents: 0,
+ blocked_reason: 'free_allowance_exhausted',
+ }}
+ />
+ ));
+
+ expect(screen.getByText(/of \$5 included/)).toBeTruthy();
+ expect(screen.queryByText(/Credits:/)).toBeNull();
+ expect(screen.queryByText(/Usage billing/)).toBeNull();
+ expect(screen.getByText(/Upgrade to keep going/)).toBeTruthy();
+ });
});
diff --git a/apps/web/src/features/settings/AiUsage.tsx b/apps/web/src/features/settings/AiUsage.tsx
index 495d002bfc..2c6b1fee19 100644
--- a/apps/web/src/features/settings/AiUsage.tsx
+++ b/apps/web/src/features/settings/AiUsage.tsx
@@ -32,6 +32,8 @@ function formatPeriodEnd(iso: string): string {
const BLOCKED_COPY: Record<AiDenyReason, string> = {
allowance_exhausted:
"You've used this period's included AI. Add credits or turn on usage billing to keep going.",
+ free_allowance_exhausted:
+ "You've used this month's free AI. Upgrade to keep going.",
overage_limit_reached:
"You've reached your usage billing limit for this period. Raise the limit or add credits to keep going.",
overage_payment_failed:
@@ -44,9 +46,11 @@ const DEFAULT_CREDIT_PACKS_CENTS = [1_000, 2_500, 5_000, 10_000];
/**
* The period's AI position: a meter of included usage plus credits and overage
- * headroom, and where the user stands right now.
+ * headroom, and where the user stands right now. Free users see only the
+ * meter against their monthly cap; they have no credits or usage billing.
*/
export function AiUsageMeter(props: { snapshot: AiUsageSnapshot }) {
+ const free = () => props.snapshot.tier === 'free';
const included = () => props.snapshot.included_cents;
const used = () => props.snapshot.used_cents;
const includedUsed = () => Math.min(used(), included());
@@ -91,12 +95,14 @@ export function AiUsageMeter(props: { snapshot: AiUsageSnapshot }) {
<Show when={beyond() > 0}>
<span>{formatCents(beyond())} beyond included</span>
</Show>
- <span>
- {props.snapshot.seats > 1 ? 'Team credits' : 'Credits'}:{' '}
- <span class="text-ink">
- {formatCents(props.snapshot.credit_balance_cents)}
+ <Show when={!free()}>
+ <span>
+ {props.snapshot.seats > 1 ? 'Team credits' : 'Credits'}:{' '}
+ <span class="text-ink">
+ {formatCents(props.snapshot.credit_balance_cents)}
+ </span>
</span>
- </span>
+ </Show>
<Show when={props.snapshot.overage_enabled}>
<span>
{props.snapshot.seats > 1
diff --git a/apps/web/src/features/settings/Billing.test.tsx b/apps/web/src/features/settings/Billing.test.tsx
index f4384f29a1..6c0075e25a 100644
--- a/apps/web/src/features/settings/Billing.test.tsx
+++ b/apps/web/src/features/settings/Billing.test.tsx
@@ -76,9 +76,9 @@ vi.mock('@queries/auth', () => ({
}),
useCreateCheckoutSessionMutation: () => ({ mutateAsync: vi.fn() }),
useIncludedAiCentsByTier: () => () => ({
- free: 0,
+ free: 500,
premium: 2_000,
- max: 2_000,
+ max: 10_000,
}),
}));
vi.mock('@service-stripe/client', () => ({
@@ -122,8 +122,9 @@ describe.each([false, true])(
const { container } = render(() => <Billing />);
expect(screen.getByRole('heading', { name: 'Billing' })).toBeTruthy();
+ // Free users see their monthly cap but have no credits or usage billing.
expect(screen.queryByTestId('usage-meter') !== null).toBe(
- aiUsageBilling && tier !== 'free'
+ aiUsageBilling
);
expect(screen.queryByTestId('usage-controls') !== null).toBe(
aiUsageBilling && tier !== 'free'
@@ -172,18 +173,42 @@ describe.each([false, true])(
).toBe(aiUsageBilling);
});
- it.each<PlanTier>(['free', 'premium'])(
- 'does not offer Max purchases from the %s plan',
- (tier) => {
- state.tier = tier;
- render(() => <Billing />);
+ it('offers both paid plans to free users', () => {
+ state.tier = 'free';
+ const { container } = render(() => <Billing />);
- expect(screen.queryByRole('button', { name: 'Get Max' })).toBeNull();
- expect(
- screen.queryByRole('button', { name: 'Upgrade to Max' })
- ).toBeNull();
- }
- );
+ expect(screen.getByRole('button', { name: 'Upgrade now' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Get Max' })).toBeTruthy();
+ expect(
+ screen.queryByRole('button', { name: 'Upgrade to Max' })
+ ).toBeNull();
+ // Allowances come from the catalog, including the free cap.
+ expect(container.textContent?.includes('$5 of AI usage')).toBe(
+ aiUsageBilling
+ );
+ expect(container.textContent?.includes('$100 of AI usage')).toBe(
+ aiUsageBilling
+ );
+ });
+
+ it('lets a Premium payer move to Max', async () => {
+ state.tier = 'premium';
+ render(() => <Billing />);
+
+ expect(
+ screen.getByText(aiUsageBilling ? 'Need more AI?' : 'Upgrade')
+ ).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Get Max' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Upgrade to Max' }));
+ await waitFor(() =>
+ expect(state.changePlan).toHaveBeenCalledWith({ plan: 'max' })
+ );
+ expect(state.toastSuccess).toHaveBeenCalledWith(
+ aiUsageBilling
+ ? 'Upgraded to Max. Your larger AI allowance applies right away.'
+ : 'Upgraded to Max.'
+ );
+ });
it('keeps the current Max plan visible and allows a Premium downgrade', async () => {
state.tier = 'max';
diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsx
index bf9e56cd2f..51c605f643 100644
--- a/apps/web/src/features/settings/Billing.tsx
+++ b/apps/web/src/features/settings/Billing.tsx
@@ -36,7 +36,12 @@ const BILLING_PLAN_FEATURES: Record<
PlanTier,
(includedAi: string | undefined) => string[]
> = {
- free: () => ['Access to Haiku', 'MCP access', '5 GB storage'],
+ free: (includedAi) => [
+ 'Access to Haiku',
+ ...(includedAi ? [`${includedAi} of AI usage at cost each month`] : []),
+ 'MCP access',
+ '5 GB storage',
+ ],
premium: (includedAi) => [
'All agents',
'All models',
@@ -283,17 +288,16 @@ export const Billing = () => {
</SettingsSection>
<Show
- when={
- aiUsageBilling().enabled &&
- hasPaid() &&
- summary.isSuccess &&
- summary.data
- }
+ when={aiUsageBilling().enabled && summary.isSuccess && summary.data}
>
{(snapshot) => (
<SettingsSection
title="AI usage"
- description="Your plan includes AI each month, measured at provider cost. Beyond that, prepaid credits and usage billing keep you going."
+ description={
+ snapshot().tier === 'free'
+ ? 'Guest access includes a fixed amount of AI each month, measured at provider cost. Upgrade for more and to unlock every model.'
+ : 'Your plan includes AI each month, measured at provider cost. Beyond that, prepaid credits and usage billing keep you going.'
+ }
>
<SettingsCard>
<section class="flex flex-col gap-5 p-4">
@@ -306,12 +310,14 @@ export const Billing = () => {
}
>
<AiUsageMeter snapshot={snapshot()} />
- <div class="border-t border-t-edge-muted pt-4">
- <AiUsageControls
- snapshot={snapshot()}
- returnUrl={returnUrl()}
- />
- </div>
+ <Show when={snapshot().tier !== 'free'}>
+ <div class="border-t border-t-edge-muted pt-4">
+ <AiUsageControls
+ snapshot={snapshot()}
+ returnUrl={returnUrl()}
+ />
+ </div>
+ </Show>
</Show>
</section>
</SettingsCard>
@@ -344,7 +350,6 @@ export const Billing = () => {
</ul>
</section>
</SettingsCard>
- {/*
<SettingsCard>
<section class="flex flex-col gap-4 p-4">
<header class="flex items-center gap-2">
@@ -353,7 +358,7 @@ export const Billing = () => {
<PlanPrice tier="max" />
</div>
<Button
- class="ml-auto rounded-full py-1.5 px-3"
+ class="ml-auto py-1.5 px-3"
depth={2}
variant="outline"
onClick={() => void handleCheckout('max')}
@@ -366,10 +371,8 @@ export const Billing = () => {
</ul>
</section>
</SettingsCard>
- */}
</SettingsSection>
</Match>
- {/*
<Match when={tier() === 'premium'}>
<SettingsSection
title={aiUsageBilling().enabled ? 'Need more AI?' : 'Upgrade'}
@@ -382,7 +385,7 @@ export const Billing = () => {
<PlanPrice tier="max" />
</div>
<Button
- class="ml-auto rounded-full py-1.5 px-3"
+ class="ml-auto py-1.5 px-3"
depth={2}
variant="cta"
disabled={changePlan.isPending}
@@ -406,7 +409,6 @@ export const Billing = () => {
</SettingsCard>
</SettingsSection>
</Match>
- */}
<Match when={tier() === 'max'}>
<SettingsSection>
<p class="px-6 text-xs text-ink-extra-muted">
diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsx
index e065141aa9..9c713ef0f6 100644
--- a/apps/web/src/features/settings/Team.tsx
+++ b/apps/web/src/features/settings/Team.tsx
@@ -1,7 +1,6 @@
import {
formatIncludedAi,
type IncludedAiCentsByTier,
- PLAN_BY_TIER,
PLANS,
type Plan,
type PlanTier,
@@ -186,19 +185,16 @@ function planOption(plan: Plan, includedAi: string | undefined): PlanOption {
};
}
+/** Every paid plan a seat can be moved to, cheapest first. */
function planOptionsFor(
- currentPlan: PaidPlan,
includedAi: IncludedAiCentsByTier,
aiUsageBilling: boolean
): PlanOption[] {
const allowance = (tier: PlanTier) =>
aiUsageBilling ? formatIncludedAi(includedAi[tier]) : undefined;
- const purchasable = PLANS.flatMap((plan) =>
+ return PLANS.flatMap((plan) =>
plan.tier === 'free' ? [] : [planOption(plan, allowance(plan.tier))]
);
- return currentPlan === 'max'
- ? [...purchasable, planOption(PLAN_BY_TIER.max, allowance('max'))]
- : purchasable;
}
/**
@@ -217,8 +213,7 @@ function PlanSelect(props: {
}) {
const includedAi = useIncludedAiCentsByTier();
const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);
- const options = () =>
- planOptionsFor(props.value, includedAi(), aiUsageBilling().enabled);
+ const options = () => planOptionsFor(includedAi(), aiUsageBilling().enabled);
const selectedOption = () =>
options().find((option) => option.value === props.value) ?? options()[0];
diff --git a/apps/web/src/lib/core/constant/AiUsageLimitState.tsx b/apps/web/src/lib/core/constant/AiUsageLimitState.tsx
index 086297a2a4..472a51a6e9 100644
--- a/apps/web/src/lib/core/constant/AiUsageLimitState.tsx
+++ b/apps/web/src/lib/core/constant/AiUsageLimitState.tsx
@@ -13,6 +13,7 @@ const [usageLimitCode, setUsageLimitCode] = createSignal<AiDenyCode | null>(
const KNOWN_CODES: readonly AiDenyCode[] = [
'ai_allowance_exhausted',
+ 'ai_free_allowance_exhausted',
'ai_overage_limit_reached',
'ai_overage_payment_failed',
];
diff --git a/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts
index dc10521798..219e0bc2b4 100644
--- a/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts
+++ b/apps/web/src/lib/service-clients/service-auth/ai-billing-types.ts
@@ -12,12 +12,14 @@ export type AiPlanTier = 'free' | 'premium' | 'max';
export type AiDenyReason =
| 'allowance_exhausted'
+ | 'free_allowance_exhausted'
| 'overage_limit_reached'
| 'overage_payment_failed';
/** Machine-readable codes carried in 402 bodies from the AI endpoints. */
export type AiDenyCode =
| 'ai_allowance_exhausted'
+ | 'ai_free_allowance_exhausted'
| 'ai_overage_limit_reached'
| 'ai_overage_payment_failed';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/denyReason.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/denyReason.ts
index 6e98d2a292..4858484e7c 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/denyReason.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/denyReason.ts
@@ -13,6 +13,7 @@ export type DenyReason = (typeof DenyReason)[keyof typeof DenyReason];
// eslint-disable-next-line @typescript-eslint/no-redeclare
export const DenyReason = {
allowance_exhausted: 'allowance_exhausted',
+ free_allowance_exhausted: 'free_allowance_exhausted',
overage_limit_reached: 'overage_limit_reached',
overage_payment_failed: 'overage_payment_failed',
} as const;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts
index 7bd36e9734..4db5a90952 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/planCatalogEntry.ts
@@ -10,7 +10,8 @@ import type { PlanTier } from './planTier';
* One plan in the catalog.
*/
export interface PlanCatalogEntry {
- /** Included AI per seat per period, in cents at provider cost. */
+ /** Included AI per seat per period, in cents at provider cost. For the
+free plan this is its monthly hard cap. */
included_ai_cents_per_seat: number;
/** Monthly subscription price per seat, cents. */
monthly_price_cents: number;
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index a238cf27a8..ef26cc383d 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -5237,6 +5237,7 @@
"description": "Why a request was refused.",
"enum": [
"allowance_exhausted",
+ "free_allowance_exhausted",
"overage_limit_reached",
"overage_payment_failed"
]
@@ -6335,7 +6336,7 @@
"included_ai_cents_per_seat": {
"type": "integer",
"format": "int64",
- "description": "Included AI per seat per period, in cents at provider cost."
+ "description": "Included AI per seat per period, in cents at provider cost. For the\nfree plan this is its monthly hard cap."
},
"monthly_price_cents": {
"type": "integer",
diff --git a/apps/web/src/lib/service-clients/service-cognition/client.ts b/apps/web/src/lib/service-clients/service-cognition/client.ts
index 5799d96c9f..0e9f5ea5dd 100644
--- a/apps/web/src/lib/service-clients/service-cognition/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/client.ts
@@ -68,8 +68,9 @@ type Success = { success: boolean };
/**
* Error code for a chat send refused by the AI billing gate (HTTP 402). The
* error's `message` carries the backend's reason code
- * (`ai_allowance_exhausted`, `ai_overage_limit_reached`,
- * `ai_overage_payment_failed`) so the UI can explain and offer the fix.
+ * (`ai_allowance_exhausted`, `ai_free_allowance_exhausted`,
+ * `ai_overage_limit_reached`, `ai_overage_payment_failed`) so the UI can
+ * explain and offer the fix.
*/
export const AI_USAGE_LIMIT_ERROR = 'AI_USAGE_LIMIT' as const;
diff --git a/crates/ai_billing/src/config.rs b/crates/ai_billing/src/config.rs
index 2c8a9204b2..370578ca98 100644
--- a/crates/ai_billing/src/config.rs
+++ b/crates/ai_billing/src/config.rs
@@ -1,12 +1,14 @@
//! Startup configuration for AI usage settlement and pricing.
//!
-//! Pricing is two mandatory Doppler values, read once at startup by every
+//! Pricing is four mandatory Doppler values, read once at startup by every
//! host that composes this crate:
//!
//! | Key | Meaning |
//! | --- | --- |
-//! | `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` | In-plan AI per paid seat per period, cents at provider cost |
-//! | `AI_USAGE_OVERAGE_MARKUP_PERCENT` | Markup on usage past the allowance, a whole percent (0-99) |
+//! | `AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS` | The free plan's hard monthly AI cap, cents at provider cost |
+//! | `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` | In-plan AI per Premium seat per period, cents at provider cost |
+//! | `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS` | In-plan AI per Max seat per period, cents at provider cost |
+//! | `AI_USAGE_OVERAGE_MARKUP_PERCENT` | Markup on paid usage past the allowance, a whole percent (0-99) |
//!
//! Hosts on MacroConfig declare them as required fields of their `Config`
//! using [`IncludedAllowanceCents`] and [`OverageMarkupPercent`] directly, so a
@@ -14,18 +16,35 @@
//! Doppler CI validator) rather than a request. Hosts reading plain env vars
//! parse the raw strings with [`parse_ai_pricing`].
-use crate::domain::{AiPricing, AiUsageBilling, IncludedAllowanceCents, OverageMarkupPercent};
+use crate::domain::{
+ AiPricing, AiUsageBilling, IncludedAllowanceCents, OverageMarkupPercent, PlanAllowances,
+};
use rootcause::prelude::ResultExt as _;
use serde::de::Error as _;
#[cfg(test)]
mod test;
-/// Doppler key for the in-plan allowance.
+/// Doppler key for the free plan's monthly cap.
+pub const AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS: &str = "AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS";
+/// Doppler key for the Premium (default paid plan) allowance.
pub const AI_USAGE_INCLUDED_ALLOWANCE_CENTS: &str = "AI_USAGE_INCLUDED_ALLOWANCE_CENTS";
+/// Doppler key for the Max allowance.
+pub const AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS: &str = "AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS";
/// Doppler key for the overage markup.
pub const AI_USAGE_OVERAGE_MARKUP_PERCENT: &str = "AI_USAGE_OVERAGE_MARKUP_PERCENT";
+/// The raw allowance values a host read itself, one per plan.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct RawPlanAllowances<'a> {
+ /// `AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS`.
+ pub free: &'a str,
+ /// `AI_USAGE_INCLUDED_ALLOWANCE_CENTS`.
+ pub premium: &'a str,
+ /// `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`.
+ pub max: &'a str,
+}
+
// Keep configuration deserialization outside the domain policy. MacroConfig
// parses the raw Doppler/environment value as a strict boolean.
impl<'de> serde::Deserialize<'de> for AiUsageBilling {
@@ -41,13 +60,12 @@ impl<'de> serde::Deserialize<'de> for AiUsageBilling {
// The pricing newtypes deserialize from the raw Doppler number. MacroConfig
// parses the string value as an integer; anything malformed or out of range
-// fails config loading, and so startup.
+// fails config loading, and so startup. The same allowance type backs every
+// plan's key, so the message names the kind of value rather than one key.
impl<'de> serde::Deserialize<'de> for IncludedAllowanceCents {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let cents = i64::deserialize(deserializer)?;
- Self::new(cents).map_err(|error| {
- D::Error::custom(format!("{AI_USAGE_INCLUDED_ALLOWANCE_CENTS}: {error}"))
- })
+ Self::new(cents).map_err(|error| D::Error::custom(format!("AI usage allowance: {error}")))
}
}
@@ -60,23 +78,31 @@ impl<'de> serde::Deserialize<'de> for OverageMarkupPercent {
}
}
-/// Build the pricing from the raw `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` and
+fn parse_allowance(
+ key: &'static str,
+ raw: &str,
+) -> Result<IncludedAllowanceCents, rootcause::Report> {
+ let cents = raw
+ .trim()
+ .parse::<i64>()
+ .context(format!("{key} must be a whole number of cents"))?;
+ Ok(IncludedAllowanceCents::new(cents).context(key)?)
+}
+
+/// Build the pricing from the raw allowance and
/// `AI_USAGE_OVERAGE_MARKUP_PERCENT` values a host read itself. Hosts on
/// MacroConfig declare the typed fields instead and need no parsing.
///
-/// Both values are mandatory; the host must propagate an error to fail startup.
+/// Every value is mandatory; the host must propagate an error to fail startup.
pub fn parse_ai_pricing(
- included_allowance_cents: &str,
+ allowances: RawPlanAllowances<'_>,
overage_markup_percent: &str,
) -> Result<AiPricing, rootcause::Report> {
- let cents = included_allowance_cents
- .trim()
- .parse::<i64>()
- .context(format!(
- "{AI_USAGE_INCLUDED_ALLOWANCE_CENTS} must be a whole number of cents"
- ))?;
- let allowance =
- IncludedAllowanceCents::new(cents).context(AI_USAGE_INCLUDED_ALLOWANCE_CENTS)?;
+ let allowances = PlanAllowances {
+ free: parse_allowance(AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS, allowances.free)?,
+ premium: parse_allowance(AI_USAGE_INCLUDED_ALLOWANCE_CENTS, allowances.premium)?,
+ max: parse_allowance(AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS, allowances.max)?,
+ };
let percent = overage_markup_percent
.trim()
.parse::<i64>()
@@ -84,7 +110,7 @@ pub fn parse_ai_pricing(
"{AI_USAGE_OVERAGE_MARKUP_PERCENT} must be a whole percent"
))?;
let markup = OverageMarkupPercent::new(percent).context(AI_USAGE_OVERAGE_MARKUP_PERCENT)?;
- Ok(AiPricing::new(allowance, markup))
+ Ok(AiPricing::new(allowances, markup))
}
/// Load `ENABLE_AI_USAGE_BILLING` once at service startup.
diff --git a/crates/ai_billing/src/config/test.rs b/crates/ai_billing/src/config/test.rs
index 23f0e1e36c..b2440db5e4 100644
--- a/crates/ai_billing/src/config/test.rs
+++ b/crates/ai_billing/src/config/test.rs
@@ -37,10 +37,7 @@ fn pricing_values_deserialize_from_integers_and_validate() {
let negative = serde_json::from_value::<IncludedAllowanceCents>(serde_json::json!(-1))
.unwrap_err()
.to_string();
- assert!(
- negative.contains(AI_USAGE_INCLUDED_ALLOWANCE_CENTS),
- "{negative}"
- );
+ assert!(negative.contains("at least 0 cents"), "{negative}");
let too_high = serde_json::from_value::<OverageMarkupPercent>(serde_json::json!(100))
.unwrap_err()
.to_string();
@@ -63,23 +60,79 @@ fn pricing_values_deserialize_from_integers_and_validate() {
#[test]
fn raw_pricing_values_parse_and_validate() {
- let pricing = parse_ai_pricing(" 2000 ", "5").unwrap();
- assert_eq!(pricing.included_allowance_cents(), 2_000);
+ use crate::domain::PlanTier;
+
+ let raw = |free, premium, max| RawPlanAllowances { free, premium, max };
+ let pricing = parse_ai_pricing(raw("500", " 2000 ", "10000"), "5").unwrap();
+ assert_eq!(pricing.included_allowance_cents_for(PlanTier::Free), 500);
+ assert_eq!(
+ pricing.included_allowance_cents_for(PlanTier::Premium),
+ 2_000
+ );
+ assert_eq!(pricing.included_allowance_cents_for(PlanTier::Max), 10_000);
assert_eq!(pricing.overage_markup_percent(), 5);
- for (allowance, markup, named) in [
- ("", "5", AI_USAGE_INCLUDED_ALLOWANCE_CENTS),
- ("twenty dollars", "5", AI_USAGE_INCLUDED_ALLOWANCE_CENTS),
- ("-1", "5", AI_USAGE_INCLUDED_ALLOWANCE_CENTS),
- ("2000", "", AI_USAGE_OVERAGE_MARKUP_PERCENT),
- ("2000", "5%", AI_USAGE_OVERAGE_MARKUP_PERCENT),
- ("2000", "100", AI_USAGE_OVERAGE_MARKUP_PERCENT),
- ("2000", "2.5", AI_USAGE_OVERAGE_MARKUP_PERCENT),
+ for (allowances, markup, named) in [
+ (
+ raw("", "2000", "10000"),
+ "5",
+ AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS,
+ ),
+ (
+ raw("-1", "2000", "10000"),
+ "5",
+ AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS,
+ ),
+ (
+ raw("500", "", "10000"),
+ "5",
+ AI_USAGE_INCLUDED_ALLOWANCE_CENTS,
+ ),
+ (
+ raw("500", "twenty dollars", "10000"),
+ "5",
+ AI_USAGE_INCLUDED_ALLOWANCE_CENTS,
+ ),
+ (
+ raw("500", "-1", "10000"),
+ "5",
+ AI_USAGE_INCLUDED_ALLOWANCE_CENTS,
+ ),
+ (
+ raw("500", "2000", ""),
+ "5",
+ AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS,
+ ),
+ (
+ raw("500", "2000", "-1"),
+ "5",
+ AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS,
+ ),
+ (
+ raw("500", "2000", "10000"),
+ "",
+ AI_USAGE_OVERAGE_MARKUP_PERCENT,
+ ),
+ (
+ raw("500", "2000", "10000"),
+ "5%",
+ AI_USAGE_OVERAGE_MARKUP_PERCENT,
+ ),
+ (
+ raw("500", "2000", "10000"),
+ "100",
+ AI_USAGE_OVERAGE_MARKUP_PERCENT,
+ ),
+ (
+ raw("500", "2000", "10000"),
+ "2.5",
+ AI_USAGE_OVERAGE_MARKUP_PERCENT,
+ ),
] {
- let error = parse_ai_pricing(allowance, markup).unwrap_err();
+ let error = parse_ai_pricing(allowances, markup).unwrap_err();
assert!(
format!("{error:?}").contains(named),
- "{allowance:?}/{markup:?}: {error:?}"
+ "{allowances:?}/{markup:?}: {error:?}"
);
}
}
diff --git a/crates/ai_billing/src/domain.rs b/crates/ai_billing/src/domain.rs
index f50d3daddb..75f328d999 100644
--- a/crates/ai_billing/src/domain.rs
+++ b/crates/ai_billing/src/domain.rs
@@ -29,6 +29,7 @@ pub use ports::{
PaymentGateway, PendingCharge, SettlementOutcome, SettlementTrigger, UsageReader,
};
pub use pricing::{
- AiPricing, IncludedAllowanceCents, OverageMarkupPercent, PricingError, cost_cents,
+ AiPricing, IncludedAllowanceCents, OverageMarkupPercent, PlanAllowances, PricingError,
+ cost_cents,
};
pub use service::BillingServiceImpl;
diff --git a/crates/ai_billing/src/domain/ledger.rs b/crates/ai_billing/src/domain/ledger.rs
index e90027ac65..db391b20b4 100644
--- a/crates/ai_billing/src/domain/ledger.rs
+++ b/crates/ai_billing/src/domain/ledger.rs
@@ -21,6 +21,9 @@
//! cap, and the chunk is worth charging). Between settlements `uncovered` is
//! simply usage that has not been booked yet; the gate accounts for it through
//! `headroom`.
+//!
+//! Free users have no credits or overage: their `remaining` is only the
+//! unused part of the free allowance, and nothing is ever settled for them.
#[cfg(test)]
mod test;
@@ -131,10 +134,13 @@ pub fn build_snapshot(
} else {
0
};
+ let seat_remaining = (included_cents - used_cost_cents).max(0);
let remaining_cents = if entitlement.unlimited {
i64::MAX
+ } else if !entitlement.tier.is_paid() {
+ // A hard cap: no credits or overage can extend the free allowance.
+ seat_remaining
} else {
- let seat_remaining = (included_cents - used_cost_cents).max(0);
let shared_headroom = ((shared_covered - shared_chargeable_customer_cents)
+ credit_balance_cents.max(0)
+ overage_room)
@@ -171,13 +177,16 @@ pub fn build_snapshot(
/// The gate: may this user start another AI request?
///
-/// Free users are not metered here (the free tier has its own limits), and
-/// enterprise users are never metered. Everyone else needs headroom.
+/// Enterprise users are never metered. Free users are allowed until their
+/// monthly cap is used up, after which only an upgrade helps. Everyone else
+/// needs headroom from their allowance, credits, or overage.
pub fn decide(snapshot: &UsageSnapshot) -> AllowanceDecision {
- if snapshot.unlimited || snapshot.tier == PlanTier::Free || snapshot.remaining_cents > 0 {
+ if snapshot.unlimited || snapshot.remaining_cents > 0 {
return AllowanceDecision::Allow;
}
- let reason = if snapshot.overage_suspended {
+ let reason = if snapshot.tier == PlanTier::Free {
+ DenyReason::FreeAllowanceExhausted
+ } else if snapshot.overage_suspended {
DenyReason::OveragePaymentFailed
} else if snapshot.overage_enabled && snapshot.overage_limit_cents > 0 {
DenyReason::OverageLimitReached
diff --git a/crates/ai_billing/src/domain/ledger/test.rs b/crates/ai_billing/src/domain/ledger/test.rs
index 8b7ad91cdc..62c571c964 100644
--- a/crates/ai_billing/src/domain/ledger/test.rs
+++ b/crates/ai_billing/src/domain/ledger/test.rs
@@ -28,18 +28,18 @@ fn state(used: i64, included: i64, consumed: i64, charged: i64, balance: i64) ->
}
#[test]
-fn included_allowance_is_the_same_at_cost_for_every_paid_seat() {
+fn included_allowance_is_each_plans_configured_amount_at_cost() {
assert_eq!(
PlanTier::Premium.included_ai_cents_per_seat(AiPricing::testing()),
2_000
);
assert_eq!(
PlanTier::Max.included_ai_cents_per_seat(AiPricing::testing()),
- 2_000
+ 10_000
);
assert_eq!(
PlanTier::Free.included_ai_cents_per_seat(AiPricing::testing()),
- 0
+ 500
);
let mut team = Entitlement::personal(user("[email protected]"), PlanTier::Premium);
@@ -81,13 +81,13 @@ fn mixed_seat_plans_keep_one_allowance_per_seat() {
.collect::<Vec<_>>(),
);
- // Max has no allowance of its own yet: every paid seat gets the same at-cost amount.
+ // Each seat gets its own plan's at-cost allowance.
assert_eq!(
allowances
.into_iter()
.map(|seat| seat.included_cents)
.collect::<Vec<_>>(),
- vec![2_000, 2_000, 2_000]
+ vec![2_000, 10_000, 2_000]
);
assert_eq!(team.tier, PlanTier::Premium);
}
@@ -331,16 +331,44 @@ fn gate_reports_failed_payment_when_suspended() {
}
#[test]
-fn free_and_unlimited_are_never_blocked() {
+fn free_users_are_hard_capped_at_the_free_allowance() {
let s = snapshot_for(
PlanTier::Free,
BillingSettings::default(),
- 99_999,
+ 499,
PeriodLedger::default(),
0,
);
+ assert_eq!(s.included_cents, 500);
+ assert_eq!(s.remaining_cents, 1);
assert_eq!(decide(&s), AllowanceDecision::Allow);
+ // Leftover credits or an (impossible) overage setting never extend the cap.
+ let s = snapshot_for(
+ PlanTier::Free,
+ BillingSettings {
+ overage_enabled: true,
+ overage_limit_cents: 10_000,
+ ..Default::default()
+ },
+ 500,
+ PeriodLedger::default(),
+ 5_000,
+ );
+ assert_eq!(s.remaining_cents, 0);
+ assert_eq!(
+ decide(&s),
+ AllowanceDecision::Deny(DenyReason::FreeAllowanceExhausted)
+ );
+ assert_eq!(s.blocked_reason, Some(DenyReason::FreeAllowanceExhausted));
+ assert_eq!(
+ DenyReason::FreeAllowanceExhausted.code(),
+ "ai_free_allowance_exhausted"
+ );
+}
+
+#[test]
+fn unlimited_is_never_blocked() {
let u = user("[email protected]");
let mut ent = Entitlement::personal(u.clone(), PlanTier::Premium);
ent.unlimited = true;
@@ -386,7 +414,7 @@ fn team_member_is_not_the_payer() {
);
assert!(!s.can_manage_billing);
assert_eq!(s.seats, 2);
- assert_eq!(s.included_cents, 2_000);
+ assert_eq!(s.included_cents, 10_000);
}
#[test]
diff --git a/crates/ai_billing/src/domain/models.rs b/crates/ai_billing/src/domain/models.rs
index 0614000a8f..4d1f2ccd20 100644
--- a/crates/ai_billing/src/domain/models.rs
+++ b/crates/ai_billing/src/domain/models.rs
@@ -79,12 +79,12 @@ pub const MIN_STRIPE_CHARGE_CENTS: i64 = 50;
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PlanTier {
- /// No subscription. AI on the free model only; metered elsewhere.
+ /// No subscription. AI on the free model only, hard-capped at the
+ /// configured free allowance each calendar month; no credits or overage.
Free,
/// The $40/seat/month plan (recorded as the legacy `sub_opus` role).
Premium,
- /// The $200/seat/month plan. Its AI allowance equals Premium's until GTM
- /// defines a Max allowance.
+ /// The $200/seat/month plan, with its own configured AI allowance.
Max,
}
@@ -98,18 +98,15 @@ impl PlanTier {
}
}
- /// AI usage included per seat per period, in cents at provider cost: the
- /// configured allowance ([`AiPricing::included_allowance_cents`]) for every
- /// paid plan, nothing for Free.
+ /// AI usage included per seat per period, in cents at provider cost: this
+ /// tier's configured allowance ([`AiPricing::included_allowance_cents_for`]).
+ /// For Free this is the whole monthly cap.
pub const fn included_ai_cents_per_seat(self, pricing: AiPricing) -> i64 {
- if self.is_paid() {
- pricing.included_allowance_cents()
- } else {
- 0
- }
+ pricing.included_allowance_cents_for(self)
}
- /// Whether this tier pays for AI at all (credits and overage need a plan).
+ /// Whether this tier pays for AI beyond its allowance (credits and overage
+ /// need a plan). Free is hard-capped at its allowance instead.
pub const fn is_paid(self) -> bool {
!matches!(self, PlanTier::Free)
}
@@ -482,6 +479,9 @@ pub enum OverageChargeStatus {
pub enum DenyReason {
/// The plan's included AI is used up and no credits or overage remain.
AllowanceExhausted,
+ /// The free plan's monthly AI is used up. Free has no credits or overage;
+ /// only an upgrade (or the next month) lifts it.
+ FreeAllowanceExhausted,
/// Overage is on but the payer's per-period cap has been reached.
OverageLimitReached,
/// An overage charge failed; overage is paused until the payer re-enables it.
@@ -493,6 +493,7 @@ impl DenyReason {
pub fn code(self) -> &'static str {
match self {
DenyReason::AllowanceExhausted => "ai_allowance_exhausted",
+ DenyReason::FreeAllowanceExhausted => "ai_free_allowance_exhausted",
DenyReason::OverageLimitReached => "ai_overage_limit_reached",
DenyReason::OveragePaymentFailed => "ai_overage_payment_failed",
}
@@ -504,6 +505,9 @@ impl DenyReason {
DenyReason::AllowanceExhausted => {
"You've used this period's included AI. Add credits or turn on usage billing to keep going."
}
+ DenyReason::FreeAllowanceExhausted => {
+ "You've used this month's free AI. Upgrade to a paid plan to keep going."
+ }
DenyReason::OverageLimitReached => {
"You've reached your AI spending limit for this period. Raise the limit or add credits to keep going."
}
diff --git a/crates/ai_billing/src/domain/policy.rs b/crates/ai_billing/src/domain/policy.rs
index 6b387cca4c..2465df7d9a 100644
--- a/crates/ai_billing/src/domain/policy.rs
+++ b/crates/ai_billing/src/domain/policy.rs
@@ -38,9 +38,11 @@ const PUBLIC_UNITS_PER_CENT: u64 = CustomerMoney::UNITS_PER_CENT / 100;
const EXTRA_RATE_DENOMINATOR: u64 = 100;
/// Non-rolling public-provider-price allowance for each activated seat and
-/// period: the configured allowance ([`AiPricing::included_allowance_cents`])
-/// of public usage. Both accounting paths read the same value, so this policy
-/// and the ledger never disagree.
+/// period: the configured Premium allowance
+/// ([`AiPricing::included_allowance_cents`]) of public usage. Both accounting
+/// paths read the same value, so this policy and the ledger never disagree.
+/// This prospective policy is not yet tier-aware; activating it for a Max seat
+/// requires threading the seat's tier through here first.
pub fn included_public_usage(pricing: AiPricing) -> PublicUsage {
// The allowance is validated non-negative at construction.
PublicUsage::from_units(pricing.included_allowance_cents() as u64 * PUBLIC_UNITS_PER_CENT)
diff --git a/crates/ai_billing/src/domain/policy/test.rs b/crates/ai_billing/src/domain/policy/test.rs
index f64bd2d3cd..4513189186 100644
--- a/crates/ai_billing/src/domain/policy/test.rs
+++ b/crates/ai_billing/src/domain/policy/test.rs
@@ -584,14 +584,17 @@ fn legacy_free_enterprise_and_exempt_features_keep_their_paths() {
AccountingRoute::Unmetered
);
assert_eq!(PlanTier::Premium.monthly_price_cents(), 4_000);
- // Both accounting paths read the same configured allowance.
+ // Both accounting paths read the same configured Premium allowance.
let pricing = AiPricing::testing();
let allowance = pricing.included_allowance_cents();
assert_eq!(
PlanTier::Premium.included_ai_cents_per_seat(pricing),
allowance
);
- assert_eq!(PlanTier::Max.included_ai_cents_per_seat(pricing), allowance);
+ assert_eq!(
+ PlanTier::Max.included_ai_cents_per_seat(pricing),
+ pricing.included_allowance_cents_for(PlanTier::Max)
+ );
assert_eq!(
included_public_usage(pricing),
public_cents(allowance as u64)
diff --git a/crates/ai_billing/src/domain/pricing.rs b/crates/ai_billing/src/domain/pricing.rs
index 1f88636433..ff4a7694b2 100644
--- a/crates/ai_billing/src/domain/pricing.rs
+++ b/crates/ai_billing/src/domain/pricing.rs
@@ -1,23 +1,26 @@
-//! The two numbers GTM owns and the conversions between provider cost and
+//! The numbers GTM owns and the conversions between provider cost and
//! customer money that every billing path shares.
//!
-//! Usage and the in-plan allowance are measured in **cost cents**: the
+//! Usage and the in-plan allowances are measured in **cost cents**: the
//! provider's public price for what was consumed, in whole cents. Credits,
//! overage charges, caps and credit packs are **customer cents**: what the
-//! customer actually pays. The two meet only where usage runs past the
+//! customer actually pays. The two meet only where paid usage runs past the
//! allowance, which is marked up by [`AiPricing::overage_markup_percent`].
//!
-//! Neither number lives in code. Every host reads the mandatory
-//! `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` and `AI_USAGE_OVERAGE_MARKUP_PERCENT`
-//! from Doppler at startup (see [`crate::config`]) and injects one
-//! [`AiPricing`] into each billing component it composes. Change the values in
-//! Doppler and redeploy to change pricing. The exact-money public-allowance
-//! policy in [`super::policy`] derives its figures from the same value, so the
-//! ledger and that policy can never disagree.
+//! None of the numbers live in code. Every host reads the mandatory
+//! `AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS`, `AI_USAGE_INCLUDED_ALLOWANCE_CENTS`
+//! (Premium), `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS` and
+//! `AI_USAGE_OVERAGE_MARKUP_PERCENT` from Doppler at startup (see
+//! [`crate::config`]) and injects one [`AiPricing`] into each billing component
+//! it composes. Change the values in Doppler and redeploy to change pricing.
+//! The exact-money public-allowance policy in [`super::policy`] derives its
+//! figures from the same values, so the ledger and that policy can never
+//! disagree.
#[cfg(test)]
mod test;
+use super::models::PlanTier;
use thiserror::Error;
/// Why a pricing value was refused.
@@ -31,8 +34,8 @@ pub enum PricingError {
MarkupOutOfRange(i64),
}
-/// In-plan AI allowance per paid seat per billing period, in cents at
-/// provider cost. The same for every paid plan until GTM defines otherwise.
+/// In-plan AI allowance per seat per billing period for one plan, in cents at
+/// provider cost.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct IncludedAllowanceCents(i64);
@@ -76,31 +79,65 @@ impl OverageMarkupPercent {
}
}
-/// The configured pricing. Allowance and markup travel together so no
+/// The in-plan allowance of every plan, so no component can be composed with
+/// one tier's allowance and not another's.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct PlanAllowances {
+ /// The free plan's hard monthly cap. Free users cannot buy credits or
+ /// enable overage, so this is all the AI they get until they upgrade.
+ pub free: IncludedAllowanceCents,
+ /// Included AI per Premium seat per period.
+ pub premium: IncludedAllowanceCents,
+ /// Included AI per Max seat per period.
+ pub max: IncludedAllowanceCents,
+}
+
+impl PlanAllowances {
+ /// The allowance for `tier`, in cost cents.
+ pub const fn for_tier(self, tier: PlanTier) -> IncludedAllowanceCents {
+ match tier {
+ PlanTier::Free => self.free,
+ PlanTier::Premium => self.premium,
+ PlanTier::Max => self.max,
+ }
+ }
+}
+
+/// The configured pricing. Allowances and markup travel together so no
/// component can be composed with one and not the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AiPricing {
- included_allowance: IncludedAllowanceCents,
+ allowances: PlanAllowances,
overage_markup: OverageMarkupPercent,
}
const PERCENT: i64 = 100;
impl AiPricing {
- /// Combine two validated values.
- pub const fn new(
- included_allowance: IncludedAllowanceCents,
- overage_markup: OverageMarkupPercent,
- ) -> Self {
+ /// Combine the validated values.
+ pub const fn new(allowances: PlanAllowances, overage_markup: OverageMarkupPercent) -> Self {
Self {
- included_allowance,
+ allowances,
overage_markup,
}
}
- /// In-plan AI allowance per paid seat per period, in cents at provider cost.
+ /// Every plan's allowance.
+ pub const fn allowances(self) -> PlanAllowances {
+ self.allowances
+ }
+
+ /// In-plan AI allowance per seat per period for `tier`, in cents at
+ /// provider cost.
+ pub const fn included_allowance_cents_for(self, tier: PlanTier) -> i64 {
+ self.allowances.for_tier(tier).cents()
+ }
+
+ /// The default paid plan's (Premium's) allowance per seat per period, in
+ /// cents at provider cost. Prefer [`Self::included_allowance_cents_for`]
+ /// whenever the tier is known.
pub const fn included_allowance_cents(self) -> i64 {
- self.included_allowance.cents()
+ self.allowances.premium.cents()
}
/// Markup on usage beyond the allowance, as a whole percent of provider cost.
@@ -145,11 +182,34 @@ pub fn cost_cents(provider_cost_usd: f64) -> i64 {
#[cfg(test)]
impl AiPricing {
- /// The $20 allowance and 5% markup the crate's tests assume.
+ /// The $5 free cap, $20 Premium and $100 Max allowances, and 5% markup
+ /// the crate's tests assume.
pub(crate) fn testing() -> Self {
Self::new(
- IncludedAllowanceCents::new(2_000).unwrap(),
+ PlanAllowances::testing(),
OverageMarkupPercent::new(5).unwrap(),
)
}
}
+
+#[cfg(test)]
+impl PlanAllowances {
+ /// The $5 free cap, $20 Premium and $100 Max allowances the crate's tests assume.
+ pub(crate) fn testing() -> Self {
+ Self {
+ free: IncludedAllowanceCents::new(500).unwrap(),
+ premium: IncludedAllowanceCents::new(2_000).unwrap(),
+ max: IncludedAllowanceCents::new(10_000).unwrap(),
+ }
+ }
+
+ /// Every plan on the same allowance (for tests of tier-independent arithmetic).
+ pub(crate) fn uniform(cents: i64) -> Self {
+ let allowance = IncludedAllowanceCents::new(cents).unwrap();
+ Self {
+ free: allowance,
+ premium: allowance,
+ max: allowance,
+ }
+ }
+}
diff --git a/crates/ai_billing/src/domain/pricing/test.rs b/crates/ai_billing/src/domain/pricing/test.rs
index bc75ec92b2..5645930a44 100644
--- a/crates/ai_billing/src/domain/pricing/test.rs
+++ b/crates/ai_billing/src/domain/pricing/test.rs
@@ -39,11 +39,22 @@ fn markup_must_be_a_whole_percent_below_one_hundred() {
}
#[test]
-fn pricing_exposes_both_configured_values() {
+fn pricing_exposes_every_configured_value() {
let pricing = AiPricing::new(
- IncludedAllowanceCents::new(3_500).unwrap(),
+ PlanAllowances {
+ free: IncludedAllowanceCents::new(500).unwrap(),
+ premium: IncludedAllowanceCents::new(3_500).unwrap(),
+ max: IncludedAllowanceCents::new(15_000).unwrap(),
+ },
OverageMarkupPercent::new(12).unwrap(),
);
+ assert_eq!(pricing.included_allowance_cents_for(PlanTier::Free), 500);
+ assert_eq!(
+ pricing.included_allowance_cents_for(PlanTier::Premium),
+ 3_500
+ );
+ assert_eq!(pricing.included_allowance_cents_for(PlanTier::Max), 15_000);
+ // The unqualified accessor is the default paid plan's.
assert_eq!(pricing.included_allowance_cents(), 3_500);
assert_eq!(pricing.overage_markup_percent(), 12);
// A different markup prices the same cost differently.
@@ -66,7 +77,7 @@ fn markup_rounds_up_on_the_cumulative_total() {
#[test]
fn zero_markup_charges_cost_exactly() {
let pricing = AiPricing::new(
- IncludedAllowanceCents::new(0).unwrap(),
+ PlanAllowances::uniform(0),
OverageMarkupPercent::new(0).unwrap(),
);
for cost in [0, 1, 7, 1_000, 123_456] {
@@ -95,7 +106,7 @@ fn cumulative_conversion_books_exact_increments() {
fn covered_cost_is_the_exact_inverse_of_the_markup() {
for markup in [0, 5, 17, 99] {
let pricing = AiPricing::new(
- IncludedAllowanceCents::new(2_000).unwrap(),
+ PlanAllowances::uniform(2_000),
OverageMarkupPercent::new(markup).unwrap(),
);
assert_eq!(pricing.cost_cents_covered_by(0), 0);
diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rs
index a1d4923b99..67d71be848 100644
--- a/crates/ai_billing/src/domain/service.rs
+++ b/crates/ai_billing/src/domain/service.rs
@@ -9,7 +9,8 @@ use super::models::{
AiUsageBilling, AllowanceDecision, AllowanceStore, BillingError, BillingPeriod,
BillingSettings, CREDIT_PACKS_CENTS, Entitlement, OVERAGE_CHARGE_THRESHOLD_CENTS,
OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS, OverageChargeStatus, PayerScope,
- PeriodAllowance, Result, SeatAllowance, SeatUsage, SubscriptionScope, UsageSnapshot,
+ PeriodAllowance, PeriodLedger, Result, SeatAllowance, SeatUsage, SubscriptionScope,
+ UsageSnapshot,
};
use super::period::{PeriodSync, SubscriptionPeriod};
use super::ports::{
@@ -223,6 +224,11 @@ where
anchor: Option<(DateTime<Utc>, DateTime<Utc>)>,
now: DateTime<Utc>,
) -> BillingPeriod {
+ if !entitlement.tier.is_paid() {
+ // The free cap is monthly. A Stripe anchor left behind by a lapsed
+ // subscription says nothing about a free user's period.
+ return BillingPeriod::calendar_month(now);
+ }
if let Some(period) = BillingPeriod::covering(anchor, now) {
return period;
}
@@ -364,9 +370,14 @@ where
.await?;
let balance = self.repo.credit_balance_cents(&entitlement.payer).await?;
(used, chargeable, ledger, balance)
- } else {
- // Free users are not metered here; skip the ledger reads.
+ } else if entitlement.unlimited {
Default::default()
+ } else {
+ // Free users are hard-capped at their own allowance: only their
+ // usage matters, and there is no ledger, credit, or overage to read.
+ let users = [user.clone().into_owned()];
+ let usage = self.usage.usage_cost_cents_by_user(&users, *period).await?;
+ (usage_for(user, &usage), 0, PeriodLedger::default(), 0)
};
Ok(build_snapshot(
user,
@@ -620,7 +631,7 @@ where
return Ok(AllowanceDecision::Allow);
}
let position = self.position(user, Utc::now()).await?;
- if !position.entitlement.is_metered() {
+ if position.entitlement.unlimited {
return Ok(AllowanceDecision::Allow);
}
let snapshot = self.snapshot_at(user, &position).await?;
diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rs
index 2e979543a1..0264f04304 100644
--- a/crates/ai_billing/src/domain/service/test.rs
+++ b/crates/ai_billing/src/domain/service/test.rs
@@ -932,8 +932,10 @@ async fn disabled_settlement_does_not_retry_pending_or_failed_charges() {
}
#[tokio::test]
-async fn free_users_are_not_gated() {
- let (svc, ..) = premium_service(1_000_000);
+async fn free_users_are_hard_capped_at_the_free_allowance() {
+ // `FakeUsage::cents` is attributed to the first requested user, which for
+ // a free user is the user themself.
+ let (svc, repo, _, usage) = premium_service(499);
let free = user("[email protected]");
assert_eq!(
svc.check_allowance(&free).await.unwrap(),
@@ -941,7 +943,70 @@ async fn free_users_are_not_gated() {
);
let snap = svc.snapshot(&free).await.unwrap();
assert_eq!(snap.tier, PlanTier::Free);
- assert_eq!(snap.used_cents, 0);
+ assert_eq!(snap.included_cents, 500);
+ assert_eq!(snap.used_cents, 499);
+ assert_eq!(snap.remaining_cents, 1);
+ assert_eq!(snap.blocked_reason, None);
+ // The free period is the calendar month: no Stripe anchor exists.
+ let month = BillingPeriod::calendar_month(Utc::now());
+ assert_eq!(
+ BillingPeriod {
+ start: snap.period_start,
+ end: snap.period_end
+ },
+ month
+ );
+ // Even a live anchor left behind by a lapsed subscription (the fake
+ // repo's settings are shared by every payer) does not move it.
+ let start = Utc::now() - chrono::Duration::days(3);
+ repo.set_period(&free, start, start + chrono::Duration::days(30))
+ .await
+ .unwrap();
+ let snap = svc.snapshot(&free).await.unwrap();
+ assert_eq!(
+ (snap.period_start, snap.period_end),
+ (month.start, month.end)
+ );
+
+ *usage.cents.lock().unwrap() = 500;
+ assert_eq!(
+ svc.check_allowance(&free).await.unwrap(),
+ AllowanceDecision::Deny(DenyReason::FreeAllowanceExhausted)
+ );
+ let snap = svc.snapshot(&free).await.unwrap();
+ assert_eq!(snap.remaining_cents, 0);
+ assert_eq!(
+ snap.blocked_reason,
+ Some(DenyReason::FreeAllowanceExhausted)
+ );
+
+ // Nothing is ever settled for a free user, and they cannot buy their way out.
+ svc.settle(&free).await.unwrap();
+ assert_eq!(repo.state.lock().unwrap().balance, 0);
+ assert!(matches!(
+ svc.update_overage(&free, true, 5_000).await,
+ Err(BillingError::FreePlan)
+ ));
+ assert!(matches!(
+ svc.create_credit_checkout(&free, 1_000, String::new(), String::new())
+ .await,
+ Err(BillingError::FreePlan)
+ ));
+}
+
+#[tokio::test]
+async fn free_users_are_not_gated_while_enforcement_is_off() {
+ let (svc, ..) = premium_service_with(AiUsageBilling::Enabled, 1_000_000);
+ let svc = svc.with_enforcement(AiUsageEnforcement::Disabled);
+ let free = user("[email protected]");
+ assert_eq!(
+ svc.check_allowance(&free).await.unwrap(),
+ AllowanceDecision::Allow
+ );
+ let snap = svc.snapshot(&free).await.unwrap();
+ assert_eq!(snap.used_cents, 1_000_000);
+ assert_eq!(snap.remaining_cents, 0);
+ assert_eq!(snap.blocked_reason, None);
}
#[tokio::test]
@@ -1774,7 +1839,7 @@ async fn position_keeps_matching_pairs_in_their_stored_order() {
let stored = vec![
SeatAllowance {
user: member.clone(),
- included_cents: 2_000,
+ included_cents: 10_000,
},
SeatAllowance {
user: owner.clone(),
diff --git a/crates/ai_billing/src/inbound/axum_router.rs b/crates/ai_billing/src/inbound/axum_router.rs
index 6b9ec9957d..3d977ebc65 100644
--- a/crates/ai_billing/src/inbound/axum_router.rs
+++ b/crates/ai_billing/src/inbound/axum_router.rs
@@ -39,7 +39,8 @@ pub struct PlanCatalogEntry {
pub tier: PlanTier,
/// Monthly subscription price per seat, cents.
pub monthly_price_cents: i64,
- /// Included AI per seat per period, in cents at provider cost.
+ /// Included AI per seat per period, in cents at provider cost. For the
+ /// free plan this is its monthly hard cap.
pub included_ai_cents_per_seat: i64,
/// Whether a new purchase or plan move may pick this plan today.
pub purchasable: bool,
diff --git a/crates/ai_billing/src/inbound/axum_router/test.rs b/crates/ai_billing/src/inbound/axum_router/test.rs
index 047ad1d72a..1952317de6 100644
--- a/crates/ai_billing/src/inbound/axum_router/test.rs
+++ b/crates/ai_billing/src/inbound/axum_router/test.rs
@@ -61,15 +61,31 @@ async fn plan_catalog_lists_every_tier_and_marks_the_purchasable_ones() {
.map(|plan| (plan.tier, plan.purchasable, plan.included_ai_cents_per_seat))
.collect::<Vec<_>>();
- // The frontend reads allowances from here, so every tier it can display is listed.
+ // The frontend reads allowances from here, so every tier it can display is
+ // listed with its own configured allowance; Free's is its monthly hard cap.
assert_eq!(
summary,
vec![
- (PlanTier::Free, false, 0),
- (PlanTier::Premium, true, pricing.included_allowance_cents()),
- (PlanTier::Max, false, pricing.included_allowance_cents()),
+ (
+ PlanTier::Free,
+ false,
+ pricing.included_allowance_cents_for(PlanTier::Free)
+ ),
+ (
+ PlanTier::Premium,
+ true,
+ pricing.included_allowance_cents_for(PlanTier::Premium)
+ ),
+ (
+ PlanTier::Max,
+ true,
+ pricing.included_allowance_cents_for(PlanTier::Max)
+ ),
]
);
+ assert_eq!(summary[0].2, 500);
+ assert_eq!(summary[1].2, 2_000);
+ assert_eq!(summary[2].2, 10_000);
}
#[test]
diff --git a/crates/ai_billing/src/lib.rs b/crates/ai_billing/src/lib.rs
index 59535f86d0..9b586bf60b 100644
--- a/crates/ai_billing/src/lib.rs
+++ b/crates/ai_billing/src/lib.rs
@@ -4,21 +4,25 @@
//!
//! # The pricing model
//!
-//! Every paid seat includes a monthly AI allowance measured **at cost**: the
-//! provider's public price for what was consumed. Usage past the allowance is
-//! covered, in order, by prepaid credits (bought in one-off Stripe Checkout
-//! payments) and then by opt-in overage, billed to the payer's Stripe customer
-//! in chunks. Both are priced at cost plus a small markup:
+//! Every seat includes a monthly AI allowance measured **at cost**: the
+//! provider's public price for what was consumed. Each plan has its own
+//! allowance. Paid usage past the allowance is covered, in order, by prepaid
+//! credits (bought in one-off Stripe Checkout payments) and then by opt-in
+//! overage, billed to the payer's Stripe customer in chunks. Both are priced
+//! at cost plus a small markup. The free plan is a hard cap: once its
+//! allowance is used, only an upgrade (or the next calendar month) helps.
//!
//! ```text
-//! allowance = AI_USAGE_INCLUDED_ALLOWANCE_CENTS (provider cost per seat per period)
+//! free cap = AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS (provider cost per user per month)
+//! premium = AI_USAGE_INCLUDED_ALLOWANCE_CENTS (provider cost per seat per period)
+//! max = AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS (provider cost per seat per period)
//! extra = cost x (100 + AI_USAGE_OVERAGE_MARKUP_PERCENT) / 100
//! ```
//!
-//! Neither number lives in code. Both are mandatory Doppler values that every
-//! host loads at startup ([`config`]) into one [`AiPricing`] and injects into
-//! each billing component it composes ([`domain::pricing`]). Change them in
-//! Doppler and redeploy. Usage and allowance are **cost cents**; credits,
+//! None of the numbers live in code. All are mandatory Doppler values that
+//! every host loads at startup ([`config`]) into one [`AiPricing`] and injects
+//! into each billing component it composes ([`domain::pricing`]). Change them
+//! in Doppler and redeploy. Usage and allowances are **cost cents**; credits,
//! charges, caps and packs are **customer cents**. The conversions on
//! [`AiPricing`] are the only place the two units meet.
//!
@@ -51,6 +55,6 @@ pub use domain::{
AdmissionFuture, AiAdmissionError, AiAdmissionService, AiPricing, AiUsageBilling,
AllowanceDecision, BillingAdmissionService, BillingError, BillingPeriod, BillingService,
BillingSettings, CREDIT_PACKS_CENTS, DenyReason, DisabledAiAdmissionService, Entitlement,
- IncludedAllowanceCents, OverageMarkupPercent, PayerScope, PlanTier, PricingError,
- UsageSnapshot, cost_cents,
+ IncludedAllowanceCents, OverageMarkupPercent, PayerScope, PlanAllowances, PlanTier,
+ PricingError, UsageSnapshot, cost_cents,
};
diff --git a/crates/ai_billing/src/outbound/pg_billing_repo.rs b/crates/ai_billing/src/outbound/pg_billing_repo.rs
index 94830e8341..9939be99ff 100644
--- a/crates/ai_billing/src/outbound/pg_billing_repo.rs
+++ b/crates/ai_billing/src/outbound/pg_billing_repo.rs
@@ -732,7 +732,8 @@ async fn read_period_ledger(
/// Pair a frozen roster with its cost-cent allowances. A missing or mismatched
/// cost array means an older binary wrote the row; every seat then gets the
-/// configured allowance, which is what that binary's seats are entitled to now.
+/// configured Premium allowance, which is what that binary's seats were all
+/// entitled to (it predates per-plan allowances).
fn parse_seat_allowances(
billed_users: Vec<String>,
included_cost_cents_by_user: Option<Vec<i64>>,
diff --git a/crates/memory/src/config.rs b/crates/memory/src/config.rs
index 9f355ce914..9912fef5d2 100644
--- a/crates/memory/src/config.rs
+++ b/crates/memory/src/config.rs
@@ -14,9 +14,13 @@ env_var!(
pub struct EnvVars {
pub DatabaseUrl,
pub UserId,
- /// In-plan AI allowance per paid seat per period, cents at provider cost.
+ /// The free plan's hard monthly AI cap, cents at provider cost.
+ pub AiUsageFreeIncludedAllowanceCents,
+ /// In-plan AI allowance per Premium seat per period, cents at provider cost.
pub AiUsageIncludedAllowanceCents,
- /// Markup on AI usage past the allowance, a whole percent of provider cost.
+ /// In-plan AI allowance per Max seat per period, cents at provider cost.
+ pub AiUsageMaxIncludedAllowanceCents,
+ /// Markup on paid AI usage past the allowance, a whole percent of provider cost.
pub AiUsageOverageMarkupPercent,
}
);
@@ -31,11 +35,17 @@ impl Config {
let EnvVars {
database_url,
user_id,
+ ai_usage_free_included_allowance_cents,
ai_usage_included_allowance_cents,
+ ai_usage_max_included_allowance_cents,
ai_usage_overage_markup_percent,
} = env_vars;
let ai_pricing = ai_billing::config::parse_ai_pricing(
- &ai_usage_included_allowance_cents,
+ ai_billing::config::RawPlanAllowances {
+ free: &ai_usage_free_included_allowance_cents,
+ premium: &ai_usage_included_allowance_cents,
+ max: &ai_usage_max_included_allowance_cents,
+ },
&ai_usage_overage_markup_percent,
)
.map_err(|error| anyhow::anyhow!("{error}"))?;
diff --git a/crates/teams/src/domain/model.rs b/crates/teams/src/domain/model.rs
index 54f7c0148a..bf8bba77b8 100644
--- a/crates/teams/src/domain/model.rs
+++ b/crates/teams/src/domain/model.rs
@@ -148,7 +148,7 @@ impl std::fmt::Display for TeamRole {
pub enum SeatPlan {
/// The $40/seat/month plan.
Premium,
- /// The $200/seat/month plan with a 5x AI allowance.
+ /// The $200/seat/month plan with a larger AI allowance.
Max,
}
@@ -157,10 +157,7 @@ impl SeatPlan {
pub const ALL: [SeatPlan; 2] = [SeatPlan::Premium, SeatPlan::Max];
/// Plans available for a new purchase or plan move.
- pub const PURCHASABLE: [SeatPlan; 1] = [
- SeatPlan::Premium,
- // SeatPlan::Max,
- ];
+ pub const PURCHASABLE: [SeatPlan; 2] = Self::ALL;
/// The role tier recorded on a user holding this seat.
pub fn product_tier(self) -> ProductTier {
diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rs
index 6ca754ab78..f50ac4f34a 100644
--- a/crates/teams/src/domain/team_service/test.rs
+++ b/crates/teams/src/domain/team_service/test.rs
@@ -2221,7 +2221,7 @@ async fn set_team_member_plan_is_a_no_op_when_already_on_plan() {
}
#[tokio::test]
-async fn set_team_member_plan_rejects_premium_to_max_without_side_effects() {
+async fn set_team_member_plan_upgrades_premium_seat_to_max_and_swaps_tier_role() {
let team_id = uuid::Uuid::from_u128(5105);
let admin_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let member_id = "macro|[email protected]";
@@ -2237,23 +2237,38 @@ async fn set_team_member_plan_rejects_premium_to_max_without_side_effects() {
let remove_calls = roles_service.remove_calls.clone();
let service = build_member_plan_service(team_repo, customer_repo, roles_service);
- let error = service
+ let member = service
.set_team_member_plan(
test_team_receipt::<AdminTeamRole>(team_id, &admin_id),
&MacroUserIdStr::parse_from_str(member_id).unwrap(),
SeatPlan::Max,
)
.await
- .unwrap_err();
+ .unwrap();
- assert!(matches!(
- error,
- SetTeamMemberPlanError::CustomerError(CustomerError::PlanUnavailable(SeatPlan::Max))
- ));
- assert!(move_calls.lock().unwrap().is_empty());
- assert!(plan_calls.lock().unwrap().is_empty());
- assert!(upsert_calls.lock().unwrap().is_empty());
- assert!(remove_calls.lock().unwrap().is_empty());
+ assert_eq!(member.plan, SeatPlan::Max);
+ assert_eq!(
+ *move_calls.lock().unwrap(),
+ vec![("sub_team".to_string(), SeatPlan::Premium, SeatPlan::Max)]
+ );
+ assert_eq!(
+ *plan_calls.lock().unwrap(),
+ vec![(team_id, member_id.to_string(), SeatPlan::Max)]
+ );
+ assert_eq!(
+ *upsert_calls.lock().unwrap(),
+ vec![(
+ member_id.to_string(),
+ vec![RoleId::TeamSubscriber, RoleId::SubMax]
+ )]
+ );
+ assert_eq!(
+ *remove_calls.lock().unwrap(),
+ vec![(
+ member_id.to_string(),
+ vec![RoleId::SubHaiku, RoleId::SubSonnet, RoleId::SubOpus]
+ )]
+ );
}
#[tokio::test]
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index 07cb6ab060..4caee3b1c2 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -560,17 +560,25 @@ must not make a fallback model call. Managed sessions use their persisted owner
for quota, not a collaborating sender. Externally funded runtimes skip session
quota, but Macro-funded tools and helpers still check independently.
-Paid plans include a monthly AI allowance per seat, measured at provider cost;
-usage beyond it is billed at a markup. Both numbers come from Doppler
-(`AI_USAGE_INCLUDED_ALLOWANCE_CENTS` and `AI_USAGE_OVERAGE_MARKUP_PERCENT`; $20 and
-5% in dev), never from code. When the allowance is used up and no credits or usage billing cover the
-request, sending a message answers HTTP 402 and the app opens the
-**AI usage limit** dialog (title `You've used this month's included AI`, or the
-spending-limit / failed-charge variants). It shows the same meter and controls
-as Settings → Billing: credit-pack buttons, the `Usage billing` toggle, an
-`Open billing settings` button, and no Max purchase or upgrade control. Team
-members who are not the payer see a note to ask the team owner to add credits
-or turn on usage billing.
+Every plan includes a monthly AI allowance per seat, measured at provider cost;
+paid usage beyond it is billed at a markup. All of the numbers come from Doppler
+(`AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS`, `AI_USAGE_INCLUDED_ALLOWANCE_CENTS`
+for Premium, `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`, and
+`AI_USAGE_OVERAGE_MARKUP_PERCENT`), never from code. When a paid allowance is
+used up and no credits or usage billing cover the request, sending a message
+answers HTTP 402 and the app opens the **AI usage limit** dialog (title
+`You've used this month's included AI`, or the spending-limit / failed-charge
+variants). It shows the same meter and controls as Settings → Billing:
+credit-pack buttons, the `Usage billing` toggle, an `Open billing settings`
+button, and `Upgrade to Max` for Premium payers (on a team this moves only the
+payer's own seat). Team members who are not the payer see a note to ask the
+team owner to add credits or turn on usage billing.
+
+The free plan is a hard cap: when its monthly allowance is used up, requests
+answer 402 with code `ai_free_allowance_exhausted` and the dialog (title
+`You've used this month's free AI`) shows the meter against the cap with an
+`Upgrade` button that opens Billing; there are no credit or usage-billing
+controls. The cap resets with the UTC calendar month.
Each team seat has its own allowance; unused allowance never moves between
members. The team owner's prepaid credits and usage-billing cap are shared.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 48854777a6..5cb1a66f51 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1848,9 +1848,9 @@ do not see it.
## Setup plan step — `/app/onboarding`
-The plan step shows two cards: Free and Premium. Premium starts Stripe Checkout.
-The step has no Max card or Max checkout path. A returning account that already
-has Max still sees Max named as its active plan.
+Onboarding has no plan picker; it ends with the 30-day Premium trial offer and a
+Guest continuation (see [login](login.md#desktop-onboarding)). Plans are chosen
+afterwards in **Settings → Billing**, where Guest users can buy Premium or Max.
## Settings — `/app/settings/<section>`
@@ -2034,17 +2034,19 @@ Existing settings URLs remain valid; `connections` still opens Integrations,
`Billing` (current plan card with
`Manage`; only in dev (`dev.macro.com/app` or a local frontend using the dev
-backend), paid plans show an **AI usage** card with the period meter, credit
-balance, credit-pack buttons `$10`/`$25`/`$50`/`$100` that redirect to Stripe
-Checkout, and a `Usage billing` toggle with per-period limit pills; these
-controls and usage-billing promotional copy are hidden outside dev; an `Upgrade`
-card for Free users to buy Premium, no Max purchase or upgrade control, and a
-`Switch to Premium` link on Max; on a team the downgrade moves only the viewer's
+backend), every plan shows an **AI usage** card with the period meter; paid
+plans add the credit balance, credit-pack buttons `$10`/`$25`/`$50`/`$100` that
+redirect to Stripe Checkout, and a `Usage billing` toggle with per-period limit
+pills, while Free shows only the meter against its monthly cap; these controls
+and usage-billing promotional copy are hidden outside dev; an `Upgrade` section
+for Free users with a Premium card (`Upgrade now`) and a Max card (`Get Max`),
+an `Upgrade to Max` card on Premium (titled `Need more AI?` in dev), and a
+`Switch to Premium` link on Max; on a team a plan change moves only the viewer's
own seat)
`Team` (members list; on a paid team each row shows the seat's plan,
-and admins/owners can move an existing Max seat to Premium with the `Seat plan`
-menu; Premium seats have no Max option; moves are prorated at once). CRM (enable/disable; once enabled, a `Deal stages` section
+and admins/owners can move a seat between Premium and Max with the `Seat plan`
+menu; moves are prorated at once). CRM (enable/disable; once enabled, a `Deal stages` section
with `Customize stages`, inline rename, reorder by drag handle or arrow keys (up/down
buttons on touch), delete, `Add stage`, `Reset to defaults`, and `Closed stages`
checkboxes, editable by the role set as `edit_stages_role`)
diff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/AI_QUOTA_ENFORCEMENT.md
index 0bb6ebb0fc..c1f56e885c 100644
--- a/docs/AI_QUOTA_ENFORCEMENT.md
+++ b/docs/AI_QUOTA_ENFORCEMENT.md
@@ -34,11 +34,14 @@ Automation, DynamicCompletionsApi, ChatRename, ChannelBot, AiEditing, Import,
AgentSession, AgentRepositoryChoice. In particular, AI editing is not exempt.
The classification is exhaustive and server-selected, not request-controlled.
-Free-plan and unlimited-entitlement allowance behavior is unchanged: these users
-are not blocked by this quota policy. Model-access and resource permissions remain
-independent. Counting eligibility is not a claim that a particular user owes money;
-it does not special-case their plan. Existing paid allowance, per-seat usage,
-payer credits, overage opt-in/cap, and denial decisions remain in the legacy ledger.
+Unlimited (enterprise) entitlements are never blocked by this quota policy.
+Free-plan users are hard-capped at `AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS` of
+counted usage per UTC calendar month: past it, admission answers
+`ai_free_allowance_exhausted` and nothing is settled, since Free has no credits
+or overage. Model-access and resource permissions remain independent. Counting
+eligibility is not a claim that a particular user owes money; it does not
+special-case their plan. Existing paid allowance, per-seat usage, payer credits,
+overage opt-in/cap, and denial decisions remain in the legacy ledger.
### Persistence
@@ -69,14 +72,16 @@ independent of `ENABLE_AI_USAGE_ENFORCEMENT` and of the deployment environment:
there is no longer an `Environment::Develop` safeguard, so a true value settles
in production.
-Pricing is two mandatory Doppler values, loaded once at startup by every host that
+Pricing is four mandatory Doppler values, loaded once at startup by every host that
composes `ai_billing` (see [`config.rs`](../crates/ai_billing/src/config.rs) and
-[`pricing.rs`](../crates/ai_billing/src/domain/pricing.rs)):
-`AI_USAGE_INCLUDED_ALLOWANCE_CENTS`, the usage each paid seat includes per period
-measured at provider cost, and `AI_USAGE_OVERAGE_MARKUP_PERCENT`, the whole-percent
-markup over cost applied to usage beyond it before credits are consumed or overage
-is charged. There is no default in code: a missing, malformed, or out-of-range value
-fails startup and the Doppler CI validator. The values live in `shared_ai` (`lcl`,
+[`pricing.rs`](../crates/ai_billing/src/domain/pricing.rs)): one allowance per plan,
+measured at provider cost — `AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS` (the free plan's
+hard cap, per user per UTC calendar month), `AI_USAGE_INCLUDED_ALLOWANCE_CENTS`
+(Premium, per seat per subscription period), and `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`
+(Max, per seat per subscription period) — and `AI_USAGE_OVERAGE_MARKUP_PERCENT`,
+the whole-percent markup over cost applied to paid usage beyond the allowance before
+credits are consumed or overage is charged. There is no default in code: a missing,
+malformed, or out-of-range value fails startup and the Doppler CI validator. The values live in `shared_ai` (`lcl`,
`dev`, `prd`), which every participating service inherits except the authentication
service, whose `dev` and `prd` configs carry them directly; the no-Doppler local
stack stubs them in `BootStubEnv`. The markup is applied to the period's cumulative
@@ -121,6 +126,7 @@ errors are not permission grants and must not disclose another user's quota.
| Result | HTTP status | Stable `code` | Retry semantics |
| --- | --- | --- | --- |
| Allowance exhausted | 402 | `ai_allowance_exhausted` | Policy/allowance must change; no automatic tight retry |
+| Free monthly cap reached | 402 | `ai_free_allowance_exhausted` | Only an upgrade (or the next calendar month) lifts it |
| Spending cap reached | 402 | `ai_overage_limit_reached` | Policy/allowance must change |
| Overage payment failed | 402 | `ai_overage_payment_failed` | Billing problem must be resolved |
| Could not validate billing | 503 | `ai_billing_unavailable` | Retry later with bounded backoff; never execute on uncertainty |
@@ -278,9 +284,10 @@ procedure. Operators must approve and record each release gate.
standalone agent trigger, and scheduled action. Include any separately launched
memory/common-tool host. Use the existing Doppler-backed application config,
not a quoted JSON string, AWS secret indirection, or a second Pulumi flag.
- The pricing values `AI_USAGE_INCLUDED_ALLOWANCE_CENTS` and
- `AI_USAGE_OVERAGE_MARKUP_PERCENT` are mandatory for these same hosts whatever
- the flags say; see [Settlement](#settlement-enable_ai_usage_billing).
+ The pricing values `AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS`,
+ `AI_USAGE_INCLUDED_ALLOWANCE_CENTS`, `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`,
+ and `AI_USAGE_OVERAGE_MARKUP_PERCENT` are mandatory for these same hosts
+ whatever the flags say; see [Settlement](#settlement-enable_ai_usage_billing).
Verify the effective startup value for every replica/worker. Registration and
hosted access require operator approval; code defaults are not proof of it.
4. **Validate locally, then in an approved staging environment.** Use the checklist
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 9dd5b8ff35..9511e21c84 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -376,7 +376,7 @@ export type CursorModelsResponse = {
/**
* Why a request was refused.
*/
-export type DenyReason = 'allowance_exhausted' | 'overage_limit_reached' | 'overage_payment_failed';
+export type DenyReason = 'allowance_exhausted' | 'free_allowance_exhausted' | 'overage_limit_reached' | 'overage_payment_failed';
/**
* Empty response is required due to custom fetch forcing `response.json()`
@@ -1196,7 +1196,8 @@ export type Permission = {
*/
export type PlanCatalogEntry = {
/**
- * Included AI per seat per period, in cents at provider cost.
+ * Included AI per seat per period, in cents at provider cost. For the
+ * free plan this is its monthly hard cap.
*/
included_ai_cents_per_seat: number;
/**
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index a238cf27a8..ef26cc383d 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -5237,6 +5237,7 @@
"description": "Why a request was refused.",
"enum": [
"allowance_exhausted",
+ "free_allowance_exhausted",
"overage_limit_reached",
"overage_payment_failed"
]
@@ -6335,7 +6336,7 @@
"included_ai_cents_per_seat": {
"type": "integer",
"format": "int64",
- "description": "Included AI per seat per period, in cents at provider cost."
+ "description": "Included AI per seat per period, in cents at provider cost. For the\nfree plan this is its monthly hard cap."
},
"monthly_price_cents": {
"type": "integer",
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index f7b7c9a867..2f9b4cf2cf 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -70,11 +70,17 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
- /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// The free plan's hard monthly AI cap, in cents at provider cost.
+ /// Mandatory; set in Doppler.
+ pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// In-plan AI allowance per Premium seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
- /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// In-plan AI allowance per Max seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
+ pub ai_usage_max_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on paid AI usage past the allowance, as a whole percent of
+ /// provider cost. Mandatory; set in Doppler.
pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// OAuth encryption key; deployments without a key do not advertise sign-in.
pub claude_oauth_kms_key_id: ClaudeOauthKmsKeyId,
@@ -213,11 +219,15 @@ pub struct Config {
}
impl Config {
- /// The AI pricing every billing component is composed with. Both values
- /// are validated when the configuration loads.
+ /// The AI pricing every billing component is composed with. Every value
+ /// is validated when the configuration loads.
pub fn ai_pricing(&self) -> ai_billing::AiPricing {
ai_billing::AiPricing::new(
- self.ai_usage_included_allowance_cents,
+ ai_billing::PlanAllowances {
+ free: self.ai_usage_free_included_allowance_cents,
+ premium: self.ai_usage_included_allowance_cents,
+ max: self.ai_usage_max_included_allowance_cents,
+ },
self.ai_usage_overage_markup_percent,
)
}
diff --git a/services/agent_trigger_service/src/config.rs b/services/agent_trigger_service/src/config.rs
index 1006f96c40..9624f07afb 100644
--- a/services/agent_trigger_service/src/config.rs
+++ b/services/agent_trigger_service/src/config.rs
@@ -16,11 +16,17 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
- /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// The free plan's hard monthly AI cap, in cents at provider cost.
+ /// Mandatory; set in Doppler.
+ pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// In-plan AI allowance per Premium seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
- /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// In-plan AI allowance per Max seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
+ pub ai_usage_max_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on paid AI usage past the allowance, as a whole percent of
+ /// provider cost. Mandatory; set in Doppler.
pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// MacroDB connection URL.
pub database_url: DatabaseUrl,
@@ -33,11 +39,15 @@ pub struct Config {
}
impl Config {
- /// The AI pricing every billing component is composed with. Both values
- /// are validated when the configuration loads.
+ /// The AI pricing every billing component is composed with. Every value
+ /// is validated when the configuration loads.
pub fn ai_pricing(&self) -> ai_billing::AiPricing {
ai_billing::AiPricing::new(
- self.ai_usage_included_allowance_cents,
+ ai_billing::PlanAllowances {
+ free: self.ai_usage_free_included_allowance_cents,
+ premium: self.ai_usage_included_allowance_cents,
+ max: self.ai_usage_max_included_allowance_cents,
+ },
self.ai_usage_overage_markup_percent,
)
}
diff --git a/services/authentication_service/src/api/user/stripe/shared/test.rs b/services/authentication_service/src/api/user/stripe/shared/test.rs
index 7727efd65b..69d4e3086f 100644
--- a/services/authentication_service/src/api/user/stripe/shared/test.rs
+++ b/services/authentication_service/src/api/user/stripe/shared/test.rs
@@ -8,22 +8,33 @@ fn prices() -> StripePrices {
}
#[test]
-fn premium_remains_available_for_purchase() {
+fn every_purchasable_plan_resolves_to_its_configured_price() {
assert_eq!(
prices().price_id(PaidPlan::Premium).unwrap(),
"price_premium"
);
+ assert_eq!(prices().price_id(PaidPlan::Max).unwrap(), "price_max");
}
#[test]
-fn max_is_rejected_as_a_purchase_target() {
+fn max_is_unavailable_until_its_price_is_configured() {
+ let prices = StripePrices {
+ premium: "price_premium".to_string(),
+ max: None,
+ };
assert!(matches!(
- prices().price_id(PaidPlan::Max),
+ prices.price_id(PaidPlan::Max),
Err(StripeOperationError::PlanUnavailable)
));
+ assert_eq!(prices.price_id(PaidPlan::Premium).unwrap(), "price_premium");
}
#[test]
-fn configured_max_prices_are_still_recognized() {
+fn configured_prices_are_recognized_by_plan() {
+ assert_eq!(
+ prices().plan_for_price("price_premium"),
+ Some(PaidPlan::Premium)
+ );
assert_eq!(prices().plan_for_price("price_max"), Some(PaidPlan::Max));
+ assert_eq!(prices().plan_for_price("price_other"), None);
}
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index ca5fdd1ba0..0e399813f5 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -95,11 +95,17 @@ pub struct Config {
/// its policy decides every settlement, however it was requested.
#[macro_config_default(ai_billing::AiUsageBilling::Disabled)]
pub enable_ai_usage_billing: ai_billing::AiUsageBilling,
- /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// The free plan's hard monthly AI cap, in cents at provider cost.
+ /// Mandatory; set in Doppler.
+ pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// In-plan AI allowance per Premium seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
- /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// In-plan AI allowance per Max seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
+ pub ai_usage_max_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on paid AI usage past the allowance, as a whole percent of
+ /// provider cost. Mandatory; set in Doppler.
pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
#[allow(dead_code)]
pub base_url: BaseUrl,
@@ -208,11 +214,15 @@ pub(crate) struct MicrosoftCredentials {
}
impl Config {
- /// The AI pricing every billing component is composed with. Both values
- /// are validated when the configuration loads.
+ /// The AI pricing every billing component is composed with. Every value
+ /// is validated when the configuration loads.
pub fn ai_pricing(&self) -> ai_billing::AiPricing {
ai_billing::AiPricing::new(
- self.ai_usage_included_allowance_cents,
+ ai_billing::PlanAllowances {
+ free: self.ai_usage_free_included_allowance_cents,
+ premium: self.ai_usage_included_allowance_cents,
+ max: self.ai_usage_max_included_allowance_cents,
+ },
self.ai_usage_overage_markup_percent,
)
}
diff --git a/services/authentication_service/src/config/test.rs b/services/authentication_service/src/config/test.rs
index 7be0ddd989..485de8f052 100644
--- a/services/authentication_service/src/config/test.rs
+++ b/services/authentication_service/src/config/test.rs
@@ -30,20 +30,31 @@ fn config_values() -> serde_json::Value {
] {
values[key] = serde_json::json!("test");
}
+ values["AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS"] = serde_json::json!(500);
values["AI_USAGE_INCLUDED_ALLOWANCE_CENTS"] = serde_json::json!(2_000);
+ values["AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS"] = serde_json::json!(10_000);
values["AI_USAGE_OVERAGE_MARKUP_PERCENT"] = serde_json::json!(5);
values
}
#[test]
fn ai_pricing_is_mandatory_and_validated() {
+ use ai_billing::PlanTier;
+
let config: Config = serde_json::from_value(config_values()).unwrap();
let pricing = config.ai_pricing();
- assert_eq!(pricing.included_allowance_cents(), 2_000);
+ assert_eq!(pricing.included_allowance_cents_for(PlanTier::Free), 500);
+ assert_eq!(
+ pricing.included_allowance_cents_for(PlanTier::Premium),
+ 2_000
+ );
+ assert_eq!(pricing.included_allowance_cents_for(PlanTier::Max), 10_000);
assert_eq!(pricing.overage_markup_percent(), 5);
for key in [
+ "AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS",
"AI_USAGE_INCLUDED_ALLOWANCE_CENTS",
+ "AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS",
"AI_USAGE_OVERAGE_MARKUP_PERCENT",
] {
let mut values = config_values();
@@ -61,9 +72,18 @@ fn ai_pricing_is_mandatory_and_validated() {
let mut values = config_values();
values["AI_USAGE_OVERAGE_MARKUP_PERCENT"] = serde_json::json!(100);
assert!(serde_json::from_value::<Config>(values).is_err());
- let mut values = config_values();
- values["AI_USAGE_INCLUDED_ALLOWANCE_CENTS"] = serde_json::json!(-1);
- assert!(serde_json::from_value::<Config>(values).is_err());
+ for key in [
+ "AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS",
+ "AI_USAGE_INCLUDED_ALLOWANCE_CENTS",
+ "AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS",
+ ] {
+ let mut values = config_values();
+ values[key] = serde_json::json!(-1);
+ assert!(
+ serde_json::from_value::<Config>(values).is_err(),
+ "{key} must be non-negative"
+ );
+ }
}
#[test]
diff --git a/services/authentication_service/src/service/subscription_checkout/test.rs b/services/authentication_service/src/service/subscription_checkout/test.rs
index 704479a4a0..49c6da49ac 100644
--- a/services/authentication_service/src/service/subscription_checkout/test.rs
+++ b/services/authentication_service/src/service/subscription_checkout/test.rs
@@ -170,20 +170,45 @@ async fn trial_does_not_require_or_stack_an_invite_discount() {
}
#[tokio::test]
-async fn missing_customer_and_unavailable_plan_never_create_checkout() {
+async fn missing_customer_never_creates_checkout() {
let service = CheckoutService::new(FakeGateway {
missing_customer: true,
..Default::default()
});
- assert!(matches!(
- service.create(request(true)).await,
- Err(CheckoutError::MissingCustomer)
- ));
+ for plan in SeatPlan::PURCHASABLE {
+ for trial in [true, false] {
+ let mut input = request(trial);
+ input.plan = plan;
+ assert!(matches!(
+ service.create(input).await,
+ Err(CheckoutError::MissingCustomer)
+ ));
+ }
+ }
+ assert!(service.gateway.created.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn max_plan_can_create_a_paid_checkout() {
+ let service = CheckoutService::new(FakeGateway::default());
+ let mut input = request(false);
+ input.plan = SeatPlan::Max;
+ let checkout = service.create(input).await.unwrap();
+ assert_eq!(checkout.trial_days, None);
+ assert_eq!(
+ *service.gateway.created.lock().unwrap(),
+ vec![(CheckoutTerms::Paid, None)]
+ );
+}
+
+#[tokio::test]
+async fn max_trial_never_creates_checkout_or_falls_back_to_paid() {
+ let service = CheckoutService::new(FakeGateway::default());
let mut input = request(true);
input.plan = SeatPlan::Max;
assert!(matches!(
service.create(input).await,
- Err(CheckoutError::PlanUnavailable)
+ Err(CheckoutError::TrialUnavailable)
));
assert!(service.gateway.created.lock().unwrap().is_empty());
}
diff --git a/services/document_cognition_service/src/config.rs b/services/document_cognition_service/src/config.rs
index fd45de2354..353cb41ef3 100644
--- a/services/document_cognition_service/src/config.rs
+++ b/services/document_cognition_service/src/config.rs
@@ -78,11 +78,17 @@ pub struct Config {
/// service's own policy decides whether it does.
#[macro_config_default(ai_billing::AiUsageBilling::Disabled)]
pub enable_ai_usage_billing: ai_billing::AiUsageBilling,
- /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// The free plan's hard monthly AI cap, in cents at provider cost.
+ /// Mandatory; set in Doppler.
+ pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// In-plan AI allowance per Premium seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
- /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// In-plan AI allowance per Max seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
+ pub ai_usage_max_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on paid AI usage past the allowance, as a whole percent of
+ /// provider cost. Mandatory; set in Doppler.
pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// The connection URL for the Postgres database this application should use.
pub database_url: DatabaseUrl,
@@ -160,11 +166,15 @@ fn default_mcp_public_url(environment: Environment) -> &'static str {
}
impl Config {
- /// The AI pricing every billing component is composed with. Both values
- /// are validated when the configuration loads.
+ /// The AI pricing every billing component is composed with. Every value
+ /// is validated when the configuration loads.
pub fn ai_pricing(&self) -> ai_billing::AiPricing {
ai_billing::AiPricing::new(
- self.ai_usage_included_allowance_cents,
+ ai_billing::PlanAllowances {
+ free: self.ai_usage_free_included_allowance_cents,
+ premium: self.ai_usage_included_allowance_cents,
+ max: self.ai_usage_max_included_allowance_cents,
+ },
self.ai_usage_overage_markup_percent,
)
}
@@ -192,8 +202,12 @@ impl Config {
Config {
enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement::Disabled,
enable_ai_usage_billing: ai_billing::AiUsageBilling::Disabled,
+ ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents::new(500)
+ .unwrap(),
ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents::new(2_000)
.unwrap(),
+ ai_usage_max_included_allowance_cents: ai_billing::IncludedAllowanceCents::new(10_000)
+ .unwrap(),
ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent::new(5).unwrap(),
environment: Environment::Local,
database_url: DatabaseUrl::Comptime("DATABASE_URL"),
diff --git a/services/document_storage_service/src/config.rs b/services/document_storage_service/src/config.rs
index 46bf59f7e6..d571af0e59 100644
--- a/services/document_storage_service/src/config.rs
+++ b/services/document_storage_service/src/config.rs
@@ -90,11 +90,17 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
- /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// The free plan's hard monthly AI cap, in cents at provider cost.
+ /// Mandatory; set in Doppler.
+ pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// In-plan AI allowance per Premium seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
- /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// In-plan AI allowance per Max seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
+ pub ai_usage_max_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on paid AI usage past the allowance, as a whole percent of
+ /// provider cost. Mandatory; set in Doppler.
pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
pub database_url: DatabaseUrl,
pub database_url_readonly: DatabaseUrlReadonly,
@@ -204,11 +210,15 @@ pub struct Config {
}
impl Config {
- /// The AI pricing every billing component is composed with. Both values
- /// are validated when the configuration loads.
+ /// The AI pricing every billing component is composed with. Every value
+ /// is validated when the configuration loads.
pub fn ai_pricing(&self) -> ai_billing::AiPricing {
ai_billing::AiPricing::new(
- self.ai_usage_included_allowance_cents,
+ ai_billing::PlanAllowances {
+ free: self.ai_usage_free_included_allowance_cents,
+ premium: self.ai_usage_included_allowance_cents,
+ max: self.ai_usage_max_included_allowance_cents,
+ },
self.ai_usage_overage_markup_percent,
)
}
diff --git a/services/mcp_service/src/config.rs b/services/mcp_service/src/config.rs
index 70b3ba7714..ef2eaea3a5 100644
--- a/services/mcp_service/src/config.rs
+++ b/services/mcp_service/src/config.rs
@@ -65,11 +65,17 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
- /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// The free plan's hard monthly AI cap, in cents at provider cost.
+ /// Mandatory; set in Doppler.
+ pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// In-plan AI allowance per Premium seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
- /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// In-plan AI allowance per Max seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
+ pub ai_usage_max_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on paid AI usage past the allowance, as a whole percent of
+ /// provider cost. Mandatory; set in Doppler.
pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// The environment we are in.
#[macro_config_default(Environment::new_or_prod())]
@@ -107,11 +113,15 @@ pub struct Config {
}
impl Config {
- /// The AI pricing every billing component is composed with. Both values
- /// are validated when the configuration loads.
+ /// The AI pricing every billing component is composed with. Every value
+ /// is validated when the configuration loads.
pub fn ai_pricing(&self) -> ai_billing::AiPricing {
ai_billing::AiPricing::new(
- self.ai_usage_included_allowance_cents,
+ ai_billing::PlanAllowances {
+ free: self.ai_usage_free_included_allowance_cents,
+ premium: self.ai_usage_included_allowance_cents,
+ max: self.ai_usage_max_included_allowance_cents,
+ },
self.ai_usage_overage_markup_percent,
)
}
diff --git a/services/scheduled_action/src/config.rs b/services/scheduled_action/src/config.rs
index 6c27e3fe7c..bcc08d0cfe 100644
--- a/services/scheduled_action/src/config.rs
+++ b/services/scheduled_action/src/config.rs
@@ -26,11 +26,17 @@ pub struct Config {
/// Default-off quota admission and prospective usage counting.
#[macro_config_default(ai_usage::AiUsageEnforcement::Disabled)]
pub enable_ai_usage_enforcement: ai_usage::AiUsageEnforcement,
- /// In-plan AI allowance per paid seat per period, in cents at provider
+ /// The free plan's hard monthly AI cap, in cents at provider cost.
+ /// Mandatory; set in Doppler.
+ pub ai_usage_free_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// In-plan AI allowance per Premium seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
pub ai_usage_included_allowance_cents: ai_billing::IncludedAllowanceCents,
- /// Markup on AI usage past the allowance, as a whole percent of provider
+ /// In-plan AI allowance per Max seat per period, in cents at provider
/// cost. Mandatory; set in Doppler.
+ pub ai_usage_max_included_allowance_cents: ai_billing::IncludedAllowanceCents,
+ /// Markup on paid AI usage past the allowance, as a whole percent of
+ /// provider cost. Mandatory; set in Doppler.
pub ai_usage_overage_markup_percent: ai_billing::OverageMarkupPercent,
/// The environment we are in.
#[macro_config_default(Environment::new_or_prod())]
@@ -54,11 +60,15 @@ pub struct Config {
}
impl Config {
- /// The AI pricing every billing component is composed with. Both values
- /// are validated when the configuration loads.
+ /// The AI pricing every billing component is composed with. Every value
+ /// is validated when the configuration loads.
pub fn ai_pricing(&self) -> ai_billing::AiPricing {
ai_billing::AiPricing::new(
- self.ai_usage_included_allowance_cents,
+ ai_billing::PlanAllowances {
+ free: self.ai_usage_free_included_allowance_cents,
+ premium: self.ai_usage_included_allowance_cents,
+ max: self.ai_usage_max_included_allowance_cents,
+ },
self.ai_usage_overage_markup_percent,
)
}
diff --git a/services/scheduled_action/src/config/test.rs b/services/scheduled_action/src/config/test.rs
index 83a5691b9a..d0a59b836f 100644
--- a/services/scheduled_action/src/config/test.rs
+++ b/services/scheduled_action/src/config/test.rs
@@ -7,18 +7,30 @@ fn config_values() -> Value {
"DATABASE_URL": "postgres://localhost/macro",
"KAFKA_BROKERS": "existing-broker:9092",
"INTERNAL_API_KEY": "test",
+ "AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS": 500,
"AI_USAGE_INCLUDED_ALLOWANCE_CENTS": 2000,
+ "AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS": 10000,
"AI_USAGE_OVERAGE_MARKUP_PERCENT": 5
})
}
#[test]
fn ai_pricing_is_mandatory_and_validated() {
+ use ai_billing::PlanTier;
+
let config: Config = serde_json::from_value(config_values()).unwrap();
- assert_eq!(config.ai_pricing().included_allowance_cents(), 2_000);
- assert_eq!(config.ai_pricing().overage_markup_percent(), 5);
+ let pricing = config.ai_pricing();
+ assert_eq!(pricing.included_allowance_cents_for(PlanTier::Free), 500);
+ assert_eq!(
+ pricing.included_allowance_cents_for(PlanTier::Premium),
+ 2_000
+ );
+ assert_eq!(pricing.included_allowance_cents_for(PlanTier::Max), 10_000);
+ assert_eq!(pricing.overage_markup_percent(), 5);
for key in [
+ "AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS",
"AI_USAGE_INCLUDED_ALLOWANCE_CENTS",
+ "AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS",
"AI_USAGE_OVERAGE_MARKUP_PERCENT",
] {
let mut values = config_values();
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
index d62e67f8e6..6c27511545 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
@@ -719,10 +719,19 @@ impl BootStubEnv {
"local-stripe-webhook-secret".into(),
);
// ai_billing's mandatory pricing (crates/ai_billing/src/config.rs). Every
- // host that composes billing refuses to boot without both; these are
- // the same values Doppler's shared_ai configs carry.
- env.insert("AI_USAGE_INCLUDED_ALLOWANCE_CENTS".into(), "2000".into());
- env.insert("AI_USAGE_OVERAGE_MARKUP_PERCENT".into(), "5".into());
+ // host that composes billing refuses to boot without all four; these
+ // mirror the published plan table ($5 free cap, $15 Pro, $150 Max,
+ // list price + 25%). Doppler's shared_ai configs are authoritative.
+ env.insert(
+ "AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS".into(),
+ "500".into(),
+ );
+ env.insert("AI_USAGE_INCLUDED_ALLOWANCE_CENTS".into(), "1500".into());
+ env.insert(
+ "AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS".into(),
+ "15000".into(),
+ );
+ env.insert("AI_USAGE_OVERAGE_MARKUP_PERCENT".into(), "25".into());
// macro_auth's `JwtValidationArgs` (used by every service that mounts
// the auth middleware) reads these at boot. The keys are only parsed
// when a Macro API token is actually validated — normal local auth