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(billing): improve plan cards and add local state preview (#7662)
Peter Chinmandeeac14b91ca
diff --git a/apps/marketing/src/app/routes/RoutePricing.tsx b/apps/marketing/src/app/routes/RoutePricing.tsxindex 5537c89c48..48286fb4ee 100644--- a/apps/marketing/src/app/routes/RoutePricing.tsx+++ b/apps/marketing/src/app/routes/RoutePricing.tsx@@ -242,7 +242,7 @@ const comparisonGroups: Array<{group: 'AI and agents',rows: [{ label: 'AI usage', free: 'Limited', pro: 'Standard', max: '10× Pro' },- { label: 'AI models', free: 'Haiku', pro: 'All', max: 'All' },+ { label: 'AI models', free: 'Gemini Flash', pro: 'All', max: 'All' },{label: 'Agents with workspace context',free: true,@@ -260,7 +260,7 @@ const comparisonGroups: Array<{pro: 'Unlimited',max: 'Unlimited',},- { label: 'Storage', free: '5 GB', pro: '1 TB', max: '1 TB' },+ { label: 'Storage', free: '5 GB', pro: '100 GB', max: '1 TB' },{label: 'Calls, recording, and transcription',free: false,@@ -278,21 +278,9 @@ const comparisonGroups: Array<{pro: 'Removed',max: 'Removed',},- {- label: 'Auto-shared email and CRM for your team',- free: false,- pro: true,- max: true,- },{label: 'Team-level memory for your agents',- free: false,- pro: true,- max: true,- },- {- label: 'Channel-based sharing and access control',- free: false,+ free: true,pro: true,max: true,},diff --git a/apps/web/src/features/paywall/PaywallComponent.tsx b/apps/web/src/features/paywall/PaywallComponent.tsxindex c0690ae9e5..de07a134c7 100644--- a/apps/web/src/features/paywall/PaywallComponent.tsx+++ b/apps/web/src/features/paywall/PaywallComponent.tsx@@ -29,7 +29,7 @@ const PAYWALL_PREMIUM_FEATURES = ['Multiple email inboxes','Calls','Teams',- '1 TB storage',+ '100 GB storage',];const PremiumFeatures = () => (diff --git a/apps/web/src/features/paywall/plans.ts b/apps/web/src/features/paywall/plans.tsindex cacfc72c31..fd700cb750 100644--- a/apps/web/src/features/paywall/plans.ts+++ b/apps/web/src/features/paywall/plans.ts@@ -103,7 +103,7 @@ const PLAN_FEATURE_ROWS: PlanFeature[] = [label: 'Storage',values: {free: '5 GB',- premium: '1 TB',+ premium: '100 GB',max: '1 TB',},},diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsxindex a6fe6ff177..faab1c4887 100644--- a/apps/web/src/features/settings/Billing.tsx+++ b/apps/web/src/features/settings/Billing.tsx@@ -1,18 +1,11 @@-import {- PLAN_BY_TIER,- PLAN_USAGE_LABELS,- type PlanTier,-} from '@app/features/paywall/plans';import { useAnalytics } from '@app/lib/analytics/analytics-context';-import { ShowFeatureFlag, useFeatureFlag } from '@app/lib/analytics/posthog';+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { useHasPaidAccess } from '@core/auth';import { toast } from '@core/component/Toast/Toast';-import { enableAiUsageBilling } from '@core/constant/featureFlags';+import { enableAiUsageBilling, LOCAL_ONLY } from '@core/constant/featureFlags';import { PERMISSION_IDS } from '@core/constant/permissions';import { usePermissions, useUserId } from '@core/context/user';-import { plural } from '@core/util/string';-import CheckIcon from '@phosphor/check.svg';-import EnvelopeIcon from '@phosphor/envelope.svg';+import { lazyNamed } from '@core/util/lazyNamed';import {useAiBillingSummaryQuery,useChangePlanMutation,@@ -20,88 +13,32 @@ import {} from '@queries/auth';import { useCurrentTeamQuery } from '@queries/team/teams';import type { PaidPlan } from '@service-auth/ai-billing-types';-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';-import { SettingsCard, SettingsPage, SettingsSection } from './primitives';--/**- * Plan bullet points. The allowance line appears only with AI usage billing on- * and describes usage relative to Pro.- */-const BILLING_PLAN_FEATURES: Record<- PlanTier,- (usage: string | undefined) => string[]-> = {- free: (usage) => [- 'Access to Haiku',- ...(usage ? [usage] : []),- 'MCP access',- '5 GB storage',- ],- premium: (usage) => [- 'All agents',- 'All models',- ...(usage ? [usage] : []),- 'No watermark',- 'AI projections',- 'Multiple email inboxes',- 'Calls',- 'Teams',- '1 TB storage',- ],- max: (usage) => [- 'Everything in Pro',- ...(usage ? [usage] : []),- 'Priority support',- ],-};--const PlanFeatures = (props: { tier: PlanTier }) => {- const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);- const allowance = () =>- aiUsageBilling().enabled ? PLAN_USAGE_LABELS[props.tier] : undefined;- return (- <For each={BILLING_PLAN_FEATURES[props.tier](allowance())}>- {(label) => (- <li class="flex items-center gap-2">- <CheckIcon class="size-3 text-success" />- <span class="text-ink-muted text-xs">{label}</span>- </li>- )}- </For>- );-};--/** "3 Pro seats, 1 Max seat" for a team's members. */-function describeSeatPlans(members: TeamMember[]): string {- const maxSeats = members.filter(- (member) => (member as TeamMember & { plan?: PaidPlan }).plan === 'max'- ).length;- const premiumSeats = members.length - maxSeats;- const parts: string[] = [];- if (premiumSeats > 0) {- parts.push(`${premiumSeats} Pro ${plural('seat', premiumSeats)}`);- }- if (maxSeats > 0) {- parts.push(`${maxSeats} Max ${plural('seat', maxSeats)}`);+import { createMemo, type JSX, Suspense } from 'solid-js';+import { BillingSettingsView } from './components/billing-settings-view';+import {+ getBillingState,+ getFreePlanCheckoutRequest,+} from './core/billing-state';++export function Billing() {+ if (import.meta.env.DEV && LOCAL_ONLY) {+ const BillingPreview = lazyNamed(+ () => import('./views/billing-preview'),+ 'BillingPreview'+ );+ return (+ <Suspense fallback={<p role="status">Loading billing…</p>}>+ <BillingPreview+ renderLive={(controls) => <LiveBilling controls={controls} />}+ />+ </Suspense>+ );}- return parts.join(', ');+ return <LiveBilling />;}-const PlanPrice = (props: { tier: PaidPlan }) => {- return (- <p class="text-ink-extra-muted text-xs">- ${PLAN_BY_TIER[props.tier].price} per seat / month- <ShowFeatureFlag flag={enableAiUsageBilling}>- <Show when={props.tier === 'max'}> · 10× usage</Show>- </ShowFeatureFlag>- </p>- );-};--export const Billing = () => {+function LiveBilling(props: { controls?: JSX.Element }) {const permissions = usePermissions();const analytics = useAnalytics();const hasPaid = useHasPaidAccess();@@ -117,7 +54,7 @@ export const Billing = () => {});const userTeam = createMemo(() => {- const currentTeam = team.data;+ const currentTeam = team.isSuccess ? team.data : undefined;const uid = userId();if (!currentTeam || !uid) return;@@ -133,30 +70,40 @@ export const Billing = () => {return team.owner_id === uid ? 'owner' : 'member';});- // The billing summary knows the tier (Pro vs Max); the license status is- // the fallback while it loads or when the user is on the free plan.- const tier = createMemo((): PlanTier => {- if (summary.isSuccess) return summary.data.tier;- return hasPaid() ? 'premium' : 'free';- });- // A member whose seat the team pays for manages nothing here; a member of- // a free team pays for themself and gets the same controls as a solo user.- const billedThroughTeam = () =>- summary.isSuccess &&- !summary.data.can_manage_billing &&- summary.data.tier !== 'free';- const isOwnerOrSolo = () =>- !teamRole() || teamRole() === 'owner' || !billedThroughTeam();- const canChangePlan = () => canManageSubscription() && isOwnerOrSolo();+ const state = () =>+ getBillingState({+ hasPaid: hasPaid(),+ canManageSubscription: team.isSuccess && canManageSubscription() === true,+ teamRole: teamRole(),+ teamPlans: team.isSuccess+ ? team.data?.members.map((member) =>+ (member as typeof member & { plan?: PaidPlan }).plan === 'max'+ ? 'max'+ : 'premium'+ )+ : undefined,+ summary: summary.isSuccess+ ? {+ tier: summary.data.tier,+ canManageBilling: summary.data.can_manage_billing,+ }+ : undefined,+ aiUsageEnabled: aiUsageBilling().enabled,+ pending: checkout.isPending || changePlan.isPending,+ });const handleCheckout = async (plan: PaidPlan) => {try {- const url = await checkout.mutateAsync({ plan });+ const url = await checkout.mutateAsync(getFreePlanCheckoutRequest(plan));analytics.track('subscription_start', { type: plan });window.location.href = url;} catch (error) {console.error(error);- toast.failure("Couldn't start checkout. Please try again.");+ toast.failure(+ error instanceof Error+ ? error.message.replace(/Premium/g, 'Pro')+ : "Couldn't start checkout. Please try again."+ );}};@@ -187,199 +134,13 @@ export const Billing = () => {};return (- <SettingsPage- title="Billing"- description={- <>- For questions about billing,{' '}- <a- class="text-link hover:text-link-hover visited:text-link-visited inline-flex items-center"- href="mailto:[email protected]"- >- contact us- <EnvelopeIcon class="size-4 inline mx-1" />- </a>- </>+ <BillingSettingsView+ state={state()}+ controls={props.controls}+ onManage={() => void handleManage()}+ onSelectPlan={(plan) =>+ void (hasPaid() ? handleChangePlan(plan) : handleCheckout(plan))}- >- <SettingsSection title="Subscription">- <SettingsCard>- <section class="flex flex-col gap-4 p-4">- <header class="flex items-center gap-2">- <div class="flex flex-col gap-1">- <div class="flex items-center gap-2">- <h2 class="text-lg font-medium text-ink">- {PLAN_BY_TIER[tier()].name} plan- </h2>-- <Layer depth={3}>- <span class="text-xs text-ink-muted px-1.5 py-0.25 border border-edge-muted rounded-md bg-active">- Current- </span>- </Layer>- </div>- <Switch>- <Match when={teamRole() === 'member' && billedThroughTeam()}>- <p class="text-ink-extra-muted text-xs">- Your seat is billed through your team. Team admins choose- each seat's plan in{' '}- <a- class="text-link hover:text-link-hover"- href="/app/settings/team"- >- Team settings- </a>- .- </p>- </Match>- <Match- when={hasPaid() && teamRole() === 'owner' && team.data}- >- {(team) => (- <p class="text-ink-extra-muted text-xs">- {team().members.length}{' '}- {plural('user', team().members.length)} •{' '}- {describeSeatPlans(team().members)} • set each seat's- plan in{' '}- <a- class="text-link hover:text-link-hover"- href="/app/settings/team"- >- Team settings- </a>- </p>- )}- </Match>- </Switch>- </div>-- <Show- when={canManageSubscription() && hasPaid() && isOwnerOrSolo()}- >- <Button- class="ml-auto bg-active"- size="sm"- depth={2}- variant="outline"- onClick={handleManage}- >- Manage- </Button>- </Show>- </header>- <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">- <PlanFeatures tier={tier()} />- </ul>- </section>- </SettingsCard>- </SettingsSection>-- <Show when={canChangePlan()}>- <Switch>- <Match when={!hasPaid()}>- <SettingsSection title="Upgrade">- <SettingsCard>- <section class="flex flex-col gap-4 p-4">- <header class="flex items-center gap-2">- <div class="flex flex-col">- <h2 class="text-lg font-medium text-ink">Pro</h2>- <PlanPrice tier="premium" />- </div>- <Button- class="ml-auto py-1.5 px-3"- depth={2}- variant="cta"- onClick={() => void handleCheckout('premium')}- >- Upgrade now- </Button>- </header>- <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">- <PlanFeatures tier="premium" />- </ul>- </section>- </SettingsCard>- <SettingsCard>- <section class="flex flex-col gap-4 p-4">- <header class="flex items-center gap-2">- <div class="flex flex-col">- <h2 class="text-lg font-medium text-ink">Max</h2>- <PlanPrice tier="max" />- </div>- <Button- class="ml-auto py-1.5 px-3"- depth={2}- variant="outline"- onClick={() => void handleCheckout('max')}- >- Get Max- </Button>- </header>- <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">- <PlanFeatures tier="max" />- </ul>- </section>- </SettingsCard>- </SettingsSection>- </Match>- <Match when={tier() === 'premium'}>- <SettingsSection- title={aiUsageBilling().enabled ? 'Need more AI?' : 'Upgrade'}- >- <SettingsCard>- <section class="flex flex-col gap-4 p-4">- <header class="flex items-center gap-2">- <div class="flex flex-col">- <h2 class="text-lg font-medium text-ink">Max</h2>- <PlanPrice tier="max" />- </div>- <Button- class="ml-auto py-1.5 px-3"- depth={2}- variant="cta"- disabled={changePlan.isPending}- onClick={() => void handleChangePlan('max')}- >- Upgrade to Max- </Button>- </header>- <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">- <PlanFeatures tier="max" />- </ul>- <p class="text-xs text-ink-extra-muted">- Prorated for the rest of this period.- <Show when={teamRole() === 'owner'}>- {' '}- This moves only your seat; teammates' plans are set per- seat in Team settings.- </Show>- </p>- </section>- </SettingsCard>- </SettingsSection>- </Match>- <Match when={tier() === 'max'}>- <SettingsSection>- <p class="px-6 text-xs text-ink-extra-muted">- Want a smaller plan?{' '}- <button- type="button"- class="text-link hover:text-link-hover"- disabled={changePlan.isPending}- onClick={() => void handleChangePlan('premium')}- >- Switch to Pro- </button>{' '}- (${PLAN_BY_TIER.premium.price} per seat / month- <ShowFeatureFlag flag={enableAiUsageBilling}>- with standard usage- </ShowFeatureFlag>- ).- </p>- </SettingsSection>- </Match>- </Switch>- </Show>- </SettingsPage>+ />);-};+}diff --git a/apps/web/src/features/settings/components/billing-settings-view.tsx b/apps/web/src/features/settings/components/billing-settings-view.tsxnew file mode 100644index 0000000000..a2963a8176--- /dev/null+++ b/apps/web/src/features/settings/components/billing-settings-view.tsx@@ -0,0 +1,289 @@+import {+ type PaidPlanTier,+ PLAN_BY_TIER,+ PLAN_USAGE_LABELS,+ type PlanTier,+} from '@app/features/paywall/plans';+import { plural } from '@core/util/string';+import CheckIcon from '@phosphor/check.svg';+import EnvelopeIcon from '@phosphor/envelope.svg';+import { Button, Layer } from '@ui';+import { For, type JSX, Match, Show, Switch } from 'solid-js';+import { type BillingState, describeSeatPlans } from '../core/billing-state';+import { SettingsCard, SettingsPage } from '../primitives';++/**+ * Plan bullet points. Free and Pro allowance labels require AI usage billing;+ * Max always explains its larger allowance relative to Pro.+ */+const BILLING_PLAN_FEATURES: Record<+ PlanTier,+ (usage: string | undefined) => string[]+> = {+ free: (usage) => [+ 'Access to Haiku',+ ...(usage ? [usage] : []),+ 'MCP access',+ '2 connected email accounts',+ '5 GB storage',+ ],+ premium: (usage) => [+ 'All agents',+ 'All models',+ ...(usage ? [usage] : []),+ 'No email watermark',+ 'AI projections',+ 'Unlimited connected email accounts',+ 'Calls',+ 'Teams',+ 'Team-level memory',+ '100 GB storage',+ ],+ max: () => [+ 'Everything in Pro',+ '10x more AI usage than Pro',+ 'Unlimited connected email accounts',+ 'Team-level memory',+ '1 TB storage',+ 'Priority support',+ ],+};++const PlanFeatures = (props: { tier: PlanTier; aiUsageEnabled: boolean }) => {+ const allowance = () =>+ props.aiUsageEnabled ? PLAN_USAGE_LABELS[props.tier] : undefined;+ return (+ <For each={BILLING_PLAN_FEATURES[props.tier](allowance())}>+ {(label) => (+ <li class="flex items-center gap-2">+ <CheckIcon class="size-3 text-success" />+ <span class="text-ink-muted text-xs">{label}</span>+ </li>+ )}+ </For>+ );+};++const PlanPrice = (props: {+ tier: PaidPlanTier;+ perSeat: boolean;+ aiUsageEnabled: boolean;+}) => {+ return (+ <p class="text-ink-extra-muted text-xs">+ ${PLAN_BY_TIER[props.tier].price}{' '}+ {props.perSeat ? 'per seat / month' : '/ month'}+ <Show when={props.aiUsageEnabled}>+ <Show when={props.tier === 'max'}> · 10× usage</Show>+ </Show>+ </p>+ );+};++export function BillingSettingsView(props: {+ state: BillingState;+ controls?: JSX.Element;+ onManage: () => void;+ onSelectPlan: (plan: PaidPlanTier) => void;+ onTeamSettings?: JSX.EventHandler<HTMLAnchorElement, MouseEvent>;+}) {+ return (+ <SettingsPage+ title="Billing"+ description={+ <>+ For questions about billing,{' '}+ <a+ class="text-link hover:text-link-hover visited:text-link-visited inline-flex items-center"+ href="mailto:[email protected]"+ >+ contact us+ <EnvelopeIcon class="size-4 inline mx-1" />+ </a>+ </>+ }+ >+ {props.controls}+ <section+ data-settings-target="subscription"+ tabIndex={-1}+ class="flex scroll-mt-4 flex-col gap-4 outline-none"+ >+ <h2 class="text-base font-medium text-ink">Subscription</h2>+ <SettingsCard>+ <section class="flex flex-col gap-4 p-5">+ <header class="flex items-center gap-2">+ <div class="flex flex-col gap-1">+ <div class="flex items-center gap-2">+ <h3 class="text-lg font-medium text-ink">+ {PLAN_BY_TIER[props.state.tier].name} plan+ </h3>++ <Layer depth={3}>+ <span class="text-xs text-ink-muted px-1.5 py-0.25 border border-edge-muted rounded-md bg-active">+ Current+ </span>+ </Layer>+ </div>+ <Switch>+ <Match+ when={+ props.state.teamRole === 'member' &&+ props.state.billedThroughTeam+ }+ >+ <p class="text-ink-extra-muted text-xs">+ Your seat is billed through your team. Team admins choose+ each seat's plan in{' '}+ <a+ class="text-link hover:text-link-hover"+ href="/app/settings/team"+ onClick={props.onTeamSettings}+ >+ Team settings+ </a>+ .+ </p>+ </Match>+ <Match+ when={+ props.state.hasPaid &&+ props.state.teamRole === 'owner' &&+ props.state.teamPlans+ }+ >+ {(plans) => (+ <p class="text-ink-extra-muted text-xs">+ {plans().length} {plural('user', plans().length)} •{' '}+ {describeSeatPlans(plans())} • set each seat's plan in{' '}+ <a+ class="text-link hover:text-link-hover"+ href="/app/settings/team"+ onClick={props.onTeamSettings}+ >+ Team settings+ </a>+ </p>+ )}+ </Match>+ </Switch>+ </div>++ <Show when={props.state.canChangePlan && props.state.hasPaid}>+ <Button+ class="ml-auto bg-active"+ size="sm"+ depth={2}+ variant="outline"+ onClick={props.onManage}+ >+ Manage+ </Button>+ </Show>+ </header>+ <ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted">+ <PlanFeatures+ tier={props.state.tier}+ aiUsageEnabled={props.state.aiUsageEnabled}+ />+ </ul>+ </section>+ </SettingsCard>+ </section>++ <Show when={props.state.canChangePlan}>+ <section+ data-settings-target="upgrade"+ tabIndex={-1}+ class="@container/plan-options flex scroll-mt-4 flex-col gap-4 outline-none"+ >+ <h2 class="text-base font-medium text-ink">+ {props.state.tier === 'max'+ ? 'Change plan'+ : props.state.hasPaid && props.state.aiUsageEnabled+ ? 'Need more AI?'+ : 'Upgrade'}+ </h2>+ <div+ class="grid grid-cols-1 gap-6"+ classList={{+ '@2xl/plan-options:grid-cols-2': !props.state.hasPaid,+ }}+ >+ <For+ each={(['premium', 'max'] as const).filter(+ (plan) => !props.state.hasPaid || plan !== props.state.tier+ )}+ >+ {(plan) => (+ <SettingsCard class="@container/plan-card h-full">+ <section class="flex h-full flex-col gap-4 p-5">+ <header class="grid grid-cols-1 items-center gap-4 @sm/plan-card:grid-cols-[minmax(0,1fr)_auto]">+ <div class="flex min-w-0 flex-col gap-1">+ <div class="flex flex-wrap items-center gap-2">+ <h3 class="text-lg font-medium text-ink">+ {PLAN_BY_TIER[plan].name}+ </h3>+ <Show+ when={!props.state.hasPaid && plan === 'premium'}+ >+ <span class="text-sm font-medium text-accent">+ Free for one month!+ </span>+ </Show>+ </div>+ <PlanPrice+ tier={plan}+ perSeat={!!props.state.teamRole}+ aiUsageEnabled={props.state.aiUsageEnabled}+ />+ </div>+ <Button+ class="w-full py-1.5 px-3 @sm/plan-card:w-auto @sm/plan-card:justify-self-end"+ depth={2}+ variant="cta"+ disabled={props.state.pending}+ onClick={() => props.onSelectPlan(plan)}+ >+ {props.state.hasPaid+ ? plan === 'premium'+ ? 'Switch to Pro'+ : 'Upgrade to Max'+ : plan === 'premium'+ ? 'Get Pro'+ : 'Get Max'}+ </Button>+ </header>+ <ul class="border-t border-t-edge-muted pt-4 flex flex-col gap-3 text-sm text-ink-muted">+ <PlanFeatures+ tier={plan}+ aiUsageEnabled={props.state.aiUsageEnabled}+ />+ </ul>+ <Show+ when={+ props.state.hasPaid &&+ (plan === 'max' || props.state.teamRole === 'owner')+ }+ >+ <p class="text-xs text-ink-extra-muted">+ <Show when={plan === 'max'}>+ Prorated for the rest of this period.+ </Show>+ <Show when={props.state.teamRole === 'owner'}>+ {' '}+ This moves only your seat; teammates' plans are set+ per seat in Team settings.+ </Show>+ </p>+ </Show>+ </section>+ </SettingsCard>+ )}+ </For>+ </div>+ </section>+ </Show>+ </SettingsPage>+ );+}diff --git a/apps/web/src/features/settings/core/billing-state.test.ts b/apps/web/src/features/settings/core/billing-state.test.tsnew file mode 100644index 0000000000..f45791cbe4--- /dev/null+++ b/apps/web/src/features/settings/core/billing-state.test.ts@@ -0,0 +1,90 @@+import type { PlanTier } from '@app/features/paywall/plans';+import { describe, expect, it } from 'vitest';+import {+ type BillingInput,+ describeSeatPlans,+ getBillingState,+ getFreePlanCheckoutRequest,+} from './billing-state';++const baseline: BillingInput = {+ hasPaid: false,+ canManageSubscription: true,+ aiUsageEnabled: false,+ pending: false,+};++describe('billing presentation policy', () => {+ it('requests a confirmed first-month trial when a Free account selects Pro', () => {+ expect(getFreePlanCheckoutRequest('premium')).toEqual({+ plan: 'premium',+ onboardingTrial: true,+ });+ });++ it('keeps Max checkout on paid terms', () => {+ expect(getFreePlanCheckoutRequest('max')).toEqual({+ plan: 'max',+ onboardingTrial: false,+ });+ });++ it.each<PlanTier>(['free', 'premium', 'max'])(+ 'hides options for a team-paid member on %s',+ (tier) => {+ expect(+ getBillingState({+ ...baseline,+ teamRole: 'member',+ hasPaid: tier !== 'free',+ summary: { tier, canManageBilling: false },+ }).canChangePlan+ ).toBe(false);+ }+ );++ it.each([undefined, 'owner', 'member'] as const)(+ 'allows a confirmed payer with role %s, but still requires subscription permission',+ (teamRole) => {+ const input: BillingInput = {+ ...baseline,+ teamRole,+ summary: { tier: 'free', canManageBilling: true },+ };+ expect(getBillingState(input).canChangePlan).toBe(true);+ expect(+ getBillingState({ ...input, canManageSubscription: false })+ .canChangePlan+ ).toBe(false);+ }+ );++ it.each([false, true])(+ 'uses the license fallback while hiding unconfirmed member options (paid=%s)',+ (hasPaid) => {+ const state = getBillingState({+ ...baseline,+ hasPaid,+ teamRole: 'member',+ });+ expect(state.tier).toBe(hasPaid ? 'premium' : 'free');+ expect(state.canChangePlan).toBe(false);+ }+ );++ it('prefers the resolved Max tier over the paid license fallback', () => {+ expect(+ getBillingState({+ ...baseline,+ hasPaid: true,+ summary: { tier: 'max', canManageBilling: true },+ }).tier+ ).toBe('max');+ });++ it('describes mixed seat plans without conflating Pro and Max', () => {+ expect(describeSeatPlans(['premium', 'premium', 'max'])).toBe(+ '2 Pro seats, 1 Max seat'+ );+ });+});diff --git a/apps/web/src/features/settings/core/billing-state.ts b/apps/web/src/features/settings/core/billing-state.tsnew file mode 100644index 0000000000..67afdf7a97--- /dev/null+++ b/apps/web/src/features/settings/core/billing-state.ts@@ -0,0 +1,45 @@+import type { PaidPlanTier, PlanTier } from '@app/features/paywall/plans';++export type BillingInput = {+ hasPaid: boolean;+ canManageSubscription: boolean;+ teamRole?: 'owner' | 'member';+ teamPlans?: readonly PaidPlanTier[];+ summary?: { tier: PlanTier; canManageBilling: boolean };+ aiUsageEnabled: boolean;+ pending: boolean;+};++/** Shared presentation policy for live billing and local previews. */+export function getBillingState(input: BillingInput) {+ const tier = input.summary?.tier ?? (input.hasPaid ? 'premium' : 'free');+ const billedThroughTeam = input.summary?.canManageBilling === false;+ const isOwnerOrSolo =+ !input.teamRole ||+ input.teamRole === 'owner' ||+ input.summary?.canManageBilling === true;+ return {+ ...input,+ tier,+ billedThroughTeam,+ canChangePlan: input.canManageSubscription && isOwnerOrSolo,+ };+}++export type BillingState = ReturnType<typeof getBillingState>;++/** Free accounts get the same server-validated Pro trial as onboarding. */+export function getFreePlanCheckoutRequest(plan: PaidPlanTier) {+ return { plan, onboardingTrial: plan === 'premium' };+}++export function describeSeatPlans(plans: readonly PaidPlanTier[]): string {+ const maxSeats = plans.filter((plan) => plan === 'max').length;+ const proSeats = plans.length - maxSeats;+ return [+ proSeats ? `${proSeats} Pro ${proSeats === 1 ? 'seat' : 'seats'}` : '',+ maxSeats ? `${maxSeats} Max ${maxSeats === 1 ? 'seat' : 'seats'}` : '',+ ]+ .filter(Boolean)+ .join(', ');+}diff --git a/apps/web/src/features/settings/views/billing-preview.tsx b/apps/web/src/features/settings/views/billing-preview.tsxnew file mode 100644index 0000000000..6bffb1602a--- /dev/null+++ b/apps/web/src/features/settings/views/billing-preview.tsx@@ -0,0 +1,231 @@+import { PLAN_BY_TIER, type PlanTier } from '@app/features/paywall/plans';+import { Button } from '@ui';+import { createSignal, For, type JSX, Show } from 'solid-js';+import { BillingSettingsView } from '../components/billing-settings-view';+import { getBillingState } from '../core/billing-state';++type Account = 'solo' | 'team-member' | 'self-paying-member' | 'team-owner';+type SummaryStatus = 'loaded' | 'loading' | 'failed';++function PreviewSelect<T extends string>(props: {+ label: string;+ value: T;+ options: readonly { value: T; label: string }[];+ onChange: (value: T) => void;+}) {+ return (+ <label class="flex min-w-0 flex-col gap-1 text-xs text-ink-muted">+ {props.label}+ <select+ class="rounded-lg border border-edge-muted bg-input px-3 py-2 text-sm text-ink"+ value={props.value}+ onChange={(event) => {+ const option = props.options.find(+ (option) => option.value === event.currentTarget.value+ );+ if (option) props.onChange(option.value);+ }}+ >+ <For each={props.options}>+ {(option) => <option value={option.value}>{option.label}</option>}+ </For>+ </select>+ </label>+ );+}++function PreviewCheckbox(props: {+ label: string;+ checked: boolean;+ onChange: (checked: boolean) => void;+}) {+ return (+ <label class="flex items-center gap-2 py-2 text-sm text-ink">+ <input+ type="checkbox"+ checked={props.checked}+ onChange={(event) => props.onChange(event.currentTarget.checked)}+ />+ {props.label}+ </label>+ );+}++/** Only loaded by Billing under the local HMR gate. No live billing capabilities. */+export function BillingPreview(props: {+ renderLive: (controls: JSX.Element) => JSX.Element;+}) {+ const [active, setActive] = createSignal(false);+ const [account, setAccount] = createSignal<Account>('solo');+ const [plan, setPlan] = createSignal<PlanTier>('free');+ const [summaryStatus, setSummaryStatus] =+ createSignal<SummaryStatus>('loaded');+ const [hasPaid, setHasPaid] = createSignal(false);+ const [permission, setPermission] = createSignal(true);+ const [aiUsage, setAiUsage] = createSignal(false);+ const [pending, setPending] = createSignal(false);+ const [action, setAction] = createSignal('');+ const state = () =>+ getBillingState({+ hasPaid: hasPaid(),+ canManageSubscription: permission(),+ teamRole:+ account() === 'solo'+ ? undefined+ : account() === 'team-owner'+ ? 'owner'+ : 'member',+ teamPlans: ['premium', 'premium', 'max'],+ summary:+ summaryStatus() === 'loaded'+ ? { tier: plan(), canManageBilling: account() !== 'team-member' }+ : undefined,+ aiUsageEnabled: aiUsage(),+ pending: pending(),+ });+ const reset = () => {+ setAccount('solo');+ setPlan('free');+ setSummaryStatus('loaded');+ setHasPaid(false);+ setPermission(true);+ setAiUsage(false);+ setPending(false);+ setAction('');+ };++ return (+ <Show+ when={active()}+ fallback={props.renderLive(+ <div class="flex flex-wrap items-center gap-3">+ <Button size="sm" variant="outline" onClick={() => setActive(true)}>+ Preview billing states+ </Button>+ <span class="text-xs text-ink-muted">Local development</span>+ </div>+ )}+ >+ <BillingSettingsView+ state={state()}+ controls={+ <section aria-label="Billing preview" class="flex flex-col gap-4">+ <div class="flex flex-wrap items-center justify-between gap-3">+ <p class="text-sm text-ink-muted">+ Local preview · billing actions are simulated+ </p>+ <div class="flex flex-wrap gap-2">+ <Button size="sm" variant="outline" onClick={reset}>+ Reset preview+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() => {+ reset();+ setActive(false);+ }}+ >+ Exit preview+ </Button>+ </div>+ </div>+ <div class="grid grid-cols-1 gap-4 @sm:grid-cols-2">+ <PreviewSelect+ label="Account"+ value={account()}+ options={[+ { value: 'solo', label: 'Solo' },+ { value: 'team-member', label: 'Team member · team pays' },+ {+ value: 'self-paying-member',+ label: 'Team member · pays for own seat',+ },+ { value: 'team-owner', label: 'Team owner' },+ ]}+ onChange={(value) => {+ setAccount(value);+ setAction('');+ }}+ />+ <PreviewSelect+ label="Plan"+ value={plan()}+ options={(['free', 'premium', 'max'] as const).map((tier) => ({+ value: tier,+ label: PLAN_BY_TIER[tier].name,+ }))}+ onChange={(value) => {+ setPlan(value);+ setHasPaid(value !== 'free');+ setAction('');+ }}+ />+ </div>+ <details>+ <summary class="text-sm text-ink-muted">+ Permissions, loading, and feature states+ </summary>+ <div class="mt-3 flex flex-col gap-3">+ <PreviewSelect+ label="Billing summary"+ value={summaryStatus()}+ options={[+ { value: 'loaded', label: 'Loaded' },+ { value: 'loading', label: 'Loading' },+ { value: 'failed', label: 'Failed' },+ ]}+ onChange={setSummaryStatus}+ />+ <div class="flex flex-wrap gap-x-6">+ <PreviewCheckbox+ label="Billing permission"+ checked={permission()}+ onChange={setPermission}+ />+ <PreviewCheckbox+ label="Active or trialing license"+ checked={hasPaid()}+ onChange={setHasPaid}+ />+ <PreviewCheckbox+ label="AI usage billing enabled"+ checked={aiUsage()}+ onChange={setAiUsage}+ />+ <PreviewCheckbox+ label="Plan action pending"+ checked={pending()}+ onChange={setPending}+ />+ </div>+ </div>+ </details>+ <p role="status" class="text-xs text-ink-muted">+ {action() ||+ (state().canChangePlan+ ? 'Personal plan options available'+ : 'Personal plan options hidden')}+ </p>+ </section>+ }+ onManage={() =>+ setAction(+ 'Preview only · Manage subscription · no billing changes made'+ )+ }+ onSelectPlan={(tier) =>+ setAction(+ `Preview only · ${hasPaid() ? 'Change plan' : 'Checkout'}: ${PLAN_BY_TIER[tier].name} · no billing changes made`+ )+ }+ onTeamSettings={(event) => {+ event.preventDefault();+ setAction(+ 'Preview only · Team settings manages teammates’ seat plans'+ );+ }}+ />+ </Show>+ );+}diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex ca5030d0f2..79a477bb87 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2234,11 +2234,32 @@ Usage controls, including usage-limit dialogs. Dev tools remain interactive:Free and paid previews can be combined with this state, and `Reset preview`restores the normal dev view.-`Billing` shows the current plan and `Manage`, an `Upgrade` section for Free-users with Premium (`Upgrade now`) and Max (`Get Max`), an `Upgrade to Max` card-on Premium, and a `Switch to Premium` link on Max. On a team, a plan change moves-only the viewer's own seat. Plan allowance copy uses the backend catalog and-still follows the `enable-ai-usage-billing` flag; usage controls live in Usage.+`Billing` shows the current plan and `Manage`. Free users see separate Pro+(`Get Pro`) and Max (`Get Max`) cards, side by side when the panel is wide enough+and stacked on narrow panels. The Pro card shows `Free for one month!` for Free+users. `Get Pro` requests the same server-validated 30-day first-subscription+trial as onboarding; checkout redirects only after the server confirms the trial.+Ineligible accounts see the rejection reason and are not silently charged.+`Get Max` keeps standard paid terms. Prices read `/ month` for solo users and+`per seat / month` for team accounts. Each card puts its button beside the price when wide enough and below+the price when narrow. Free lists 2 connected email accounts; Pro and Max list+unlimited connected email accounts. Pro users see a Max card (`Upgrade to Max`); Max+users see a Pro card (`Switch to Pro`). Cards appear only for users who can+manage their subscription. Team-paid members see no plan options, including+on Free seats. Member options stay hidden until the billing summary confirms+they pay for their own seat. On a team, a plan change moves only the viewer's+own seat. Max lists "10x more AI usage than Pro"; Free and Pro allowance labels+still follow the `enable-ai-usage-billing` flag. Usage controls live in Usage.++On a local HMR dev server, `Preview billing states` opens an opt-in preview in+Billing. Choose Solo, a team-paid member, a self-paying member, or a team owner,+and Free, Pro, or Max. `Permissions, loading, and feature states` exposes the+billing summary status, billing permission, active/trialing license, AI usage+flag, and pending plan actions. The preview uses the real Billing UI with local+fixtures; checkout, plan changes, Manage, and Team settings only show preview+status messages. `Reset preview` restores Solo/Free; `Exit preview` restores+the signed-in account. State is not persisted and resets on leaving Billing.+These controls are excluded from deployed builds, including dev.macro.com.`Team` (members list; on a paid team each row shows the seat's plan,and admins/owners can move a seat between Premium and Max with the `Seat plan`