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
fix(billing): restore paid Pro signup and guard duplicate checkout (#8164)
Peter Chinman53c4d3e71443
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 0ca215be01..4f15a42bad 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -100,6 +100,16 @@ the startup bundle, and Lexical nodes.## Notes- Don't shy away from pulling good examples into context. In the case of solid-primtiives/kobalte try reading documentation, or just temp clone into /tmp to reference+## Subscription offers++Use `useTrialEligibilityQuery` for trial copy and checkout terms in Billing,+paywall, and onboarding. Never infer first-subscription eligibility from Free+access or legacy `hasTrialed`; show trial copy only for confirmed eligibility,+and keep Pro checkout disabled while eligibility is unknown. Refresh the offer+on focus/reconnect; route existing subscriptions to billing management. Keep+known management access through refetch failures, but hide unconfirmed trials.+Reset rejected checkout offers before refetching eligibility.+## iOS gotcha: Web Workers must be lazyOn iOS WKWebView, eagerly constructing an ES module Web Worker (`new Worker(url, { type: 'module' })`) whose script is served via the `tauri://` custom URL scheme **deadlocks the WebContent process**. The worker thread parks in WebKit's sync module loader waiting for an IPC response that never wakes it; JS execution silently stops after that point.diff --git a/apps/web/src/features/billing-lab/create-billing-lab.ts b/apps/web/src/features/billing-lab/create-billing-lab.tsindex beb74ed743..86dbe9e6b1 100644--- a/apps/web/src/features/billing-lab/create-billing-lab.ts+++ b/apps/web/src/features/billing-lab/create-billing-lab.ts@@ -100,6 +100,7 @@ export function createBillingLab(initial: ScenarioId) {return plan ? { plan, effectiveAt: state().periodEnd } : undefined;},hasPaid: () => state().tier !== 'free',+ trialEligible: () => state().tier === 'free',aiUsageBilling: () => state().status !== 'before-launch',teamRole: () =>state().role === 'solo'diff --git a/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts b/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.tsindex 02b24e60a3..6c90d4ca32 100644--- a/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts+++ b/apps/web/src/features/onboarding/browser-test/onboarding.browser.e2e.ts@@ -681,3 +681,75 @@ test('enables an existing native tool without reconnecting', async ({expect((await fakeWorld(page)).connectedTools).toEqual([]);expect((await fakeWorld(page)).nativeTools[0].enabled).toBe(true);});++for (const width of [1280, 390]) {+ test(`returning customer buys Pro without a trial at ${width}px`, async ({+ page,+ }) => {+ await page.setViewportSize({ width, height: 900 });+ await openFixture(page, '/?view=flow', { trialEligible: false });+ await page.evaluate(() => {+ sessionStorage.setItem(+ 'onboarding-flow-step',+ JSON.stringify({ user: 'macro|[email protected]', step: 'plan' })+ );+ });+ await page.reload();+ await expect(heading(page, 'Get more with Pro.')).toBeVisible();+ await expect(page.getByText('Free Claude & GPT for 30 days.')).toHaveCount(+ 0+ );+ await expect(+ page.getByRole('button', { name: 'Start 30 day trial' })+ ).toHaveCount(0);+ await expect(+ page.getByText('30 days free, then', { exact: false })+ ).toHaveCount(0);+ await page.getByRole('button', { name: 'Get Pro', exact: true }).click();+ await expectLanded(page, 'Entered Macro at /home');+ });+}++test.describe('subscription recovery', () => {+ test.use({ hasTouch: true });+ for (const width of [1280, 390]) {+ test(`existing subscription opens management without replacement at ${width}px${width === 390 ? ' after eligibility fails' : ''}`, async ({+ page,+ }) => {+ await page.setViewportSize({ width, height: 900 });+ await openFixture(page, '/?view=flow', {+ trialEligible: false,+ existingSubscription: true,+ failures: width === 390 ? { trialEligibility: 'offline' } : {},+ });+ await page.evaluate(() =>+ sessionStorage.setItem(+ 'onboarding-flow-step',+ JSON.stringify({ user: 'macro|[email protected]', step: 'plan' })+ )+ );+ await page.reload();+ await expect(heading(page, 'Manage your subscription.')).toBeVisible();+ await expect(+ page.getByText('30 days free, then', { exact: false })+ ).toHaveCount(0);+ await expect(+ page.getByRole('button', { name: 'Continue with Pro', exact: true })+ ).toBeDisabled();+ await expect(+ page.getByRole('button', { name: 'Continue with Max', exact: true })+ ).toBeDisabled();+ await page+ .getByRole('button', { name: 'Manage subscription', exact: true })+ .tap();+ const calls = await page.evaluate(() => window.onboardingFixture.calls());+ expect(calls).toContain('manageSubscription');+ expect(calls.some((call) => call.startsWith('checkout:'))).toBe(false);+ expect(+ await page.evaluate(+ () => document.documentElement.scrollWidth <= innerWidth+ )+ ).toBe(true);+ });+ }+});diff --git a/apps/web/src/features/onboarding/components/plan-comparison.tsx b/apps/web/src/features/onboarding/components/plan-comparison.tsxindex d76061260a..28ee055d92 100644--- a/apps/web/src/features/onboarding/components/plan-comparison.tsx+++ b/apps/web/src/features/onboarding/components/plan-comparison.tsx@@ -7,6 +7,8 @@ import { PLAN_COMPARISON } from '../core/plan-comparison';export function PlanComparison(props: {catalog: Loadable<AiPlanCatalog>;disabled: boolean;+ trialEligible: boolean;+ existingSubscription: boolean;onRetry: () => void;onContinueFree: () => void;onBackToPro: () => void;@@ -65,7 +67,11 @@ export function PlanComparison(props: {'$0') : (<>- <Show when={plan.tier === 'premium'}>+ <Show+ when={+ plan.tier === 'premium' && props.trialEligible+ }+ >30 days free, then{' '}</Show><span class="block whitespace-nowrap max-[375px]:text-[10px]">@@ -113,6 +119,7 @@ export function PlanComparison(props: {type="button"disabled={props.disabled ||+ (plan.tier !== 'free' && props.existingSubscription) ||(plan.tier === 'max' &&!entries().find((item) => item.tier === 'max')?.purchasable)diff --git a/apps/web/src/features/onboarding/context/onboarding-context.tsx b/apps/web/src/features/onboarding/context/onboarding-context.tsxindex f160fba8e4..40acf3b259 100644--- a/apps/web/src/features/onboarding/context/onboarding-context.tsx+++ b/apps/web/src/features/onboarding/context/onboarding-context.tsx@@ -120,6 +120,13 @@ export type OnboardingContext = {joinTeam(inviteId: string): Promise<void>;/** The invite promotion the account holds; null when it has none. */createInviteOffer(): Accessor<Loadable<InviteOffer | null>>;+ createTrialEligibility(): {+ eligibility: Accessor<Loadable<boolean>>;+ existingSubscription: Accessor<boolean>;+ managing: Accessor<boolean>;+ manage(): Promise<void>;+ retry(): void;+ };createPlanCatalog(): {catalog: Accessor<Loadable<AiPlanCatalog>>;retry(): void;diff --git a/apps/web/src/features/onboarding/create-app-onboarding-context.ts b/apps/web/src/features/onboarding/create-app-onboarding-context.tsindex 3b3a8cafca..e1437a564d 100644--- a/apps/web/src/features/onboarding/create-app-onboarding-context.ts+++ b/apps/web/src/features/onboarding/create-app-onboarding-context.ts@@ -7,8 +7,10 @@ import { useAddInboxFlow } from '@core/email-link';import { idToDisplayName, idToEmail } from '@core/user/util';import {useAiBillingPlansQuery,+ useCreateBillingPortalMutation,useCreateCheckoutSessionMutation,useGithubLinkStatusQuery,+ useTrialEligibilityQuery,} from '@queries/auth';import { useCompleteTutorialMutation } from '@queries/auth/tutorial';import { type UserInfoData, useUserInfoQuery } from '@queries/auth/user-info';@@ -88,6 +90,7 @@ export function createAppOnboardingContext(): OnboardingContext {const createTeam = useCreateTeamWithInvitesMutation();const joinTeam = useJoinTeamMutation();const checkout = useCreateCheckoutSessionMutation();+ const billingPortal = useCreateBillingPortalMutation();const completeOnboarding = useCompleteOnboardingMutation();const completeTutorial = useCompleteTutorialMutation();const connectTool = createOnboardingToolConnect();@@ -226,6 +229,33 @@ export function createAppOnboardingContext(): OnboardingContext {const query = useGtmInviteOfferQuery({ enabled: needsOnboarding });return () => loadableQuery(query, (offer) => offer ?? null);},+ createTrialEligibility: () => {+ const query = useTrialEligibilityQuery({ enabled: needsOnboarding });+ return {+ eligibility: () =>+ loadableQuery(query, (data) => data.eligible, {+ retainDataOnError: false,+ }),+ existingSubscription: () =>+ queryReadyGate(query) && query.data.existingSubscription,+ managing: () => billingPortal.isPending,+ manage: async () => {+ try {+ const result = await billingPortal.mutateAsync({+ returnUrl: window.location.href,+ });+ window.location.href = result;+ } catch {+ toast.failure(+ "Couldn't open billing management. Please try again."+ );+ }+ },+ retry: () => {+ void query.refetch();+ },+ };+ },createPlanCatalog: () => {const query = useAiBillingPlansQuery();return {diff --git a/apps/web/src/features/onboarding/queries/loadable-query.test.ts b/apps/web/src/features/onboarding/queries/loadable-query.test.tsindex 28bc063d02..67ffbeb401 100644--- a/apps/web/src/features/onboarding/queries/loadable-query.test.ts+++ b/apps/web/src/features/onboarding/queries/loadable-query.test.ts@@ -35,6 +35,16 @@ describe('onboarding query sources', () => {).toEqual({ t: 'error' });});+ it('can reject a retained trial offer after its eligibility refresh fails', () => {+ expect(+ loadableQuery(+ { isPending: false, isError: true, data: { eligible: true } },+ (data) => data.eligible,+ { retainDataOnError: false }+ )+ ).toEqual({ t: 'error' });+ });+it('treats a loaded null offer as ready', () => {expect(loadableQuery(diff --git a/apps/web/src/features/onboarding/queries/loadable-query.ts b/apps/web/src/features/onboarding/queries/loadable-query.tsindex 4701fc4983..9cdf2122a1 100644--- a/apps/web/src/features/onboarding/queries/loadable-query.ts+++ b/apps/web/src/features/onboarding/queries/loadable-query.ts@@ -4,8 +4,11 @@ import type { Loadable } from '../context/onboarding-context';/** Adapt query state to the onboarding contract without suspending the form. */export function loadableQuery<T, R>(query: { isPending: boolean; isError: boolean; data: T | undefined },- map: (data: T) => R+ map: (data: T) => R,+ options?: { retainDataOnError?: boolean }): Loadable<R> {+ if (query.isError && options?.retainDataOnError === false)+ return { t: 'error' };// Retained data wins over a background error; pending resources are never read.if (queryReadyGate(query)) return { t: 'ready', value: map(query.data) };if (query.isError) return { t: 'error' };diff --git a/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts b/apps/web/src/features/onboarding/tests/fake-onboarding-context.tsindex 79a793bed3..ef59f67ea2 100644--- a/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts+++ b/apps/web/src/features/onboarding/tests/fake-onboarding-context.ts@@ -43,6 +43,8 @@ export type FakeOnboardingWorld = {connectionFailures: ('pipedream' | 'native' | 'github')[];githubStars: number | undefined;inviteOffer: InviteOffer | null;+ trialEligible: boolean;+ existingSubscription: boolean;planCatalog: AiPlanCatalog;/** License refreshes left before the Stripe webhook lands; undefined when none is pending. */webhookPollsRemaining: number | undefined;@@ -58,6 +60,7 @@ export type FakeOnboardingWorld = {| 'createTeam'| 'joinTeam'| 'planCatalog'+ | 'trialEligibility'| 'checkout'| 'completion',string@@ -96,6 +99,8 @@ export function defaultFakeWorld(): FakeOnboardingWorld {connectionFailures: [],githubStars: 12_345,inviteOffer: null,+ trialEligible: true,+ existingSubscription: false,planCatalog: {plans: [{@@ -317,6 +322,16 @@ export function createFakeOnboarding(});},createInviteOffer: () => () => ({ t: 'ready', value: world.inviteOffer }),+ createTrialEligibility: () => ({+ eligibility: () =>+ loadable('trialEligibility', () => world.trialEligible),+ existingSubscription: () => world.existingSubscription,+ managing: () => false,+ manage: async () => {+ call('manageSubscription');+ },+ retry: () => call('retryTrialEligibility'),+ }),createPlanCatalog: () => ({catalog: () => loadable('planCatalog', () => world.planCatalog),retry: () => call('retryPlanCatalog'),diff --git a/apps/web/src/features/onboarding/views/plan-comparison-view.tsx b/apps/web/src/features/onboarding/views/plan-comparison-view.tsxindex 578be6aafa..610ec95157 100644--- a/apps/web/src/features/onboarding/views/plan-comparison-view.tsx+++ b/apps/web/src/features/onboarding/views/plan-comparison-view.tsx@@ -8,11 +8,19 @@ export function PlanComparisonView(props: {onBackToPro: () => void;onStartMax: () => void;}) {- const plans = useOnboardingContext().createPlanCatalog();+ const context = useOnboardingContext();+ const plans = context.createPlanCatalog();+ const trial = context.createTrialEligibility();+ const trialEligible = () => {+ const state = trial.eligibility();+ return state.t === 'ready' && state.value;+ };return (<PlanComparison{...props}catalog={plans.catalog()}+ trialEligible={trialEligible()}+ existingSubscription={trial.existingSubscription()}onRetry={plans.retry}/>);diff --git a/apps/web/src/features/onboarding/views/plan-step.test.tsx b/apps/web/src/features/onboarding/views/plan-step.test.tsxindex 4378ed0c85..2fa86c63a3 100644--- a/apps/web/src/features/onboarding/views/plan-step.test.tsx+++ b/apps/web/src/features/onboarding/views/plan-step.test.tsx@@ -195,3 +195,101 @@ describe('live trial checkout', () => {expect(guest).toHaveBeenCalledOnce();});});++it('offers paid Pro without trial copy to an ineligible returning customer', () => {+ const { checkout } = setup(undefined, { trialEligible: false });+ expect(screen.queryByText(/Free Claude & GPT/)).toBeNull();+ expect(screen.queryByText(/first 30 days/)).toBeNull();+ expect(+ screen.queryByRole('button', { name: 'Start 30 day trial' })+ ).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Get Pro' }));+ expect(checkout).toHaveBeenCalledWith('premium', 'standard');+});++it('offers a retry without advertising a trial or starting checkout when eligibility fails', () => {+ const { checkout, fake } = setup(undefined, {+ failures: { trialEligibility: 'offline' },+ });+ expect(screen.queryByText(/Free Claude & GPT/)).toBeNull();+ const button = screen.getByRole('button', { name: 'Get Pro' });+ expect(button.hasAttribute('disabled')).toBe(true);+ fireEvent.click(button);+ expect(checkout).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));+ expect(fake.calls()).toContain('retryTrialEligibility');+});++it('routes an existing subscription to management without starting a replacement checkout', () => {+ const { checkout, fake } = setup(undefined, {+ trialEligible: false,+ existingSubscription: true,+ });+ expect(screen.queryByText('Start 30 day trial')).toBeNull();+ expect(screen.queryByText('$40/user/month, billed monthly')).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Manage subscription' }));+ expect(fake.calls()).toContain('manageSubscription');+ expect(checkout).not.toHaveBeenCalled();+});++it('keeps known subscription management available when eligibility refresh fails', () => {+ const { checkout, fake } = setup(undefined, {+ trialEligible: false,+ existingSubscription: true,+ failures: { trialEligibility: 'offline' },+ });+ const manage = screen.getByRole('button', { name: 'Manage subscription' });+ expect(manage.hasAttribute('disabled')).toBe(false);+ expect(screen.queryByText("Couldn't confirm your Pro offer.")).toBeNull();+ fireEvent.click(manage);+ expect(fake.calls()).toContain('manageSubscription');+ expect(checkout).not.toHaveBeenCalled();+});++it('does not expose an invite checkout when eligibility fails', () => {+ const { checkout } = setup(undefined, {+ inviteOffer: {+ firstName: 'Ada',+ freeMonths: 3,+ linkId: 'link-1',+ promoCode: 'ADA3',+ redeemedAt: '2026-10-01T00:00:00Z',+ },+ failures: { trialEligibility: 'offline' },+ });+ expect(+ screen.queryByRole('button', { name: 'Claim your free months' })+ ).toBeNull();+ expect(+ screen.getByRole('button', { name: 'Get Pro' }).hasAttribute('disabled')+ ).toBe(true);+ expect(screen.getByRole('button', { name: 'Try again' })).toBeTruthy();+ expect(checkout).not.toHaveBeenCalled();+});++it('does not advertise a trial in the comparison to a returning customer', () => {+ const { back, checkout } = setupComparison({ trialEligible: false });+ expect(screen.queryByText(/30 days free/)).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'Continue with Pro' }));+ expect(back).toHaveBeenCalledOnce();+ expect(checkout).not.toHaveBeenCalled();+});++it('prevents replacement purchases from the comparison for an existing subscription', () => {+ setupComparison({ trialEligible: false, existingSubscription: true });+ expect(+ screen+ .getByRole('button', { name: 'Continue with Max' })+ .hasAttribute('disabled')+ ).toBe(true);+ expect(+ screen+ .getByRole('button', { name: 'Continue with Pro' })+ .hasAttribute('disabled')+ ).toBe(true);+ expect(+ screen+ .getByRole('button', { name: 'Continue with Free' })+ .hasAttribute('disabled')+ ).toBe(false);+});diff --git a/apps/web/src/features/onboarding/views/plan-step.tsx b/apps/web/src/features/onboarding/views/plan-step.tsxindex 6a3f87f8b2..8ec5940798 100644--- a/apps/web/src/features/onboarding/views/plan-step.tsx+++ b/apps/web/src/features/onboarding/views/plan-step.tsx@@ -1,4 +1,5 @@import type { PaidPlanTier } from '@app/features/paywall/plans';+import { Button } from '@ui';import { type Accessor, type JSX, Show } from 'solid-js';import { match } from 'ts-pattern';import { ContinueButton } from '../components/controls';@@ -34,15 +35,23 @@ export function PlanStep(props: {onConfirmed: props.onPremiumPaid,});const offer = context.createInviteOffer();+ const trial = context.createTrialEligibility();+ const trialEligible = () => {+ const eligibility = trial.eligibility();+ return eligibility.t === 'ready' && eligibility.value;+ };// An invite's free months beat the trial, which would replace them.const inviteOffer = () => {const state = offer();- return plan.state().t === 'offer' && state.t === 'ready'+ return trial.eligibility().t === 'ready' &&+ !trial.existingSubscription() &&+ plan.state().t === 'offer' &&+ state.t === 'ready'? state.value: null;};- const trialOffer = () => (+ const subscriptionOffer = () => (<section class="mx-auto flex w-full max-w-lg flex-col py-2 sm:py-4"><header class="text-center"><h1@@ -50,12 +59,20 @@ export function PlanStep(props: {class="font-[Roboto_Slab_Variable] text-[clamp(1.75rem,8vw,3rem)] font-[315] leading-[1.12] tracking-tight outline-none text-balance">{plan.state().t === 'offer'- ? 'Free Claude & GPT for 30 days.'+ ? trial.existingSubscription()+ ? 'Manage your subscription.'+ : trialEligible()+ ? 'Free Claude & GPT for 30 days.'+ : 'Get more with Pro.': 'Your workspace is ready.'}</h1><p class="mx-auto mt-6 max-w-[400px] text-sm leading-6 text-ink-muted text-balance sm:text-[15px]">{plan.state().t === 'offer'- ? 'Every feature, every AI model and 1 TB of storage. Your first 30 days are on us, then $40/user/month.'+ ? trial.existingSubscription()+ ? 'You have an existing subscription. Review your subscription and payment details to restore access.'+ : trialEligible()+ ? 'Every feature, every AI model and 1 TB of storage. Your first 30 days are on us, then $40/user/month.'+ : 'Every feature, every AI model and 1 TB of storage. $40/user/month.': "We're confirming your access so you can continue to your workspace."}</p></header>@@ -79,32 +96,64 @@ export function PlanStep(props: {? 'Opening your workspace…': state.t === 'continue'? 'Continue to workspace'- : 'Start 30 day trial'+ : trial.existingSubscription()+ ? 'Manage subscription'+ : trial.eligibility().t === 'loading'+ ? 'Loading your Pro offer…'+ : trialEligible()+ ? 'Start 30 day trial'+ : 'Get Pro')}// Until the invite lookup settles, starting a trial could skip it.disabled={plan.state().t === 'confirming' ||props.finishing ||- (plan.state().t === 'offer' && offer().t === 'loading')+ trial.managing() ||+ (plan.state().t === 'offer' &&+ !trial.existingSubscription() &&+ (offer().t === 'loading' || trial.eligibility().t !== 'ready'))}onClick={() =>plan.state().t === 'offer'- ? props.onStartCheckout('premium', 'trial')+ ? trial.existingSubscription()+ ? void trial.manage()+ : props.onStartCheckout(+ 'premium',+ trialEligible() ? 'trial' : 'standard'+ ): void plan.confirm()}/></div>- <Show when={plan.state().t === 'offer'}>+ <Show when={plan.state().t === 'offer' && !trial.existingSubscription()}><p class="mx-auto mt-3 max-w-52 text-center text-xs leading-5 text-ink-extra-muted"><span class="block">$40/user/month, billed monthly</span>- <span class="block">after the trial. Cancel anytime.</span>+ <span class="block">+ {trialEligible()+ ? 'after the trial. Cancel anytime.'+ : 'Cancel anytime.'}+ </span></p></Show>+ <Show+ when={+ plan.state().t === 'offer' &&+ !trial.existingSubscription() &&+ trial.eligibility().t === 'error'+ }+ >+ <div role="alert" class="mt-4 text-center text-sm text-ink-muted">+ <p>Couldn't confirm your Pro offer.</p>+ <Button variant="ghost" size="sm" onClick={trial.retry}>+ Try again+ </Button>+ </div>+ </Show></section>);return (- <Show when={inviteOffer()} keyed fallback={trialOffer()}>+ <Show when={inviteOffer()} keyed fallback={subscriptionOffer()}>{(invite) =>props.renderInviteOffer(invite, {finishing: () => props.finishing,diff --git a/apps/web/src/features/paywall/PaywallComponent.tsx b/apps/web/src/features/paywall/PaywallComponent.tsxindex 78ac6d5459..87a72d4b02 100644--- a/apps/web/src/features/paywall/PaywallComponent.tsx+++ b/apps/web/src/features/paywall/PaywallComponent.tsx@@ -4,7 +4,11 @@ import { enableAiUsageBilling } from '@core/constant/featureFlags';import { type PaywallKey, PaywallMessages } from '@core/constant/PaywallState';import { useSettingsState } from '@core/constant/SettingsState';import { useUserId } from '@core/context/user';-import { useAiBillingSummaryQuery } from '@queries/auth';+import {+ useAiBillingSummaryQuery,+ useTrialEligibilityQuery,+} from '@queries/auth';+import { queryReadyGate } from '@queries/gate';import { useCurrentTeamQuery } from '@queries/team/teams';import { getBillingState } from '../settings/core/billing-state';import { PaywallView } from './components/paywall-view';@@ -22,6 +26,9 @@ const PaywallComponent = (props: PaywallProps) => {const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);const team = useCurrentTeamQuery();const summary = useAiBillingSummaryQuery();+ const trialEligibility = useTrialEligibilityQuery({+ enabled: () => !hasPaid(),+ });const availability = () =>team.isPending || summary.isPending? 'loading'@@ -47,6 +54,10 @@ const PaywallComponent = (props: PaywallProps) => {: undefined,aiUsageEnabled: aiUsageBilling().enabled,pending: false,+ trialEligible:+ trialEligibility.isSuccess && queryReadyGate(trialEligibility)+ ? trialEligibility.data.eligible+ : undefined,});};diff --git a/apps/web/src/features/settings/Billing.test.tsx b/apps/web/src/features/settings/Billing.test.tsxnew file mode 100644index 0000000000..c8b658e566--- /dev/null+++ b/apps/web/src/features/settings/Billing.test.tsx@@ -0,0 +1,189 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { Billing } from './Billing';+import { BillingSettingsView } from './components/billing-settings-view';+import { getBillingState } from './core/billing-state';++const mocks = vi.hoisted(() => ({+ teamReady: true,+ eligibility: {+ isSuccess: true,+ isPending: false,+ isError: false,+ data: { eligible: false, existingSubscription: false },+ refetch: vi.fn(),+ },+ checkout: vi.fn(() => new Promise<string>(() => {})),+}));+vi.mock('@app/lib/analytics/analytics-context', () => ({+ useAnalytics: () => ({ track: vi.fn() }),+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => ({ enabled: false }),+}));+vi.mock('@core/auth', () => ({ useHasPaidAccess: () => () => false }));+vi.mock('@core/constant/featureFlags', () => ({+ LOCAL_ONLY: false,+ enableAiUsageBilling: {},+}));+vi.mock('@core/context/user', () => ({+ usePermissions: () => () => ['write:stripe_subscription'],+ useUserId: () => () => 'macro|[email protected]',+}));+vi.mock('@queries/team/teams', () => ({+ useCurrentTeamQuery: () => ({+ isSuccess: mocks.teamReady,+ isPending: false,+ data: undefined,+ }),+}));+vi.mock('@queries/auth', () => ({+ useAiBillingSummaryQuery: () => ({+ isSuccess: true,+ data: { tier: 'free', can_manage_billing: true },+ }),+ useSubscriptionStatusQuery: () => ({ isPending: true }),+ useTrialEligibilityQuery: () => mocks.eligibility,+ useChangePlanMutation: () => ({ isPending: false }),+ useCreateCheckoutSessionMutation: () => ({+ isPending: false,+ mutateAsync: mocks.checkout,+ }),+}));+vi.mock('@service-stripe/client', () => ({ stripeServiceClient: {} }));+vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure: vi.fn() } }));++beforeEach(() => {+ mocks.checkout.mockClear();+ mocks.teamReady = true;+ Object.assign(mocks.eligibility, {+ isSuccess: true,+ isPending: false,+ isError: false,+ data: { eligible: false, existingSubscription: false },+ });+});+afterEach(cleanup);++it.each([true, false])(+ 'Billing sends the terms it advertises (eligible=%s)',+ (eligible) => {+ mocks.eligibility.data.eligible = eligible;+ render(() => <Billing />);+ expect(screen.queryByText('Free for one month!') !== null).toBe(eligible);+ fireEvent.click(screen.getByRole('button', { name: 'Get Pro' }));+ expect(mocks.checkout).toHaveBeenCalledWith({+ plan: 'premium',+ onboardingTrial: eligible,+ });+ }+);++it.each(['loading', 'error'])(+ 'does not sell Pro on unconfirmed terms while eligibility is %s',+ (status) => {+ Object.assign(mocks.eligibility, {+ isSuccess: false,+ isPending: status === 'loading',+ isError: status === 'error',+ });+ render(() => <Billing />);+ expect(screen.queryByText('Free for one month!')).toBeNull();+ const button = screen.getByRole('button', { name: 'Get Pro' });+ expect(button.hasAttribute('disabled')).toBe(true);+ fireEvent.click(button);+ expect(mocks.checkout).not.toHaveBeenCalled();+ if (status === 'error') {+ fireEvent.click(screen.getByRole('button', { name: 'Try again' }));+ expect(mocks.eligibility.refetch).toHaveBeenCalled();+ }+ fireEvent.click(screen.getByRole('button', { name: 'Get Max' }));+ expect(mocks.checkout).toHaveBeenCalledWith({+ plan: 'max',+ onboardingTrial: false,+ });+ }+);++it('shows subscription management rather than replacement plans for a recoverable subscription', () => {+ mocks.eligibility.data.existingSubscription = true;+ render(() => <Billing />);+ expect(screen.getByRole('button', { name: 'Manage' })).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Get Pro' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Get Max' })).toBeNull();+ expect(mocks.checkout).not.toHaveBeenCalled();+});++it('keeps Max upgrades available after paid access recovers while eligibility data is retained', () => {+ const select = vi.fn();+ render(() => (+ <BillingSettingsView+ state={getBillingState({+ hasPaid: true,+ canManageSubscription: true,+ aiUsageEnabled: true,+ pending: false,+ existingSubscription: true,+ summary: { tier: 'premium', canManageBilling: true },+ })}+ onManage={() => {}}+ onSelectPlan={select}+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Upgrade to Max' }));+ expect(select).toHaveBeenCalledWith('max');+});++it('keeps known subscription management available after a failed eligibility refresh', () => {+ Object.assign(mocks.eligibility, {+ isSuccess: false,+ isPending: false,+ isError: true,+ data: { eligible: false, existingSubscription: true },+ });+ render(() => <Billing />);+ expect(screen.getByRole('button', { name: 'Manage' })).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Get Pro' })).toBeNull();+ expect(screen.queryByRole('button', { name: 'Get Max' })).toBeNull();+});++it('keeps management available when team lookup fails without enabling plan changes', () => {+ mocks.teamReady = false;+ mocks.eligibility.data.existingSubscription = true;+ render(() => <Billing />);+ expect(screen.getByRole('button', { name: 'Manage' })).toBeTruthy();+ expect(screen.getByText(/Use Manage to review/)).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Get Pro' })).toBeNull();+});++it('does not direct a user without billing permission to a hidden Manage action', () => {+ render(() => (+ <BillingSettingsView+ state={getBillingState({+ hasPaid: false,+ canManageSubscription: false,+ aiUsageEnabled: false,+ pending: false,+ existingSubscription: true,+ })}+ onManage={() => {}}+ onSelectPlan={() => {}}+ />+ ));+ expect(screen.queryByRole('button', { name: 'Manage' })).toBeNull();+ expect(screen.queryByText(/Use Manage to review/)).toBeNull();+});++it('hides a previously confirmed trial after its background refresh fails', () => {+ Object.assign(mocks.eligibility, {+ isSuccess: false,+ isPending: false,+ isError: true,+ data: { eligible: true, existingSubscription: false },+ });+ render(() => <Billing />);+ expect(screen.queryByText('Free for one month!')).toBeNull();+ expect(+ screen.getByRole('button', { name: 'Get Pro' }).hasAttribute('disabled')+ ).toBe(true);+});diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsxindex 5bee9230bf..019d03d8e8 100644--- a/apps/web/src/features/settings/Billing.tsx+++ b/apps/web/src/features/settings/Billing.tsx@@ -11,6 +11,7 @@ import {useChangePlanMutation,useCreateCheckoutSessionMutation,useSubscriptionStatusQuery,+ useTrialEligibilityQuery,} from '@queries/auth';import { queryReadyGate } from '@queries/gate';import { useCurrentTeamQuery } from '@queries/team/teams';@@ -53,6 +54,9 @@ function LiveBilling(props: { controls?: JSX.Element }) {const checkout = useCreateCheckoutSessionMutation();const effectiveHasPaid = () =>hasPaid() || (summary.isSuccess && summary.data.tier !== 'free');+ const trialEligibility = useTrialEligibilityQuery({+ enabled: () => !effectiveHasPaid(),+ });const subscriptionStatus = useSubscriptionStatusQuery({enabled: effectiveHasPaid,@@ -63,7 +67,7 @@ function LiveBilling(props: { controls?: JSX.Element }) {});const userTeam = createMemo(() => {- const currentTeam = team.isSuccess ? team.data : undefined;+ const currentTeam = queryReadyGate(team) ? team.data : undefined;const uid = userId();if (!currentTeam || !uid) return;@@ -82,7 +86,8 @@ function LiveBilling(props: { controls?: JSX.Element }) {const state = () =>getBillingState({hasPaid: effectiveHasPaid(),- canManageSubscription: team.isSuccess && canManageSubscription() === true,+ canManageSubscription: canManageSubscription() === true,+ teamReady: team.isSuccess,teamRole: teamRole(),teamPlans: team.isSuccess? team.data?.members.map((member) =>@@ -99,11 +104,23 @@ function LiveBilling(props: { controls?: JSX.Element }) {: undefined,aiUsageEnabled: aiUsageBilling().enabled,pending: checkout.isPending || changePlan.isPending,+ existingSubscription: queryReadyGate(trialEligibility)+ ? trialEligibility.data.existingSubscription+ : false,+ trialEligible:+ trialEligibility.isSuccess && queryReadyGate(trialEligibility)+ ? trialEligibility.data.eligible+ : undefined,});const handleCheckout = async (plan: PaidPlan) => {+ if (state().existingSubscription) return;+ const eligible = state().trialEligible;+ if (plan === 'premium' && eligible === undefined) return;try {- const url = await checkout.mutateAsync(getFreePlanCheckoutRequest(plan));+ const url = await checkout.mutateAsync(+ getFreePlanCheckoutRequest(plan, eligible === true)+ );analytics.track('subscription_start', { type: plan });window.location.href = url;} catch (error) {@@ -142,6 +159,7 @@ function LiveBilling(props: { controls?: JSX.Element }) {window.location.href = url;} catch (error) {console.error(error);+ toast.failure("Couldn't open billing management. Please try again.");}};@@ -161,6 +179,8 @@ function LiveBilling(props: { controls?: JSX.Element }) {}subscriptionStatusFailed={subscriptionStatus.isError}onRefreshStatus={() => void subscriptionStatus.refetch()}+ trialEligibilityFailed={!effectiveHasPaid() && trialEligibility.isError}+ onRefreshTrialEligibility={() => void trialEligibility.refetch()}onKeepPlan={(plan) => void handleChangePlan(plan)}onManage={() => void handleManage()}onSelectPlan={(plan) =>diff --git a/apps/web/src/features/settings/components/billing-plan-card.test.tsx b/apps/web/src/features/settings/components/billing-plan-card.test.tsxnew file mode 100644index 0000000000..793d08b9cb--- /dev/null+++ b/apps/web/src/features/settings/components/billing-plan-card.test.tsx@@ -0,0 +1,41 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import { afterEach, expect, it, vi } from 'vitest';+import { getFreePlanCheckoutRequest } from '../core/billing-state';+import { BillingPlanCard } from './billing-plan-card';++afterEach(cleanup);++it.each([true, false, undefined])(+ 'only advertises and requests a confirmed trial (eligible=%s)',+ (trialEligible) => {+ const checkout = vi.fn();+ render(() => (+ <BillingPlanCard+ plan="premium"+ state={{+ hasPaid: false,+ aiUsageEnabled: false,+ pending: false,+ trialEligible,+ }}+ onSelectPlan={(plan) =>+ checkout(getFreePlanCheckoutRequest(plan, trialEligible === true))+ }+ />+ ));+ expect(screen.queryByText('Free for one month!') !== null).toBe(+ trialEligible === true+ );+ const button = screen.getByRole('button', { name: 'Get Pro' });+ expect(button.hasAttribute('disabled')).toBe(trialEligible === undefined);+ fireEvent.click(button);+ if (trialEligible === undefined) {+ expect(checkout).not.toHaveBeenCalled();+ } else {+ expect(checkout).toHaveBeenCalledWith({+ plan: 'premium',+ onboardingTrial: trialEligible,+ });+ }+ }+);diff --git a/apps/web/src/features/settings/components/billing-plan-card.tsx b/apps/web/src/features/settings/components/billing-plan-card.tsxindex 423afa5f2f..5962da00a3 100644--- a/apps/web/src/features/settings/components/billing-plan-card.tsx+++ b/apps/web/src/features/settings/components/billing-plan-card.tsx@@ -47,7 +47,7 @@ export function BillingPlanCard(props: {plan: PaidPlanTier;state: Pick<BillingState,- 'hasPaid' | 'teamRole' | 'aiUsageEnabled' | 'pending'+ 'hasPaid' | 'teamRole' | 'aiUsageEnabled' | 'pending' | 'trialEligible'>;onSelectPlan?: (plan: PaidPlanTier) => void;}) {@@ -66,7 +66,13 @@ export function BillingPlanCard(props: {<h3 class="text-lg font-medium text-ink">{PLAN_BY_TIER[props.plan].name}</h3>- <Show when={!props.state.hasPaid && props.plan === 'premium'}>+ <Show+ when={+ !props.state.hasPaid &&+ props.plan === 'premium' &&+ props.state.trialEligible === true+ }+ ><span class="text-sm font-medium text-accent">Free for one month!</span>@@ -83,7 +89,12 @@ export function BillingPlanCard(props: {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}+ disabled={+ props.state.pending ||+ (!props.state.hasPaid &&+ props.plan === 'premium' &&+ props.state.trialEligible === undefined)+ }onClick={() => props.onSelectPlan?.(props.plan)}>{props.state.hasPaiddiff --git a/apps/web/src/features/settings/components/billing-settings-view.tsx b/apps/web/src/features/settings/components/billing-settings-view.tsxindex ccbe9a9181..6c4fb75ec9 100644--- a/apps/web/src/features/settings/components/billing-settings-view.tsx+++ b/apps/web/src/features/settings/components/billing-settings-view.tsx@@ -15,6 +15,8 @@ export function BillingSettingsView(props: {scheduledChange?: { plan: 'free' | 'premium' | 'max'; effectiveAt: string };subscriptionStatusFailed?: boolean;onRefreshStatus?: () => void;+ trialEligibilityFailed?: boolean;+ onRefreshTrialEligibility?: () => void;onKeepPlan?: (plan: PaidPlanTier) => void;teamSeatDescription?: string;onManage: () => void;@@ -129,7 +131,12 @@ export function BillingSettingsView(props: {</Show></div>- <Show when={props.state.canChangePlan && props.state.hasPaid}>+ <Show+ when={+ props.state.canManageBilling &&+ (props.state.hasPaid || props.state.existingSubscription)+ }+ ><Buttonclass="ml-auto bg-active"size="sm"@@ -141,6 +148,18 @@ export function BillingSettingsView(props: {</Button></Show></header>+ <Show+ when={+ props.state.canManageBilling &&+ props.state.existingSubscription &&+ !props.state.hasPaid+ }+ >+ <p role="status" class="text-sm text-ink-muted">+ You have an existing subscription. Use Manage to review your+ subscription and payment details.+ </p>+ </Show><ul class="border-t border-t-edge-muted pt-4 flex flex-wrap gap-4 text-sm text-ink-muted"><PlanFeaturestier={props.state.tier}@@ -195,7 +214,13 @@ export function BillingSettingsView(props: {</Show></section>- <Show when={props.state.canChangePlan && props.state.tier !== 'max'}>+ <Show+ when={+ props.state.canChangePlan &&+ props.state.tier !== 'max' &&+ (props.state.hasPaid || !props.state.existingSubscription)+ }+ ><sectiondata-settings-target="upgrade"tabIndex={-1}@@ -206,6 +231,21 @@ export function BillingSettingsView(props: {? 'Need more AI?': 'Upgrade'}</h2>+ <Show when={props.trialEligibilityFailed}>+ <div+ role="alert"+ class="flex flex-wrap items-center gap-3 text-sm text-ink-muted"+ >+ <p>Couldn't confirm your Pro offer. Please try again.</p>+ <Button+ variant="ghost"+ size="sm"+ onClick={props.onRefreshTrialEligibility}+ >+ Try again+ </Button>+ </div>+ </Show><divclass="grid grid-cols-1 gap-6"classList={{diff --git a/apps/web/src/features/settings/context/billing-context.ts b/apps/web/src/features/settings/context/billing-context.tsindex 32af2b517a..741ce2a110 100644--- a/apps/web/src/features/settings/context/billing-context.ts+++ b/apps/web/src/features/settings/context/billing-context.ts@@ -11,6 +11,7 @@ export type BillingContext = {{ plan: PlanTier; effectiveAt: string } | undefined>;hasPaid: Accessor<boolean>;+ trialEligible?: Accessor<boolean | undefined>;aiUsageBilling: Accessor<boolean>;teamRole: Accessor<'owner' | 'member' | undefined>;teamSeatDescription: Accessor<string | undefined>;diff --git a/apps/web/src/features/settings/core/billing-state.test.ts b/apps/web/src/features/settings/core/billing-state.test.tsindex 09978c9524..d1f09fce3c 100644--- a/apps/web/src/features/settings/core/billing-state.test.ts+++ b/apps/web/src/features/settings/core/billing-state.test.ts@@ -17,19 +17,26 @@ const baseline: BillingInput = {describe('billing presentation policy', () => {it('requests a confirmed first-month trial when a Free account selects Pro', () => {- expect(getFreePlanCheckoutRequest('premium')).toEqual({+ expect(getFreePlanCheckoutRequest('premium', true)).toEqual({plan: 'premium',onboardingTrial: true,});});it('keeps Max checkout on paid terms', () => {- expect(getFreePlanCheckoutRequest('max')).toEqual({+ expect(getFreePlanCheckoutRequest('max', true)).toEqual({plan: 'max',onboardingTrial: false,});});+ it('lets a returning customer purchase Pro without requesting another trial', () => {+ expect(getFreePlanCheckoutRequest('premium', false)).toEqual({+ plan: 'premium',+ onboardingTrial: false,+ });+ });+it.each<PlanTier>(['free', 'premium', 'max'])('hides options for a team-paid member on %s',(tier) => {diff --git a/apps/web/src/features/settings/core/billing-state.ts b/apps/web/src/features/settings/core/billing-state.tsindex a099385f54..6f947cc6f9 100644--- a/apps/web/src/features/settings/core/billing-state.ts+++ b/apps/web/src/features/settings/core/billing-state.ts@@ -3,11 +3,15 @@ import type { PaidPlanTier, PlanTier } from '@app/features/paywall/plans';export type BillingInput = {hasPaid: boolean;canManageSubscription: boolean;+ teamReady?: boolean;teamRole?: 'owner' | 'member';teamPlans?: readonly PaidPlanTier[];summary?: { tier: PlanTier; canManageBilling: boolean };aiUsageEnabled: boolean;pending: boolean;+ /** Undefined until the server confirms eligibility; never advertise a trial then. */+ trialEligible?: boolean;+ existingSubscription?: boolean;};/** The billing summary's tier wins; without it, paid access implies Pro. */@@ -30,15 +34,20 @@ export function getBillingState(input: BillingInput) {...input,tier,billedThroughTeam,- canChangePlan: input.canManageSubscription && isOwnerOrSolo,+ canManageBilling: input.canManageSubscription && isOwnerOrSolo,+ canChangePlan:+ input.teamReady !== false && 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' };+/** Returning customers buy on paid terms; only confirmed first-time customers get a trial. */+export function getFreePlanCheckoutRequest(+ plan: PaidPlanTier,+ trialEligible: boolean+) {+ return { plan, onboardingTrial: plan === 'premium' && trialEligible };}export function describeSeatPlans(plans: readonly PaidPlanTier[]): string {diff --git a/apps/web/src/features/settings/views/billing-preview.tsx b/apps/web/src/features/settings/views/billing-preview.tsxindex 0bc456ca4b..6cb23cefc6 100644--- a/apps/web/src/features/settings/views/billing-preview.tsx+++ b/apps/web/src/features/settings/views/billing-preview.tsx@@ -64,6 +64,7 @@ export function BillingPreview(props: {const [summaryStatus, setSummaryStatus] =createSignal<SummaryStatus>('loaded');const [hasPaid, setHasPaid] = createSignal(false);+ const [trialEligible, setTrialEligible] = createSignal(true);const [permission, setPermission] = createSignal(true);const [aiUsage, setAiUsage] = createSignal(false);const [pending, setPending] = createSignal(false);@@ -85,12 +86,14 @@ export function BillingPreview(props: {: undefined,aiUsageEnabled: aiUsage(),pending: pending(),+ trialEligible: trialEligible(),});const reset = () => {setAccount('solo');setPlan('free');setSummaryStatus('loaded');setHasPaid(false);+ setTrialEligible(true);setPermission(true);setAiUsage(false);setPending(false);@@ -175,6 +178,11 @@ export function BillingPreview(props: {onChange={setSummaryStatus}/><div class="flex flex-wrap gap-x-6">+ <PreviewCheckbox+ label="Eligible for Pro trial"+ checked={trialEligible()}+ onChange={setTrialEligible}+ /><PreviewCheckboxlabel="Billing permission"checked={permission()}@@ -209,7 +217,7 @@ export function BillingPreview(props: {const selectPlan = (tier: 'premium' | 'max') =>setAction(- `Preview only · ${state().tier === 'free' ? 'Checkout' : 'Change plan'}: ${PLAN_BY_TIER[tier].name}${state().tier === 'free' && tier === 'premium' ? ' · 30-day trial' : ''} · no billing changes made`+ `Preview only · ${state().tier === 'free' ? 'Checkout' : 'Change plan'}: ${PLAN_BY_TIER[tier].name}${state().tier === 'free' && tier === 'premium' && trialEligible() ? ' · 30-day trial' : ''} · no billing changes made`);const manage = () =>setAction('Preview only · Manage subscription · no billing changes made');diff --git a/apps/web/src/features/settings/views/billing-settings.tsx b/apps/web/src/features/settings/views/billing-settings.tsxindex 7233219673..d2cfa7dadf 100644--- a/apps/web/src/features/settings/views/billing-settings.tsx+++ b/apps/web/src/features/settings/views/billing-settings.tsx@@ -6,10 +6,13 @@ export const BillingSettingsView = (props: { context: BillingContext }) => (state={{tier: props.context.tier(),hasPaid: props.context.hasPaid(),+ trialEligible: props.context.trialEligible?.(),aiUsageEnabled: props.context.aiUsageBilling(),teamRole: props.context.teamRole(),billedThroughTeam: props.context.billedThroughTeam(),canManageSubscription: props.context.canManageSubscription(),+ canManageBilling:+ props.context.canManageSubscription() && props.context.isOwnerOrSolo(),canChangePlan: props.context.canChangePlan(),pending: props.context.changingPlan(),}}diff --git a/apps/web/src/lib/queries/auth/index.ts b/apps/web/src/lib/queries/auth/index.tsindex e784d064ce..09fa38cf54 100644--- a/apps/web/src/lib/queries/auth/index.ts+++ b/apps/web/src/lib/queries/auth/index.ts@@ -33,6 +33,7 @@ export {type CreateCheckoutSessionArgs,useCreateBillingPortalMutation,useCreateCheckoutSessionMutation,+ useTrialEligibilityQuery,} from './stripe-checkout';export type { UserInfoData } from './user-info';export {diff --git a/apps/web/src/lib/queries/auth/keys.ts b/apps/web/src/lib/queries/auth/keys.tsindex 06e004d16f..caf9d75378 100644--- a/apps/web/src/lib/queries/auth/keys.ts+++ b/apps/web/src/lib/queries/auth/keys.ts@@ -4,6 +4,7 @@ export const authKeys = createQueryKeys('auth', {aiBillingPlans: null,aiBillingSummary: null,subscriptionStatus: null,+ trialEligibility: null,codexStatus: null,codexEnvironments: null,codexLogin: (attemptId: string) => ({ queryKey: [attemptId] }),diff --git a/apps/web/src/lib/queries/auth/stripe-checkout.test.tsx b/apps/web/src/lib/queries/auth/stripe-checkout.test.tsxnew file mode 100644index 0000000000..2defb956db--- /dev/null+++ b/apps/web/src/lib/queries/auth/stripe-checkout.test.tsx@@ -0,0 +1,128 @@+import { loadableQuery } from '@app/features/onboarding/queries/loadable-query';+import { cleanup, render } from '@solidjs/testing-library';+import {+ focusManager,+ onlineManager,+ QueryClientProvider,+} from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { queryClient } from '../client';+import {+ useCreateCheckoutSessionMutation,+ useTrialEligibilityQuery,+} from './stripe-checkout';++const mocks = vi.hoisted(() => ({ eligibility: vi.fn(), checkout: vi.fn() }));+vi.mock('@service-auth/client', () => ({+ authServiceClient: { getTrialEligibility: mocks.eligibility },+}));+vi.mock('@service-stripe/client', () => ({+ stripeServiceClient: { createCheckoutSessionV2: mocks.checkout },+}));+vi.mock('../client', async () => {+ const { QueryClient } = await import('@tanstack/solid-query');+ return {+ queryClient: new QueryClient({+ defaultOptions: {+ queries: {+ staleTime: 300_000,+ refetchOnWindowFocus: false,+ retryDelay: 0,+ },+ },+ }),+ };+});++function setup() {+ let checkout: ReturnType<typeof useCreateCheckoutSessionMutation> | undefined;+ function Offer() {+ const query = useTrialEligibilityQuery();+ checkout = useCreateCheckoutSessionMutation();+ const label = () => {+ const value = loadableQuery(query, (offer) => offer.eligible, {+ retainDataOnError: false,+ });+ return value.t === 'ready' ? (value.value ? 'trial' : 'paid') : value.t;+ };+ return (+ <button disabled={label() === 'loading' || label() === 'error'}>+ {label()}+ </button>+ );+ }+ return {+ ...render(() => (+ <QueryClientProvider client={queryClient}>+ <Offer />+ </QueryClientProvider>+ )),+ checkout: () => checkout,+ };+}++beforeEach(() => {+ vi.useFakeTimers();+ mocks.eligibility+ .mockResolvedValueOnce(ok({ eligible: true, existingSubscription: false }))+ .mockResolvedValue(ok({ eligible: false, existingSubscription: false }));+});+afterEach(() => {+ cleanup();+ queryClient.clear();+ focusManager.setFocused(undefined);+ onlineManager.setOnline(true);+ vi.resetAllMocks();+ vi.useRealTimers();+});++it.each(['focus', 'reconnect'])(+ 'refreshes trial eligibility on %s despite global caching defaults',+ async (event) => {+ const view = setup();+ await vi.advanceTimersByTimeAsync(1);+ expect(view.container.textContent).toBe('trial');+ if (event === 'focus') {+ focusManager.setFocused(false);+ focusManager.setFocused(true);+ } else {+ onlineManager.setOnline(false);+ onlineManager.setOnline(true);+ }+ await vi.advanceTimersByTimeAsync(1);+ expect(view.container.textContent).toBe('paid');+ expect(mocks.eligibility).toHaveBeenCalledTimes(2);+ }+);++it('refreshes the real eligibility query after a checkout conflict without a paid retry', async () => {+ const view = setup();+ await vi.advanceTimersByTimeAsync(1);+ const paidEligibility = ok({ eligible: false, existingSubscription: false });+ const refreshed = Promise.withResolvers<typeof paidEligibility>();+ mocks.eligibility.mockReturnValueOnce(refreshed.promise);+ mocks.checkout.mockRejectedValue(new Error('Trial no longer available'));+ await expect(+ view.checkout()?.mutateAsync({ plan: 'premium', onboardingTrial: true })+ ).rejects.toThrow('Trial no longer available');+ await vi.advanceTimersByTimeAsync(1);+ expect(view.container.textContent).toBe('loading');+ expect(view.container.querySelector('button')?.disabled).toBe(true);+ refreshed.resolve(paidEligibility);+ await vi.advanceTimersByTimeAsync(1);+ expect(view.container.textContent).toBe('paid');+ expect(mocks.checkout).toHaveBeenCalledTimes(1);+ expect(mocks.eligibility).toHaveBeenCalledTimes(2);+});++it('removes the retained trial offer when a refresh fails', async () => {+ const view = setup();+ await vi.advanceTimersByTimeAsync(1);+ expect(view.container.textContent).toBe('trial');+ mocks.eligibility.mockResolvedValue(err('unavailable'));+ focusManager.setFocused(false);+ focusManager.setFocused(true);+ await vi.advanceTimersByTimeAsync(10);+ expect(view.container.textContent).toBe('error');+});diff --git a/apps/web/src/lib/queries/auth/stripe-checkout.ts b/apps/web/src/lib/queries/auth/stripe-checkout.tsindex 4b8ee1cf4d..f8be810471 100644--- a/apps/web/src/lib/queries/auth/stripe-checkout.ts+++ b/apps/web/src/lib/queries/auth/stripe-checkout.ts@@ -1,7 +1,29 @@import { throwOnErr } from '@core/util/result';import { authServiceClient } from '@service-auth/client';import { stripeServiceClient } from '@service-stripe/client';-import { useMutation } from '@tanstack/solid-query';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { queryClient } from '../client';+import { authKeys } from './keys';++function trialEligibilityQueryOptions(enabled: boolean) {+ return {+ queryKey: authKeys.trialEligibility.queryKey,+ queryFn: () => throwOnErr(() => authServiceClient.getTrialEligibility()),+ enabled,+ staleTime: 0,+ refetchOnWindowFocus: true,+ refetchOnReconnect: true,+ throwOnError: false,+ retry: 1,+ };+}++/** Confirm introductory eligibility before advertising or requesting a trial. */+export function useTrialEligibilityQuery(options?: { enabled: () => boolean }) {+ return useQuery(() =>+ trialEligibilityQueryOptions(options?.enabled() ?? true)+ );+}/** The arguments the Stripe client's v2 checkout accepts. */export type CreateCheckoutSessionArgs = NonNullable<@@ -22,6 +44,13 @@ export function useCreateCheckoutSessionMutation() {}return url;},+ onError: () => {+ // The rejected offer is no longer confirmed. Clear it before refetching,+ // and never retry an advertised trial as an immediate charge.+ void queryClient.resetQueries({+ queryKey: authKeys.trialEligibility.queryKey,+ });+ },}));}diff --git a/apps/web/src/lib/service-clients/service-auth/client.test.ts b/apps/web/src/lib/service-clients/service-auth/client.test.tsindex f0e2201ce4..96bba982be 100644--- a/apps/web/src/lib/service-clients/service-auth/client.test.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.test.ts@@ -101,3 +101,27 @@ describe('credit checkout', () => {});});++describe('subscription checkout conflicts', () => {+ test.each([+ ['The 30-day trial is only available for your first Premium subscription'],+ ['User already has an active subscription'],+ ])('preserves the actionable server explanation: %s', async (message) => {+ fetchCheckout.mockImplementationOnce(+ async (_input: RequestInfo, init: FetchWithTokenInit) => {+ const error = await init.errorResponseHandler?.(+ new Response(JSON.stringify({ message }), { status: 409 })+ );+ if (!error) throw new Error('Expected a checkout error handler');+ return err([error]);+ }+ );+ const result = await authServiceClient.createCheckoutSessionV2({+ plan: 'premium',+ onboardingTrial: true,+ successUrl: 'https://macro.com/app',+ cancelUrl: 'https://macro.com/app',+ });+ expect(result._unsafeUnwrapErr()[0]).toEqual({ code: 'CONFLICT', message });+ });+});diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.tsindex fbf0d6073d..2f480051c5 100644--- a/apps/web/src/lib/service-clients/service-auth/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/client.ts@@ -40,6 +40,7 @@ import type {SendMobileWelcomeEmailResponse,SetGithubPullRequestDraftRequest,SetGithubPullRequestDraftResponse,+ TrialEligibility,UserQuota,} from './generated/schemas';import type { AppleLoginRequest } from './generated/schemas/appleLoginRequest';@@ -712,6 +713,13 @@ export const authServiceClient = {},// Stripe HTTP methods (replacing RPC calls)+ async getTrialEligibility() {+ return await fetchWithAuth<TrialEligibility>(+ `${authHost}/user/stripe/trial_eligibility`,+ { method: 'GET' }+ );+ },+async createCheckoutSessionV2(args: {successUrl: string;cancelUrl: string;@@ -738,6 +746,22 @@ export const authServiceClient = {plan: args.plan,onboardingTrial: args.onboardingTrial,}),+ errorResponseHandler: async (response) => {+ if (response.status === 409) {+ const body: unknown = await response.json().catch(() => null);+ return {+ code: 'CONFLICT',+ message:+ body &&+ typeof body === 'object' &&+ 'message' in body &&+ typeof body.message === 'string'+ ? body.message+ : 'Your subscription status changed. Please refresh your plans.',+ };+ }+ return statusError(response.status);+ },});},diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex 838a929eb5..4092102436 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -93,6 +93,7 @@ import type {TeamWithMembers,ToggleAutoJoinDomainResponse,ToggleNonAdminInvitesResponse,+ TrialEligibility,UpdateAutoReloadRequest,UpdateOverageRequest,UsageSnapshot,@@ -5931,6 +5932,69 @@ export const createPortalSession = async (} as createPortalSessionResponse;};+/**+ * @summary Read the caller's eligibility; checkout revalidates before granting a trial.+ */+export type getTrialEligibilityResponse200 = {+ data: TrialEligibility;+ status: 200;+};++export type getTrialEligibilityResponse400 = {+ data: ErrorResponse;+ status: 400;+};++export type getTrialEligibilityResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type getTrialEligibilityResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type getTrialEligibilityResponseSuccess =+ getTrialEligibilityResponse200 & {+ headers: Headers;+ };+export type getTrialEligibilityResponseError = (+ | getTrialEligibilityResponse400+ | getTrialEligibilityResponse401+ | getTrialEligibilityResponse500+) & {+ headers: Headers;+};++export type getTrialEligibilityResponse =+ | getTrialEligibilityResponseSuccess+ | getTrialEligibilityResponseError;++export const getGetTrialEligibilityUrl = () => {+ return `/user/stripe/trial_eligibility`;+};++export const getTrialEligibility = async (+ options?: RequestInit+): Promise<getTrialEligibilityResponse> => {+ const res = await fetch(getGetTrialEligibilityUrl(), {+ ...options,+ method: 'GET',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: getTrialEligibilityResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as getTrialEligibilityResponse;+};+/*** @summary Updates the user's tutorialComplete flag.*/diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.tsindex d8363937a7..be3ba67be3 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts@@ -208,6 +208,7 @@ export * from './teamWithMembersScheduledSeatPlansAnyOf';export * from './toggleAutoJoinDomainResponse';export * from './toggleAutoJoinDomainResponseAutoJoinDomain';export * from './toggleNonAdminInvitesResponse';+export * from './trialEligibility';export * from './updateAutoReloadRequest';export * from './updateAutoReloadRequestMonthlySpendLimitCents';export * from './updateOverageRequest';diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/trialEligibility.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/trialEligibility.tsnew file mode 100644index 0000000000..a003b39464--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/trialEligibility.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Whether the authenticated customer can receive the introductory Pro trial.+ */+export interface TrialEligibility {+ /** Confirmed against the same subscription history used during checkout. */+ eligible: boolean;+ /** An existing subscription requires management instead of a new checkout. */+ existingSubscription: boolean;+}diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 760f29c380..92ec6f6b84 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -4982,6 +4982,55 @@}}},+ "/user/stripe/trial_eligibility": {+ "get": {+ "tags": ["user::stripe::trial_eligibility"],+ "summary": "Read the caller's eligibility; checkout revalidates before granting a trial.",+ "operationId": "get_trial_eligibility",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TrialEligibility"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/user/tutorial": {"patch": {"tags": ["user::patch_tutorial"],@@ -7227,6 +7276,21 @@}}},+ "TrialEligibility": {+ "type": "object",+ "description": "Whether the authenticated customer can receive the introductory Pro trial.",+ "required": ["eligible", "existingSubscription"],+ "properties": {+ "eligible": {+ "type": "boolean",+ "description": "Confirmed against the same subscription history used during checkout."+ },+ "existingSubscription": {+ "type": "boolean",+ "description": "An existing subscription requires management instead of a new checkout."+ }+ }+ },"UpdateAutoReloadRequest": {"type": "object","description": "Request body for [`update_auto_reload_handler`].",diff --git a/apps/web/src/lib/service-clients/service-stripe/checkout.integration.test.ts b/apps/web/src/lib/service-clients/service-stripe/checkout.integration.test.tsnew file mode 100644index 0000000000..8079075eae--- /dev/null+++ b/apps/web/src/lib/service-clients/service-stripe/checkout.integration.test.ts@@ -0,0 +1,118 @@+import { getFreePlanCheckoutRequest } from '@app/features/settings/core/billing-state';+import { authServiceClient } from '@service-auth/client';+import { ok } from 'neverthrow';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { stripeServiceClient } from './client';++vi.mock('@core/constant/featureFlags', async (original) => ({+ ...(await original<typeof import('@core/constant/featureFlags')>()),+ ENABLE_BEARER_TOKEN_AUTH: true,+ LOCAL_ONLY: false,+}));++const token = `header.${btoa(JSON.stringify({ exp: 4_000_000_000 }))}.signature`;++beforeEach(() => {+ vi.spyOn(authServiceClient, 'macroApiToken').mockResolvedValue(+ ok({ macro_api_token: token })+ );+});+afterEach(() => vi.restoreAllMocks());++it.each([true, false])(+ 'carries confirmed eligibility through the real authenticated HTTP clients (eligible=%s)',+ async (eligible) => {+ const fetch = vi+ .spyOn(window, 'fetch')+ .mockResolvedValueOnce(Response.json({ eligible }))+ .mockResolvedValueOnce(+ Response.json({+ url: 'https://checkout.stripe.com/confirmed',+ trialDays: eligible ? 30 : null,+ })+ );++ const offer = await authServiceClient.getTrialEligibility();+ expect(offer.isOk()).toBe(true);+ if (offer.isErr()) throw new Error('Eligibility request failed');+ await expect(+ stripeServiceClient.createCheckoutSessionV2(+ getFreePlanCheckoutRequest('premium', offer.value.eligible)+ )+ ).resolves.toBe('https://checkout.stripe.com/confirmed');++ expect(fetch.mock.calls[0]?.[0]).toMatch(+ /\/user\/stripe\/trial_eligibility$/+ );+ expect(fetch.mock.calls[0]?.[1]?.method).toBe('GET');+ expect(fetch.mock.calls[1]?.[0]).toMatch(/\/user\/stripe\/checkoutv2$/);+ expect(fetch.mock.calls[1]?.[1]?.method).toBe('POST');+ const body = fetch.mock.calls[1]?.[1]?.body;+ if (typeof body !== 'string')+ throw new Error('Expected a JSON checkout body');+ expect(JSON.parse(body)).toMatchObject({+ plan: 'premium',+ onboardingTrial: eligible,+ });+ for (const [, init] of fetch.mock.calls) {+ expect(new Headers(init?.headers).get('Authorization')).toBe(+ `Bearer ${token}`+ );+ }+ expect(fetch).toHaveBeenCalledTimes(2);+ }+);++it('preserves a stale-trial conflict through the real transport without retrying a paid checkout', async () => {+ const message =+ 'The 30-day trial is only available for your first Premium subscription';+ const fetch = vi+ .spyOn(window, 'fetch')+ .mockResolvedValueOnce(Response.json({ message }, { status: 409 }));+ await expect(+ stripeServiceClient.createCheckoutSessionV2({+ plan: 'premium',+ onboardingTrial: true,+ })+ ).rejects.toThrow(message);+ expect(fetch).toHaveBeenCalledTimes(1);+});++it('does not retry checkout after losing the HTTP response', async () => {+ const fetch = vi+ .spyOn(window, 'fetch')+ .mockRejectedValueOnce(new TypeError('Failed to fetch'));+ await expect(+ stripeServiceClient.createCheckoutSessionV2({+ plan: 'premium',+ onboardingTrial: false,+ })+ ).rejects.toThrow('Network error occurred');+ expect(fetch).toHaveBeenCalledTimes(1);+});++it.each([401, 404, 500])(+ 'treats eligibility HTTP %i as unknown, not ineligible',+ async (status) => {+ vi.spyOn(window, 'fetch').mockResolvedValueOnce(+ Response.json({ message: 'unavailable' }, { status })+ );+ const result = await authServiceClient.getTrialEligibility();+ expect(result.isErr()).toBe(true);+ }+);++it('rejects an advertised trial when the HTTP response confirms paid terms', async () => {+ vi.spyOn(window, 'fetch').mockResolvedValueOnce(+ Response.json({+ url: 'https://checkout.stripe.com/paid',+ trialDays: null,+ })+ );+ await expect(+ stripeServiceClient.createCheckoutSessionV2({+ plan: 'premium',+ onboardingTrial: true,+ })+ ).rejects.toThrow('Your free trial could not be confirmed');+});diff --git a/docs/agent-guide/login.md b/docs/agent-guide/login.mdindex 094539bd9d..51bf90fa5f 100644--- a/docs/agent-guide/login.md+++ b/docs/agent-guide/login.md@@ -187,23 +187,28 @@ The confirmed tutorial save updates the session cache before leaving. A successffinish must not show "Couldn't finish setup — please try again", including whena background session refresh overlaps it.-The final screen keeps the “Free Claude & GPT for 30 days” headline and trial-button above the fold. The “See more” scroll cue opens the pricing grid+The final screen shows “Free Claude & GPT for 30 days” and the trial button+only after the server confirms first-subscription eligibility. Returning+customers without an existing subscription see “Get more with Pro.” and+`Get Pro` with paid monthly terms. Existing subscribers see `Manage subscription`+to review their subscription and payment details. The “See more” scroll cue opens the pricing gridbelow, comparing Free, Pro, and Max. The grid loads monthly subscription pricesfrom the billing catalog and describes Max as 10× Pro usage, without displayingdollar-denominated included AI allowances. Monthly prices use the compact`/usr/mo` unit on one line; Free email branding reads “Sent with Macro”.Free completes onboarding without a-card. Pro returns to the trial offer; Max starts standard paid checkout.+card. Pro returns to the account-specific Pro offer; Max starts standard paid checkout.The trial button requests 30 days free through Stripe Checkout, with no couponrequired. Stripe collects the payment method for billing after the trial. Only acustomer's first subscription qualifies, including canceled subscriptions in that-check. Ineligible requests show an error instead of opening an immediately paid-checkout. Invite promotions retain their own offer and terms.+check. Eligibility loading or failure disables Pro checkout without advertising+a trial; a failed lookup offers `Try again`. A trial rejected at checkout+shows the server explanation and refreshes eligibility, without automatically+retrying as a paid purchase. Invite promotions retain their own offer and terms.Cancellation returns to this step. A successful return polls the server's licensestate, completes onboarding, and enters the app without an extra confirmationclick. A pending webhook shows a retryable confirmation state. If the catalog-cannot load, Free remains available, Pro still returns to the trial offer, and+cannot load, Free remains available, Pro still returns to its offer, andMax checkout stays disabled until prices can be loaded with the retry action.Both completion paths preserve an original `next` destination and otherwise land on Home (`/app/home`). Old saved email,connector, building, and summary step names are migrated on resume.@@ -216,7 +221,7 @@ with no plan header or divider. The card scrolls internally at a maximum of360px or half the viewport height. Entering at least 15 digits in the localpreview input reveals expiration, security code, country, and ZIP previews;clearing it hides them again. Use a test number such as `4242 4242 4242 4242`.-The primary CTA reads `Start 30 day trial`, with the billing and cancellation+For eligible customers, the primary CTA reads `Start 30 day trial`, with the billing and cancellationnote immediately below it. The quiet `Continue as Guest` scroll cue beneath itmoves focus to the below-fold Guest and Pro comparison,using the same layout as the security details. The table includes email accountdiff --git a/docs/agent-guide/media/billing/returning-customer.png b/docs/agent-guide/media/billing/returning-customer.pngnew file mode 100644index 0000000000..2751db5e5fBinary files /dev/null and b/docs/agent-guide/media/billing/returning-customer.png differdiff --git a/docs/agent-guide/media/billing/subscription-recovery.png b/docs/agent-guide/media/billing/subscription-recovery.pngnew file mode 100644index 0000000000..3f52894771Binary files /dev/null and b/docs/agent-guide/media/billing/subscription-recovery.png differdiff --git a/docs/agent-guide/onboarding.md b/docs/agent-guide/onboarding.mdindex cc843acff0..906aecd3d3 100644--- a/docs/agent-guide/onboarding.md+++ b/docs/agent-guide/onboarding.md@@ -8,6 +8,12 @@ do not see it.## Setup plan step — `/app/onboarding`-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.+The final step offers Pro with a 30-day trial only after the server confirms+first-subscription eligibility. Returning customers see `Get more with Pro.`+and `Get Pro` at the paid monthly price, without trial copy. A loading or failed+eligibility lookup disables Pro checkout; failure offers `Try again`. Invite+promotions keep their own terms. Accounts with an existing subscription see+`Manage subscription`, which opens Stripe billing management instead of creating+a replacement subscription. The comparison below the offer includes Free,+Pro, and Max (see [login](login.md#desktop-onboarding)). Customers can also+purchase plans afterwards in **Settings → Billing**.diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.mdindex 2d2c34faeb..c267974247 100644--- a/docs/agent-guide/settings.md+++ b/docs/agent-guide/settings.md@@ -325,10 +325,25 @@ See [Billing Lab setup and boundaries](../../apps/web/src/features/billing-lab/R`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.+and stacked on narrow panels. The Pro card shows `Free for one month!` only after+`GET /user/stripe/trial_eligibility` confirms eligibility. Eligible customers get+the server-validated 30-day first-subscription trial; returning customers see+paid terms and `Get Pro` opens ordinary paid checkout. Eligibility loading+disables Pro checkout without showing a trial offer; a failed lookup adds+`Try again`. Checkout revalidates eligibility, and a stale trial offer reports+the server rejection rather than silently switching to an immediate charge.+Returning to the tab or reconnecting refreshes the offer. Accounts with an+existing recoverable subscription see `Manage` and payment-management guidance+instead of new checkout cards, even when their access is Free. A failed background+eligibility refresh preserves known subscription management but hides trial+claims. Management remains available if team lookup fails; plan changes wait for+team data. Checkout rejection clears the offer until eligibility refreshes. Retries reuse the+same open offer; changing plans invalidates the old link first. Competing tabs+can show a retryable checkout conflict without creating two payable sessions.+Reference captures from the isolated billing fixture: [returning customer](media/billing/returning-customer.png)+and [subscription recovery](media/billing/subscription-recovery.png). These show+phone-width layouts; payment-provider interactions are covered separately.+`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 belowthe price when narrow. Free lists 2 connected email accounts; Pro and Max list@@ -351,8 +366,8 @@ lookup; failed lookups show `Try again` rather than guessed upgrade options.On a local HMR dev server, `Preview billing & paywall` opens an opt-in preview inBilling. 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+billing summary status, billing permission, active/trialing license, Pro trial+eligibility, AI usage flag, and pending plan actions. The preview uses the real Billing UI with localfixtures; checkout, plan changes, Manage, and Team settings only show previewstatus messages. `Preview paywall` opens the same modal for the selected state,without developer controls inside it. Dismissing the modal returns to Billingdiff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.tsindex 2ebf327bd5..dca64770e6 100644--- a/packages/sdk/generated/auth/index.ts+++ b/packages/sdk/generated/auth/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-tsexport { type Options, Sdk } from './sdk.gen';-export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';+export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, AutoReloadDefaults, AutoReloadMonthlyBudget, AutoReloadSnapshot, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, CheckoutSessionV2Response, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityError, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponse, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusError, GetSubscriptionStatusErrors, GetSubscriptionStatusResponse, GetSubscriptionStatusResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityError, GetTrialEligibilityErrors, GetTrialEligibilityResponse, GetTrialEligibilityResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubMergeMethod, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestMergeability, GithubPullRequestMergeabilityEntry, GithubPullRequestMergeabilityRequest, GithubPullRequestMergeabilityResponse, GithubPullRequestNumber, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestError, MergeGithubPullRequestErrors, MergeGithubPullRequestRequest, MergeGithubPullRequestResponse, MergeGithubPullRequestResponse2, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, ScheduledSeatPlan, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftError, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftRequest, SetGithubPullRequestDraftResponse, SetGithubPullRequestDraftResponse2, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, SubscriptionStatus, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, TrialEligibility, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadError, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponse, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateAutoReloadRequest, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.tsindex 449f68e12c..95fbb67b7a 100644--- a/packages/sdk/generated/auth/sdk.gen.ts+++ b/packages/sdk/generated/auth/sdk.gen.ts@@ -2,7 +2,7 @@import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';import { client } from './client.gen';-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponses, ChangePlanData, ChangePlanErrors, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, ConfigureCodexData, ConfigureCodexResponses, CreateAiCreditCheckoutData, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkErrors, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, DeleteCursorApiKeyData, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, DisconnectCodexData, DisconnectCodexResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetAiBillingPlansData, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryErrors, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyErrors, GetCursorApiKeyResponses, GetGithubPullRequestMergeabilityData, GetGithubPullRequestMergeabilityErrors, GetGithubPullRequestMergeabilityResponses, GetGtmInviteOfferData, GetGtmInviteOfferErrors, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetSubscriptionStatusData, GetSubscriptionStatusErrors, GetSubscriptionStatusResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetTrialEligibilityData, GetTrialEligibilityErrors, GetTrialEligibilityResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, ListCodexEnvironmentsData, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsErrors, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksErrors, ListGtmInviteLinksResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, MergeGithubPullRequestData, MergeGithubPullRequestErrors, MergeGithubPullRequestResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanErrors, PatchTeamMemberPlanResponses, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PollCodexLoginData, PollCodexLoginResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutCursorApiKeyData, PutCursorApiKeyErrors, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelErrors, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SetGithubPullRequestDraftData, SetGithubPullRequestDraftErrors, SetGithubPullRequestDraftResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, StartCodexLoginData, StartCodexLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingAutoReloadData, UpdateAiBillingAutoReloadErrors, UpdateAiBillingAutoReloadResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -1001,6 +1001,13 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Read the caller's eligibility; checkout revalidates before granting a trial.+ */+ public getTrialEligibility<ThrowOnError extends boolean = false>(options?: Options<GetTrialEligibilityData, ThrowOnError>): RequestResult<GetTrialEligibilityResponses, GetTrialEligibilityErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<GetTrialEligibilityResponses, GetTrialEligibilityErrors, ThrowOnError>({ url: '/user/stripe/trial_eligibility', ...options });+ }+/*** Updates the user's tutorialComplete flag.*/diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex 7d31029e8b..3bcda9417e 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -1694,6 +1694,20 @@ export type ToggleNonAdminInvitesResponse = {allow_non_admin_invites: boolean;};+/**+ * Whether the authenticated customer can receive the introductory Pro trial.+ */+export type TrialEligibility = {+ /**+ * Confirmed against the same subscription history used during checkout.+ */+ eligible: boolean;+ /**+ * An existing subscription requires management instead of a new checkout.+ */+ existingSubscription: boolean;+};+/*** Request body for [`update_auto_reload_handler`].*/@@ -4011,6 +4025,27 @@ export type CreatePortalSessionResponses = {export type CreatePortalSessionResponse = CreatePortalSessionResponses[keyof CreatePortalSessionResponses];+export type GetTrialEligibilityData = {+ body?: never;+ path?: never;+ query?: never;+ url: '/user/stripe/trial_eligibility';+};++export type GetTrialEligibilityErrors = {+ 400: ErrorResponse;+ 401: ErrorResponse;+ 500: ErrorResponse;+};++export type GetTrialEligibilityError = GetTrialEligibilityErrors[keyof GetTrialEligibilityErrors];++export type GetTrialEligibilityResponses = {+ 200: TrialEligibility;+};++export type GetTrialEligibilityResponse = GetTrialEligibilityResponses[keyof GetTrialEligibilityResponses];+export type PatchUserTutorialData = {body: PatchUserTutorialRequest;path?: never;diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex 760f29c380..92ec6f6b84 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -4982,6 +4982,55 @@}}},+ "/user/stripe/trial_eligibility": {+ "get": {+ "tags": ["user::stripe::trial_eligibility"],+ "summary": "Read the caller's eligibility; checkout revalidates before granting a trial.",+ "operationId": "get_trial_eligibility",+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/TrialEligibility"+ }+ }+ }+ },+ "400": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/user/tutorial": {"patch": {"tags": ["user::patch_tutorial"],@@ -7227,6 +7276,21 @@}}},+ "TrialEligibility": {+ "type": "object",+ "description": "Whether the authenticated customer can receive the introductory Pro trial.",+ "required": ["eligible", "existingSubscription"],+ "properties": {+ "eligible": {+ "type": "boolean",+ "description": "Confirmed against the same subscription history used during checkout."+ },+ "existingSubscription": {+ "type": "boolean",+ "description": "An existing subscription requires management instead of a new checkout."+ }+ }+ },"UpdateAutoReloadRequest": {"type": "object","description": "Request body for [`update_auto_reload_handler`].",diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex e74c7705fa..3d79f99cd1 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -83,6 +83,8 @@ export const authExcluded = [// Renewal and scheduled-plan details are part of the app's billing settings.'getSubscriptionStatus','getTeamInvites',+ // Introductory offers belong to the app's subscription checkout flow.+ 'getTrialEligibility','getUserInvites','getUserLinkExists','getUserName',diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.mdindex a342cfa223..a535f08d46 100644--- a/services/authentication_service/AGENTS.md+++ b/services/authentication_service/AGENTS.md@@ -23,10 +23,11 @@ key issuance, and account merge/link flows.- Owns: FusionAuth-backed login/session issuance, JWT minting, signupallowlisting, OAuth/OAuth2 account linking, GTM invite links, shared-mailbox- relocation signup, Cursor/Codex API key endpoints.+ relocation signup, Cursor/Codex API key endpoints, introductory trial+ eligibility and subscription checkout.- Not here: authorization/permission decisions on other entities →- `crates/macro_authorization`; subscription/billing logic itself →- `crates/ai_billing`, `crates/initiative`.+ `crates/macro_authorization`; metered AI credits → `crates/ai_billing`;+ team lifecycle and seats → `crates/teams`.## Recipes@@ -45,6 +46,33 @@ key issuance, and account merge/link flows.`env -u DATABASE_URL cargo test -p authentication_service --bin authentication_service config::test`and `cargo run -p authentication_service --bin authentication_service_doppler_config`.+## Subscription checkout++- `src/service/subscription_checkout.rs` owns introductory eligibility and+ checkout terms; its Stripe adapter reads every subscription status and page.+- `GET /user/stripe/trial_eligibility` reads the authenticated customer's+ eligibility without creating checkout. Any prior subscription disqualifies+ the first-subscription trial, including canceled or incomplete subscriptions.+- Nonterminal subscriptions (including past due, unpaid, paused, and incomplete)+ require management; only canceled and incomplete-expired subscriptions allow+ replacement. Eligibility includes `existingSubscription` for recovery UI.+- Share checkout idempotency generations across Pro, Max, and trial terms. Reuse+ exact open offers; expire other open subscription sessions before replacement.+ Never advance a generation after an ambiguous provider failure. Complete the+ backend rollout before releasing clients that depend on these protections.+- Stripe can cache a create failure under its idempotency key. If no session+ becomes visible, retries deliberately retain that key: rotating it could double+ bill after an ambiguous create. Reconcile using the opaque customer, session,+ and idempotency fields in `billing.checkout` traces and Stripe request logs;+ recover an existing subscription, reuse a confirmed matching checkout, or+ expire a confirmed obsolete open session before retrying. If there is no session to reconcile, escalate to Stripe/support and+ wait for Stripe's key retention to expire (at least 24 hours). Never invent a+ fresh key solely to bypass a failed response.+- Keep eligibility reads and checkout validation on the same policy; the legacy+ `hasTrialed` flag tracks trials only and cannot identify paid-only customers.+- Deploy the eligibility endpoint before web clients that require it; otherwise+ the clients keep Pro checkout disabled until the lookup can succeed.+## Gotchas- The signup allowlist has a temporary Develop-only bypassdiff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rsindex b594ab52da..8d704ad922 100644--- a/services/authentication_service/src/api/swagger.rs+++ b/services/authentication_service/src/api/swagger.rs@@ -147,6 +147,7 @@ use model::user::{user::stripe::create_portal_session::create_portal_session,user::stripe::change_plan::change_plan,user::stripe::subscription_status::subscription_status,+ user::stripe::trial_eligibility::trial_eligibility,/// /ai-billingai_billing::inbound::axum_router::get_summary_handler::<crate::api::context::AiBillingServiceType, crate::api::context::AuthorizationService>,diff --git a/services/authentication_service/src/api/user.rs b/services/authentication_service/src/api/user.rsindex c6a455672e..9041f62c4e 100644--- a/services/authentication_service/src/api/user.rs+++ b/services/authentication_service/src/api/user.rs@@ -46,6 +46,10 @@ fn router_with_auth() -> Router<ApiContext> {.route("/tutorial", patch(patch_tutorial::handler)).route("/ai_consent", patch(patch_ai_consent::handler)).route("/quota", get(get_user_quota::handler))+ .route(+ "/stripe/trial_eligibility",+ get(stripe::trial_eligibility::trial_eligibility),+ ).route("/stripe/checkoutv2",post(diff --git a/services/authentication_service/src/api/user/stripe/mod.rs b/services/authentication_service/src/api/user/stripe/mod.rsindex 9f081b8c6b..0006b737ce 100644--- a/services/authentication_service/src/api/user/stripe/mod.rs+++ b/services/authentication_service/src/api/user/stripe/mod.rs@@ -3,5 +3,6 @@ pub mod create_checkout_session_v2;pub mod create_portal_session;mod shared;pub mod subscription_status;+pub mod trial_eligibility;pub use shared::{PaidPlan, StripeOperationError, StripePrices, StripeSessionResponse};diff --git a/services/authentication_service/src/api/user/stripe/shared.rs b/services/authentication_service/src/api/user/stripe/shared.rsindex 9f6aa2b90b..83a1c08932 100644--- a/services/authentication_service/src/api/user/stripe/shared.rs+++ b/services/authentication_service/src/api/user/stripe/shared.rs@@ -68,9 +68,11 @@ pub enum StripeOperationError {UnexpectedStripeResponse,#[error("The 30-day trial is only available for your first Premium subscription")]TrialUnavailable,+ #[error("Checkout changed in another tab. Please try again.")]+ CheckoutConflict,#[error("Could not create checkout")]CheckoutGateway(StripeCheckoutError),- #[error("User already has an active subscription")]+ #[error("You already have a subscription. Open Manage in Settings → Billing to update it.")]AlreadySubscribed,#[error("Teams service error")]TeamsErr(#[from] teams::domain::model::TeamError),@@ -104,6 +106,7 @@ impl IntoResponse for StripeOperationError {StripeOperationError::StripeErr(_) => StatusCode::INTERNAL_SERVER_ERROR,StripeOperationError::PromoCodeNotFound => StatusCode::NOT_FOUND,StripeOperationError::UnexpectedStripeResponse => StatusCode::INTERNAL_SERVER_ERROR,+ StripeOperationError::CheckoutConflict => StatusCode::CONFLICT,StripeOperationError::AlreadySubscribed => StatusCode::CONFLICT,StripeOperationError::TrialUnavailable => StatusCode::CONFLICT,StripeOperationError::CheckoutGateway(_) => StatusCode::INTERNAL_SERVER_ERROR,@@ -153,6 +156,11 @@ impl From<CheckoutError<StripeCheckoutError>> for StripeOperationError {CheckoutError::TrialUnavailable => Self::TrialUnavailable,CheckoutError::PlanUnavailable => Self::PlanUnavailable,CheckoutError::PromoCodeNotFound => Self::PromoCodeNotFound,+ CheckoutError::Gateway(StripeCheckoutError::TrialUnavailable) => Self::TrialUnavailable,+ CheckoutError::Gateway(StripeCheckoutError::ExistingSubscription) => {+ Self::AlreadySubscribed+ }+ CheckoutError::Gateway(StripeCheckoutError::CheckoutConflict) => Self::CheckoutConflict,CheckoutError::Gateway(error) => Self::CheckoutGateway(error),}}diff --git a/services/authentication_service/src/api/user/stripe/trial_eligibility.rs b/services/authentication_service/src/api/user/stripe/trial_eligibility.rsnew file mode 100644index 0000000000..524396555f--- /dev/null+++ b/services/authentication_service/src/api/user/stripe/trial_eligibility.rs@@ -0,0 +1,33 @@+//! Authenticated, read-only introductory trial eligibility.++use axum::{Json, extract::State};+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};+use model::response::ErrorResponse;++use super::StripeOperationError;+use crate::api::context::{ApiContext, AuthorizationService};+use crate::service::subscription_checkout::TrialEligibility;++/// Read the caller's eligibility; checkout revalidates before granting a trial.+#[utoipa::path(+ get,+ path = "/user/stripe/trial_eligibility",+ operation_id = "get_trial_eligibility",+ responses(+ (status = 200, body = TrialEligibility),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(skip_all, err)]+pub async fn trial_eligibility(+ State(ctx): State<ApiContext>,+ user: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,+) -> Result<Json<TrialEligibility>, StripeOperationError> {+ Ok(Json(+ ctx.subscription_checkout+ .trial_eligibility(&user.authorization.user.macro_user_id)+ .await?,+ ))+}diff --git a/services/authentication_service/src/outbound/subscription_checkout.rs b/services/authentication_service/src/outbound/subscription_checkout.rsindex 0831c5240a..4fb1f5f89a 100644--- a/services/authentication_service/src/outbound/subscription_checkout.rs+++ b/services/authentication_service/src/outbound/subscription_checkout.rs@@ -4,9 +4,11 @@ use std::sync::Arc;use gtm_invite::domain::{models::GtmInviteError, ports::GtmInviteService};use macro_user_id::user_id::MacroUserIdStr;+use sha2::{Digest, Sha256};use sqlx::PgPool;use teams::domain::model::{CustomerError, SeatPrices};use thiserror::Error;+use tracing::Instrument;use crate::service::subscription_checkout::{CheckoutGateway, CheckoutRequest, CheckoutTerms, ONBOARDING_TRIAL_DAYS, SubscriptionHistory,@@ -14,7 +16,7 @@ use crate::service::subscription_checkout::{const TRIAL_SESSION_MARKER: &str = "onboarding_trial";-enum TrialSessionAttempt {+enum SessionAttempt {Reuse(String),Create(String),}@@ -43,6 +45,18 @@ pub enum StripeCheckoutError {/// Stripe returned an invalid URL.#[error(transparent)]Url(#[from] url::ParseError),+ /// Checkout terms could not be serialized.+ #[error(transparent)]+ Serialization(#[from] serde_json::Error),+ /// A subscription completed while checkout was being prepared.+ #[error("You already have a subscription. Open Manage in Settings → Billing to update it.")]+ ExistingSubscription,+ /// Subscription history changed after the introductory offer was approved.+ #[error("The 30-day trial is only available for your first Premium subscription")]+ TrialUnavailable,+ /// Another request is preparing different checkout terms.+ #[error("Checkout changed in another tab. Please try again.")]+ CheckoutConflict,/// Stripe omitted data needed to complete the operation safely.#[error("Unexpected Stripe response")]UnexpectedResponse,@@ -72,69 +86,169 @@ impl<I> StripeCheckoutGateway<I> {}}- // Reuse an open attempt. Anchor Stripe's idempotency key to the previous- // expired attempt so concurrent tabs cannot stockpile usable trial links,- // while an abandoned/expired checkout remains retryable.- async fn trial_attempt(+ // One generation key is shared across all plans and terms. Stripe atomically+ // replays identical creates and rejects competing parameters. Advance only+ // after every older payable link has been conclusively invalidated.+ #[tracing::instrument(name = "billing.checkout.prepare", skip_all, fields(stripe_customer_id = %customer, ?terms), err)]+ async fn session_attempt(&self,customer: &stripe::CustomerId,- request: &CheckoutRequest<'_>,- ) -> Result<TrialSessionAttempt, StripeCheckoutError> {+ fingerprint: &str,+ terms: CheckoutTerms,+ ) -> Result<SessionAttempt, StripeCheckoutError> {let mut params = stripe::ListCheckoutSessions::new();params.customer = Some(customer.clone());params.limit = Some(100);+ let mut sessions = Vec::new();loop {- let page = stripe::CheckoutSession::list(&self.stripe, ¶ms).await?;- if let Some(session) = page.data.iter().find(|session| {- session- .metadata- .as_ref()- .is_some_and(|metadata| metadata.contains_key(TRIAL_SESSION_MARKER))- }) {- return match session.status {- Some(stripe::CheckoutSessionStatus::Open)- if trial_session_matches(session, request) =>+ let page = stripe::CheckoutSession::list(&self.stripe, ¶ms)+ .instrument(tracing::info_span!("stripe.checkout.list"))+ .await?;+ let next = page.data.last().map(|session| session.id.clone());+ sessions.extend(+ page.data+ .into_iter()+ .filter(|session| session.mode == stripe::CheckoutSessionMode::Subscription),+ );+ if !page.has_more {+ break;+ }+ params.starting_after = Some(next.ok_or(StripeCheckoutError::UnexpectedResponse)?);+ }+ let mut reusable = None;+ for session in &sessions {+ match session.status {+ Some(stripe::CheckoutSessionStatus::Open) => {+ if reusable.is_none()+ && session+ .metadata+ .as_ref()+ .and_then(|m| m.get("checkout_terms"))+ .is_some_and(|value| value == fingerprint){- Ok(TrialSessionAttempt::Reuse(+ tracing::info!(checkout_session_id = %session.id, outcome = "reuse", "matched checkout offer");+ reusable = Some(session.url.clone().ok_or(StripeCheckoutError::UnexpectedResponse)?,- ))- }- Some(stripe::CheckoutSessionStatus::Open) => {- // A changed team or return destination needs fresh metadata.- stripe::CheckoutSession::expire(&self.stripe, &session.id).await?;- Ok(TrialSessionAttempt::Create(format!(- "onboarding-trial-{customer}-after-{}",- session.id- )))+ );+ } else {+ // A failure may mean completion raced expiration. Never create+ // or return another payable link after an ambiguous expiration.+ let expired =+ stripe::CheckoutSession::expire(&self.stripe, &session.id)+ .instrument(tracing::info_span!("stripe.checkout.expire", checkout_session_id = %session.id))+ .await?;+ if expired.status != Some(stripe::CheckoutSessionStatus::Expired) {+ return Err(StripeCheckoutError::UnexpectedResponse);+ }}- Some(stripe::CheckoutSessionStatus::Expired) => {- Ok(TrialSessionAttempt::Create(format!(- "onboarding-trial-{customer}-after-{}",- session.id- )))+ }+ Some(stripe::CheckoutSessionStatus::Complete)+ if sessions+ .first()+ .is_some_and(|latest| latest.id == session.id) =>+ {+ // A list/history race must not turn a completed checkout into+ // permission to subscribe again. Read its subscription directly.+ let subscription = session+ .subscription+ .as_ref()+ .ok_or(StripeCheckoutError::UnexpectedResponse)?;+ let subscription =+ stripe::Subscription::retrieve(&self.stripe, &subscription.id(), &[])+ .instrument(tracing::info_span!("stripe.subscription.retrieve", subscription_id = %subscription.id()))+ .await?;+ if !subscription_terminal(subscription.status) {+ return Err(StripeCheckoutError::ExistingSubscription);}- // The customer finished checkout between history lookup and- // this read. Do not create a second subscription in that race.- _ => Err(StripeCheckoutError::UnexpectedResponse),- };+ }+ Some(+ stripe::CheckoutSessionStatus::Expired+ | stripe::CheckoutSessionStatus::Complete,+ ) => {}+ None => return Err(StripeCheckoutError::UnexpectedResponse),}- if !page.has_more {- break;+ }+ let history = subscription_history(&self.stripe, customer).await?;+ if history.has_existing_subscription {+ return Err(StripeCheckoutError::ExistingSubscription);+ }+ if terms == CheckoutTerms::Trial && !history.trial_eligible() {+ return Err(StripeCheckoutError::TrialUnavailable);+ }+ if let Some(url) = reusable {+ return Ok(SessionAttempt::Reuse(url));+ }+ Ok(SessionAttempt::Create(match sessions.first() {+ Some(session) => format!("subscription-checkout-{customer}-after-{}", session.id),+ None => format!("subscription-checkout-{customer}-first"),+ }))+ }++ #[tracing::instrument(name = "billing.checkout", skip_all, fields(stripe_customer_id = %customer, ?terms), err)]+ async fn checkout(+ &self,+ customer: stripe::CustomerId,+ request: CheckoutRequest<'_>,+ terms: CheckoutTerms,+ promotion: Option<stripe::PromotionCodeId>,+ ) -> Result<String, StripeCheckoutError> {+ let mut params = checkout_params(+ customer.clone(),+ &request,+ self.prices.price_id(request.plan)?,+ terms,+ promotion,+ );+ // Sort nested metadata too: HashMap iteration order changes between requests.+ let mut payload = serde_json::to_value(¶ms)?;+ payload.sort_all_objects();+ let payload = serde_json::to_vec(&payload)?;+ let fingerprint = format!("{:x}", Sha256::digest(payload));+ params+ .metadata+ .get_or_insert_default()+ .insert("checkout_terms".into(), fingerprint.clone());+ let key = match self.session_attempt(&customer, &fingerprint, terms).await? {+ SessionAttempt::Reuse(url) => {+ url::Url::parse(&url)?;+ return Ok(url);}- params.starting_after = Some(- page.data- .last()- .ok_or(StripeCheckoutError::UnexpectedResponse)?- .id- .clone(),- );+ SessionAttempt::Create(key) => key,+ };+ tracing::info!(idempotency_key = %key, outcome = "create", "creating checkout offer");+ let stripe = self+ .stripe+ .as_ref()+ .clone()+ .with_strategy(stripe::RequestStrategy::Idempotent(key));+ let session = stripe::CheckoutSession::create(&stripe, params)+ .instrument(tracing::info_span!("stripe.checkout.create"))+ .await+ .map_err(|error| match &error {+ stripe::StripeError::Stripe(error)+ if error.http_status == 409+ || error.error_type == stripe::ErrorType::IdempotencyError =>+ {+ StripeCheckoutError::CheckoutConflict+ }+ _ => StripeCheckoutError::Stripe(error),+ })?;+ // An idempotency replay contains the original response, even if another+ // tab has since expired that session. Never redirect to that stale URL.+ let session = stripe::CheckoutSession::retrieve(&self.stripe, &session.id, &[])+ .instrument(+ tracing::info_span!("stripe.checkout.retrieve", checkout_session_id = %session.id),+ )+ .await?;+ if session.status != Some(stripe::CheckoutSessionStatus::Open) {+ return Err(StripeCheckoutError::CheckoutConflict);}- Ok(TrialSessionAttempt::Create(format!(- "onboarding-trial-{customer}-first"- )))+ let url = session.url.ok_or(StripeCheckoutError::UnexpectedResponse)?;+ url::Url::parse(&url)?;+ Ok(url)}}@@ -188,32 +302,7 @@ impl<I: GtmInviteService> CheckoutGateway for StripeCheckoutGateway<I> {terms: CheckoutTerms,promotion: Option<Self::Promotion>,) -> Result<String, Self::Error> {- let stripe = match terms {- CheckoutTerms::Paid => self.stripe.as_ref().clone(),- CheckoutTerms::Trial => match self.trial_attempt(&customer, &request).await? {- TrialSessionAttempt::Reuse(url) => {- url::Url::parse(&url)?;- return Ok(url);- }- TrialSessionAttempt::Create(key) => self- .stripe- .as_ref()- .clone()- .with_strategy(stripe::RequestStrategy::Idempotent(key)),- },- };- let params = checkout_params(- customer,- &request,- self.prices.price_id(request.plan)?,- terms,- promotion,- );- let session = stripe::CheckoutSession::create(&stripe, params).await?;- let url = session.url.ok_or(StripeCheckoutError::UnexpectedResponse)?;- // Preserve the exact signed/opaque URL returned by Stripe.- url::Url::parse(&url)?;- Ok(url)+ self.checkout(customer, request, terms, promotion).await}}@@ -260,18 +349,14 @@ fn checkout_params<'a>(}}-fn trial_session_matches(session: &stripe::CheckoutSession, request: &CheckoutRequest<'_>) -> bool {- session.success_url.as_deref() == Some(request.success_url.as_str())- && session.cancel_url.as_deref() == Some(request.cancel_url.as_str())- && ["team_id", "owner_id"].iter().all(|key| {- session- .metadata- .as_ref()- .and_then(|metadata| metadata.get(*key))- == request.metadata.get(*key)- })+fn subscription_terminal(status: stripe::SubscriptionStatus) -> bool {+ matches!(+ status,+ stripe::SubscriptionStatus::Canceled | stripe::SubscriptionStatus::IncompleteExpired+ )}+#[tracing::instrument(skip_all, fields(stripe_customer_id = %customer), err, ret)]async fn subscription_history(stripe_client: &stripe::Client,customer: &stripe::CustomerId,@@ -284,12 +369,10 @@ async fn subscription_history(loop {let page = stripe::Subscription::list(stripe_client, ¶ms).await?;history.has_previous_subscription |= !page.data.is_empty();- history.has_active_subscription |= page.data.iter().any(|sub| {- matches!(- sub.status,- stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing- )- });+ history.has_existing_subscription |= page+ .data+ .iter()+ .any(|sub| !subscription_terminal(sub.status));if !page.has_more {break;}diff --git a/services/authentication_service/src/outbound/subscription_checkout/test.rs b/services/authentication_service/src/outbound/subscription_checkout/test.rsindex f2af015233..c097119ab9 100644--- a/services/authentication_service/src/outbound/subscription_checkout/test.rs+++ b/services/authentication_service/src/outbound/subscription_checkout/test.rs@@ -1,3 +1,4 @@+mod concurrency;use super::*;use axum::{Json, Router,@@ -45,26 +46,6 @@ fn trial_payload_requires_no_coupon_and_works_without_metadata() {assert_eq!(json["cancel_url"], input.cancel_url);}-#[test]-fn an_open_trial_is_reused_only_for_the_same_team_and_return_destinations() {- let mut input = request();- input.metadata.insert("team_id".into(), "team-first".into());- let session = stripe::CheckoutSession {- success_url: Some(input.success_url.clone()),- cancel_url: Some(input.cancel_url.clone()),- metadata: Some(input.metadata.clone()),- ..Default::default()- };- assert!(trial_session_matches(&session, &input));- input- .metadata- .insert("team_id".into(), "team-second".into());- assert!(!trial_session_matches(&session, &input));- input.metadata.insert("team_id".into(), "team-first".into());- input.success_url = "https://dev.macro.com/app/onboarding?subscriptionSuccess=true".into();- assert!(!trial_session_matches(&session, &input));-}-#[test]fn trial_keeps_team_and_conversion_metadata() {let mut input = request();@@ -172,7 +153,8 @@ fn existing_session(status: stripe::CheckoutSessionStatus) -> stripe::CheckoutSeurl: Some("https://checkout.stripe.com/existing".into()),success_url: Some(input.success_url),cancel_url: Some(input.cancel_url),- metadata: Some([(TRIAL_SESSION_MARKER.into(), "30".into())].into()),+ metadata: Some([("checkout_terms".into(), "same-terms".into())].into()),+ mode: stripe::CheckoutSessionMode::Subscription,..Default::default()}}@@ -183,54 +165,114 @@ fn page(sessions: Vec<stripe::CheckoutSession>, more: bool) -> serde_json::Value#[tokio::test]async fn reopening_checkout_reuses_the_existing_trial_link() {- let (gateway, stub, task) = stub_gateway(vec![page(- vec![existing_session(stripe::CheckoutSessionStatus::Open)],- false,- )])+ let (gateway, stub, task) = stub_gateway(vec![+ page(+ vec![existing_session(stripe::CheckoutSessionStatus::Open)],+ false,+ ),+ empty_history(),+ ]).await;let attempt = gateway- .trial_attempt(&"cus_test".parse().unwrap(), &request())+ .session_attempt(+ &"cus_test".parse().unwrap(),+ "same-terms",+ CheckoutTerms::Trial,+ ).await.unwrap();task.abort();assert!(- matches!(attempt, TrialSessionAttempt::Reuse(url) if url == "https://checkout.stripe.com/existing")+ matches!(attempt, SessionAttempt::Reuse(url) if url == "https://checkout.stripe.com/existing"));- assert_eq!(stub.requests.lock().unwrap().len(), 1);+ assert_eq!(stub.requests.lock().unwrap().len(), 2);}#[tokio::test]async fn expired_checkout_has_a_stable_new_idempotency_key() {- let (gateway, _, task) = stub_gateway(vec![page(- vec![existing_session(stripe::CheckoutSessionStatus::Expired)],- false,- )])+ let (gateway, _, task) = stub_gateway(vec![+ page(+ vec![existing_session(stripe::CheckoutSessionStatus::Expired)],+ false,+ ),+ empty_history(),+ ]).await;let attempt = gateway- .trial_attempt(&"cus_test".parse().unwrap(), &request())+ .session_attempt(+ &"cus_test".parse().unwrap(),+ "same-terms",+ CheckoutTerms::Trial,+ ).await.unwrap();task.abort();assert!(- matches!(attempt, TrialSessionAttempt::Create(key) if key == "onboarding-trial-cus_test-after-cs_test_existing")+ matches!(attempt, SessionAttempt::Create(key) if key == "subscription-checkout-cus_test-after-cs_test_existing"));}#[tokio::test]-async fn checkout_completed_during_history_lookup_cannot_be_created_again() {- let (gateway, _, task) = stub_gateway(vec![page(- vec![existing_session(stripe::CheckoutSessionStatus::Complete)],- false,- )])- .await;- let attempt = gateway- .trial_attempt(&"cus_test".parse().unwrap(), &request())- .await;- task.abort();+async fn completed_checkout_must_have_a_terminal_subscription_before_paid_replacement() {+ for (status, blocked) in [+ (stripe::SubscriptionStatus::Active, true),+ (stripe::SubscriptionStatus::PastDue, true),+ (stripe::SubscriptionStatus::Canceled, false),+ (stripe::SubscriptionStatus::IncompleteExpired, false),+ ] {+ let subscription = stripe::Subscription {+ id: "sub_existing".parse().unwrap(),+ customer: stripe::Expandable::Id("cus_test".parse().unwrap()),+ status,+ ..Default::default()+ };+ let mut session = existing_session(stripe::CheckoutSessionStatus::Complete);+ session.subscription = Some(stripe::Expandable::Id(subscription.id.clone()));+ let (gateway, stub, task) = stub_gateway(vec![+ page(vec![session], false),+ serde_json::to_value(&subscription).unwrap(),+ serde_json::json!({"object":"list", "url":"/v1/subscriptions", "data":[subscription], "has_more":false}),+ ]).await;+ let attempt = gateway+ .session_attempt(&"cus_test".parse().unwrap(), "paid", CheckoutTerms::Paid)+ .await;+ if blocked {+ assert!(matches!(+ attempt,+ Err(StripeCheckoutError::ExistingSubscription)+ ));+ } else {+ assert!(+ matches!(attempt, Ok(SessionAttempt::Create(key)) if key == "subscription-checkout-cus_test-after-cs_test_existing")+ );+ }+ assert!(stub.requests.lock().unwrap()[1].starts_with("GET /v1/subscriptions/sub_existing"));+ task.abort();+ }+}++#[tokio::test]+async fn a_new_trial_is_rejected_if_another_checkout_completed_and_canceled_during_validation() {+ let subscription = stripe::Subscription {+ id: "sub_existing".parse().unwrap(),+ customer: stripe::Expandable::Id("cus_test".parse().unwrap()),+ status: stripe::SubscriptionStatus::Canceled,+ ..Default::default()+ };+ let mut session = existing_session(stripe::CheckoutSessionStatus::Complete);+ session.subscription = Some(stripe::Expandable::Id(subscription.id.clone()));+ let (gateway, _, task) = stub_gateway(vec![+ page(vec![session], false),+ serde_json::to_value(&subscription).unwrap(),+ serde_json::json!({"object":"list", "url":"/v1/subscriptions", "data":[subscription], "has_more":false}),+ ]).await;assert!(matches!(- attempt,- Err(StripeCheckoutError::UnexpectedResponse)+ gateway+ .session_attempt(&"cus_test".parse().unwrap(), "trial", CheckoutTerms::Trial)+ .await,+ Err(StripeCheckoutError::TrialUnavailable)));+ task.abort();}#[tokio::test]@@ -240,16 +282,19 @@ async fn changed_team_expires_the_old_trial_before_creating_another() {let (gateway, stub, task) = stub_gateway(vec![page(vec![session], false),serde_json::to_value(expired).unwrap(),+ empty_history(),]).await;- let mut input = request();- input.metadata.insert("team_id".into(), "new-team".into());let attempt = gateway- .trial_attempt(&"cus_test".parse().unwrap(), &input)+ .session_attempt(+ &"cus_test".parse().unwrap(),+ "different-terms",+ CheckoutTerms::Trial,+ ).await.unwrap();task.abort();- assert!(matches!(attempt, TrialSessionAttempt::Create(_)));+ assert!(matches!(attempt, SessionAttempt::Create(_)));assert_eq!(stub.requests.lock().unwrap()[1],"POST /v1/checkout/sessions/cs_test_existing/expire"@@ -268,14 +313,19 @@ async fn trial_lookup_reads_past_a_page_of_unrelated_checkouts() {vec![existing_session(stripe::CheckoutSessionStatus::Open)],false,),+ empty_history(),]).await;let attempt = gateway- .trial_attempt(&"cus_test".parse().unwrap(), &request())+ .session_attempt(+ &"cus_test".parse().unwrap(),+ "same-terms",+ CheckoutTerms::Trial,+ ).await.unwrap();task.abort();- assert!(matches!(attempt, TrialSessionAttempt::Reuse(_)));+ assert!(matches!(attempt, SessionAttempt::Reuse(_)));assert!(stub.requests.lock().unwrap()[1].contains("starting_after=cs_test_unrelated"));}@@ -302,7 +352,7 @@ async fn history_includes_canceled_subscriptions_and_every_page() {.unwrap();task.abort();assert!(history.has_previous_subscription);- assert!(history.has_active_subscription);+ assert!(history.has_existing_subscription);let requests = stub.requests.lock().unwrap();assert!(requests@@ -311,3 +361,71 @@ async fn history_includes_canceled_subscriptions_and_every_page() {);assert!(requests[1].contains("starting_after=sub_canceled"));}++fn empty_history() -> serde_json::Value {+ serde_json::json!({"object":"list", "url":"/v1/subscriptions", "data":[], "has_more":false})+}++#[tokio::test]+async fn only_terminal_subscriptions_allow_a_replacement() {+ for (status, blocked) in [+ (stripe::SubscriptionStatus::Active, true),+ (stripe::SubscriptionStatus::Trialing, true),+ (stripe::SubscriptionStatus::PastDue, true),+ (stripe::SubscriptionStatus::Unpaid, true),+ (stripe::SubscriptionStatus::Paused, true),+ (stripe::SubscriptionStatus::Incomplete, true),+ (stripe::SubscriptionStatus::Canceled, false),+ (stripe::SubscriptionStatus::IncompleteExpired, false),+ ] {+ let subscription = stripe::Subscription {+ id: "sub_test".parse().unwrap(),+ customer: stripe::Expandable::Id("cus_test".parse().unwrap()),+ status,+ ..Default::default()+ };+ let (gateway, _, task) = stub_gateway(vec![serde_json::json!({+ "object":"list", "url":"/v1/subscriptions", "data":[subscription], "has_more":false+ })])+ .await;+ let history = subscription_history(&gateway.stripe, &"cus_test".parse().unwrap())+ .await+ .unwrap();+ task.abort();+ assert_eq!(history.has_existing_subscription, blocked, "{status:?}");+ assert!(history.has_previous_subscription);+ }+}++#[tokio::test]+async fn legacy_open_sessions_on_later_pages_are_expired_before_reusing_the_current_offer() {+ let matching = existing_session(stripe::CheckoutSessionStatus::Open);+ let mut legacy = existing_session(stripe::CheckoutSessionStatus::Open);+ legacy.id = "cs_test_legacy".parse().unwrap();+ legacy.metadata = None;+ let mut expired = legacy.clone();+ expired.status = Some(stripe::CheckoutSessionStatus::Expired);+ let (gateway, stub, task) = stub_gateway(vec![+ page(vec![matching], true),+ page(vec![legacy], false),+ serde_json::to_value(expired).unwrap(),+ empty_history(),+ ])+ .await;+ assert!(matches!(+ gateway+ .session_attempt(+ &"cus_test".parse().unwrap(),+ "same-terms",+ CheckoutTerms::Paid+ )+ .await+ .unwrap(),+ SessionAttempt::Reuse(_)+ ));+ assert_eq!(+ stub.requests.lock().unwrap()[2],+ "POST /v1/checkout/sessions/cs_test_legacy/expire"+ );+ task.abort();+}diff --git a/services/authentication_service/src/outbound/subscription_checkout/test/concurrency.rs b/services/authentication_service/src/outbound/subscription_checkout/test/concurrency.rsnew file mode 100644index 0000000000..4579aae413--- /dev/null+++ b/services/authentication_service/src/outbound/subscription_checkout/test/concurrency.rs@@ -0,0 +1,371 @@+use super::*;+use axum::{body::to_bytes, http::StatusCode, response::IntoResponse};+use std::collections::BTreeMap;+use tokio::sync::Barrier;++#[derive(Default)]+struct ProviderState {+ sessions: Vec<stripe::CheckoutSession>,+ idempotency: HashMap<String, (BTreeMap<String, String>, stripe::CheckoutSession)>,+ creates: usize,+ create_keys: Vec<String>,+ cached_server_failure: bool,+ fail_first_response: bool,+ hide_created_once: bool,+ complete_on_expire: bool,+ expire_before_retrieve: bool,+ list_count: usize,+}++#[derive(Clone)]+struct Provider {+ state: Arc<Mutex<ProviderState>>,+ initial_lists: Option<Arc<Barrier>>,+}++async fn provider(State(provider): State<Provider>, request: Request) -> axum::response::Response {+ let method = request.method().clone();+ let path = request.uri().path().to_owned();+ let key = request+ .headers()+ .get("idempotency-key")+ .map(|value| value.to_str().unwrap().to_owned());+ let body = to_bytes(request.into_body(), 1_000_000).await.unwrap();+ let params: BTreeMap<String, String> =+ url::form_urlencoded::parse(&body).into_owned().collect();+ let first_list = {+ let mut state = provider.state.lock().unwrap();+ if path == "/v1/checkout/sessions" && method == "GET" {+ state.list_count += 1;+ state.list_count <= 2 && provider.initial_lists.is_some()+ } else {+ false+ }+ };+ if first_list {+ provider.initial_lists.as_ref().unwrap().wait().await;+ return Json(page(vec![], false)).into_response();+ }+ let mut state = provider.state.lock().unwrap();+ if path == "/v1/subscriptions" {+ return Json(empty_history()).into_response();+ }+ if path == "/v1/checkout/sessions" && method == "GET" {+ if state.hide_created_once {+ state.hide_created_once = false;+ return Json(page(vec![], false)).into_response();+ }+ return Json(page(state.sessions.clone(), false)).into_response();+ }+ if path.ends_with("/expire") {+ if state.complete_on_expire {+ return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error":{"type":"invalid_request_error", "message":"Session has completed"}}))).into_response();+ }+ let id = path.split('/').nth(4).unwrap();+ let session = state+ .sessions+ .iter_mut()+ .find(|session| session.id.as_str() == id)+ .unwrap();+ session.status = Some(stripe::CheckoutSessionStatus::Expired);+ return Json(session.clone()).into_response();+ }+ if path == "/v1/checkout/sessions" && method == "POST" {+ let key = key.expect("every subscription create must be idempotent");+ state.create_keys.push(key.clone());+ if state.cached_server_failure {+ return (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"error":{"type":"api_error", "message":"Cached provider failure"}}))).into_response();+ }+ if let Some((original, session)) = state.idempotency.get(&key) {+ if original != ¶ms {+ return (StatusCode::BAD_REQUEST, Json(serde_json::json!({"error":{"type":"idempotency_error", "message":"Parameters differ"}}))).into_response();+ }+ return Json(session.clone()).into_response();+ }+ state.creates += 1;+ let session = stripe::CheckoutSession {+ id: format!("cs_test_{}", state.creates).parse().unwrap(),+ status: Some(stripe::CheckoutSessionStatus::Open),+ mode: stripe::CheckoutSessionMode::Subscription,+ url: Some(format!("https://checkout.stripe.com/{}", state.creates)),+ metadata: Some(+ [(+ "checkout_terms".into(),+ params.get("metadata[checkout_terms]").unwrap().clone(),+ )]+ .into(),+ ),+ ..Default::default()+ };+ state.idempotency.insert(key, (params, session.clone()));+ state.sessions.insert(0, session.clone());+ if state.fail_first_response {+ state.fail_first_response = false;+ state.hide_created_once = true;+ // The provider committed a 200 result, but the response body is+ // truncated in transit. Its idempotency cache still holds success.+ return (StatusCode::OK, "{\"id\":").into_response();+ }+ return Json(session).into_response();+ }+ if method == "GET" && path.starts_with("/v1/checkout/sessions/") {+ let id = path.rsplit('/').next().unwrap();+ let expired = state.expire_before_retrieve;+ let session = state+ .sessions+ .iter_mut()+ .find(|session| session.id.as_str() == id)+ .unwrap();+ if expired {+ session.status = Some(stripe::CheckoutSessionStatus::Expired);+ }+ return Json(session.clone()).into_response();+ }+ panic!("unexpected request: {method} {path}");+}++async fn setup(+ concurrent: bool,+) -> (+ StripeCheckoutGateway<()>,+ Provider,+ tokio::task::JoinHandle<()>,+) {+ let provider_state = Provider {+ state: Arc::new(Mutex::new(ProviderState::default())),+ initial_lists: concurrent.then(|| Arc::new(Barrier::new(2))),+ };+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}/", listener.local_addr().unwrap());+ let app = Router::new()+ .fallback(provider)+ .with_state(provider_state.clone());+ let task = tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ let gateway = StripeCheckoutGateway::new(+ sqlx::postgres::PgPoolOptions::new()+ .connect_lazy("postgres://unused:unused@localhost/unused")+ .unwrap(),+ Arc::new(stripe::Client::from_url(url.as_str(), "sk_test_fixture")),+ Arc::new(()),+ SeatPrices {+ premium: "price_pro".into(),+ max: Some("price_max".into()),+ },+ );+ (gateway, provider_state, task)+}++#[tokio::test]+async fn simultaneous_same_plan_creates_one_payable_session() {+ let (gateway, provider, task) = setup(true).await;+ let (first, second) = tokio::join!(+ gateway.checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None+ ),+ gateway.checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None+ ),+ );+ assert_eq!(first.unwrap(), second.unwrap());+ assert_eq!(provider.state.lock().unwrap().creates, 1);+ task.abort();+}++#[tokio::test]+async fn concurrent_pro_and_max_intents_conflict_instead_of_creating_two_sessions() {+ let (gateway, provider, task) = setup(true).await;+ let mut max = request();+ max.plan = SeatPlan::Max;+ let (first, second) = tokio::join!(+ gateway.checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None+ ),+ gateway.checkout("cus_test".parse().unwrap(), max, CheckoutTerms::Paid, None),+ );+ assert!(matches!(+ (&first, &second),+ (Ok(_), Err(StripeCheckoutError::CheckoutConflict))+ | (Err(StripeCheckoutError::CheckoutConflict), Ok(_))+ ));+ assert_eq!(provider.state.lock().unwrap().creates, 1);+ task.abort();+}++#[tokio::test]+async fn concurrent_trial_and_paid_intents_share_the_same_generation() {+ let (gateway, provider, task) = setup(true).await;+ let (first, second) = tokio::join!(+ gateway.checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Trial,+ None+ ),+ gateway.checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None+ ),+ );+ assert!(matches!(+ (&first, &second),+ (Ok(_), Err(StripeCheckoutError::CheckoutConflict))+ | (Err(StripeCheckoutError::CheckoutConflict), Ok(_))+ ));+ assert_eq!(provider.state.lock().unwrap().creates, 1);+ task.abort();+}++#[tokio::test]+async fn lost_successful_response_reuses_the_key_even_before_session_is_listed() {+ let (gateway, provider, task) = setup(false).await;+ provider.state.lock().unwrap().fail_first_response = true;+ assert!(+ gateway+ .checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None+ )+ .await+ .is_err()+ );+ let retry = gateway+ .checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None,+ )+ .await+ .unwrap();+ assert_eq!(retry, "https://checkout.stripe.com/1");+ assert_eq!(provider.state.lock().unwrap().creates, 1);+ task.abort();+}++#[tokio::test]+async fn changing_plan_expires_the_old_link_and_retries_reuse_the_new_one() {+ let (gateway, provider, task) = setup(false).await;+ gateway+ .checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None,+ )+ .await+ .unwrap();+ let mut max = request();+ max.plan = SeatPlan::Max;+ let url = gateway+ .checkout("cus_test".parse().unwrap(), max, CheckoutTerms::Paid, None)+ .await+ .unwrap();+ let mut max = request();+ max.plan = SeatPlan::Max;+ assert_eq!(+ gateway+ .checkout("cus_test".parse().unwrap(), max, CheckoutTerms::Paid, None)+ .await+ .unwrap(),+ url+ );+ let state = provider.state.lock().unwrap();+ assert_eq!(state.creates, 2);+ assert_eq!(+ state+ .sessions+ .iter()+ .filter(|session| session.status == Some(stripe::CheckoutSessionStatus::Open))+ .count(),+ 1+ );+ task.abort();+}++#[tokio::test]+async fn completion_racing_expiration_prevents_a_new_checkout() {+ let (gateway, provider, task) = setup(false).await;+ gateway+ .checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None,+ )+ .await+ .unwrap();+ provider.state.lock().unwrap().complete_on_expire = true;+ let mut max = request();+ max.plan = SeatPlan::Max;+ assert!(+ gateway+ .checkout("cus_test".parse().unwrap(), max, CheckoutTerms::Paid, None)+ .await+ .is_err()+ );+ assert_eq!(provider.state.lock().unwrap().creates, 1);+ task.abort();+}++#[tokio::test]+async fn an_idempotency_response_for_an_expired_session_is_not_redirected_to() {+ let (gateway, provider, task) = setup(false).await;+ provider.state.lock().unwrap().expire_before_retrieve = true;+ assert!(matches!(+ gateway+ .checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None+ )+ .await,+ Err(StripeCheckoutError::CheckoutConflict)+ ));+ assert_eq!(provider.state.lock().unwrap().creates, 1);+ task.abort();+}++#[tokio::test]+async fn a_cached_stripe_failure_never_rotates_the_key_to_risk_another_charge() {+ let (gateway, provider, task) = setup(false).await;+ provider.state.lock().unwrap().cached_server_failure = true;+ for _ in 0..2 {+ assert!(+ gateway+ .checkout(+ "cus_test".parse().unwrap(),+ request(),+ CheckoutTerms::Paid,+ None+ )+ .await+ .is_err()+ );+ }+ let state = provider.state.lock().unwrap();+ assert_eq!(+ state.create_keys,+ [+ "subscription-checkout-cus_test-first",+ "subscription-checkout-cus_test-first"+ ]+ );+ assert_eq!(state.creates, 0);+ task.abort();+}diff --git a/services/authentication_service/src/service/subscription_checkout.rs b/services/authentication_service/src/service/subscription_checkout.rsindex 2bb8275a67..1d81f02522 100644--- a/services/authentication_service/src/service/subscription_checkout.rs+++ b/services/authentication_service/src/service/subscription_checkout.rs@@ -15,12 +15,28 @@ pub const ONBOARDING_TRIAL_DAYS: u8 = 30;/// Facts across the customer's entire subscription history, including canceled subscriptions.#[derive(Debug, Default, Clone, Copy)]pub struct SubscriptionHistory {- /// An active subscription already owns the customer's paid access.- pub has_active_subscription: bool,+ /// A nonterminal subscription must be recovered or managed, never replaced.+ pub has_existing_subscription: bool,/// Any previous subscription makes the customer ineligible for an introductory trial.pub has_previous_subscription: bool,}+impl SubscriptionHistory {+ pub(crate) fn trial_eligible(self) -> bool {+ !self.has_existing_subscription && !self.has_previous_subscription+ }+}++/// Whether the authenticated customer can receive the introductory Pro trial.+#[derive(Debug, serde::Serialize, utoipa::ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct TrialEligibility {+ /// Confirmed against the same subscription history used during checkout.+ pub eligible: bool,+ /// An existing subscription requires management instead of a new checkout.+ pub existing_subscription: bool,+}+/// Authenticated purchase intent; the caller cannot choose a customer or price ID.pub struct CheckoutRequest<'a> {/// Identity established by the authentication boundary.@@ -63,7 +79,7 @@ pub enum CheckoutError<E> {#[error("User does not have a stripe id")]MissingCustomer,/// A second subscription must not be created.- #[error("User already has an active subscription")]+ #[error("You already have a subscription. Open Manage in Settings → Billing to update it.")]AlreadySubscribed,/// Never silently replace an advertised trial with an immediate charge.#[error("The 30-day trial is only available for your first Premium subscription")]@@ -129,6 +145,29 @@ impl<G: CheckoutGateway> CheckoutService<G> {Self { gateway }}+ /// Read eligibility without creating a checkout or granting an offer.+ #[tracing::instrument(skip_all, err)]+ pub async fn trial_eligibility(+ &self,+ user: &MacroUserIdStr<'_>,+ ) -> Result<TrialEligibility, CheckoutError<G::Error>> {+ let customer = self+ .gateway+ .customer(user)+ .await+ .map_err(CheckoutError::Gateway)?+ .ok_or(CheckoutError::MissingCustomer)?;+ let history = self+ .gateway+ .history(&customer)+ .await+ .map_err(CheckoutError::Gateway)?;+ Ok(TrialEligibility {+ eligible: history.trial_eligible(),+ existing_subscription: history.has_existing_subscription,+ })+ }+/// Create a paid checkout or a code-free first-subscription trial.pub async fn create(&self,@@ -148,11 +187,11 @@ impl<G: CheckoutGateway> CheckoutService<G> {.history(&customer).await.map_err(CheckoutError::Gateway)?;- if history.has_active_subscription {+ if history.has_existing_subscription {return Err(CheckoutError::AlreadySubscribed);}let terms = if request.onboarding_trial {- if request.plan != SeatPlan::Premium || history.has_previous_subscription {+ if request.plan != SeatPlan::Premium || !history.trial_eligible() {return Err(CheckoutError::TrialUnavailable);}CheckoutTerms::Trialdiff --git a/services/authentication_service/src/service/subscription_checkout/test.rs b/services/authentication_service/src/service/subscription_checkout/test.rsindex 49c6da49ac..c885807166 100644--- a/services/authentication_service/src/service/subscription_checkout/test.rs+++ b/services/authentication_service/src/service/subscription_checkout/test.rs@@ -77,7 +77,7 @@ async fn canceled_subscription_does_not_get_another_trial_or_a_paid_fallback() {let service = CheckoutService::new(FakeGateway {history: SubscriptionHistory {has_previous_subscription: true,- has_active_subscription: false,+ has_existing_subscription: false,},..Default::default()});@@ -93,7 +93,7 @@ async fn active_and_trialing_customers_cannot_buy_a_second_subscription() {let service = CheckoutService::new(FakeGateway {history: SubscriptionHistory {has_previous_subscription: true,- has_active_subscription: true,+ has_existing_subscription: true,},..Default::default()});@@ -125,7 +125,7 @@ async fn ordinary_checkout_keeps_its_paid_terms_and_invite_promotion() {invite: true,history: SubscriptionHistory {has_previous_subscription: true,- has_active_subscription: false,+ has_existing_subscription: false,},..Default::default()});@@ -212,3 +212,58 @@ async fn max_trial_never_creates_checkout_or_falls_back_to_paid() {));assert!(service.gateway.created.lock().unwrap().is_empty());}++#[tokio::test]+async fn trial_eligibility_and_checkout_use_the_same_subscription_history() {+ for history in [+ SubscriptionHistory::default(),+ SubscriptionHistory {+ has_previous_subscription: true,+ has_existing_subscription: false,+ },+ SubscriptionHistory {+ has_previous_subscription: true,+ has_existing_subscription: true,+ },+ ] {+ let service = CheckoutService::new(FakeGateway {+ history,+ ..Default::default()+ });+ let eligibility = service+ .trial_eligibility(&request(true).user_id)+ .await+ .unwrap();+ assert_eq!(eligibility.eligible, !history.has_previous_subscription);+ assert!(service.gateway.created.lock().unwrap().is_empty());+ assert_eq!(+ service.create(request(true)).await.is_ok(),+ eligibility.eligible+ );+ }+}++#[tokio::test]+async fn eligibility_lookup_failure_does_not_advertise_a_trial() {+ let service = CheckoutService::new(FakeGateway {+ history_failure: true,+ ..Default::default()+ });+ assert!(matches!(+ service.trial_eligibility(&request(true).user_id).await,+ Err(CheckoutError::Gateway(_))+ ));+ assert!(service.gateway.created.lock().unwrap().is_empty());+}++#[tokio::test]+async fn missing_billing_customer_cannot_be_confirmed_trial_eligible() {+ let service = CheckoutService::new(FakeGateway {+ missing_customer: true,+ ..Default::default()+ });+ assert!(matches!(+ service.trial_eligibility(&request(true).user_id).await,+ Err(CheckoutError::MissingCustomer)+ ));+}