Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(billing): hide inactive subscription seats (#7528)
LinYushenaa86cd7af885
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex a92c604673..62b2b7d4b0 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -1057,9 +1057,8 @@ describe("ApiClient schema fallback", () => {it("parses seat reconciliation into camelCase", async () => {stubFetchJson({workspace_id: "workspace-1",- billed_seats: 5,- actual_seats: 4,- action: "scheduled_decrease",+ action: "restored_high_water",+ version: 8,});const client = new ApiClient("https://api.example.test");@@ -1067,9 +1066,8 @@ describe("ApiClient schema fallback", () => {client.reconcileWorkspaceSubscriptionSeats(),).resolves.toEqual({workspaceId: "workspace-1",- billedSeats: 5,- actualSeats: 4,- action: "scheduled_decrease",+ action: "restored_high_water",+ version: 8,});});});@@ -1122,16 +1120,19 @@ describe("workspace subscription contract", () => {stubFetchJson({entitlement,billing_interval: "year",- actual_seats: 3,- billed_seats: 5,- pending_seat_quantity: 3,- used_seats: 3,- reserved_seats: 2,- purchase_version: 11,- active_seat_purchase: {- request_id: "22222222-2222-2222-2222-222222222222",- target_seats: 7,- status: "processing",+ human_members: 3,+ seat_capacity: {+ purchased: 5,+ used: 3,+ reserved: 2,+ available: 0,+ version: 11,+ pending_quantity: 3,+ active_purchase: {+ request_id: "22222222-2222-2222-2222-222222222222",+ target_seats: 7,+ status: "processing",+ },},cancel_at_period_end: true,grace_until: "2026-09-08T00:00:00Z",@@ -1144,12 +1145,14 @@ describe("workspace subscription contract", () => {expect(summary?.entitlement.plan).toBe("pro");expect(summary?.entitlement.version).toBe(7);expect(summary?.billingInterval).toBe("year");- expect(summary?.billedSeats).toBe(5);- expect(summary?.pendingSeatQuantity).toBe(3);- expect(summary?.usedSeats).toBe(3);- expect(summary?.reservedSeats).toBe(2);- expect(summary?.purchaseVersion).toBe(11);- expect(summary?.activeSeatPurchase).toEqual({+ expect(summary?.humanMembers).toBe(3);+ expect(summary?.seatCapacity?.purchased).toBe(5);+ expect(summary?.seatCapacity?.pendingQuantity).toBe(3);+ expect(summary?.seatCapacity?.used).toBe(3);+ expect(summary?.seatCapacity?.reserved).toBe(2);+ expect(summary?.seatCapacity?.available).toBe(0);+ expect(summary?.seatCapacity?.version).toBe(11);+ expect(summary?.seatCapacity?.activePurchase).toEqual({requestId: "22222222-2222-2222-2222-222222222222",targetSeats: 7,status: "processing",@@ -1160,32 +1163,35 @@ describe("workspace subscription contract", () => {expect(summary?.hasStripeCustomer).toBe(true);});- it("keeps a paid summary readable when optional fields are absent", async () => {- // A cloud that predates the optional seat/cancellation fields still has to- // produce a usable Pro summary rather than failing the whole read.- stubFetchJson({ entitlement, actual_seats: 3 });+ it("represents canceled subscriptions without current seat capacity", async () => {+ stubFetchJson({+ entitlement: { ...entitlement, plan: "free", status: "canceled" },+ billing_interval: "month",+ human_members: 3,+ seat_capacity: null,+ cancel_at_period_end: false,+ grace_until: null,+ has_stripe_customer: true,+ });const client = new ApiClient("https://api.example.test");const summary = await client.getWorkspaceSubscriptionSummary();- expect(summary?.entitlement.plan).toBe("pro");- expect(summary?.billingInterval).toBeNull();- expect(summary?.billedSeats).toBeNull();- expect(summary?.pendingSeatQuantity).toBeNull();- expect(summary?.usedSeats).toBe(3);- expect(summary?.reservedSeats).toBe(0);- expect(summary?.purchaseVersion).toBeNull();- expect(summary?.activeSeatPurchase).toBeNull();- expect(summary?.cancelAtPeriodEnd).toBe(false);- expect(summary?.graceUntil).toBeNull();- // Absent means "no Stripe customer known", which is the safe reading: the- // caller hides Portal rather than offering a control that would 404.- expect(summary?.hasStripeCustomer).toBe(false);+ expect(summary?.entitlement.plan).toBe("free");+ expect(summary?.entitlement.status).toBe("canceled");+ expect(summary?.humanMembers).toBe(3);+ expect(summary?.seatCapacity).toBeNull();+ expect(summary?.hasStripeCustomer).toBe(true);});it("preserves unknown plans and statuses instead of coercing them", async () => {stubFetchJson({entitlement: { ...entitlement, plan: "business", status: "paused" },- actual_seats: 9,+ billing_interval: null,+ human_members: 9,+ seat_capacity: null,+ cancel_at_period_end: false,+ grace_until: null,+ has_stripe_customer: false,});const client = new ApiClient("https://api.example.test");const summary = await client.getWorkspaceSubscriptionSummary();@@ -1195,7 +1201,7 @@ describe("workspace subscription contract", () => {});it("returns null — never a Free-looking shape — for a malformed summary", async () => {- stubFetchJson({ entitlement: { plan: "pro" }, actual_seats: "many" });+ stubFetchJson({ entitlement: { plan: "pro" }, human_members: "many" });const client = new ApiClient("https://api.example.test");expect(await client.getWorkspaceSubscriptionSummary()).toBeNull();});@@ -1223,7 +1229,12 @@ describe("workspace subscription contract", () => {it("accepts additive cloud fields on summary and prices", async () => {stubFetchJson({entitlement: { ...entitlement, trial_ends_at: "2026-10-01T00:00:00Z" },- actual_seats: 3,+ billing_interval: "month",+ human_members: 3,+ seat_capacity: null,+ cancel_at_period_end: false,+ grace_until: null,+ has_stripe_customer: true,future_field: { nested: true },});const client = new ApiClient("https://api.example.test");diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 92c253f797..16b8b1f023 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2571,50 +2571,62 @@ export const WorkspaceSubscriptionEntitlementsSchema = zexport const WorkspaceSubscriptionSummarySchema = z.object({entitlement: WorkspaceSubscriptionEntitlementsSchema,- billing_interval: WorkspaceSubscriptionIntervalSchema.nullable().optional(),- actual_seats: z.number().int().nonnegative(),- billed_seats: z.number().int().nonnegative().nullable().optional(),- pending_seat_quantity: z.number().int().nonnegative().nullable().optional(),- used_seats: z.number().int().nonnegative().optional().catch(undefined),- reserved_seats: z.number().int().nonnegative().optional().catch(0),- purchase_version: z.number().int().positive().optional().catch(undefined),- active_seat_purchase: z+ billing_interval: WorkspaceSubscriptionIntervalSchema.nullable(),+ human_members: z.number().int().nonnegative(),+ seat_capacity: z.object({- request_id: z.string(),- target_seats: z.number().int().positive(),- status: z.enum(["pending", "processing", "submitted"]),- expires_at: z.string().min(1).optional().catch(undefined),+ purchased: z.number().int().positive(),+ used: z.number().int().nonnegative(),+ reserved: z.number().int().nonnegative(),+ available: z.number().int().nonnegative(),+ version: z.number().int().positive(),+ pending_quantity: z.number().int().positive().nullable(),+ active_purchase: z+ .object({+ request_id: z.string(),+ target_seats: z.number().int().positive(),+ status: z.enum(["pending", "processing", "submitted"]),+ expires_at: z.string().min(1).optional(),+ })+ .loose()+ .optional(),}).loose()- .nullable()- .optional()- .catch(null),- cancel_at_period_end: z.boolean().optional(),- grace_until: z.string().nullable().optional(),- has_stripe_customer: z.boolean().optional(),+ .nullable(),+ cancel_at_period_end: z.boolean(),+ grace_until: z.string().nullable(),+ has_stripe_customer: z.boolean(),}).loose().transform((value): WorkspaceSubscriptionSummary => ({entitlement: value.entitlement,- billingInterval: value.billing_interval ?? null,- actualSeats: value.actual_seats,- billedSeats: value.billed_seats ?? null,- pendingSeatQuantity: value.pending_seat_quantity ?? null,- usedSeats: value.used_seats ?? value.actual_seats,- reservedSeats: value.reserved_seats ?? 0,- purchaseVersion: value.purchase_version ?? null,- activeSeatPurchase: value.active_seat_purchase+ billingInterval: value.billing_interval,+ humanMembers: value.human_members,+ seatCapacity: value.seat_capacity? {- requestId: value.active_seat_purchase.request_id,- targetSeats: value.active_seat_purchase.target_seats,- status: value.active_seat_purchase.status,- expiresAt: value.active_seat_purchase.expires_at ?? null,+ purchased: value.seat_capacity.purchased,+ used: value.seat_capacity.used,+ reserved: value.seat_capacity.reserved,+ available: value.seat_capacity.available,+ version: value.seat_capacity.version,+ pendingQuantity: value.seat_capacity.pending_quantity,+ activePurchase: value.seat_capacity.active_purchase+ ? {+ requestId:+ value.seat_capacity.active_purchase.request_id,+ targetSeats:+ value.seat_capacity.active_purchase.target_seats,+ status: value.seat_capacity.active_purchase.status,+ expiresAt:+ value.seat_capacity.active_purchase.expires_at ?? null,+ }+ : null,}: null,- cancelAtPeriodEnd: value.cancel_at_period_end ?? false,- graceUntil: value.grace_until ?? null,- hasStripeCustomer: value.has_stripe_customer ?? false,+ cancelAtPeriodEnd: value.cancel_at_period_end,+ graceUntil: value.grace_until,+ hasStripeCustomer: value.has_stripe_customer,}),);@@ -2676,17 +2688,15 @@ export const CreateWorkspaceSubscriptionCheckoutResponseSchema = zexport const WorkspaceSubscriptionSeatReconcileResultSchema = z.object({workspace_id: z.string(),- billed_seats: z.number().int().nonnegative(),- actual_seats: z.number().int().nonnegative(),action: z.string(),+ version: z.number().int().nonnegative(),}).loose().transform((value): WorkspaceSubscriptionSeatReconcileResult => ({workspaceId: value.workspace_id,- billedSeats: value.billed_seats,- actualSeats: value.actual_seats,action: value.action,+ version: value.version,}),);diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex 75257274b0..fba065b8ff 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -218,18 +218,9 @@ export interface WorkspaceSubscriptionSummary {entitlement: WorkspaceSubscriptionEntitlements;billingInterval: WorkspaceSubscriptionInterval | null;/** Authoritative current human-member count. Agents never take a seat. */- actualSeats: number;- /** Persisted Stripe seat high-water; null when no subscription exists yet. */- billedSeats: number | null;- /** A lower quantity already scheduled for the next period, if any. */- pendingSeatQuantity: number | null;- /** Confirmed human members consuming Cloud-owned commercial capacity. */- usedSeats: number;- /** Live pending invitations that reserve purchased capacity. */- reservedSeats: number;- /** Null when connected to a Cloud version that predates seat purchases. */- purchaseVersion: number | null;- activeSeatPurchase: WorkspaceSeatPurchaseSummary | null;+ humanMembers: number;+ /** Null when the workspace has no currently effective purchased capacity. */+ seatCapacity: WorkspaceSeatCapacity | null;cancelAtPeriodEnd: boolean;graceUntil: string | null;/**@@ -240,6 +231,18 @@ export interface WorkspaceSubscriptionSummary {hasStripeCustomer: boolean;}+export interface WorkspaceSeatCapacity {+ purchased: number;+ used: number;+ reserved: number;+ /** Server-computed purchased capacity not currently used or reserved. */+ available: number;+ version: number;+ /** A lower quantity already scheduled for the next period, if any. */+ pendingQuantity: number | null;+ activePurchase: WorkspaceSeatPurchaseSummary | null;+}+export interface WorkspaceSeatPurchaseSummary {requestId: string;targetSeats: number;@@ -312,9 +315,8 @@ export interface PurchaseWorkspaceSeatsResponse {export interface WorkspaceSubscriptionSeatReconcileResult {workspaceId: string;- billedSeats: number;- actualSeats: number;action: string;+ version: number;}export interface CreateWorkspaceSubscriptionPortalResponse {diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 9e1aa8cd38..0382e981fd 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -311,6 +311,7 @@ export type {WorkspaceSubscriptionInterval,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,+ WorkspaceSeatCapacity,WorkspaceSeatPurchaseSummary,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPrices,diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 623c97d924..7e500ef4fc 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -97,7 +97,6 @@"upgrade": "Upgrade to Pro","manage": "Manage billing","add_seats": "Add seats",- "refresh_seats": "Refresh seats","cancel": "Cancel","continue_to_stripe": "Continue to Stripe"},@@ -110,9 +109,7 @@"checkout_failed": "Checkout could not be created. Retry in a moment.","portal_response": "The Billing Portal could not open because the server response was unreadable.","portal_unavailable": "The Billing Portal is not available for this workspace. The current plan has been refreshed.",- "portal_failed": "The Billing Portal could not be opened. Retry in a moment.",- "reconcile_response": "Seats were refreshed, but the result could not be read. Reload the page to confirm the current count.",- "reconcile_failed": "Seats could not be refreshed. Member changes are still saved and periodic reconciliation will retry."+ "portal_failed": "The Billing Portal could not be opened. Retry in a moment."},"return": {"cancel_title": "Checkout canceled",@@ -227,8 +224,7 @@"summary_unavailable_description": "The current plan is still shown, but purchased and scheduled seat quantities could not be loaded.","members_over_capacity_title": "Members exceed purchased seats","members_over_capacity_description": "This workspace has {{actual}} members but only {{purchased}} purchased seats. Add enough seats or remove members before sending more invitations.",- "updated": "Seats refreshed",- "reconciled": "Current members: {{actual}} · billed seats: {{billed}}"+ "updated": "Seat purchase submitted"},"seat_purchase": {"title": "Add seats",@@ -255,7 +251,7 @@"pending_description_other": "Stripe is confirming the subscription update to {{count}} seats.","delayed_title": "Seat confirmation is taking longer than expected","delayed_description": "Automatic checking has stopped. The purchase may still complete; check again later or contact support before starting another purchase.",- "delayed_description_with_expiry": "Automatic checking has stopped. If the attempt is still pending after {{date}}, refresh seats to release it and request a new quote; contact support before starting another purchase.",+ "delayed_description_with_expiry": "Automatic checking has stopped. If the attempt is still pending after {{date}}, reload this page before requesting another quote; contact support if it remains pending.","submitted_one": "A purchase for {{count}} seat was submitted. The new capacity appears after Stripe confirms it.","submitted_other": "A purchase for {{count}} seats was submitted. The new capacity appears after Stripe confirms it.","error_title": "Could not update the estimate"diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 70163e9344..a8017f088c 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -97,7 +97,6 @@"upgrade": "Pro にアップグレード","manage": "請求を管理","add_seats": "席を追加",- "refresh_seats": "席数を更新","cancel": "キャンセル","continue_to_stripe": "Stripe に進む"},@@ -110,9 +109,7 @@"checkout_failed": "Checkout を作成できませんでした。しばらくしてから再試行してください。","portal_response": "サーバー応答を読み取れないため Billing Portal を開けませんでした。","portal_unavailable": "このワークスペースでは Billing Portal を利用できません。現在のプランを更新しました。",- "portal_failed": "Billing Portal を開けませんでした。しばらくしてから再試行してください。",- "reconcile_response": "席数は更新されましたが、結果を読み取れませんでした。ページを再読み込みして確認してください。",- "reconcile_failed": "席数を更新できませんでした。メンバー変更は保存済みで、定期照合は引き続き再試行されます。"+ "portal_failed": "Billing Portal を開けませんでした。しばらくしてから再試行してください。"},"return": {"cancel_title": "Checkout をキャンセルしました",@@ -223,8 +220,7 @@"summary_unavailable_description": "現在のプランは表示できますが、購入済みの席数と変更予定の席数を読み込めませんでした。","members_over_capacity_title": "メンバー数が購入済みの席数を超えています","members_over_capacity_description": "このワークスペースには {{actual}} 人のメンバーがいますが、購入済みの席は {{purchased}} 席です。さらに招待する前に席を追加するか、メンバーを削除してください。",- "updated": "席数を更新しました",- "reconciled": "現在のメンバー: {{actual}} · 請求席数: {{billed}}"+ "updated": "席数の購入を送信しました"},"seat_purchase": {"title": "席を追加",@@ -249,7 +245,7 @@"pending_description_other": "Stripe が {{count}}席へのサブスクリプション更新を確認しています。","delayed_title": "席の確認に時間がかかっています","delayed_description": "自動確認を停止しました。購入はまだ完了する可能性があります。別の購入を始める前に、後でもう一度確認するかサポートへお問い合わせください。",- "delayed_description_with_expiry": "自動確認を停止しました。{{date}} を過ぎても保留中の場合は、席数を更新してリクエストを解放し、新しい見積もりを取得してください。別の購入を始める前にサポートへお問い合わせいただくこともできます。",+ "delayed_description_with_expiry": "自動確認を停止しました。{{date}} を過ぎても保留中の場合は、ページを再読み込みしてから新しい見積もりを取得してください。保留状態が続く場合はサポートへお問い合わせください。","submitted_other": "{{count}}席の購入を送信しました。Stripe の確認後に新しい容量が表示されます。","error_title": "見積もりを更新できません"},diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex ea42d9d213..40be302ccb 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -97,7 +97,6 @@"upgrade": "Pro로 업그레이드","manage": "결제 관리","add_seats": "좌석 추가",- "refresh_seats": "좌석 새로고침","cancel": "취소","continue_to_stripe": "Stripe로 이동"},@@ -110,9 +109,7 @@"checkout_failed": "Checkout을 만들지 못했습니다. 잠시 후 다시 시도하세요.","portal_response": "서버 응답을 읽을 수 없어 Billing Portal을 열지 못했습니다.","portal_unavailable": "이 워크스페이스에서는 Billing Portal을 사용할 수 없습니다. 현재 요금제를 새로고침했습니다.",- "portal_failed": "Billing Portal을 열지 못했습니다. 잠시 후 다시 시도하세요.",- "reconcile_response": "좌석은 새로고침되었지만 결과를 읽지 못했습니다. 페이지를 다시 불러와 현재 수를 확인하세요.",- "reconcile_failed": "좌석을 새로고침하지 못했습니다. 멤버 변경은 저장되었으며 정기 조정이 계속 재시도됩니다."+ "portal_failed": "Billing Portal을 열지 못했습니다. 잠시 후 다시 시도하세요."},"return": {"cancel_title": "Checkout 취소됨",@@ -223,8 +220,7 @@"summary_unavailable_description": "현재 요금제는 계속 표시되지만 구매한 좌석과 예정 좌석 수를 불러오지 못했습니다.","members_over_capacity_title": "멤버 수가 구매한 좌석 수를 초과합니다","members_over_capacity_description": "이 워크스페이스에는 멤버가 {{actual}}명이지만 구매한 좌석은 {{purchased}}개입니다. 더 초대하기 전에 좌석을 추가하거나 멤버를 제거하세요.",- "updated": "좌석 새로고침됨",- "reconciled": "현재 멤버: {{actual}} · 결제 좌석: {{billed}}"+ "updated": "좌석 구매를 제출했습니다"},"seat_purchase": {"title": "좌석 추가",@@ -249,7 +245,7 @@"pending_description_other": "Stripe가 좌석 {{count}}개로 구독 업데이트를 확인하고 있습니다.","delayed_title": "좌석 확인이 예상보다 오래 걸리고 있습니다","delayed_description": "자동 확인이 중지되었습니다. 구매는 계속 완료될 수 있습니다. 다른 구매를 시작하기 전에 나중에 다시 확인하거나 지원팀에 문의하세요.",- "delayed_description_with_expiry": "자동 확인이 중지되었습니다. {{date}} 이후에도 대기 중이면 좌석을 새로고침하여 요청을 해제하고 새 견적을 받으세요. 다른 구매를 시작하기 전에 지원팀에 문의할 수도 있습니다.",+ "delayed_description_with_expiry": "자동 확인이 중지되었습니다. {{date}} 이후에도 대기 중이면 페이지를 다시 불러온 후 새 견적을 요청하세요. 대기 상태가 계속되면 지원팀에 문의하세요.","submitted_other": "좌석 {{count}}개 구매를 제출했습니다. Stripe 확인 후 새 용량이 표시됩니다.","error_title": "예상 금액을 업데이트할 수 없습니다"},diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex d77ab855d0..4cb1d910e9 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -97,7 +97,6 @@"upgrade": "升级到 Pro","manage": "管理账单","add_seats": "添加席位",- "refresh_seats": "刷新席位","cancel": "取消","continue_to_stripe": "前往 Stripe"},@@ -110,9 +109,7 @@"checkout_failed": "无法创建 Checkout,请稍后重试。","portal_response": "服务端响应无法读取,无法打开 Billing Portal。","portal_unavailable": "这个工作区暂时无法使用 Billing Portal,当前套餐已刷新。",- "portal_failed": "无法打开 Billing Portal,请稍后重试。",- "reconcile_response": "席位已刷新,但无法读取结果。请重新加载页面确认当前数量。",- "reconcile_failed": "无法刷新席位。成员变更已保存,定期对账仍会继续重试。"+ "portal_failed": "无法打开 Billing Portal,请稍后重试。"},"return": {"cancel_title": "已取消 Checkout",@@ -223,8 +220,7 @@"summary_unavailable_description": "当前套餐仍会显示,但暂时无法加载已购席位和待生效席位。","members_over_capacity_title": "成员数超过已购席位","members_over_capacity_description": "当前工作区有 {{actual}} 名成员,但只购买了 {{purchased}} 个席位。继续邀请前,请补足席位或移除成员。",- "updated": "席位已刷新",- "reconciled": "当前成员:{{actual}} · 计费席位:{{billed}}"+ "updated": "席位购买已提交"},"seat_purchase": {"title": "添加席位",@@ -249,7 +245,7 @@"pending_description_other": "Stripe 正在确认订阅更新至 {{count}} 个席位。","delayed_title": "席位确认时间超出预期","delayed_description": "自动检查已停止,购买仍可能完成。开始另一笔购买前,请稍后再查看或联系支持人员。",- "delayed_description_with_expiry": "自动检查已停止。若到 {{date}} 仍在等待,请刷新席位以释放本次请求并重新获取报价;开始另一笔购买前也可联系支持人员。",+ "delayed_description_with_expiry": "自动检查已停止。若到 {{date}} 仍在等待,请重新加载页面后再获取报价;若状态仍未更新,请联系支持人员。","submitted_other": "购买 {{count}} 个席位的请求已提交。Stripe 确认后会显示新容量。","error_title": "无法更新估算金额"},diff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.tsindex 37ddd35e82..18becb3510 100644--- a/packages/views/settings/components/billing-state.test.ts+++ b/packages/views/settings/components/billing-state.test.ts@@ -8,7 +8,8 @@ import type {} from "@multica/core/types";import {canPurchaseWorkspaceSubscription,- hasManagedWorkspaceSubscription,+ hasActiveWorkspaceSeatCapacity,+ hasWorkspaceBillingRelationship,resolveAutopilotUsage,} from "./billing-state";@@ -116,34 +117,34 @@ describe("resolveAutopilotUsage", () => {});describe("billing subscription state", () => {- it("prefers subscription facts and keeps safe compatibility fallbacks", () => {- const summary = {+ it("keeps billing history separate from current seat capacity", () => {+ const canceledSummary = {entitlement: freeEntitlements,billingInterval: null,- actualSeats: 3,- billedSeats: null,- pendingSeatQuantity: null,- usedSeats: 3,- reservedSeats: 0,- purchaseVersion: null,- activeSeatPurchase: null,+ humanMembers: 3,+ seatCapacity: null,cancelAtPeriodEnd: false,graceUntil: null,hasStripeCustomer: true,} satisfies WorkspaceSubscriptionSummary;- expect(hasManagedWorkspaceSubscription(freeEntitlements, summary)).toBe(- true,- );- expect(- hasManagedWorkspaceSubscription(- { ...freeEntitlements, status: "incomplete_expired" },- undefined,- ),- ).toBe(true);- expect(hasManagedWorkspaceSubscription(freeEntitlements, undefined)).toBe(- false,- );+ expect(hasActiveWorkspaceSeatCapacity(canceledSummary)).toBe(false);+ expect(hasWorkspaceBillingRelationship(canceledSummary)).toBe(true);++ const activeSummary = {+ ...canceledSummary,+ seatCapacity: {+ purchased: 5,+ used: 3,+ reserved: 1,+ available: 1,+ version: 2,+ pendingQuantity: null,+ activePurchase: null,+ },+ } satisfies WorkspaceSubscriptionSummary;+ expect(hasActiveWorkspaceSeatCapacity(activeSummary)).toBe(true);+ expect(hasWorkspaceBillingRelationship(undefined)).toBe(false);});it.each([diff --git a/packages/views/settings/components/billing-state.ts b/packages/views/settings/components/billing-state.tsindex 8838f01469..90b410d8b8 100644--- a/packages/views/settings/components/billing-state.ts+++ b/packages/views/settings/components/billing-state.ts@@ -75,37 +75,22 @@ export function resolveAutopilotUsage(return { kind: "unavailable" };}-const MANAGED_SUBSCRIPTION_STATUSES = new Set([- "active",- "trialing",- "past_due",- "canceled",- "incomplete",- "incomplete_expired",- "paused",- "unpaid",-]);-const PURCHASABLE_SUBSCRIPTION_STATUSES = new Set(["inactive","canceled","incomplete_expired",]);-/**- * Summary facts are primary. Plan and status are compatibility fallbacks so- * an older or temporarily unavailable summary does not hide the recovery UI.- */-export function hasManagedWorkspaceSubscription(- entitlements: WorkspaceSubscriptionEntitlements,+export function hasActiveWorkspaceSeatCapacity(summary: WorkspaceSubscriptionSummary | null | undefined,): boolean {- return (- summary?.hasStripeCustomer === true ||- summary?.billedSeats !== null && summary?.billedSeats !== undefined ||- entitlements.plan === "pro" ||- MANAGED_SUBSCRIPTION_STATUSES.has(entitlements.status)- );+ return summary?.seatCapacity != null;+}++export function hasWorkspaceBillingRelationship(+ summary: WorkspaceSubscriptionSummary | null | undefined,+): boolean {+ return summary?.hasStripeCustomer === true;}/**diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex f9931b4c15..988d77a47b 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -10,7 +10,6 @@ const mocks = vi.hoisted(() => ({useQuery: vi.fn(),checkout: vi.fn(),portal: vi.fn(),- reconcile: vi.fn(),previewSeats: vi.fn(),purchaseSeats: vi.fn(),refetch: vi.fn(),@@ -61,17 +60,20 @@ const mocks = vi.hoisted(() => ({summary: {entitlement: null as never,billingInterval: null as "month" | "year" | null,- actualSeats: 3,- billedSeats: null as number | null,- pendingSeatQuantity: null as number | null,- usedSeats: 3,- reservedSeats: 0,- purchaseVersion: null as number | null,- activeSeatPurchase: null as {- requestId: string;- targetSeats: number;- status: string;- expiresAt: string | null;+ humanMembers: 3,+ seatCapacity: null as {+ purchased: number;+ used: number;+ reserved: number;+ available: number;+ version: number;+ pendingQuantity: number | null;+ activePurchase: {+ requestId: string;+ targetSeats: number;+ status: "pending" | "processing" | "submitted";+ expiresAt: string | null;+ } | null;} | null,cancelAtPeriodEnd: false,graceUntil: null as string | null,@@ -111,10 +113,6 @@ vi.mock("@multica/core/billing", () => ({mutateAsync: mocks.portal,isPending: false,}),- useReconcileWorkspaceSubscriptionSeats: () => ({- mutateAsync: mocks.reconcile,- isPending: false,- }),usePreviewWorkspaceSeatPurchase: () => ({mutateAsync: mocks.previewSeats,isPending: false,@@ -162,6 +160,37 @@ vi.mock("../../platform", () => ({ openExternal: mocks.openExternal }));import { BillingTab, formatStripeMinorAmount } from "./billing-tab";+function setSeatCapacity({+ humanMembers = 4,+ purchased = 5,+ used = humanMembers,+ reserved = 0,+ available = Math.max(0, purchased - used - reserved),+ version = 9,+ pendingQuantity = null,+ activePurchase = null,+}: {+ humanMembers?: number;+ purchased?: number;+ used?: number;+ reserved?: number;+ available?: number;+ version?: number;+ pendingQuantity?: number | null;+ activePurchase?: NonNullable<typeof mocks.summary.seatCapacity>["activePurchase"];+} = {}) {+ mocks.summary.humanMembers = humanMembers;+ mocks.summary.seatCapacity = {+ purchased,+ used,+ reserved,+ available,+ version,+ pendingQuantity,+ activePurchase,+ };+}+describe("BillingTab", () => {beforeEach(() => {vi.clearAllMocks();@@ -208,13 +237,8 @@ describe("BillingTab", () => {Object.assign(mocks.summary, {entitlement: mocks.entitlements,billingInterval: null,- actualSeats: 3,- billedSeats: null,- pendingSeatQuantity: null,- usedSeats: 3,- reservedSeats: 0,- purchaseVersion: null,- activeSeatPurchase: null,+ humanMembers: 3,+ seatCapacity: null,cancelAtPeriodEnd: false,graceUntil: null,hasStripeCustomer: false,@@ -279,12 +303,6 @@ describe("BillingTab", () => {mocks.portal.mockResolvedValue({url: "https://billing.stripe.com/test-session",});- mocks.reconcile.mockResolvedValue({- workspaceId: "workspace-1",- billedSeats: 3,- actualSeats: 3,- action: "none",- });mocks.refetchSummary.mockResolvedValue({ data: mocks.summary });mocks.previewSeats.mockResolvedValue({currentSeats: 5,@@ -451,7 +469,7 @@ describe("BillingTab", () => {it("shows the unit price without a zero estimated total when seats are unavailable", () => {mocks.entitlements.seats = 0;- mocks.summary.actualSeats = 0;+ mocks.summary.humanMembers = 0;renderWithI18n(<BillingTab />);@@ -674,14 +692,11 @@ describe("BillingTab", () => {expect(screen.getByText("Read-only billing access")).toBeInTheDocument();expect(screen.getAllByText("3 members")).toHaveLength(1);- expect(screen.getByText("3 seats")).toBeInTheDocument();+ expect(screen.queryByText("Purchased seats")).not.toBeInTheDocument();expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();expect(screen.queryByRole("button", { name: "Upgrade to Pro" }),).not.toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "Refresh seats" }),- ).not.toBeInTheDocument();});it("renders authoritative subscription seat facts", () => {@@ -701,21 +716,24 @@ describe("BillingTab", () => {});Object.assign(mocks.summary, {billingInterval: "month",- actualSeats: 4,- usedSeats: 3,- billedSeats: 5,- pendingSeatQuantity: 4,- reservedSeats: 1,- purchaseVersion: 9,hasStripeCustomer: true,});+ setSeatCapacity({+ humanMembers: 4,+ purchased: 5,+ used: 4,+ reserved: 1,+ available: 0,+ pendingQuantity: 4,+ });renderWithI18n(<BillingTab />);expect(screen.getByText("Monthly")).toBeInTheDocument();expect(screen.getByText("5 seats")).toBeInTheDocument();- expect(screen.getByText("3 seats")).toBeInTheDocument();- expect(screen.getAllByText("1 seat")).toHaveLength(2);+ expect(screen.getByText("4 seats")).toBeInTheDocument();+ expect(screen.getByText("1 seat")).toBeInTheDocument();+ expect(screen.getByText("0 seats")).toBeInTheDocument();expect(screen.getByText(/4 seats from Feb 1, 2030/)).toBeInTheDocument();expect(screen.getAllByText("4 members")).toHaveLength(1);});@@ -728,14 +746,8 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- reservedSeats: 0,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();mocks.previewSeats.mockImplementation(({ additionalSeats }: { additionalSeats: number }) =>Promise.resolve({@@ -808,14 +820,8 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- reservedSeats: 0,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();mocks.refetchSummary.mockReturnValueOnce(new Promise((resolve) => {resolveSummaryRefresh = resolve;@@ -848,10 +854,7 @@ describe("BillingTab", () => {expect(screen.queryByRole("alert")).not.toBeInTheDocument();await act(async () => {- Object.assign(mocks.summary, {- billedSeats: 4,- purchaseVersion: 10,- });+ setSeatCapacity({ purchased: 4, version: 10 });resolveSummaryRefresh({ data: mocks.summary });});@@ -875,14 +878,8 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- reservedSeats: 0,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();mocks.previewSeats.mockRejectedValueOnce(new ApiError("conflict", 409, "Conflict", {code: "seat_capacity_changed",@@ -911,14 +908,8 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- reservedSeats: 0,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();mocks.refetchSummary.mockResolvedValueOnce({data: mocks.summary,isError: true,@@ -956,19 +947,10 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- reservedSeats: 0,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();mocks.refetchSummary.mockImplementationOnce(async () => {- Object.assign(mocks.summary, {- billedSeats: 4,- purchaseVersion: 10,- });+ setSeatCapacity({ purchased: 4, version: 10 });return { data: mocks.summary };});mocks.previewSeats.mockRejectedValue(@@ -1008,13 +990,8 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();mocks.purchaseSeats.mockRejectedValue(new ApiError("conflict", 409, "Conflict", { code }),);@@ -1041,13 +1018,8 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();const { rerender } = renderWithI18n(<BillingTab />);await user.click(screen.getByRole("button", { name: "Add seats" }));@@ -1074,13 +1046,8 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();mocks.purchaseSeats.mockResolvedValue(null);renderWithI18n(<BillingTab />);@@ -1113,13 +1080,8 @@ describe("BillingTab", () => {issueWindow: null,autopilotRuns: null,});- Object.assign(mocks.summary, {- actualSeats: 4,- usedSeats: 4,- billedSeats: 5,- purchaseVersion: 9,- hasStripeCustomer: true,- });+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity();mocks.purchaseSeats.mockRejectedValue(new ApiError("payment failed", 402, "Payment Required", {code: "seat_purchase_payment_failed",@@ -1141,8 +1103,9 @@ describe("BillingTab", () => {it("stops seat purchase polling after two minutes", () => {vi.useFakeTimers();- Object.assign(mocks.summary, {- activeSeatPurchase: {+ Object.assign(mocks.entitlements, { plan: "pro", status: "active" });+ setSeatCapacity({+ activePurchase: {requestId: "seat-request-pending",targetSeats: 7,status: "pending",@@ -1164,7 +1127,7 @@ describe("BillingTab", () => {}).format(new Date("2030-01-01T00:15:00Z"));expect(screen.getByText(- `Automatic checking has stopped. If the attempt is still pending after ${formattedExpiry}, refresh seats to release it and request a new quote; contact support before starting another purchase.`,+ `Automatic checking has stopped. If the attempt is still pending after ${formattedExpiry}, reload this page before requesting another quote; contact support if it remains pending.`,),).toBeInTheDocument();const summaryOptions = mocks.useQuery.mock.calls@@ -1184,8 +1147,9 @@ describe("BillingTab", () => {it("does not promise an unlock time for a submitted seat purchase", () => {vi.useFakeTimers();- Object.assign(mocks.summary, {- activeSeatPurchase: {+ Object.assign(mocks.entitlements, { plan: "pro", status: "active" });+ setSeatCapacity({+ activePurchase: {requestId: "seat-request-submitted",targetSeats: 7,status: "submitted",@@ -1286,6 +1250,7 @@ describe("BillingTab", () => {cancelAtPeriodEnd: true,hasStripeCustomer: true,});+ setSeatCapacity();renderWithI18n(<BillingTab />);@@ -1328,7 +1293,8 @@ describe("BillingTab", () => {it("keeps cancellation and pending-seat dates on one summary snapshot", () => {Object.assign(mocks.entitlements, {- plan: "free",+ plan: "pro",+ status: "active",currentPeriodEnd: "2030-03-01T00:00:00Z",});Object.assign(mocks.summary, {@@ -1336,10 +1302,10 @@ describe("BillingTab", () => {...mocks.entitlements,currentPeriodEnd: "2030-04-01T00:00:00Z",},- pendingSeatQuantity: 4,cancelAtPeriodEnd: true,hasStripeCustomer: true,});+ setSeatCapacity({ pendingQuantity: 4 });renderWithI18n(<BillingTab />);@@ -1371,6 +1337,8 @@ describe("BillingTab", () => {limit: null,reset_at: null,});+ mocks.summary.hasStripeCustomer = true;+ setSeatCapacity({ humanMembers: 3, purchased: 3 });renderWithI18n(<BillingTab />);@@ -1397,13 +1365,7 @@ describe("BillingTab", () => {autopilotRuns: null,version: 3,});- Object.assign(mocks.summary, {- actualSeats: 5,- usedSeats: 4,- billedSeats: 4,- reservedSeats: 0,- purchaseVersion: 9,- });+ setSeatCapacity({ humanMembers: 5, purchased: 4, used: 5 });renderWithI18n(<BillingTab />);@@ -1423,13 +1385,7 @@ describe("BillingTab", () => {autopilotRuns: null,version: 3,});- Object.assign(mocks.summary, {- actualSeats: 5,- usedSeats: 4,- billedSeats: 5,- reservedSeats: 0,- purchaseVersion: 9,- });+ setSeatCapacity({ humanMembers: 5, purchased: 5, used: 5 });renderWithI18n(<BillingTab />);@@ -1448,7 +1404,7 @@ describe("BillingTab", () => {version: 4,});Object.assign(mocks.summary, {- billedSeats: 3,+ seatCapacity: null,hasStripeCustomer: true,});@@ -1460,6 +1416,7 @@ describe("BillingTab", () => {expect(screen.getByRole("button", { name: "Upgrade to Pro" }),).toBeInTheDocument();+ expect(screen.queryByText("Purchased seats")).not.toBeInTheDocument();expect(mocks.useQuery).toHaveBeenCalledWith(expect.objectContaining({queryKey: ["workspace-subscriptions", "workspace-1", "prices"],@@ -1477,6 +1434,7 @@ describe("BillingTab", () => {version: 4,});mocks.summary.graceUntil = "2000-01-01T00:00:00Z";+ mocks.summary.hasStripeCustomer = true;renderWithI18n(<BillingTab />);diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex f9f80c4478..fc0e10643e 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -19,7 +19,6 @@ import {useCreateWorkspaceSubscriptionPortal,usePreviewWorkspaceSeatPurchase,usePurchaseWorkspaceSeats,- useReconcileWorkspaceSubscriptionSeats,workspaceSubscriptionEntitlementsOptions,workspaceSubscriptionPricesOptions,workspaceSubscriptionSummaryOptions,@@ -76,7 +75,8 @@ import {} from "./settings-layout";import {canPurchaseWorkspaceSubscription,- hasManagedWorkspaceSubscription,+ hasActiveWorkspaceSeatCapacity,+ hasWorkspaceBillingRelationship,resolveAutopilotUsage,} from "./billing-state";@@ -281,7 +281,9 @@ function BillingTabContent() {useState(false);const [actionError, setActionError] = useState<string | null>(null);const [portalUnavailable, setPortalUnavailable] = useState(false);- const [reconcileMessage, setReconcileMessage] = useState<string | null>(null);+ const [seatPurchaseMessage, setSeatPurchaseMessage] = useState<string | null>(+ null,+ );const [isSyncingCheckout, setIsSyncingCheckout] = useState(returnResult === "success",);@@ -319,7 +321,7 @@ function BillingTabContent() {setSeatPurchasePollingTimedOut(false);setPortalUnavailable(false);setActionError(null);- setReconcileMessage(null);+ setSeatPurchaseMessage(null);}, [wsId]);// Consume Stripe callback params once, then remove them with replace so a@@ -377,13 +379,13 @@ function BillingTabContent() {// browser polling forever.refetchInterval: (query) =>isSyncingCheckout ||- (query.state.data?.activeSeatPurchase &&+ (query.state.data?.seatCapacity?.activePurchase &&!seatPurchasePollingTimedOut)? 2_000: false,});const activeSeatPurchaseRequestId =- summaryQuery.data?.activeSeatPurchase?.requestId ?? null;+ summaryQuery.data?.seatCapacity?.activePurchase?.requestId ?? null;useEffect(() => {if (!activeSeatPurchaseRequestId) {@@ -401,9 +403,10 @@ function BillingTabContent() {summaryQuery.isError ||(!summaryQuery.isPending && summaryQuery.data == null);const quotaUsageQuery = useQuery(autopilotQuotaUsageOptions(wsId));- const hasManagedSubscription = entitlements- ? hasManagedWorkspaceSubscription(entitlements, summaryQuery.data)- : false;+ const hasSeatCapacity = hasActiveWorkspaceSeatCapacity(summaryQuery.data);+ const hasBillingRelationship = hasWorkspaceBillingRelationship(+ summaryQuery.data,+ );const canUpgrade = entitlements? canPurchaseWorkspaceSubscription(entitlements): false;@@ -413,7 +416,6 @@ function BillingTabContent() {});const checkoutMutation = useCreateWorkspaceSubscriptionCheckout(wsId);const portalMutation = useCreateWorkspaceSubscriptionPortal(wsId);- const reconcileMutation = useReconcileWorkspaceSubscriptionSeats(wsId);const previewSeatPurchaseMutation = usePreviewWorkspaceSeatPurchase();const purchaseSeatsMutation = usePurchaseWorkspaceSeats(wsId);const refetchEntitlements = entitlementQuery.refetch;@@ -424,8 +426,8 @@ function BillingTabContent() {if (!seatPurchaseOpen) return;const value = additionalSeatsInput.trim();const additionalSeats = /^\d+$/.test(value) ? Number(value) : 0;- const currentSeats = summaryQuery.data?.billedSeats ?? null;- const purchaseVersion = summaryQuery.data?.purchaseVersion ?? null;+ const currentSeats = summaryQuery.data?.seatCapacity?.purchased ?? null;+ const purchaseVersion = summaryQuery.data?.seatCapacity?.version ?? null;const retryInputKey = `${wsId}:${value}`;if (seatPreviewCapacityRetryRef.current?.inputKey !== retryInputKey) {seatPreviewCapacityRetryRef.current = {@@ -517,9 +519,10 @@ function BillingTabContent() {);return;}- const refreshedSeats = refreshed.data?.billedSeats ?? null;+ const refreshedSeats =+ refreshed.data?.seatCapacity?.purchased ?? null;const refreshedVersion =- refreshed.data?.purchaseVersion ?? null;+ refreshed.data?.seatCapacity?.version ?? null;if (refreshedSeats === currentSeats &&refreshedVersion === purchaseVersion@@ -558,8 +561,8 @@ function BillingTabContent() {refetchSummary,seatPurchaseOpen,seatPreviewRevision,- summaryQuery.data?.billedSeats,- summaryQuery.data?.purchaseVersion,+ summaryQuery.data?.seatCapacity?.purchased,+ summaryQuery.data?.seatCapacity?.version,t,wsId,]);@@ -702,27 +705,6 @@ function BillingTabContent() {}};- const handleReconcile = async () => {- setActionError(null);- setReconcileMessage(null);- try {- const response = await reconcileMutation.mutateAsync();- if (!response) {- setActionError(t(($) => $.workspace.errors.reconcile_response));- return;- }- setReconcileMessage(- t(($) => $.workspace.seats.reconciled, {- actual: response.actualSeats,- billed: response.billedSeats,- }),- );- await Promise.all([entitlementQuery.refetch(), summaryQuery.refetch()]);- } catch (error) {- reportActionError(error, t(($) => $.workspace.errors.reconcile_failed));- }- };-const handleSeatPurchase = async () => {const confirmedPreview = seatPreview;if (!confirmedPreview) return;@@ -772,7 +754,7 @@ function BillingTabContent() {seatPreviewInputRef.current = "";setSeatPurchaseOpen(false);setSeatPreview(null);- setReconcileMessage(+ setSeatPurchaseMessage(t(($) => $.workspace.seat_purchase.submitted, {count: response.resultingSeats,}),@@ -900,35 +882,27 @@ function BillingTabContent() {entitlements.plan === "pro" &&(entitlements.status !== "past_due" || hasActiveProGrace) &&(returnResult !== "success" || isCheckoutProConfirmed);- const actualSeats = summaryQuery.data?.actualSeats ?? entitlements.seats;- const usedSeats = summaryQuery.data?.usedSeats ?? actualSeats;- const billedSeats = summaryQuery.data?.billedSeats;- const pendingSeatQuantity = summaryQuery.data?.pendingSeatQuantity;- const reservedSeats = summaryQuery.data?.reservedSeats ?? 0;+ const actualSeats = summaryQuery.data?.humanMembers ?? entitlements.seats;+ const seatCapacity = summaryQuery.data?.seatCapacity ?? null;+ const usedSeats = seatCapacity?.used ?? actualSeats;+ const billedSeats = seatCapacity?.purchased ?? null;+ const pendingSeatQuantity = seatCapacity?.pendingQuantity ?? null;+ const reservedSeats = seatCapacity?.reserved ?? 0;const membersExceedPurchasedSeats =- hasManagedSubscription &&- summaryQuery.data !== undefined &&+ hasSeatCapacity &&billedSeats !== null &&- billedSeats !== undefined &&actualSeats > billedSeats;- const availableSeats =- billedSeats === null || billedSeats === undefined- ? null- : Math.max(0, billedSeats - usedSeats - reservedSeats);- const activeSeatPurchase = summaryQuery.data?.activeSeatPurchase ?? null;+ const availableSeats = seatCapacity?.available ?? null;+ const activeSeatPurchase = seatCapacity?.activePurchase ?? null;const activeSeatPurchaseExpiry = formatDateTime(activeSeatPurchase?.expiresAt ?? null,locale,);const canAddSeats =canManage &&- hasManagedSubscription &&+ hasSeatCapacity &&(entitlements.status === "active" || entitlements.status === "trialing") &&!summaryQuery.data?.cancelAtPeriodEnd &&- summaryQuery.data?.purchaseVersion !== null &&- summaryQuery.data?.purchaseVersion !== undefined &&- billedSeats !== null &&- billedSeats !== undefined &&activeSeatPurchase === null;const quotaUsage = resolveAutopilotUsage(entitlements,@@ -944,7 +918,6 @@ function BillingTabContent() {const isMutating =checkoutMutation.isPending ||portalMutation.isPending ||- reconcileMutation.isPending ||purchaseSeatsMutation.isPending;const selectedPrice = pricesQuery.data?.[interval] ?? null;const formattedUnitPrice = selectedPrice@@ -1317,7 +1290,7 @@ function BillingTabContent() {</SettingsSection>) : null}- {hasManagedSubscription && canManage ? (+ {hasBillingRelationship && canManage ? (<SettingsSectiontitle={t(($) => $.workspace.management.title)}description={t(($) => $.workspace.management.description)}@@ -1452,159 +1425,66 @@ function BillingTabContent() {</SettingsCard></SettingsSection>- <SettingsSection- title={t(($) => $.workspace.seats.title)}- description={t(($) => $.workspace.seats.description)}- >- {summaryUnavailable ? (- <Alert className="mb-3">- <AlertCircle />- <AlertTitle>- {t(($) => $.workspace.seats.summary_unavailable_title)}- </AlertTitle>- <AlertDescription>- <p>- {t(($) => $.workspace.seats.summary_unavailable_description)}- </p>- <Button- className="mt-3"- type="button"- variant="outline"- size="sm"- aria-busy={summaryQuery.isFetching}- disabled={summaryQuery.isFetching}- onClick={() => void summaryQuery.refetch()}- >- {summaryQuery.isFetching ? (- <Loader2 className="animate-spin motion-reduce:animate-none" />- ) : (- <RefreshCw />- )}- {t(($) => $.workspace.actions.retry)}- </Button>- </AlertDescription>- </Alert>- ) : null}- {reconcileMessage ? (- <Alert className="mb-3">- <CheckCircle2 />- <AlertTitle>{t(($) => $.workspace.seats.updated)}</AlertTitle>- <AlertDescription>{reconcileMessage}</AlertDescription>- </Alert>- ) : null}- {membersExceedPurchasedSeats ? (- <Alert className="mb-3">- <AlertCircle />- <AlertTitle>- {t(($) => $.workspace.seats.members_over_capacity_title)}- </AlertTitle>- <AlertDescription>- <p>- {t(($) => $.workspace.seats.members_over_capacity_description, {- actual: actualSeats,- purchased: billedSeats,- })}- </p>- {canAddSeats ? (+ {hasSeatCapacity || summaryUnavailable ? (+ <SettingsSection+ title={t(($) => $.workspace.seats.title)}+ description={t(($) => $.workspace.seats.description)}+ >+ {summaryUnavailable ? (+ <Alert className="mb-3">+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.seats.summary_unavailable_title)}+ </AlertTitle>+ <AlertDescription>+ <p>+ {t(($) => $.workspace.seats.summary_unavailable_description)}+ </p><ButtonclassName="mt-3"type="button"variant="outline"size="sm"- disabled={isMutating}- onClick={() => handleSeatPurchaseOpenChange(true)}- >- <Plus />- {t(($) => $.workspace.actions.add_seats)}- </Button>- ) : null}- </AlertDescription>- </Alert>- ) : null}- {activeSeatPurchase ? (- <Alert className="mb-3">- {seatPurchasePollingTimedOut ? (- <AlertCircle />- ) : (- <Loader2 className="animate-spin motion-reduce:animate-none" />- )}- <AlertTitle>- {seatPurchasePollingTimedOut- ? t(($) => $.workspace.seat_purchase.delayed_title)- : t(($) => $.workspace.seat_purchase.pending_title)}- </AlertTitle>- <AlertDescription>- {seatPurchasePollingTimedOut- ? activeSeatPurchaseExpiry- ? t(- ($) =>- $.workspace.seat_purchase- .delayed_description_with_expiry,- { date: activeSeatPurchaseExpiry },- )- : t(($) => $.workspace.seat_purchase.delayed_description)- : t(($) => $.workspace.seat_purchase.pending_description, {- count: activeSeatPurchase.targetSeats,- })}- </AlertDescription>- </Alert>- ) : null}- <SettingsCard>- <SettingsRow- label={t(($) => $.workspace.seats.human_members)}- description={t(($) => $.workspace.seats.human_members_description)}- >- <div className="flex flex-col gap-2 sm:items-end">- <span className="tabular-nums">- {t(($) => $.workspace.seats.seat_count, {- count: usedSeats,- })}- </span>- {canManage && hasManagedSubscription ? (- <Button- className="h-11 w-full sm:w-auto"- variant="outline"- disabled={isMutating}- onClick={() => void handleReconcile()}+ aria-busy={summaryQuery.isFetching}+ disabled={summaryQuery.isFetching}+ onClick={() => void summaryQuery.refetch()}>- {reconcileMutation.isPending ? (+ {summaryQuery.isFetching ? (<Loader2 className="animate-spin motion-reduce:animate-none" />) : (<RefreshCw />)}- {t(($) => $.workspace.actions.refresh_seats)}+ {t(($) => $.workspace.actions.retry)}</Button>- ) : null}- </div>- </SettingsRow>- <SettingsRow- label={t(($) => $.workspace.seats.billed)}- description={t(($) => $.workspace.seats.billed_description)}- >- {summaryQuery.isPending ? (- <Skeleton- className="h-5 w-20 motion-reduce:animate-none"- aria-label={t(($) => $.workspace.seats.summary_loading)}- />- ) : summaryUnavailable ? (- <span className="text-muted-foreground">- {t(($) => $.workspace.seats.unavailable)}- </span>- ) : billedSeats === null || billedSeats === undefined ? (- <span className="text-muted-foreground">- {t(($) => $.workspace.seats.not_subscribed)}- </span>- ) : (- <div className="flex flex-col gap-2 sm:items-end">- <span className="tabular-nums">- {t(($) => $.workspace.seats.seat_count, {- count: billedSeats,+ </AlertDescription>+ </Alert>+ ) : null}+ {seatPurchaseMessage ? (+ <Alert className="mb-3">+ <CheckCircle2 />+ <AlertTitle>{t(($) => $.workspace.seats.updated)}</AlertTitle>+ <AlertDescription>{seatPurchaseMessage}</AlertDescription>+ </Alert>+ ) : null}+ {membersExceedPurchasedSeats ? (+ <Alert className="mb-3">+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.seats.members_over_capacity_title)}+ </AlertTitle>+ <AlertDescription>+ <p>+ {t(($) => $.workspace.seats.members_over_capacity_description, {+ actual: actualSeats,+ purchased: billedSeats,})}- </span>+ </p>{canAddSeats ? (<Button- className="h-11 w-full sm:w-auto"+ className="mt-3"type="button"+ variant="outline"+ size="sm"disabled={isMutating}onClick={() => handleSeatPurchaseOpenChange(true)}>@@ -1612,88 +1492,165 @@ function BillingTabContent() {{t(($) => $.workspace.actions.add_seats)}</Button>) : null}- </div>- )}- </SettingsRow>- <SettingsRow- label={t(($) => $.workspace.seats.pending_invitations)}- description={t(- ($) => $.workspace.seats.pending_invitations_description,- )}- >- {summaryQuery.isPending ? (- <Skeleton- className="h-5 w-20 motion-reduce:animate-none"- aria-label={t(($) => $.workspace.seats.summary_loading)}- />- ) : summaryUnavailable ? (- <span className="text-muted-foreground">- {t(($) => $.workspace.seats.unavailable)}- </span>- ) : (- <span className="tabular-nums">- {t(($) => $.workspace.seats.seat_count, {- count: reservedSeats,- })}- </span>- )}- </SettingsRow>- <SettingsRow- label={t(($) => $.workspace.seats.available)}- description={t(($) => $.workspace.seats.available_description)}- >- {summaryQuery.isPending ? (- <Skeleton- className="h-5 w-20 motion-reduce:animate-none"- aria-label={t(($) => $.workspace.seats.summary_loading)}- />- ) : summaryUnavailable || availableSeats === null ? (- <span className="text-muted-foreground">- {t(($) => $.workspace.seats.unavailable)}- </span>- ) : (- <span className="tabular-nums">- {t(($) => $.workspace.seats.seat_count, {- count: availableSeats,- })}- </span>- )}- </SettingsRow>- <SettingsRow- label={t(($) => $.workspace.seats.pending)}- description={t(($) => $.workspace.seats.pending_description)}- >- {summaryQuery.isPending ? (- <Skeleton- className="h-5 w-28 motion-reduce:animate-none"- aria-label={t(($) => $.workspace.seats.summary_loading)}- />- ) : summaryUnavailable ? (- <span className="text-muted-foreground">- {t(($) => $.workspace.seats.unavailable)}- </span>- ) : pendingSeatQuantity === null ||- pendingSeatQuantity === undefined ? (- <span className="text-muted-foreground">- {t(($) => $.workspace.seats.none_pending)}- </span>- ) : summaryPeriodEnd ? (- <span className="tabular-nums">- {t(($) => $.workspace.seats.pending_with_date, {- count: pendingSeatQuantity,- date: summaryPeriodEnd,- })}- </span>- ) : (+ </AlertDescription>+ </Alert>+ ) : null}+ {activeSeatPurchase ? (+ <Alert className="mb-3">+ {seatPurchasePollingTimedOut ? (+ <AlertCircle />+ ) : (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ )}+ <AlertTitle>+ {seatPurchasePollingTimedOut+ ? t(($) => $.workspace.seat_purchase.delayed_title)+ : t(($) => $.workspace.seat_purchase.pending_title)}+ </AlertTitle>+ <AlertDescription>+ {seatPurchasePollingTimedOut+ ? activeSeatPurchaseExpiry+ ? t(+ ($) =>+ $.workspace.seat_purchase+ .delayed_description_with_expiry,+ { date: activeSeatPurchaseExpiry },+ )+ : t(($) => $.workspace.seat_purchase.delayed_description)+ : t(($) => $.workspace.seat_purchase.pending_description, {+ count: activeSeatPurchase.targetSeats,+ })}+ </AlertDescription>+ </Alert>+ ) : null}+ <SettingsCard>+ <SettingsRow+ label={t(($) => $.workspace.seats.human_members)}+ description={t(($) => $.workspace.seats.human_members_description)}+ ><span className="tabular-nums">{t(($) => $.workspace.seats.seat_count, {- count: pendingSeatQuantity,+ count: usedSeats,})}</span>- )}- </SettingsRow>- </SettingsCard>- </SettingsSection>+ </SettingsRow>+ <SettingsRow+ label={t(($) => $.workspace.seats.billed)}+ description={t(($) => $.workspace.seats.billed_description)}+ >+ {summaryQuery.isPending ? (+ <Skeleton+ className="h-5 w-20 motion-reduce:animate-none"+ aria-label={t(($) => $.workspace.seats.summary_loading)}+ />+ ) : summaryUnavailable ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.unavailable)}+ </span>+ ) : billedSeats === null ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.not_subscribed)}+ </span>+ ) : (+ <div className="flex flex-col gap-2 sm:items-end">+ <span className="tabular-nums">+ {t(($) => $.workspace.seats.seat_count, {+ count: billedSeats,+ })}+ </span>+ {canAddSeats ? (+ <Button+ className="h-11 w-full sm:w-auto"+ type="button"+ disabled={isMutating}+ onClick={() => handleSeatPurchaseOpenChange(true)}+ >+ <Plus />+ {t(($) => $.workspace.actions.add_seats)}+ </Button>+ ) : null}+ </div>+ )}+ </SettingsRow>+ <SettingsRow+ label={t(($) => $.workspace.seats.pending_invitations)}+ description={t(+ ($) => $.workspace.seats.pending_invitations_description,+ )}+ >+ {summaryQuery.isPending ? (+ <Skeleton+ className="h-5 w-20 motion-reduce:animate-none"+ aria-label={t(($) => $.workspace.seats.summary_loading)}+ />+ ) : summaryUnavailable ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.unavailable)}+ </span>+ ) : (+ <span className="tabular-nums">+ {t(($) => $.workspace.seats.seat_count, {+ count: reservedSeats,+ })}+ </span>+ )}+ </SettingsRow>+ <SettingsRow+ label={t(($) => $.workspace.seats.available)}+ description={t(($) => $.workspace.seats.available_description)}+ >+ {summaryQuery.isPending ? (+ <Skeleton+ className="h-5 w-20 motion-reduce:animate-none"+ aria-label={t(($) => $.workspace.seats.summary_loading)}+ />+ ) : summaryUnavailable || availableSeats === null ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.unavailable)}+ </span>+ ) : (+ <span className="tabular-nums">+ {t(($) => $.workspace.seats.seat_count, {+ count: availableSeats,+ })}+ </span>+ )}+ </SettingsRow>+ <SettingsRow+ label={t(($) => $.workspace.seats.pending)}+ description={t(($) => $.workspace.seats.pending_description)}+ >+ {summaryQuery.isPending ? (+ <Skeleton+ className="h-5 w-28 motion-reduce:animate-none"+ aria-label={t(($) => $.workspace.seats.summary_loading)}+ />+ ) : summaryUnavailable ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.unavailable)}+ </span>+ ) : pendingSeatQuantity === null ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.none_pending)}+ </span>+ ) : summaryPeriodEnd ? (+ <span className="tabular-nums">+ {t(($) => $.workspace.seats.pending_with_date, {+ count: pendingSeatQuantity,+ date: summaryPeriodEnd,+ })}+ </span>+ ) : (+ <span className="tabular-nums">+ {t(($) => $.workspace.seats.seat_count, {+ count: pendingSeatQuantity,+ })}+ </span>+ )}+ </SettingsRow>+ </SettingsCard>+ </SettingsSection>+ ) : null}<Dialogopen={seatPurchaseOpen}@@ -1723,9 +1680,7 @@ function BillingTabContent() {inputMode="numeric"min={1}max={- billedSeats === null || billedSeats === undefined- ? 10_000- : 10_000 - billedSeats+ billedSeats === null ? 10_000 : 10_000 - billedSeats}step={1}value={additionalSeatsInput}