Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat: enable AI usage billing only in dev (#6989)
Will Hutchinson3932fcb8529f
diff --git a/Cargo.lock b/Cargo.lockindex 3bd883332c..c7ede28dde 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -651,6 +651,7 @@ dependencies = ["chrono","macro_authorization","macro_db_migrator",+ "macro_env","macro_user_id","macro_uuid","roles_and_permissions",diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsxindex 31ab3140d3..3f2491b851 100644--- a/apps/web/src/components/app/Layout.tsx+++ b/apps/web/src/components/app/Layout.tsx@@ -23,8 +23,7 @@ import {isAddInboxDialogOpen,} from '@app/features/inbox/AddInboxDialog';import { MacroMcpSetupModal } from '@app/features/integrations/mcp-setup/MacroMcpSetupModal';-// AI usage billing is temporarily disabled.-// import { AiUsageLimitDialog } from '@app/features/paywall/AiUsageLimitDialog';+import { AiUsageLimitDialog } from '@app/features/paywall/AiUsageLimitDialog';import { Paywall } from '@app/features/paywall/Paywall';import { PropertyEditorModal } from '@app/features/property/editor/PropertyEditorModal';import { ReminderComposerModal } from '@app/features/reminders/ReminderComposerModal';@@ -54,8 +53,8 @@ import {} from '@components/app/sidebarVisibility';import { useIsAuthenticated } from '@core/auth';import { UserCardDrawer } from '@core/component/UserCardDrawer';-// import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';-import { enableReminders } from '@core/constant/featureFlags';+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';+import { DEV_MODE_ENV, enableReminders } from '@core/constant/featureFlags';import { usePaywallState } from '@core/constant/PaywallState';import { isSoloSettings } from '@core/constant/SettingsState';import { attachGlobalDOMScope } from '@core/hotkey/hotkeys';@@ -355,7 +354,7 @@ function NewOnboardingRedirect() {function LayoutInner(props: RouteSectionProps) {const isAuthenticated = useIsAuthenticated();const { paywallOpen, showPaywall } = usePaywallState();- // const { usageLimitOpen } = useAiUsageLimitState();+ const { usageLimitOpen } = useAiUsageLimitState();const location = useLocation();const [sidebarOverlayOpen, setSidebarOverlayOpen] = createSignal(false);const [sidebarOverlayTriggerHovered, setSidebarOverlayTriggerHovered] =@@ -502,11 +501,9 @@ function LayoutInner(props: RouteSectionProps) {<Paywall /></Suspense></Show>- {/* AI usage billing is temporarily disabled.- <Show when={usageLimitOpen()}>+ <Show when={DEV_MODE_ENV && usageLimitOpen()}><AiUsageLimitDialog /></Show>- */}<div class="max-h-full grow flex">{/* The provider spans the sidebar too so its favorites can registersortables with the same drag-drop context as the entity drags. */}diff --git a/apps/web/src/features/paywall/plans.ts b/apps/web/src/features/paywall/plans.tsindex 95246c18b4..0752f406bd 100644--- a/apps/web/src/features/paywall/plans.ts+++ b/apps/web/src/features/paywall/plans.ts@@ -1,3 +1,5 @@+import { DEV_MODE_ENV } from '@core/constant/featureFlags';+export type PlanTier = 'free' | 'premium' | 'max';export type Plan = {tier: PlanTier;@@ -46,19 +48,19 @@ export const PLAN_BY_TIER: Record<PlanTier, Plan> = {interface PlanFeature {label: string;values: Record<PlanTier, string>;+ devOnly?: boolean;}-export const PLAN_FEATURES: PlanFeature[] = [- /* AI usage billing is temporarily disabled.+const planFeatures: PlanFeature[] = [{label: 'AI usage included',+ devOnly: true,values: {free: 'Limited',premium: '$40 / mo',max: '$200 / mo',},},- */{label: 'AI Agent',values: {@@ -67,16 +69,15 @@ export const PLAN_FEATURES: PlanFeature[] = [max: 'All models',},},- /* AI usage billing is temporarily disabled.{label: 'Beyond included',+ devOnly: true,values: {free: '—',premium: 'Credits or usage billing',max: 'Credits or usage billing',},},- */{label: 'Storage',values: {@@ -86,3 +87,7 @@ export const PLAN_FEATURES: PlanFeature[] = [},},];++export const PLAN_FEATURES = planFeatures.filter(+ (feature) => !feature.devOnly || DEV_MODE_ENV+);diff --git a/apps/web/src/features/settings/Billing.test.tsx b/apps/web/src/features/settings/Billing.test.tsxindex 9c6ae83efb..eccf416477 100644--- a/apps/web/src/features/settings/Billing.test.tsx+++ b/apps/web/src/features/settings/Billing.test.tsx@@ -1,12 +1,36 @@-import { PLAN_FEATURES, type PlanTier } from '@app/features/paywall/plans';+import type { PlanTier } from '@app/features/paywall/plans';import { PERMISSION_IDS } from '@core/constant/permissions';-import { cleanup, render, screen } from '@solidjs/testing-library';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';import type { JSX } from 'solid-js';-import { afterEach, describe, expect, it, vi } from 'vitest';-import { Billing } from './Billing';+import {+ afterEach,+ beforeAll,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from 'vitest';-const state = vi.hoisted(() => ({ tier: 'premium' as PlanTier }));+const state = vi.hoisted(() => ({+ tier: 'premium' as PlanTier,+ dev: false,+ summarySuccess: true,+ unlimited: false,+ toastSuccess: vi.fn(),+}));+vi.mock('@core/constant/featureFlags', () => ({+ get DEV_MODE_ENV() {+ return state.dev;+ },+}));vi.mock('@app/lib/analytics/analytics-context', () => ({useAnalytics: () => ({ track: vi.fn() }),}));@@ -18,22 +42,25 @@ vi.mock('@core/context/user', () => ({useUserId: () => () => 'macro|[email protected]',}));vi.mock('@core/component/Toast/Toast', () => ({- toast: { success: vi.fn(), failure: vi.fn() },+ toast: { success: state.toastSuccess, failure: vi.fn() },}));vi.mock('@queries/team/teams', () => ({useCurrentTeamQuery: () => ({ data: undefined }),}));vi.mock('@queries/auth', () => ({useAiBillingSummaryQuery: () => ({- isSuccess: true,- data: {- tier: state.tier,- can_manage_billing: true,- unlimited: false,- used_cents: 1_000_000,- included_cents: 4_000,- credit_balance_cents: 0,- blocked_reason: 'ai_allowance_exhausted',+ isSuccess: state.summarySuccess,+ get data() {+ if (!state.summarySuccess) throw new Error('Read pending summary');+ return {+ tier: state.tier,+ can_manage_billing: true,+ unlimited: state.unlimited,+ used_cents: 1_000_000,+ included_cents: 4_000,+ credit_balance_cents: 0,+ blocked_reason: 'ai_allowance_exhausted',+ };},}),useChangePlanMutation: () => ({ isPending: false, mutateAsync: vi.fn() }),@@ -43,52 +70,106 @@ vi.mock('@service-stripe/client', () => ({stripeServiceClient: { createPortalSession: vi.fn() },}));vi.mock('./AiUsage', () => ({- AiUsageMeter: () => {- throw new Error('AI usage meter must not mount while billing is paused');- },- AiUsageControls: () => {- throw new Error(- 'AI credit controls must not mount while billing is paused'- );- },+ AiUsageMeter: () => <div data-testid="usage-meter">AI usage meter</div>,+ AiUsageControls: () => <div data-testid="usage-controls">Add credits</div>,}));vi.mock('@ui', () => ({cn: (...values: unknown[]) => values.filter(Boolean).join(' '),Layer: (props: { children: JSX.Element }) => <>{props.children}</>,- Button: (props: { children: JSX.Element }) => (- <button type="button">{props.children}</button>+ Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button type="button" onClick={props.onClick}>+ {props.children}+ </button>),}));afterEach(cleanup);-describe('Billing while AI usage billing is paused', () => {+describe.each([false, true])('Billing with DEV_MODE_ENV=%s', (dev) => {+ let Billing: typeof import('./Billing').Billing;+ let PLAN_FEATURES: typeof import('@app/features/paywall/plans').PLAN_FEATURES;++ beforeAll(async () => {+ state.dev = dev;+ vi.resetModules();+ ({ Billing } = await import('./Billing'));+ ({ PLAN_FEATURES } = await import('@app/features/paywall/plans'));+ });++ beforeEach(() => {+ state.tier = 'premium';+ state.summarySuccess = true;+ state.unlimited = false;+ state.toastSuccess.mockClear();+ });+it.each<PlanTier>(['free', 'premium', 'max'])(- 'keeps %s subscription controls without usage or credit UI',+ 'keeps %s subscription controls and gates usage UI and copy on dev',(tier) => {state.tier = tier;const { container } = render(() => <Billing />);expect(screen.getByRole('heading', { name: 'Billing' })).toBeTruthy();- expect(container.textContent).not.toMatch(- /AI usage|Add credits|Usage billing|included AI|out of credits/i+ expect(screen.queryByTestId('usage-meter') !== null).toBe(+ dev && tier !== 'free'+ );+ expect(screen.queryByTestId('usage-controls') !== null).toBe(+ dev && tier !== 'free');- if (tier === 'free') {+ expect(container.textContent?.includes('of AI usage')).toBe(dev);+ if (!dev) {+ expect(container.textContent).not.toMatch(+ /AI usage|Add credits|Usage billing|included AI|out of credits/i+ );+ }+ expect(+ screen.getByRole('button', {+ name: tier === 'free' ? 'Upgrade now' : 'Manage',+ })+ ).toBeTruthy();+ if (tier === 'premium') {expect(- screen.getByRole('button', { name: 'Upgrade now' })+ screen.getByText(dev ? 'Need more AI?' : 'Upgrade')).toBeTruthy();- } else {- expect(screen.getByRole('button', { name: 'Manage' })).toBeTruthy();}});- it('does not advertise credit or usage billing in the plan comparison', () => {- expect(PLAN_FEATURES.map((feature) => feature.label)).not.toContain(- 'AI usage included'- );- expect(PLAN_FEATURES.map((feature) => feature.label)).not.toContain(- 'Beyond included'+ it('gates usage-billing rows in the plan comparison on dev', () => {+ const labels = PLAN_FEATURES.map((feature) => feature.label);+ expect(labels.includes('AI usage included')).toBe(dev);+ expect(labels.includes('Beyond included')).toBe(dev);+ expect(labels).toContain('AI Agent');+ expect(labels).toContain('Storage');+ });++ it('does not read a pending billing summary', () => {+ state.summarySuccess = false;+ render(() => <Billing />);+ expect(screen.queryByTestId('usage-meter')).toBeNull();+ expect(screen.getByRole('button', { name: 'Manage' })).toBeTruthy();+ });++ it('keeps unlimited plans free of credit controls', () => {+ state.unlimited = true;+ render(() => <Billing />);+ expect(screen.queryByTestId('usage-controls')).toBeNull();+ expect(+ screen.queryByText(+ 'Your enterprise plan includes unlimited AI usage.'+ ) !== null+ ).toBe(dev);+ });++ it('only advertises an increased allowance in the dev upgrade toast', async () => {+ render(() => <Billing />);+ fireEvent.click(screen.getByRole('button', { name: 'Upgrade to Max' }));+ await waitFor(() =>+ expect(state.toastSuccess).toHaveBeenCalledWith(+ dev+ ? 'Upgraded to Max. Your larger AI allowance applies right away.'+ : 'Upgraded to Max.'+ ));});});diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsxindex 54fda34d08..c94780e106 100644--- a/apps/web/src/features/settings/Billing.tsx+++ b/apps/web/src/features/settings/Billing.tsx@@ -2,6 +2,7 @@ import { PLAN_BY_TIER, type PlanTier } from '@app/features/paywall/plans';import { useAnalytics } from '@app/lib/analytics/analytics-context';import { useHasPaidAccess } from '@core/auth';import { toast } from '@core/component/Toast/Toast';+import { DEV_MODE_ENV } from '@core/constant/featureFlags';import { PERMISSION_IDS } from '@core/constant/permissions';import { usePermissions, useUserId } from '@core/context/user';import { plural } from '@core/util/string';@@ -18,8 +19,7 @@ import type { TeamMember } from '@service-auth/generated/schemas/teamMember';import { stripeServiceClient } from '@service-stripe/client';import { Button, Layer } from '@ui';import { createMemo, For, Match, Show, Switch } from 'solid-js';-// AI usage billing is temporarily disabled; keep the UI for re-enabling.-// import { AiUsageControls, AiUsageMeter } from './AiUsage';+import { AiUsageControls, AiUsageMeter } from './AiUsage';import { SettingsCard, SettingsPage, SettingsSection } from './primitives';const BILLING_PLAN_FEATURES: Record<PlanTier, string[]> = {@@ -27,7 +27,7 @@ const BILLING_PLAN_FEATURES: Record<PlanTier, string[]> = {premium: ['All agents','All models',- // '$40 of AI usage each month',+ ...(DEV_MODE_ENV ? ['$40 of AI usage each month'] : []),'No watermark','AI projections','Multiple email inboxes',@@ -37,7 +37,7 @@ const BILLING_PLAN_FEATURES: Record<PlanTier, string[]> = {],max: ['Everything in Premium',- // '$200 of AI usage each month',+ ...(DEV_MODE_ENV ? ['$200 of AI usage each month'] : []),'Priority support',],};@@ -72,9 +72,10 @@ function describeSeatPlans(members: TeamMember[]): string {const PlanPrice = (props: { tier: PaidPlan }) => (<p class="text-ink-extra-muted text-xs">${PLAN_BY_TIER[props.tier].price} per seat / month- {/* AI usage billing is temporarily disabled.- · includes ${PLAN_BY_TIER[props.tier].aiIncluded} of AI usage- */}+ <Show when={DEV_MODE_ENV}>+ {' '}+ · includes ${PLAN_BY_TIER[props.tier].aiIncluded} of AI usage+ </Show></p>);@@ -140,14 +141,12 @@ export const Billing = () => {try {await changePlan.mutateAsync({ plan });analytics.track('plan_changed', { plan });- // AI usage billing is temporarily disabled.- // toast.success(- // plan === 'max'- // ? 'Upgraded to Max. Your larger AI allowance applies right away.'- // : 'Switched to Premium.'- // );toast.success(- plan === 'max' ? 'Upgraded to Max.' : 'Switched to Premium.'+ plan === 'max'+ ? DEV_MODE_ENV+ ? 'Upgraded to Max. Your larger AI allowance applies right away.'+ : 'Upgraded to Max.'+ : 'Switched to Premium.');} catch (error) {console.error(error);@@ -164,7 +163,7 @@ export const Billing = () => {}};- // const returnUrl = () => `${window.location.origin}/app/settings/billing`;+ const returnUrl = () => `${window.location.origin}/app/settings/billing`;return (<SettingsPage@@ -254,8 +253,9 @@ export const Billing = () => {</SettingsCard></SettingsSection>- {/* AI usage billing is temporarily disabled.- <Show when={hasPaid() && summary.isSuccess && summary.data}>+ <Show+ when={DEV_MODE_ENV && hasPaid() && summary.isSuccess && summary.data}+ >{(snapshot) => (<SettingsSectiontitle="AI usage"@@ -284,7 +284,6 @@ export const Billing = () => {</SettingsSection>)}</Show>- */}<Show when={canChangePlan()}><Switch>@@ -335,8 +334,7 @@ export const Billing = () => {</SettingsSection></Match><Match when={tier() === 'premium'}>- {/* <SettingsSection title="Need more AI?"> */}- <SettingsSection title="Upgrade">+ <SettingsSection title={DEV_MODE_ENV ? 'Need more AI?' : 'Upgrade'}><SettingsCard><section class="flex flex-col gap-4 p-4"><header class="flex items-center gap-2">@@ -381,8 +379,8 @@ export const Billing = () => {>Switch to Premium</button>{' '}- {/* ($40 per seat / month with $40 of AI usage). */}- ($40 per seat / month).+ ($40 per seat / month+ <Show when={DEV_MODE_ENV}> with $40 of AI usage</Show>).</p></SettingsSection></Match>diff --git a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.test.tsx b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.test.tsxindex b593533d98..2d27eb2534 100644--- a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.test.tsx+++ b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.test.tsx@@ -8,11 +8,43 @@ import {modelsForPlan,type TModel,} from '@core/component/AI/constant';-import { fireEvent, render } from '@solidjs/testing-library';-import { createSignal } from 'solid-js';-import { describe, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render } from '@solidjs/testing-library';+import { createSignal, type JSX } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { type ModelOption, ModelSelector } from './ModelSelector';+const state = vi.hoisted(() => ({ dev: false, mobile: false }));+vi.mock('@core/constant/featureFlags', () => ({+ get DEV_MODE_ENV() {+ return state.dev;+ },+}));+vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => state.mobile }));+vi.mock('@components/app/mobile/MobileDrawer', () => {+ const Slot = (props: { children?: JSX.Element }) => (+ <div>{props.children}</div>+ );+ return {+ MobileDrawer: Object.assign(Slot, {+ Trigger: Slot,+ Portal: Slot,+ Overlay: Slot,+ Content: Slot,+ Handle: Slot,+ Close: Slot,+ ScrollBody: Slot,+ Section: Slot,+ Item: Slot,+ }),+ };+});++beforeEach(() => {+ state.dev = false;+ state.mobile = false;+});+afterEach(cleanup);+// Render the Kobalte dropdown as a transparent passthrough so the menu items// are always in the DOM — we're testing ModelSelector's own logic (which models// render, lock state, select vs. paywall routing), not the dropdown primitive.@@ -32,7 +64,13 @@ vi.mock('@ui', () => {{p.children}</div>);- return { cn, Dropdown };+ return {+ cn,+ Dropdown,+ Button: (props: { children?: JSX.Element }) => (+ <button type="button">{props.children}</button>+ ),+ };});// Neutralize SVG imports; tag the lock so we can assert it renders.@@ -75,12 +113,22 @@ describe('ModelSelector: availability', () => {);});- it('hides usage multipliers while AI usage billing is paused', () => {- const { container } = render(() => (- <ModelSelector models={ALL_PAID} onSelect={() => {}} />- ));- expect(container.textContent).not.toContain('× usage');- });+ it.each([+ { dev: false, mobile: false },+ { dev: true, mobile: false },+ { dev: false, mobile: true },+ { dev: true, mobile: true },+ ])(+ 'gates usage multipliers on dev ($dev), mobile=$mobile',+ ({ dev, mobile }) => {+ state.dev = dev;+ state.mobile = mobile;+ const { container } = render(() => (+ <ModelSelector models={ALL_PAID} onSelect={() => {}} />+ ));+ expect(container.textContent?.includes('× usage')).toBe(dev);+ }+ );it('grays out and locks inaccessible models, leaving accessible ones clean', () => {// A free user: only the fast model is available.diff --git a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsxindex b256559adc..b065ab2f92 100644--- a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx+++ b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx@@ -4,9 +4,10 @@ import {MODEL_PRETTYNAME,MODEL_PROVIDER_ICON,Model,- // modelUsageHint,+ modelUsageHint,} from '@core/component/AI/constant';import type { TModel } from '@core/component/AI/types';+import { DEV_MODE_ENV } from '@core/constant/featureFlags';import { isMobile } from '@core/mobile/isMobile';import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';import CheckIcon from '@phosphor/check.svg';@@ -98,9 +99,8 @@ export function ModelSelector(props: ModelSelectorProps) {<span class="flex-1 truncate">{MODEL_PRETTYNAME[option.id]}</span>- {/* AI usage billing is temporarily disabled.- Decorative: the item's accessible name stays the model.- <Show when={modelUsageHint(option.id)}>+ {/* Decorative: the item's accessible name stays the model. */}+ <Show when={DEV_MODE_ENV && modelUsageHint(option.id)}>{(hint) => (<spanaria-hidden="true"@@ -110,7 +110,6 @@ export function ModelSelector(props: ModelSelectorProps) {</span>)}</Show>- */}<Show when={!option.available}><LockIcon class="size-3.5 shrink-0 text-ink-extra-muted" /></Show>@@ -191,15 +190,15 @@ export function ModelSelector(props: ModelSelectorProps) {<span class="text-base font-medium leading-5">{MODEL_PRETTYNAME[option.id]}</span>- {/* AI usage billing is temporarily disabled.- <Show when={modelUsageHint(option.id)}>+ <Show+ when={DEV_MODE_ENV && modelUsageHint(option.id)}+ >{(hint) => (<span class="text-xs text-ink-extra-muted">{hint()}</span>)}</Show>- */}</span><span class="text-[13px] leading-[18px] text-ink-muted">{MODEL_DESCRIPTION[option.id]}diff --git a/crates/ai_billing/Cargo.toml b/crates/ai_billing/Cargo.tomlindex 8a99d34082..3805548d60 100644--- a/crates/ai_billing/Cargo.toml+++ b/crates/ai_billing/Cargo.toml@@ -18,6 +18,7 @@ chrono = { workspace = true }macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum",] }+macro_env = { path = "../macro_env" }macro_user_id = { path = "../macro_user_id", features = ["schema"] }macro_uuid = { path = "../macro_uuid" }roles_and_permissions = { path = "../roles_and_permissions", default-features = false, features = [diff --git a/crates/ai_billing/src/domain/service.rs b/crates/ai_billing/src/domain/service.rsindex c2701f43e6..48186e0e93 100644--- a/crates/ai_billing/src/domain/service.rs+++ b/crates/ai_billing/src/domain/service.rs@@ -4,21 +4,19 @@#[cfg(test)]mod test;-// AI usage billing is temporarily disabled; retain settlement and gating for re-enabling.-// use super::ledger::{SettlementPolicy, build_snapshot, decide};-use super::ledger::build_snapshot;+use super::ledger::{SettlementPolicy, build_snapshot, decide};use super::models::{AllowanceDecision, AllowanceStore, BillingError, BillingPeriod, BillingSettings,- CREDIT_PACKS_CENTS, Entitlement, OVERAGE_LIMIT_MAX_CENTS, OVERAGE_LIMIT_MIN_CENTS,- OverageChargeStatus, PayerScope, Result, SeatAllowance, SeatUsage, UsageSnapshot,+ CREDIT_PACKS_CENTS, Entitlement, OVERAGE_CHARGE_THRESHOLD_CENTS, OVERAGE_LIMIT_MAX_CENTS,+ OVERAGE_LIMIT_MIN_CENTS, OverageChargeStatus, PayerScope, PeriodAllowance, PlanTier, Result,+ SeatAllowance, SeatUsage, UsageSnapshot,};-// use super::models::{OVERAGE_CHARGE_THRESHOLD_CENTS, PeriodAllowance, PlanTier};use super::ports::{- BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, PaymentGateway,- UsageReader,+ BillingRepo, BillingService, CreditCheckoutRequest, EntitlementSource, OverageChargeRequest,+ PaymentGateway, PendingCharge, UsageReader,};-// use super::ports::{OverageChargeRequest, PendingCharge};use chrono::{DateTime, Utc};+use macro_env::Environment;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;use teams::domain::open_seat_release::OpenSeatRelease;@@ -30,16 +28,18 @@ pub struct BillingServiceImpl<E, U, R, P> {usage: U,repo: R,payments: P,+ environment: Environment,}impl<E, U, R, P> BillingServiceImpl<E, U, R, P> {- /// Construct the service.- pub fn new(entitlements: E, usage: U, repo: R, payments: P) -> Self {+ /// Construct the service. Allowance enforcement and settlement run only in dev.+ pub fn new(entitlements: E, usage: U, repo: R, payments: P, environment: Environment) -> Self {Self {entitlements,usage,repo,payments,+ environment,}}}@@ -208,7 +208,6 @@ where))}- /* AI usage billing is temporarily disabled. Keep settlement helpers for re-enabling./// Per-seat allowances to settle `period` with.////// A closed period uses the freeze recorded while it was open. An open@@ -400,8 +399,6 @@ whereself.repo.suspend_overage(payer).await}- */-fn require_payer(entitlement: &Entitlement, user: &MacroUserIdStr<'_>) -> Result<()> {if !entitlement.is_payer(user) {return Err(BillingError::NotPayer);@@ -448,33 +445,34 @@ where{#[tracing::instrument(skip(self), err)]async fn check_allowance(&self, user: &MacroUserIdStr<'_>) -> Result<AllowanceDecision> {- // AI usage billing is temporarily disabled: do not block requests on credits.- // let position = self.position(user, Utc::now()).await?;- // if position.entitlement.unlimited || position.entitlement.tier == PlanTier::Free {- // return Ok(AllowanceDecision::Allow);- // }- // let snapshot = self.snapshot_at(user, &position).await?;- // Ok(decide(&snapshot))- Ok(AllowanceDecision::Allow)+ if !matches!(self.environment, Environment::Develop) {+ return Ok(AllowanceDecision::Allow);+ }+ let position = self.position(user, Utc::now()).await?;+ if position.entitlement.unlimited || position.entitlement.tier == PlanTier::Free {+ return Ok(AllowanceDecision::Allow);+ }+ let snapshot = self.snapshot_at(user, &position).await?;+ Ok(decide(&snapshot))}#[tracing::instrument(skip(self), err)]async fn snapshot(&self, user: &MacroUserIdStr<'_>) -> Result<UsageSnapshot> {let position = self.position(user, Utc::now()).await?;- // self.snapshot_at(user, &position).awaitlet mut snapshot = self.snapshot_at(user, &position).await?;- // Match check_allowance while enforcement is paused. Restore the original- // return above when re-enabling; keep build_snapshot's billing logic intact.- snapshot.blocked_reason = None;+ // Keep the summary consistent with the allowance gate outside dev.+ if !matches!(self.environment, Environment::Develop) {+ snapshot.blocked_reason = None;+ }Ok(snapshot)}#[tracing::instrument(skip(self), err)]async fn settle(&self, user: &MacroUserIdStr<'_>) -> Result<()> {- // AI usage billing is temporarily disabled for every caller (summary reads,- // usage recording, settings changes, purchases, and internal settlement).- // Do not consume credits, reserve charges, or create/retry Stripe invoices.- /*+ // Guard every caller: summary reads, settings, purchases, and internal settlement.+ if !matches!(self.environment, Environment::Develop) {+ return Ok(());+ }let now = Utc::now();let position = self.position(user, now).await?;if position.entitlement.unlimited || !position.entitlement.tier.is_paid() {@@ -488,8 +486,6 @@ where.await?;self.settle_period(&position.entitlement, position.period, now).await- */- Ok(())}#[tracing::instrument(skip(self), err)]diff --git a/crates/ai_billing/src/domain/service/test.rs b/crates/ai_billing/src/domain/service/test.rsindex 8eceaba5b0..a0abbcd520 100644--- a/crates/ai_billing/src/domain/service/test.rs+++ b/crates/ai_billing/src/domain/service/test.rs@@ -1,10 +1,10 @@use super::*;-use crate::domain::ledger::{SettlementPolicy, plan_settlement};+use crate::domain::ledger::plan_settlement;use crate::domain::models::{AllowanceStore, DenyReason, OpenPeriodStart, PayerScope, PeriodAllowance, PeriodLedger,PlanTier, SeatGeneration,};-use crate::domain::ports::{OverageChargeRequest, PendingCharge, SettlementOutcome};+use crate::domain::ports::SettlementOutcome;use macro_user_id::cowlike::CowLike;use macro_uuid::Uuid;use std::collections::HashMap;@@ -486,6 +486,13 @@ impl PaymentGateway for FakePayments {type Service = BillingServiceImpl<FakeEntitlements, FakeUsage, FakeRepo, FakePayments>;fn premium_service(used_cents: i64) -> (Service, FakeRepo, FakePayments, FakeUsage) {+ premium_service_in(Environment::Develop, used_cents)+}++fn premium_service_in(+ environment: Environment,+ used_cents: i64,+) -> (Service, FakeRepo, FakePayments, FakeUsage) {let payer = user("[email protected]");let ents = FakeEntitlements::default().with(Entitlement::personal(payer.clone(), PlanTier::Premium))@@ -497,7 +504,13 @@ fn premium_service(used_cents: i64) -> (Service, FakeRepo, FakePayments, FakeUsalet repo = FakeRepo::default();let payments = FakePayments::default();(- BillingServiceImpl::new(ents, usage.clone(), repo.clone(), payments.clone()),+ BillingServiceImpl::new(+ ents,+ usage.clone(),+ repo.clone(),+ payments.clone(),+ environment,+ ),repo,payments,usage,@@ -505,7 +518,6 @@ fn premium_service(used_cents: i64) -> (Service, FakeRepo, FakePayments, FakeUsa}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with the gate"]async fn allows_within_allowance_and_denies_past_it() {let (svc, _, _, usage) = premium_service(3_000);let payer = user("[email protected]");@@ -518,90 +530,102 @@ async fn allows_within_allowance_and_denies_past_it() {svc.check_allowance(&payer).await.unwrap(),AllowanceDecision::Deny(DenyReason::AllowanceExhausted));-}--#[tokio::test]-async fn billing_pause_allows_exhausted_allowances_caps_and_failed_payments() {- let (svc, repo, _, _) = premium_service(1_000_000);- let payer = user("[email protected]");- assert_eq!(- svc.check_allowance(&payer).await.unwrap(),- AllowanceDecision::Allow- );- assert_eq!(svc.snapshot(&payer).await.unwrap().blocked_reason, None);-- let snapshot = svc.update_overage(&payer, true, 1_000).await.unwrap();- assert_eq!(snapshot.blocked_reason, None);- assert_eq!(- svc.check_allowance(&payer).await.unwrap(),- AllowanceDecision::Allow- );-- repo.state.lock().unwrap().suspended = true;assert_eq!(- svc.check_allowance(&payer).await.unwrap(),- AllowanceDecision::Allow+ svc.snapshot(&payer).await.unwrap().blocked_reason,+ Some(DenyReason::AllowanceExhausted));- assert_eq!(svc.snapshot(&payer).await.unwrap().blocked_reason, None);}#[tokio::test]-async fn billing_pause_preserves_credits_and_never_reserves_or_collects_overage() {- let (svc, repo, payments, usage, _, payer, previous, current) = anchored_premium(1_000_000);- svc.sync_period(&payer, current.start, current.end)- .await- .unwrap();- usage.add(- &payer,- previous.start + chrono::Duration::days(2),- 1_000_000,- );+async fn outside_dev_allows_exhausted_allowances_caps_and_failed_payments() {+ for environment in [Environment::Production, Environment::Local] {+ let (svc, repo, _, _) = premium_service_in(environment, 1_000_000);+ let payer = user("[email protected]");+ assert_eq!(+ svc.check_allowance(&payer).await.unwrap(),+ AllowanceDecision::Allow+ );+ assert_eq!(svc.snapshot(&payer).await.unwrap().blocked_reason, None);- svc.update_overage(&payer, true, 10_000).await.unwrap();- svc.apply_credit_purchase(&payer, 2_500, "cs_paused")- .await- .unwrap();- svc.apply_credit_purchase(&payer, 2_500, "cs_paused")- .await- .unwrap();- svc.settle(&payer).await.unwrap();- svc.settle(&payer).await.unwrap();+ let snapshot = svc.update_overage(&payer, true, 1_000).await.unwrap();+ assert_eq!(snapshot.blocked_reason, None);+ assert_eq!(+ svc.check_allowance(&payer).await.unwrap(),+ AllowanceDecision::Allow+ );- let snapshot = svc.snapshot(&payer).await.unwrap();- assert_eq!(snapshot.used_cents, 1_000_000);- assert_eq!(snapshot.credit_balance_cents, 2_500);- assert_eq!(snapshot.credits_consumed_cents, 0);- assert_eq!(snapshot.overage_charged_cents, 0);- assert!(repo.state.lock().unwrap().consumed.is_empty());- assert!(repo.charges().is_empty());- assert!(payments.opened().is_empty());- assert!(payments.payments().is_empty());+ repo.state.lock().unwrap().suspended = true;+ assert_eq!(+ svc.check_allowance(&payer).await.unwrap(),+ AllowanceDecision::Allow+ );+ assert_eq!(svc.snapshot(&payer).await.unwrap().blocked_reason, None);+ }}#[tokio::test]-async fn billing_pause_does_not_retry_pending_or_failed_charges() {- for status in [OverageChargeStatus::Pending, OverageChargeStatus::Failed] {- for invoice in [None, Some("in_existing".to_string())] {- let (svc, repo, payments, _) = premium_service(1_000_000);- let payer = user("[email protected]");- let period = BillingPeriod::current(None, Utc::now());- repo.state.lock().unwrap().charges.push(FakeCharge {- id: macro_uuid::generate_uuid_v7(),- period_start: period.start,- amount_cents: 1_000,- status,- invoice: invoice.clone(),- });+async fn outside_dev_preserves_credits_and_never_reserves_or_collects_overage() {+ for environment in [Environment::Production, Environment::Local] {+ let (mut svc, repo, payments, usage, _, payer, previous, current) =+ anchored_premium(1_000_000);+ svc.environment = environment;+ svc.sync_period(&payer, current.start, current.end)+ .await+ .unwrap();+ usage.add(+ &payer,+ previous.start + chrono::Duration::days(2),+ 1_000_000,+ );- svc.update_overage(&payer, true, 10_000).await.unwrap();- svc.settle(&payer).await.unwrap();+ svc.update_overage(&payer, true, 10_000).await.unwrap();+ svc.apply_credit_purchase(&payer, 2_500, "cs_paused")+ .await+ .unwrap();+ svc.apply_credit_purchase(&payer, 2_500, "cs_paused")+ .await+ .unwrap();+ svc.settle(&payer).await.unwrap();+ svc.settle(&payer).await.unwrap();++ let snapshot = svc.snapshot(&payer).await.unwrap();+ assert_eq!(snapshot.used_cents, 1_000_000);+ assert_eq!(snapshot.credit_balance_cents, 2_500);+ assert_eq!(snapshot.credits_consumed_cents, 0);+ assert_eq!(snapshot.overage_charged_cents, 0);+ assert!(repo.state.lock().unwrap().consumed.is_empty());+ assert!(repo.charges().is_empty());+ assert!(payments.opened().is_empty());+ assert!(payments.payments().is_empty());+ }+}- let charges = repo.charges();- assert_eq!(charges.len(), 1);- assert_eq!(charges[0].status, status);- assert_eq!(charges[0].invoice, invoice);- assert!(payments.opened().is_empty());- assert!(payments.payments().is_empty());+#[tokio::test]+async fn outside_dev_does_not_retry_pending_or_failed_charges() {+ for environment in [Environment::Production, Environment::Local] {+ for status in [OverageChargeStatus::Pending, OverageChargeStatus::Failed] {+ for invoice in [None, Some("in_existing".to_string())] {+ let (svc, repo, payments, _) = premium_service_in(environment, 1_000_000);+ let payer = user("[email protected]");+ let period = BillingPeriod::current(None, Utc::now());+ repo.state.lock().unwrap().charges.push(FakeCharge {+ id: macro_uuid::generate_uuid_v7(),+ period_start: period.start,+ amount_cents: 1_000,+ status,+ invoice: invoice.clone(),+ });++ svc.update_overage(&payer, true, 10_000).await.unwrap();+ svc.settle(&payer).await.unwrap();++ let charges = repo.charges();+ assert_eq!(charges.len(), 1);+ assert_eq!(charges[0].status, status);+ assert_eq!(charges[0].invoice, invoice);+ assert!(payments.opened().is_empty());+ assert!(payments.payments().is_empty());+ }}}}@@ -620,7 +644,6 @@ async fn free_users_are_not_gated() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn credits_unblock_and_settlement_consumes_them() {let (svc, repo, ..) = premium_service(4_600);let payer = user("[email protected]");@@ -651,7 +674,6 @@ async fn credits_unblock_and_settlement_consumes_them() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn overage_is_charged_in_chunks_and_respects_the_cap() {let (svc, repo, payments, usage) = premium_service(4_500);let payer = user("[email protected]");@@ -687,7 +709,6 @@ async fn overage_is_charged_in_chunks_and_respects_the_cap() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn failed_overage_charge_suspends_overage_and_is_retried_not_duplicated() {let (svc, repo, payments, _) = premium_service(5_500);let payer = user("[email protected]");@@ -726,7 +747,6 @@ async fn failed_overage_charge_suspends_overage_and_is_retried_not_duplicated()}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn opening_the_invoice_failing_marks_the_charge_failed() {let (svc, repo, payments, _) = premium_service(5_500);let payer = user("[email protected]");@@ -750,7 +770,6 @@ async fn opening_the_invoice_failing_marks_the_charge_failed() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn a_failed_uninvoiced_charge_whose_usage_credits_covered_is_not_retried() {let (svc, repo, payments, _) = premium_service(5_800);let payer = user("[email protected]");@@ -779,7 +798,6 @@ async fn a_failed_uninvoiced_charge_whose_usage_credits_covered_is_not_retried()}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn failed_invoiced_charge_keeps_coverage_when_credits_are_bought() {let (svc, repo, payments, _) = premium_service(7_000);let payer = user("[email protected]");@@ -812,7 +830,6 @@ async fn failed_invoiced_charge_keeps_coverage_when_credits_are_bought() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn a_declined_card_leaves_the_invoice_open_for_the_webhook() {let (svc, repo, payments, _) = premium_service(5_500);let payer = user("[email protected]");@@ -855,6 +872,7 @@ async fn only_the_payer_manages_billing_and_needs_a_paid_plan() {FakeUsage::default(),FakeRepo::default(),FakePayments::default(),+ Environment::Develop,);assert!(matches!(@@ -896,7 +914,6 @@ async fn only_the_payer_manages_billing_and_needs_a_paid_plan() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn team_seats_keep_allowances_separate_and_share_credits() {let owner = user("[email protected]");let member = user("[email protected]");@@ -916,8 +933,13 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {let usage = FakeUsage::default();usage.add(&member, Utc::now(), 5_000);let repo = FakeRepo::default();- let service =- BillingServiceImpl::new(entitlements, usage, repo.clone(), FakePayments::default());+ let service = BillingServiceImpl::new(+ entitlements,+ usage,+ repo.clone(),+ FakePayments::default(),+ Environment::Develop,+ );let owner_snapshot = service.snapshot(&owner).await.unwrap();assert_eq!(owner_snapshot.used_cents, 0);@@ -942,7 +964,6 @@ async fn team_seats_keep_allowances_separate_and_share_credits() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn overage_invoice_webhooks_update_suspension() {let (svc, repo, payments, _) = premium_service(5_500);let payer = user("[email protected]");@@ -972,7 +993,6 @@ async fn overage_invoice_webhooks_update_suspension() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn out_of_order_invoice_webhooks_follow_the_newest_charge() {let (svc, repo, payments, usage) = premium_service(6_000);let payer = user("[email protected]");@@ -1062,7 +1082,13 @@ fn anchored_premium(};let repo = FakeRepo::default();let payments = FakePayments::default();- let svc = BillingServiceImpl::new(ents.clone(), usage.clone(), repo.clone(), payments.clone());+ let svc = BillingServiceImpl::new(+ ents.clone(),+ usage.clone(),+ repo.clone(),+ payments.clone(),+ Environment::Develop,+ );let current_start = Utc::now() - chrono::Duration::days(3);let current_end = current_start + chrono::Duration::days(30);let current = BillingPeriod {@@ -1098,7 +1124,6 @@ async fn snapshot_freezes_the_open_period_allowance_and_refreshes_it() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn previous_period_overage_survives_an_upgrade() {let (svc, repo, payments, usage, ents, payer, previous, current) = anchored_premium(0);svc.sync_period(&payer, current.start, current.end)@@ -1161,7 +1186,6 @@ async fn previous_period_does_not_charge_included_usage_after_a_downgrade() {}#[tokio::test]-#[ignore = "AI usage billing is temporarily disabled; restore with settlement"]async fn previous_period_usage_uses_the_frozen_billed_users() {let owner = user("[email protected]");let member_a = user("[email protected]");@@ -1185,7 +1209,13 @@ async fn previous_period_usage_uses_the_frozen_billed_users() {let usage = FakeUsage::default();let repo = FakeRepo::default();let payments = FakePayments::default();- let svc = BillingServiceImpl::new(ents.clone(), usage.clone(), repo.clone(), payments.clone());+ let svc = BillingServiceImpl::new(+ ents.clone(),+ usage.clone(),+ repo.clone(),+ payments.clone(),+ Environment::Develop,+ );let current_start = Utc::now() - chrono::Duration::days(3);let current_end = current_start + chrono::Duration::days(30);let current = BillingPeriod {@@ -1280,6 +1310,7 @@ async fn release_targets_the_payer_open_period() {FakeUsage::default(),repo.clone(),FakePayments::default(),+ Environment::Develop,);svc.release(team_id, &member).await.unwrap();@@ -1314,6 +1345,7 @@ async fn release_missing_team_leaves_allowances_unchanged() {FakeUsage::default(),repo.clone(),FakePayments::default(),+ Environment::Develop,);svc.release(Uuid::from_u128(8), &member).await.unwrap();@@ -1351,6 +1383,7 @@ async fn release_refuses_to_remove_the_payer() {FakeUsage::default(),repo.clone(),FakePayments::default(),+ Environment::Develop,);svc.release(team_id, &owner).await.unwrap();@@ -1403,6 +1436,7 @@ async fn position_keeps_matching_pairs_in_their_stored_order() {FakeUsage::default(),repo.clone(),FakePayments::default(),+ Environment::Develop,);svc.position(&owner, now).await.unwrap();@@ -1465,6 +1499,7 @@ async fn position_does_not_restore_a_member_released_between_entitlement_reads()FakeUsage::default(),repo.clone(),FakePayments::default(),+ Environment::Develop,);let position = svc.position(&owner, now).await.unwrap();diff --git a/crates/ai_billing/src/outbound/settling_recorder.rs b/crates/ai_billing/src/outbound/settling_recorder.rsindex 457dab6748..75fe2d141a 100644--- a/crates/ai_billing/src/outbound/settling_recorder.rs+++ b/crates/ai_billing/src/outbound/settling_recorder.rs@@ -1,10 +1,13 @@//! A [`UsageRecorder`] that books usage and then asks for settlement when the//! payer has usage past their allowance.+#[cfg(test)]+mod test;+use crate::domain::{BillingService, SettlementTrigger};use ai_usage::domain::service::UsageServiceImpl;-// use ai_usage::SYSTEM_USER_ID;-use ai_usage::{UsageEvent, UsageRecorder, UsageRepo};+use ai_usage::{SYSTEM_USER_ID, UsageEvent, UsageRecorder, UsageRepo};+use macro_env::Environment;use std::sync::Arc;use std::time::Duration;@@ -27,19 +30,24 @@ const RECORD_RETRY_BACKOFF: [Duration; 3] = [/// re-delivered after an ambiguous failure could double count instead.pub struct SettlingUsageRecorder<Repo, B, T> {inner: Arc<UsageServiceImpl<Repo>>,- #[expect(dead_code, reason = "AI usage billing is temporarily disabled")]billing: Arc<B>,- #[expect(dead_code, reason = "AI usage billing is temporarily disabled")]trigger: T,+ environment: Environment,}impl<Repo, B, T> SettlingUsageRecorder<Repo, B, T> {- /// Build the recorder.- pub fn new(inner: Arc<UsageServiceImpl<Repo>>, billing: Arc<B>, trigger: T) -> Self {+ /// Build the recorder. Usage is recorded everywhere; settlement is requested only in dev.+ pub fn new(+ inner: Arc<UsageServiceImpl<Repo>>,+ billing: Arc<B>,+ trigger: T,+ environment: Environment,+ ) -> Self {Self {inner,billing,trigger,+ environment,}}}@@ -52,11 +60,11 @@ where{fn record(&self, event: UsageEvent) {let inner = self.inner.clone();- // AI usage billing is temporarily disabled; keep recording usage with retries.- // let billing = self.billing.clone();- // let trigger = self.trigger.clone();+ let billing = self.billing.clone();+ let trigger = self.trigger.clone();+ let environment = self.environment;tokio::spawn(async move {- // let user = event.user.clone();+ let user = event.user.clone();let mut backoff = RECORD_RETRY_BACKOFF.iter();loop {let Err(e) = inner.record_now(event.clone()).await else {@@ -79,8 +87,9 @@ where}}}- /* AI usage billing is temporarily disabled: do not request settlement.- if user.as_ref() == SYSTEM_USER_ID.as_ref() {+ if !matches!(environment, Environment::Develop)+ || user.as_ref() == SYSTEM_USER_ID.as_ref()+ {return;}match billing.snapshot(&user).await {@@ -96,7 +105,6 @@ wheretracing::warn!(error = ?e, "failed to read ai billing position");}}- */});}}diff --git a/crates/ai_billing/src/outbound/settling_recorder/test.rs b/crates/ai_billing/src/outbound/settling_recorder/test.rsnew file mode 100644index 0000000000..fc035801d8--- /dev/null+++ b/crates/ai_billing/src/outbound/settling_recorder/test.rs@@ -0,0 +1,230 @@+use super::*;+use crate::domain::{+ AllowanceDecision, BillingPeriod, BillingSettings, Entitlement, PlanTier, Result,+ UsageSnapshot, ledger::build_snapshot,+};+use ai_usage::domain::{Result as UsageResult, UsageError};+use ai_usage::{AiFeature, CompletionUsage, ModelPricing, UsageApiParams, UsageContext};+use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;+use std::sync::atomic::{AtomicUsize, Ordering};+use tokio::sync::Notify;++#[derive(Clone, Default)]+struct FakeUsageRepo {+ attempts: Arc<AtomicUsize>,+ recorded: Arc<Notify>,+ fail_first: bool,+}++impl UsageRepo for FakeUsageRepo {+ async fn insert_usage(&self, _usage: &CompletionUsage) -> UsageResult<()> {+ let attempt = self.attempts.fetch_add(1, Ordering::SeqCst);+ if self.fail_first && attempt == 0 {+ return Err(UsageError::Other(anyhow::anyhow!(+ "transient write failure"+ )));+ }+ self.recorded.notify_one();+ Ok(())+ }++ async fn get_pricing(&self, _model: &str) -> UsageResult<Option<ModelPricing>> {+ Ok(None)+ }++ async fn set_pricing(&self, _model: &str, _pricing: ModelPricing) -> UsageResult<()> {+ unreachable!()+ }++ async fn query_usage(&self, _params: &UsageApiParams) -> UsageResult<Vec<CompletionUsage>> {+ unreachable!()+ }+}++struct FakeBilling {+ snapshots: AtomicUsize,+ snapshot: UsageSnapshot,+}++impl BillingService for FakeBilling {+ async fn snapshot(&self, _user: &MacroUserIdStr<'_>) -> Result<UsageSnapshot> {+ self.snapshots.fetch_add(1, Ordering::SeqCst);+ Ok(self.snapshot.clone())+ }++ async fn check_allowance(&self, _user: &MacroUserIdStr<'_>) -> Result<AllowanceDecision> {+ unreachable!()+ }++ async fn settle(&self, _user: &MacroUserIdStr<'_>) -> Result<()> {+ unreachable!("the recorder must use the settlement trigger")+ }++ async fn update_overage(+ &self,+ _user: &MacroUserIdStr<'_>,+ _enabled: bool,+ _limit_cents: i64,+ ) -> Result<UsageSnapshot> {+ unreachable!()+ }++ async fn create_credit_checkout(+ &self,+ _user: &MacroUserIdStr<'_>,+ _amount_cents: i64,+ _success_url: String,+ _cancel_url: String,+ ) -> Result<String> {+ unreachable!()+ }++ async fn apply_credit_purchase(+ &self,+ _payer: &MacroUserIdStr<'_>,+ _amount_cents: i64,+ _stripe_reference: &str,+ ) -> Result<()> {+ unreachable!()+ }++ async fn sync_period(+ &self,+ _payer: &MacroUserIdStr<'_>,+ _start: DateTime<Utc>,+ _end: DateTime<Utc>,+ ) -> Result<()> {+ unreachable!()+ }++ async fn mark_overage_invoice(&self, _stripe_invoice_id: &str, _paid: bool) -> Result<()> {+ unreachable!()+ }+}++#[derive(Clone, Default)]+struct FakeTrigger(Arc<AtomicUsize>);++impl SettlementTrigger for FakeTrigger {+ fn request_settlement(&self, _payer: MacroUserIdStr<'static>) {+ self.0.fetch_add(1, Ordering::SeqCst);+ }+}++async fn record(+ environment: Environment,+ user: MacroUserIdStr<'static>,+ tier: PlanTier,+ unlimited: bool,+ chargeable_cents: i64,+ fail_first: bool,+) -> (usize, usize, usize) {+ let repo = FakeUsageRepo {+ fail_first,+ ..Default::default()+ };+ let mut entitlement = Entitlement::personal(user.clone(), tier);+ entitlement.unlimited = unlimited;+ let billing = Arc::new(FakeBilling {+ snapshots: AtomicUsize::new(0),+ snapshot: build_snapshot(+ &user,+ &entitlement,+ &BillingSettings::default(),+ BillingPeriod::current(None, Utc::now()),+ 5_000,+ chargeable_cents,+ Default::default(),+ 0,+ ),+ });+ let trigger = FakeTrigger::default();+ let recorder = SettlingUsageRecorder::new(+ Arc::new(UsageServiceImpl::new(repo.clone())),+ billing.clone(),+ trigger.clone(),+ environment,+ );+ recorder.record(UsageContext::new(AiFeature::Chat, user).into_event(+ "test-model".into(),+ 10,+ 10,+ ));+ tokio::time::timeout(Duration::from_secs(2), repo.recorded.notified())+ .await+ .expect("usage must be recorded in every environment, including after a retry");+ // All fake billing/trigger calls are immediately ready; let the recording task finish.+ tokio::task::yield_now().await;+ (+ repo.attempts.load(Ordering::SeqCst),+ billing.snapshots.load(Ordering::SeqCst),+ trigger.0.load(Ordering::SeqCst),+ )+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap()+}++#[tokio::test]+async fn records_everywhere_but_only_requests_settlement_in_dev() {+ for (environment, expected) in [+ (Environment::Develop, 1),+ (Environment::Production, 0),+ (Environment::Local, 0),+ ] {+ for fail_first in [false, true] {+ let (attempts, snapshots, requests) = record(+ environment,+ user(),+ PlanTier::Premium,+ false,+ 1_000,+ fail_first,+ )+ .await;+ assert_eq!(attempts, if fail_first { 2 } else { 1 });+ assert_eq!(snapshots, expected);+ assert_eq!(requests, expected);+ }+ }+}++#[tokio::test]+async fn system_usage_never_requests_settlement() {+ assert_eq!(+ record(+ Environment::Develop,+ SYSTEM_USER_ID.clone(),+ PlanTier::Premium,+ false,+ 1_000,+ false,+ )+ .await,+ (1, 0, 0)+ );+}++#[tokio::test]+async fn dev_does_not_settle_free_unlimited_or_covered_usage() {+ for (tier, unlimited, chargeable) in [+ (PlanTier::Free, false, 1_000),+ (PlanTier::Premium, true, 1_000),+ (PlanTier::Premium, false, 0),+ ] {+ assert_eq!(+ record(+ Environment::Develop,+ user(),+ tier,+ unlimited,+ chargeable,+ false,+ )+ .await,+ (1, 1, 0)+ );+ }+}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex e63edcfecd..664227c1df 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -285,13 +285,16 @@ documents:## AI usage limits-AI usage billing is temporarily paused. Chat requests are not blocked by-Macro's credit allowance, spending cap, or failed-overage-payment state. The-app does not show usage meters, credit-purchase controls, out-of-credit dialogs,-or model usage multipliers. Normal paid-model access rules still apply.--<!-- Retained for when AI usage billing is re-enabled.-Paid plans include a monthly AI allowance (Premium $40, Max $200, at Macro's+AI usage billing is enabled only in the dev environment (`dev.macro.com/app`,+including a local frontend pointed at the dev backend). The backend enforces+allowances and settles usage only in `Environment::Develop`. In production and+local-backend environments, requests are not blocked by credits, spending caps,+or failed-overage-payment state, and usage is recorded without settlement.+Usage meters, credit controls, out-of-credit dialogs, and model usage multipliers+are hidden outside frontend development mode. Normal paid-model access rules+still apply everywhere.++In dev, paid plans include a monthly AI allowance (Premium $40, Max $200, at Macro'susage rates). When it is used up and no credits or usage billing cover therequest, 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@@ -302,7 +305,6 @@ team this moves only the payer's own seat). Team members who are not the payersee a note to ask the team owner, or a team admin to move their seat to Max.Each team seat has its own allowance; unused allowance never moves betweenmembers. The team owner's prepaid credits and usage-billing cap are shared.--->## Start a doc-scoped chat@@ -358,7 +360,7 @@ existing text sizing.- Contenteditable composer (placeholder `Ask AI, @mention anything` / `Describe the edit…`).- Model picker button showing the current model (e.g. `Haiku 4.5`). Paid plans list`Sonnet 5`, `Opus 5`, `Fable 5.1`, `Haiku 4.5`, `GPT-6 Astra`, `GPT-5.6`, `GPT-5.6 mini`;- <!-- heavy models carry a `2.5× usage` / `5× usage` hint. -->+ in dev, heavy models carry a `2.5× usage` / `5× usage` hint.On the free plan everything but `Haiku 4.5` isdimmed with a lock and opens the `Smart models are premium` paywall when clicked.- `Send` button (disabled when empty). While streaming it becomes `Stop generating`.diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 0c0130fa17..cdce7d1d95 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -1006,13 +1006,11 @@ and split navigation.Left nav: General → `Account` (profile, delete account), `API Keys` (create /list / delete personal keys; the secret is shown only once and is sent as`x-macro-user-api-key`), `Notifications`, `Billing` (current plan card with-`Manage`; AI usage meters, balances, credit purchases, and usage-billing-controls are temporarily hidden;-<!-- Retained for when AI usage billing is re-enabled: on paid plans 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; -->-an+`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`/`Upgrade to Max` card, or a `Switch to Premium` link on Max; on a teamthe plan change moves only the viewer's own seat),`Appearance`, `Agents`, `Mobile App`, `Shortcuts` (interactive keyboard visualization, not a list);diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rsindex 183f2f7a0d..c3785397d1 100644--- a/services/authentication_service/src/main.rs+++ b/services/authentication_service/src/main.rs@@ -503,6 +503,7 @@ async fn main() -> anyhow::Result<()> {ai_billing::outbound::PgUsageReader::new(db.clone()),ai_billing::outbound::PgBillingRepo::new(db.clone()),ai_billing::outbound::StripePaymentGateway::new(stripe_client.clone()),+ config.environment,));let teams_service_impl = TeamServiceImpl::new_with_analytics(teams_repo_impl.clone(),diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rsindex 07e90d72dd..7a2bbd124f 100644--- a/services/document_cognition_service/src/api/context/test.rs+++ b/services/document_cognition_service/src/api/context/test.rs@@ -527,6 +527,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arai_billing::outbound::PgUsageReader::new(pool.clone()),ai_billing::outbound::PgBillingRepo::new(pool.clone()),ai_billing::outbound::NoOpPaymentGateway,+ macro_env::Environment::Local,)),user_permissions_service,config: Arc::new(Config::new_empty_for_test()),diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rsindex d302f157e5..76c439a8e6 100644--- a/services/document_cognition_service/src/main.rs+++ b/services/document_cognition_service/src/main.rs@@ -471,6 +471,7 @@ async fn main() -> anyhow::Result<()> {ai_billing::outbound::PgUsageReader::new(db.clone()),ai_billing::outbound::PgBillingRepo::new(db.clone()),ai_billing::outbound::NoOpPaymentGateway,+ config.environment,));let auth_service_client = Arc::new(authentication_service_client::AuthServiceClient::new(internal_api_key.clone(),@@ -483,6 +484,7 @@ async fn main() -> anyhow::Result<()> {)),ai_billing.clone(),ai_billing::outbound::HttpSettlementTrigger::new(auth_service_client),+ config.environment,));// The import pipeline: staged/imported external items, gather jobs over