Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6529: let admins add workspace seats (#7388)
Multica Eve13f9f8e5caa3
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 7980116c86..e4c8bd7990 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -211,6 +211,10 @@ import type {CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,WorkspaceSubscriptionSeatReconcileResult,+ PreviewWorkspaceSeatPurchaseRequest,+ WorkspaceSeatPurchasePreview,+ PurchaseWorkspaceSeatsRequest,+ PurchaseWorkspaceSeatsResponse,CreateWorkspaceSubscriptionPortalResponse,} from "../types";import type { OnboardingCompletionPath } from "../onboarding/types";@@ -322,6 +326,8 @@ import {WorkspaceSubscriptionPricesSchema,CreateWorkspaceSubscriptionCheckoutResponseSchema,WorkspaceSubscriptionSeatReconcileResultSchema,+ WorkspaceSeatPurchasePreviewSchema,+ PurchaseWorkspaceSeatsResponseSchema,CreateWorkspaceSubscriptionPortalResponseSchema,DingTalkInstallationSchema,ListDingTalkInstallationsResponseSchema,@@ -1774,6 +1780,56 @@ export class ApiClient {);}+ async previewWorkspaceSeatPurchase(+ data: PreviewWorkspaceSeatPurchaseRequest,+ ): Promise<WorkspaceSeatPurchasePreview | null> {+ const res = await this.fetchRaw(+ "/api/cloud-subscriptions/seats/purchase-preview",+ {+ method: "POST",+ body: JSON.stringify({ additional_seats: data.additionalSeats }),+ extraHeaders: { "Content-Type": "application/json" },+ },+ );+ const raw = (await res.json()) as unknown;+ return parseWithFallback<WorkspaceSeatPurchasePreview | null>(+ raw,+ WorkspaceSeatPurchasePreviewSchema,+ null,+ { endpoint: "POST /api/cloud-subscriptions/seats/purchase-preview" },+ );+ }++ async purchaseWorkspaceSeats(+ data: PurchaseWorkspaceSeatsRequest,+ ): Promise<PurchaseWorkspaceSeatsResponse | null> {+ const res = await this.fetchRaw(+ "/api/cloud-subscriptions/seats/purchases",+ {+ method: "POST",+ body: JSON.stringify({+ additional_seats: data.additionalSeats,+ expected_current_seats: data.expectedCurrentSeats,+ expected_purchase_version: data.expectedPurchaseVersion,+ accepted_proration_amount: data.acceptedProrationAmount,+ currency: data.currency,+ idempotency_key: data.idempotencyKey,+ }),+ extraHeaders: {+ "Content-Type": "application/json",+ "Idempotency-Key": data.idempotencyKey,+ },+ },+ );+ const raw = (await res.json()) as unknown;+ return parseWithFallback<PurchaseWorkspaceSeatsResponse | null>(+ raw,+ PurchaseWorkspaceSeatsResponseSchema,+ null,+ { endpoint: "POST /api/cloud-subscriptions/seats/purchases" },+ );+ }+async createWorkspaceSubscriptionPortal(idempotencyKey: string,): Promise<CreateWorkspaceSubscriptionPortalResponse | null> {diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex cc833f7be1..59d98fff68 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -1091,6 +1091,14 @@ describe("workspace subscription contract", () => {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",+ },cancel_at_period_end: true,grace_until: "2026-09-08T00:00:00Z",has_stripe_customer: true,@@ -1104,6 +1112,15 @@ describe("workspace subscription contract", () => {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({+ requestId: "22222222-2222-2222-2222-222222222222",+ targetSeats: 7,+ status: "processing",+ expiresAt: null,+ });expect(summary?.cancelAtPeriodEnd).toBe(true);expect(summary?.graceUntil).toBe("2026-09-08T00:00:00Z");expect(summary?.hasStripeCustomer).toBe(true);@@ -1120,6 +1137,10 @@ describe("workspace subscription contract", () => {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@@ -1223,4 +1244,73 @@ describe("workspace subscription contract", () => {expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();});++ it("maps seat purchase previews and confirmations without trusting client totals", async () => {+ stubFetchJson({+ current_seats: 5,+ additional_seats: 2,+ resulting_seats: 7,+ purchase_version: 9,+ currency: "usd",+ proration_amount: 425,+ next_invoice_amount: 14000,+ quoted_at: "2026-08-21T06:00:00Z",+ });+ const client = new ApiClient("https://api.example.test");+ await expect(+ client.previewWorkspaceSeatPurchase({ additionalSeats: 2 }),+ ).resolves.toEqual({+ currentSeats: 5,+ additionalSeats: 2,+ resultingSeats: 7,+ purchaseVersion: 9,+ currency: "usd",+ prorationAmount: 425,+ nextInvoiceAmount: 14000,+ quotedAt: "2026-08-21T06:00:00Z",+ });+ expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(+ "https://api.example.test/api/cloud-subscriptions/seats/purchase-preview",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({ additional_seats: 2 }),+ }),+ );++ stubFetchJson({+ request_id: "33333333-3333-3333-3333-333333333333",+ current_seats: 5,+ additional_seats: 2,+ resulting_seats: 7,+ currency: "usd",+ proration_amount: 425,+ next_invoice_amount: 14000,+ status: "submitted",+ }, 202);+ await expect(+ client.purchaseWorkspaceSeats({+ additionalSeats: 2,+ expectedCurrentSeats: 5,+ expectedPurchaseVersion: 9,+ acceptedProrationAmount: 425,+ currency: "usd",+ idempotencyKey: "seat-request-1",+ }),+ ).resolves.toMatchObject({ resultingSeats: 7, status: "submitted" });+ expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(+ "https://api.example.test/api/cloud-subscriptions/seats/purchases",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({+ additional_seats: 2,+ expected_current_seats: 5,+ expected_purchase_version: 9,+ accepted_proration_amount: 425,+ currency: "usd",+ idempotency_key: "seat-request-1",+ }),+ headers: expect.objectContaining({ "Idempotency-Key": "seat-request-1" }),+ }),+ );+ });});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 4af75e0ff5..c114607887 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -27,6 +27,8 @@ import type {WorkspaceSubscriptionPrices,CreateWorkspaceSubscriptionCheckoutResponse,WorkspaceSubscriptionSeatReconcileResult,+ WorkspaceSeatPurchasePreview,+ PurchaseWorkspaceSeatsResponse,CreateWorkspaceSubscriptionPortalResponse,CronPreviewResponse,DingTalkInstallation,@@ -2443,6 +2445,20 @@ export const WorkspaceSubscriptionSummarySchema = zactual_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+ .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),+ })+ .loose()+ .nullable()+ .optional()+ .catch(null),cancel_at_period_end: z.boolean().optional(),grace_until: z.string().nullable().optional(),has_stripe_customer: z.boolean().optional(),@@ -2455,6 +2471,17 @@ export const WorkspaceSubscriptionSummarySchema = zactualSeats: 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+ ? {+ 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,+ }+ : null,cancelAtPeriodEnd: value.cancel_at_period_end ?? false,graceUntil: value.grace_until ?? null,hasStripeCustomer: value.has_stripe_customer ?? false,@@ -2533,6 +2560,56 @@ export const WorkspaceSubscriptionSeatReconcileResultSchema = z}),);+export const WorkspaceSeatPurchasePreviewSchema = z+ .object({+ current_seats: z.number().int().positive(),+ additional_seats: z.number().int().positive(),+ resulting_seats: z.number().int().positive(),+ purchase_version: z.number().int().positive(),+ currency: z.string().regex(/^[a-z]{3}$/),+ proration_amount: z.number().int().nonnegative(),+ next_invoice_amount: z.number().int().nonnegative(),+ quoted_at: z.string().min(1),+ })+ .loose()+ .transform(+ (value): WorkspaceSeatPurchasePreview => ({+ currentSeats: value.current_seats,+ additionalSeats: value.additional_seats,+ resultingSeats: value.resulting_seats,+ purchaseVersion: value.purchase_version,+ currency: value.currency,+ prorationAmount: value.proration_amount,+ nextInvoiceAmount: value.next_invoice_amount,+ quotedAt: value.quoted_at,+ }),+ );++export const PurchaseWorkspaceSeatsResponseSchema = z+ .object({+ request_id: z.string(),+ current_seats: z.number().int().positive(),+ additional_seats: z.number().int().positive(),+ resulting_seats: z.number().int().positive(),+ currency: z.string().regex(/^[a-z]{3}$/),+ proration_amount: z.number().int().nonnegative(),+ next_invoice_amount: z.number().int().nonnegative(),+ status: z.enum(["pending", "submitted", "confirmed"]),+ })+ .loose()+ .transform(+ (value): PurchaseWorkspaceSeatsResponse => ({+ requestId: value.request_id,+ currentSeats: value.current_seats,+ additionalSeats: value.additional_seats,+ resultingSeats: value.resulting_seats,+ currency: value.currency,+ prorationAmount: value.proration_amount,+ nextInvoiceAmount: value.next_invoice_amount,+ status: value.status,+ }),+ );+export const CreateWorkspaceSubscriptionPortalResponseSchema = z.object({url: StripeHostedURLSchema,diff --git a/packages/core/billing/workspace-subscription-mutations.ts b/packages/core/billing/workspace-subscription-mutations.tsindex 8353cb15e1..ef88b6f656 100644--- a/packages/core/billing/workspace-subscription-mutations.ts+++ b/packages/core/billing/workspace-subscription-mutations.ts@@ -1,6 +1,10 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { api } from "../api";-import type { CreateWorkspaceSubscriptionCheckoutRequest } from "../types";+import type {+ CreateWorkspaceSubscriptionCheckoutRequest,+ PreviewWorkspaceSeatPurchaseRequest,+ PurchaseWorkspaceSeatsRequest,+} from "../types";import { workspaceSubscriptionKeys } from "./workspace-subscription-queries";export function useCreateWorkspaceSubscriptionCheckout(wsId: string) {@@ -28,6 +32,29 @@ export function useReconcileWorkspaceSubscriptionSeats(wsId: string) {});}+export function usePreviewWorkspaceSeatPurchase() {+ return useMutation({+ mutationFn: (data: PreviewWorkspaceSeatPurchaseRequest) =>+ api.previewWorkspaceSeatPurchase(data),+ });+}++export function usePurchaseWorkspaceSeats(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (data: PurchaseWorkspaceSeatsRequest) =>+ api.purchaseWorkspaceSeats(data),+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: workspaceSubscriptionKeys.entitlements(wsId),+ });+ void queryClient.invalidateQueries({+ queryKey: workspaceSubscriptionKeys.summary(wsId),+ });+ },+ });+}+export function useCreateWorkspaceSubscriptionPortal(wsId: string) {const queryClient = useQueryClient();return useMutation({diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex 51748b58fe..75257274b0 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -185,8 +185,9 @@ export interface CreateBillingPortalSessionResponse {// Workspace subscriptions (`/api/cloud-subscriptions/*`)//// Workspace-scoped, unlike the account-level wallet types above. The server-// injects the workspace from the authenticated request context, so no client-// ever names a workspace, an amount, a Price ID, or a seat quantity.+// injects the workspace from the authenticated request context. Clients never+// name a workspace, amount, or Price ID. Seat purchases use additive counts;+// Cloud validates and converts them to an absolute Stripe quantity.//// Every field the server may not know is nullable rather than defaulted. A// missing value has to stay visibly unknown: rendering an absent plan as Free@@ -222,6 +223,13 @@ export interface WorkspaceSubscriptionSummary {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;cancelAtPeriodEnd: boolean;graceUntil: string | null;/**@@ -232,6 +240,13 @@ export interface WorkspaceSubscriptionSummary {hasStripeCustomer: boolean;}+export interface WorkspaceSeatPurchaseSummary {+ requestId: string;+ targetSeats: number;+ status: "pending" | "processing" | "submitted";+ expiresAt: string | null;+}+/** Display-safe subset of a configured Stripe Price. IDs stay server-side. */export interface WorkspaceSubscriptionPrice {currency: string;@@ -258,6 +273,43 @@ export interface CreateWorkspaceSubscriptionCheckoutResponse {url: string;}+export interface PreviewWorkspaceSeatPurchaseRequest {+ additionalSeats: number;+}++export interface WorkspaceSeatPurchasePreview {+ currentSeats: number;+ additionalSeats: number;+ resultingSeats: number;+ purchaseVersion: number;+ currency: string;+ /** Estimated immediate proration in Stripe's minor currency unit. */+ prorationAmount: number;+ /** Estimated next full recurring invoice in minor currency units. */+ nextInvoiceAmount: number;+ quotedAt: string;+}++export interface PurchaseWorkspaceSeatsRequest {+ additionalSeats: number;+ expectedCurrentSeats: number;+ expectedPurchaseVersion: number;+ acceptedProrationAmount: number;+ currency: string;+ idempotencyKey: string;+}++export interface PurchaseWorkspaceSeatsResponse {+ requestId: string;+ currentSeats: number;+ additionalSeats: number;+ resultingSeats: number;+ currency: string;+ prorationAmount: number;+ nextInvoiceAmount: number;+ status: "pending" | "submitted" | "confirmed";+}+export interface WorkspaceSubscriptionSeatReconcileResult {workspaceId: string;billedSeats: number;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex cea78fc777..4cfddcfcd9 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -311,10 +311,15 @@ export type {WorkspaceSubscriptionInterval,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,+ WorkspaceSeatPurchaseSummary,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPrices,CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,+ PreviewWorkspaceSeatPurchaseRequest,+ WorkspaceSeatPurchasePreview,+ PurchaseWorkspaceSeatsRequest,+ PurchaseWorkspaceSeatsResponse,WorkspaceSubscriptionSeatReconcileResult,CreateWorkspaceSubscriptionPortalResponse,} from "./billing";diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 4b5eabf32d..1cb8c2bc0f 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -96,6 +96,7 @@"retry_autopilots": "Retry automation usage","upgrade": "Upgrade to Pro","manage": "Manage billing",+ "add_seats": "Add seats","refresh_seats": "Refresh seats","cancel": "Cancel","continue_to_stripe": "Continue to Stripe"@@ -203,11 +204,15 @@},"seats": {"title": "Seats",- "description": "Every current human member counts as a Pro seat. Agents and pending invitations do not.",- "human_members": "Current human members",- "human_members_description": "Refresh after membership changes to ask cloud billing to reconcile Stripe quantity.",- "billed": "Billed seats",- "billed_description": "The seat quantity currently persisted for Stripe billing.",+ "description": "Purchased seats cover current human members and pending invitations. Agents never use a seat.",+ "human_members": "Used seats",+ "human_members_description": "Confirmed human members consuming purchased capacity. Refresh after a membership change to reconcile the count.",+ "billed": "Purchased seats",+ "billed_description": "The seat quantity currently purchased through Stripe.",+ "pending_invitations": "Pending invitations",+ "pending_invitations_description": "Live invitations reserve purchased seats until accepted or expired.",+ "available": "Available seats",+ "available_description": "Purchased seats not used by members or reserved for invitations.","pending": "Scheduled seat quantity","pending_description": "A lower quantity that cloud billing reports for the next period.","seat_count_one": "{{count}} seat",@@ -219,10 +224,39 @@"unavailable": "Unavailable","summary_loading": "Loading subscription seat details","summary_unavailable_title": "Some seat details are unavailable",- "summary_unavailable_description": "The current plan is still shown, but billed and scheduled seat quantities could not be loaded.",+ "summary_unavailable_description": "The current plan is still shown, but purchased and scheduled seat quantities could not be loaded.","updated": "Seats refreshed","reconciled": "Current members: {{actual}} · billed seats: {{billed}}"},+ "seat_purchase": {+ "title": "Add seats",+ "description": "Enter the number of seats to add. A fresh Stripe estimate appears before you confirm.",+ "additional_label": "Additional seats",+ "additional_hint": "Enter seats to add, not the new total.",+ "preview_loading": "Updating estimate...",+ "preview_unreadable": "The estimate could not be read. Change the seat count or retry.",+ "preview_failed": "The estimate is temporarily unavailable. Retry in a moment.",+ "in_progress": "Another seat purchase is being processed. Wait for it to finish; contact support if it remains here.",+ "purchase_unreadable": "The purchase response could not be read. Retry this quote; the same purchase request will be reused.",+ "purchase_failed": "Seats could not be added. Retry with the same quote, or refresh if it has expired.",+ "payment_failed": "Payment could not be completed. Update the payment method in Stripe, then request a new quote.",+ "quote_changed": "The seat count or estimate changed. Review the refreshed quote before confirming again.",+ "seats_after": "Seats after purchase",+ "charge_today": "Estimated charge today",+ "next_invoice": "Estimated next renewal",+ "tax_notice": "Stripe determines taxes, credits, and final invoice details. Seats become available after Stripe confirms the subscription update.",+ "confirm_one": "Add {{count}} seat",+ "confirm_other": "Add {{count}} seats",+ "pending_title": "Seat purchase processing",+ "pending_description_one": "Stripe is confirming the subscription update to {{count}} seat.",+ "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.",+ "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"+ },"confirm": {"title": "Continue to Stripe Checkout?","description": "Billing interval: {{interval}}. Current human members: {{count}}. Stripe will re-count seats and show the final amount before payment."diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 92bd2f2806..a291d51b7c 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -96,6 +96,7 @@"retry_autopilots": "自動化の使用量を再取得","upgrade": "Pro にアップグレード","manage": "請求を管理",+ "add_seats": "席を追加","refresh_seats": "席数を更新","cancel": "キャンセル","continue_to_stripe": "Stripe に進む"@@ -201,11 +202,15 @@},"seats": {"title": "席数",- "description": "現在のユーザーメンバーはそれぞれ Pro の 1 席として数えられます。エージェントと保留中の招待は含まれません。",- "human_members": "現在のユーザーメンバー",- "human_members_description": "メンバー変更後に更新すると、Cloud Billing が Stripe の quantity を照合します。",- "billed": "請求席数",- "billed_description": "Stripe 請求に現在保存されている席数です。",+ "description": "購入済みの席は現在のユーザーメンバーと保留中の招待に使われます。エージェントは席を使用しません。",+ "human_members": "使用中の席",+ "human_members_description": "購入済みの容量を使用している確認済みユーザーメンバーです。メンバー変更後に更新できます。",+ "billed": "購入済みの席",+ "billed_description": "Stripe で現在購入済みの席数です。",+ "pending_invitations": "保留中の招待",+ "pending_invitations_description": "有効な招待は、承認または期限切れまで購入済みの席を予約します。",+ "available": "利用可能な席",+ "available_description": "メンバーが使用せず、招待にも予約されていない購入済みの席です。","pending": "変更予定の席数","pending_description": "Cloud Billing が次の期間に対して報告した、より少ない席数です。","seat_count_other": "{{count}}席",@@ -215,10 +220,36 @@"unavailable": "利用できません","summary_loading": "サブスクリプションの席数詳細を読み込み中","summary_unavailable_title": "一部の席数詳細を利用できません",- "summary_unavailable_description": "現在のプランは表示できますが、請求席数と変更予定の席数を読み込めませんでした。",+ "summary_unavailable_description": "現在のプランは表示できますが、購入済みの席数と変更予定の席数を読み込めませんでした。","updated": "席数を更新しました","reconciled": "現在のメンバー: {{actual}} · 請求席数: {{billed}}"},+ "seat_purchase": {+ "title": "席を追加",+ "description": "追加する席数を入力してください。確定前に最新の Stripe 見積もりを表示します。",+ "additional_label": "追加する席数",+ "additional_hint": "新しい合計ではなく、追加する数を入力してください。",+ "preview_loading": "見積もりを更新中...",+ "preview_unreadable": "見積もりを読み取れませんでした。席数を変更するか、再試行してください。",+ "preview_failed": "見積もりは一時的に利用できません。しばらくしてから再試行してください。",+ "in_progress": "別の席購入を処理中です。完了をお待ちください。長時間完了しない場合はサポートにお問い合わせください。",+ "purchase_unreadable": "購入レスポンスを読み取れませんでした。この見積もりを再試行すると、同じ購入リクエストが再利用されます。",+ "purchase_failed": "席を追加できませんでした。同じ見積もりで再試行するか、期限切れの場合は更新してください。",+ "payment_failed": "支払いを完了できませんでした。Stripe で支払い方法を更新してから、新しい見積もりを取得してください。",+ "quote_changed": "席数または見積もりが変更されました。更新後の見積もりを確認してください。",+ "seats_after": "購入後の席数",+ "charge_today": "本日の見積請求額",+ "next_invoice": "次回更新時の見積額",+ "tax_notice": "税金、クレジット、最終請求内容は Stripe が決定します。Stripe がサブスクリプション更新を確認後、新しい席を利用できます。",+ "confirm_other": "{{count}}席を追加",+ "pending_title": "席購入を処理中",+ "pending_description_other": "Stripe が {{count}}席へのサブスクリプション更新を確認しています。",+ "delayed_title": "席の確認に時間がかかっています",+ "delayed_description": "自動確認を停止しました。購入はまだ完了する可能性があります。別の購入を始める前に、後でもう一度確認するかサポートへお問い合わせください。",+ "delayed_description_with_expiry": "自動確認を停止しました。{{date}} を過ぎても保留中の場合は、席数を更新してリクエストを解放し、新しい見積もりを取得してください。別の購入を始める前にサポートへお問い合わせいただくこともできます。",+ "submitted_other": "{{count}}席の購入を送信しました。Stripe の確認後に新しい容量が表示されます。",+ "error_title": "見積もりを更新できません"+ },"confirm": {"title": "Stripe Checkout に進みますか?","description": "請求期間: {{interval}}。現在のユーザーメンバー: {{count}}。Stripe が席数を再集計し、お支払い前に最終金額を表示します。"diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex c3fd89f3af..763b75c3ed 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -96,6 +96,7 @@"retry_autopilots": "자동화 사용량 다시 시도","upgrade": "Pro로 업그레이드","manage": "결제 관리",+ "add_seats": "좌석 추가","refresh_seats": "좌석 새로고침","cancel": "취소","continue_to_stripe": "Stripe로 이동"@@ -201,11 +202,15 @@},"seats": {"title": "좌석",- "description": "현재 사용자 멤버 한 명당 Pro 좌석 하나로 계산됩니다. 에이전트와 대기 중인 초대는 포함되지 않습니다.",- "human_members": "현재 사용자 멤버",- "human_members_description": "멤버 변경 후 새로고침하면 Cloud Billing이 Stripe quantity를 조정합니다.",- "billed": "결제 좌석",- "billed_description": "Stripe 결제에 현재 저장된 좌석 수입니다.",+ "description": "구매한 좌석은 현재 사용자 멤버와 대기 중인 초대에 사용됩니다. 에이전트는 좌석을 사용하지 않습니다.",+ "human_members": "사용 중인 좌석",+ "human_members_description": "구매한 용량을 사용 중인 확인된 사용자 멤버입니다. 멤버 변경 후 새로고침할 수 있습니다.",+ "billed": "구매한 좌석",+ "billed_description": "현재 Stripe를 통해 구매한 좌석 수입니다.",+ "pending_invitations": "대기 중인 초대",+ "pending_invitations_description": "유효한 초대는 수락되거나 만료될 때까지 구매한 좌석을 예약합니다.",+ "available": "사용 가능한 좌석",+ "available_description": "멤버가 사용하지 않고 초대에도 예약되지 않은 구매 좌석입니다.","pending": "예정 좌석 수","pending_description": "Cloud Billing이 다음 결제 기간에 대해 보고한 더 적은 좌석 수입니다.","seat_count_other": "좌석 {{count}}개",@@ -215,10 +220,36 @@"unavailable": "사용할 수 없음","summary_loading": "구독 좌석 상세 정보 불러오는 중","summary_unavailable_title": "일부 좌석 상세 정보를 불러올 수 없습니다",- "summary_unavailable_description": "현재 요금제는 계속 표시되지만 결제 좌석과 예정 좌석 수를 불러오지 못했습니다.",+ "summary_unavailable_description": "현재 요금제는 계속 표시되지만 구매한 좌석과 예정 좌석 수를 불러오지 못했습니다.","updated": "좌석 새로고침됨","reconciled": "현재 멤버: {{actual}} · 결제 좌석: {{billed}}"},+ "seat_purchase": {+ "title": "좌석 추가",+ "description": "추가할 좌석 수를 입력하세요. 확인 전에 최신 Stripe 예상 금액을 표시합니다.",+ "additional_label": "추가 좌석",+ "additional_hint": "새 총수가 아니라 추가할 수를 입력하세요.",+ "preview_loading": "예상 금액 업데이트 중...",+ "preview_unreadable": "예상 금액을 읽지 못했습니다. 좌석 수를 변경하거나 다시 시도하세요.",+ "preview_failed": "예상 금액을 일시적으로 불러올 수 없습니다. 잠시 후 다시 시도하세요.",+ "in_progress": "다른 좌석 구매가 처리 중입니다. 완료될 때까지 기다리세요. 오래 지속되면 지원팀에 문의하세요.",+ "purchase_unreadable": "구매 응답을 읽지 못했습니다. 이 견적을 다시 시도하면 같은 구매 요청이 재사용됩니다.",+ "purchase_failed": "좌석을 추가하지 못했습니다. 같은 견적으로 다시 시도하거나 만료된 경우 새로고침하세요.",+ "payment_failed": "결제를 완료하지 못했습니다. Stripe에서 결제 수단을 업데이트한 후 새 견적을 요청하세요.",+ "quote_changed": "좌석 수 또는 예상 금액이 변경되었습니다. 갱신된 견적을 확인하세요.",+ "seats_after": "구매 후 좌석",+ "charge_today": "오늘 예상 결제액",+ "next_invoice": "다음 갱신 예상액",+ "tax_notice": "세금, 크레딧 및 최종 청구 세부 정보는 Stripe가 결정합니다. Stripe가 구독 업데이트를 확인한 후 새 좌석을 사용할 수 있습니다.",+ "confirm_other": "좌석 {{count}}개 추가",+ "pending_title": "좌석 구매 처리 중",+ "pending_description_other": "Stripe가 좌석 {{count}}개로 구독 업데이트를 확인하고 있습니다.",+ "delayed_title": "좌석 확인이 예상보다 오래 걸리고 있습니다",+ "delayed_description": "자동 확인이 중지되었습니다. 구매는 계속 완료될 수 있습니다. 다른 구매를 시작하기 전에 나중에 다시 확인하거나 지원팀에 문의하세요.",+ "delayed_description_with_expiry": "자동 확인이 중지되었습니다. {{date}} 이후에도 대기 중이면 좌석을 새로고침하여 요청을 해제하고 새 견적을 받으세요. 다른 구매를 시작하기 전에 지원팀에 문의할 수도 있습니다.",+ "submitted_other": "좌석 {{count}}개 구매를 제출했습니다. Stripe 확인 후 새 용량이 표시됩니다.",+ "error_title": "예상 금액을 업데이트할 수 없습니다"+ },"confirm": {"title": "Stripe Checkout으로 이동할까요?","description": "결제 주기: {{interval}}. 현재 사용자 멤버: {{count}}. Stripe가 좌석을 다시 계산하고 결제 전에 최종 금액을 표시합니다."diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 1f4e964f43..7af3cba6b3 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -96,6 +96,7 @@"retry_autopilots": "重试加载自动化用量","upgrade": "升级到 Pro","manage": "管理账单",+ "add_seats": "添加席位","refresh_seats": "刷新席位","cancel": "取消","continue_to_stripe": "前往 Stripe"@@ -201,11 +202,15 @@},"seats": {"title": "席位",- "description": "每位当前成员都会计为一个 Pro 席位,智能体和待接受的邀请不计。",- "human_members": "当前成员",- "human_members_description": "成员变化后刷新,通知 Cloud Billing 对账 Stripe quantity。",- "billed": "计费席位",- "billed_description": "Stripe 账单当前保存的席位数量。",+ "description": "已购席位用于当前成员和待接受邀请,智能体不占席位。",+ "human_members": "已用席位",+ "human_members_description": "已确认占用已购容量的工作区成员。成员变化后可刷新对账。",+ "billed": "已购席位",+ "billed_description": "当前通过 Stripe 购买的席位数量。",+ "pending_invitations": "待接受邀请",+ "pending_invitations_description": "有效邀请在接受或过期前会预留已购席位。",+ "available": "可用席位",+ "available_description": "未被成员使用、也未被邀请预留的已购席位。","pending": "待生效席位","pending_description": "Cloud Billing 报告的下一周期较低席位数量。","seat_count_other": "{{count}} 个席位",@@ -215,10 +220,36 @@"unavailable": "不可用","summary_loading": "正在加载订阅席位详情","summary_unavailable_title": "部分席位详情不可用",- "summary_unavailable_description": "当前套餐仍会显示,但暂时无法加载计费席位和待生效席位。",+ "summary_unavailable_description": "当前套餐仍会显示,但暂时无法加载已购席位和待生效席位。","updated": "席位已刷新","reconciled": "当前成员:{{actual}} · 计费席位:{{billed}}"},+ "seat_purchase": {+ "title": "添加席位",+ "description": "输入要增加的席位数,确认前会显示最新的 Stripe 估算金额。",+ "additional_label": "增加席位数",+ "additional_hint": "请输入增加数量,而不是新的席位总数。",+ "preview_loading": "正在更新估算金额...",+ "preview_unreadable": "无法读取估算结果。请修改席位数或重试。",+ "preview_failed": "暂时无法获取估算金额,请稍后重试。",+ "in_progress": "另一笔席位购买正在处理中。请等待其完成;若长时间未完成,请联系支持人员。",+ "purchase_unreadable": "无法读取购买响应。请重试当前报价;系统会复用同一购买请求。",+ "purchase_failed": "无法添加席位。可使用同一报价重试;报价过期时请刷新。",+ "payment_failed": "付款未能完成。请在 Stripe 更新付款方式,然后重新获取报价。",+ "quote_changed": "席位数或估算金额已变化,请查看刷新后的报价再确认。",+ "seats_after": "购买后席位",+ "charge_today": "预计今日费用",+ "next_invoice": "预计下次续费",+ "tax_notice": "税费、抵扣和最终账单明细由 Stripe 确定。Stripe 确认订阅更新后,新席位才可用。",+ "confirm_other": "添加 {{count}} 个席位",+ "pending_title": "席位购买处理中",+ "pending_description_other": "Stripe 正在确认订阅更新至 {{count}} 个席位。",+ "delayed_title": "席位确认时间超出预期",+ "delayed_description": "自动检查已停止,购买仍可能完成。开始另一笔购买前,请稍后再查看或联系支持人员。",+ "delayed_description_with_expiry": "自动检查已停止。若到 {{date}} 仍在等待,请刷新席位以释放本次请求并重新获取报价;开始另一笔购买前也可联系支持人员。",+ "submitted_other": "购买 {{count}} 个席位的请求已提交。Stripe 确认后会显示新容量。",+ "error_title": "无法更新估算金额"+ },"confirm": {"title": "前往 Stripe Checkout?","description": "付款周期:{{interval}}。当前成员:{{count}}。Stripe 会重新统计席位,并在付款前显示最终金额。"diff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.tsindex c1dc9a18d8..37ddd35e82 100644--- a/packages/views/settings/components/billing-state.test.ts+++ b/packages/views/settings/components/billing-state.test.ts@@ -123,6 +123,10 @@ describe("billing subscription state", () => {actualSeats: 3,billedSeats: null,pendingSeatQuantity: null,+ usedSeats: 3,+ reservedSeats: 0,+ purchaseVersion: null,+ activeSeatPurchase: null,cancelAtPeriodEnd: false,graceUntil: null,hasStripeCustomer: true,diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex 6a47cb8a87..eeda4822e1 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({checkout: vi.fn(),portal: vi.fn(),reconcile: vi.fn(),+ previewSeats: vi.fn(),+ purchaseSeats: vi.fn(),refetch: vi.fn(),refetchSummary: vi.fn(),refetchUsage: vi.fn(),@@ -39,6 +41,7 @@ const mocks = vi.hoisted(() => ({summaryFetching: false,summaryError: false,summaryMalformed: false,+ purchasePending: false,usagePending: false,usageFetching: false,usageError: false,@@ -61,6 +64,15 @@ const mocks = vi.hoisted(() => ({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;+ } | null,cancelAtPeriodEnd: false,graceUntil: null as string | null,hasStripeCustomer: false,@@ -103,6 +115,14 @@ vi.mock("@multica/core/billing", () => ({mutateAsync: mocks.reconcile,isPending: false,}),+ usePreviewWorkspaceSeatPurchase: () => ({+ mutateAsync: mocks.previewSeats,+ isPending: false,+ }),+ usePurchaseWorkspaceSeats: () => ({+ mutateAsync: mocks.purchaseSeats,+ isPending: mocks.purchasePending,+ }),}));vi.mock("@multica/core/autopilots", () => ({@@ -169,6 +189,7 @@ describe("BillingTab", () => {mocks.summaryFetching = false;mocks.summaryError = false;mocks.summaryMalformed = false;+ mocks.purchasePending = false;mocks.usagePending = false;mocks.usageFetching = false;mocks.usageError = false;@@ -190,6 +211,10 @@ describe("BillingTab", () => {actualSeats: 3,billedSeats: null,pendingSeatQuantity: null,+ usedSeats: 3,+ reservedSeats: 0,+ purchaseVersion: null,+ activeSeatPurchase: null,cancelAtPeriodEnd: false,graceUntil: null,hasStripeCustomer: false,@@ -260,6 +285,26 @@ describe("BillingTab", () => {actualSeats: 3,action: "none",});+ mocks.previewSeats.mockResolvedValue({+ currentSeats: 5,+ additionalSeats: 1,+ resultingSeats: 6,+ purchaseVersion: 9,+ currency: "usd",+ prorationAmount: 250,+ nextInvoiceAmount: 6000,+ quotedAt: "2030-01-01T00:00:00Z",+ });+ mocks.purchaseSeats.mockResolvedValue({+ requestId: "seat-request-1",+ currentSeats: 5,+ additionalSeats: 1,+ resultingSeats: 6,+ currency: "usd",+ prorationAmount: 250,+ nextInvoiceAmount: 6000,+ status: "submitted",+ });configStore.getState().setFeatureFlags({[BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG]: true,});@@ -582,7 +627,7 @@ describe("BillingTab", () => {).toBeInTheDocument();expect(screen.queryByText("Pro is active")).not.toBeInTheDocument();expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();- expect(screen.getByText("Unavailable")).toBeInTheDocument();+ expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0);expect(screen.getByText("5 / 7")).toBeInTheDocument();expect(mocks.useQuery).toHaveBeenCalledWith(expect.objectContaining({ refetchInterval: 2_000 }),@@ -627,7 +672,8 @@ describe("BillingTab", () => {renderWithI18n(<BillingTab />);expect(screen.getByText("Read-only billing access")).toBeInTheDocument();- expect(screen.getAllByText("3 members")).toHaveLength(2);+ expect(screen.getAllByText("3 members")).toHaveLength(1);+ expect(screen.getByText("3 seats")).toBeInTheDocument();expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();expect(screen.queryByRole("button", { name: "Upgrade to Pro" }),@@ -655,8 +701,11 @@ describe("BillingTab", () => {Object.assign(mocks.summary, {billingInterval: "month",actualSeats: 4,+ usedSeats: 3,billedSeats: 5,pendingSeatQuantity: 4,+ reservedSeats: 1,+ purchaseVersion: 9,hasStripeCustomer: true,});@@ -664,8 +713,304 @@ describe("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 from Feb 1, 2030/)).toBeInTheDocument();- expect(screen.getAllByText("4 members")).toHaveLength(2);+ expect(screen.getAllByText("4 members")).toHaveLength(1);+ });++ it("quotes and confirms an additive seat purchase", async () => {+ const user = userEvent.setup();+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ });+ Object.assign(mocks.summary, {+ actualSeats: 4,+ usedSeats: 4,+ billedSeats: 5,+ reservedSeats: 0,+ purchaseVersion: 9,+ hasStripeCustomer: true,+ });+ mocks.previewSeats.mockImplementation(+ ({ additionalSeats }: { additionalSeats: number }) =>+ Promise.resolve({+ currentSeats: 5,+ additionalSeats,+ resultingSeats: 5 + additionalSeats,+ purchaseVersion: 9,+ currency: "usd",+ prorationAmount: 250 * additionalSeats,+ nextInvoiceAmount: 1000 * (5 + additionalSeats),+ quotedAt: "2030-01-01T00:00:00Z",+ }),+ );+ mocks.purchaseSeats.mockResolvedValue({+ requestId: "seat-request-2",+ currentSeats: 5,+ additionalSeats: 2,+ resultingSeats: 7,+ currency: "usd",+ prorationAmount: 500,+ nextInvoiceAmount: 7000,+ status: "submitted",+ });++ renderWithI18n(<BillingTab />);+ await user.click(screen.getByRole("button", { name: "Add seats" }));++ await waitFor(() =>+ expect(mocks.previewSeats).toHaveBeenCalledWith({ additionalSeats: 1 }),+ );+ expect(screen.getByText("Estimated charge today")).toBeInTheDocument();+ expect(screen.getByText("$2.50")).toBeInTheDocument();+ expect(screen.getByText("$60.00")).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Add 1 seat" }),+ ).toBeInTheDocument();++ const input = screen.getByRole("spinbutton", { name: "Additional seats" });+ await user.clear(input);+ await user.type(input, "2");+ await waitFor(() =>+ expect(mocks.previewSeats).toHaveBeenLastCalledWith({+ additionalSeats: 2,+ }),+ );+ await waitFor(() => expect(screen.getByText("$5.00")).toBeInTheDocument());++ await user.click(screen.getByRole("button", { name: "Add 2 seats" }));+ expect(mocks.purchaseSeats).toHaveBeenCalledWith(+ expect.objectContaining({+ additionalSeats: 2,+ expectedCurrentSeats: 5,+ expectedPurchaseVersion: 9,+ acceptedProrationAmount: 500,+ currency: "usd",+ idempotencyKey: expect.stringContaining(+ "workspace-seat-purchase-workspace-1-",+ ),+ }),+ );+ await waitFor(() => expect(mocks.refetchSummary).toHaveBeenCalled());+ });++ it.each([+ [+ "seat_quote_changed",+ "The seat count or estimate changed. Review the refreshed quote before confirming again.",+ ],+ [+ "seat_purchase_in_progress",+ "Another seat purchase is being processed. Wait for it to finish; contact support if it remains here.",+ ],+ ])("maps purchase conflict %s to actionable copy", async (code, copy) => {+ const user = userEvent.setup();+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ });+ Object.assign(mocks.summary, {+ actualSeats: 4,+ usedSeats: 4,+ billedSeats: 5,+ purchaseVersion: 9,+ hasStripeCustomer: true,+ });+ mocks.purchaseSeats.mockRejectedValue(+ new ApiError("conflict", 409, "Conflict", { code }),+ );++ renderWithI18n(<BillingTab />);+ await user.click(screen.getByRole("button", { name: "Add seats" }));+ await screen.findByRole("button", { name: "Add 1 seat" });+ await user.click(screen.getByRole("button", { name: "Add 1 seat" }));++ expect(await screen.findByText(copy)).toBeInTheDocument();+ expect(mocks.refetchSummary).toHaveBeenCalled();+ if (code === "seat_quote_changed") {+ await waitFor(() => expect(mocks.previewSeats).toHaveBeenCalledTimes(2));+ } else {+ expect(mocks.previewSeats).toHaveBeenCalledTimes(1);+ }+ });++ it("keeps the seat dialog open while purchase submission is pending", async () => {+ const user = userEvent.setup();+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ });+ Object.assign(mocks.summary, {+ actualSeats: 4,+ usedSeats: 4,+ billedSeats: 5,+ purchaseVersion: 9,+ hasStripeCustomer: true,+ });++ const { rerender } = renderWithI18n(<BillingTab />);+ await user.click(screen.getByRole("button", { name: "Add seats" }));+ await screen.findByRole("button", { name: "Add 1 seat" });++ mocks.purchasePending = true;+ rerender(<BillingTab />);+ await user.keyboard("{Escape}");+ expect(screen.getByRole("dialog", { name: "Add seats" })).toBeInTheDocument();++ mocks.purchasePending = false;+ rerender(<BillingTab />);+ await user.keyboard("{Escape}");+ await waitFor(() =>+ expect(screen.queryByRole("dialog", { name: "Add seats" })).not.toBeInTheDocument(),+ );+ });++ it("reuses an unreadable purchase intent after closing and reopening", async () => {+ const user = userEvent.setup();+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ });+ Object.assign(mocks.summary, {+ actualSeats: 4,+ usedSeats: 4,+ billedSeats: 5,+ purchaseVersion: 9,+ hasStripeCustomer: true,+ });+ mocks.purchaseSeats.mockResolvedValue(null);++ renderWithI18n(<BillingTab />);+ await user.click(screen.getByRole("button", { name: "Add seats" }));+ await screen.findByRole("button", { name: "Add 1 seat" });+ await user.click(screen.getByRole("button", { name: "Add 1 seat" }));+ expect(+ await screen.findByText(+ "The purchase response could not be read. Retry this quote; the same purchase request will be reused.",+ ),+ ).toBeInTheDocument();+ const firstKey = mocks.purchaseSeats.mock.calls[0]?.[0].idempotencyKey;++ await user.click(screen.getByRole("button", { name: "Cancel" }));+ await user.click(screen.getByRole("button", { name: "Add seats" }));+ await user.click(+ await screen.findByRole("button", { name: "Add 1 seat" }),+ );++ expect(mocks.purchaseSeats).toHaveBeenCalledTimes(2);+ expect(mocks.purchaseSeats.mock.calls[1]?.[0].idempotencyKey).toBe(firstKey);+ expect(mocks.previewSeats).toHaveBeenCalledTimes(1);+ });++ it("shows payment recovery copy and releases the local intent on 402", async () => {+ const user = userEvent.setup();+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ });+ Object.assign(mocks.summary, {+ actualSeats: 4,+ usedSeats: 4,+ billedSeats: 5,+ purchaseVersion: 9,+ hasStripeCustomer: true,+ });+ mocks.purchaseSeats.mockRejectedValue(+ new ApiError("payment failed", 402, "Payment Required", {+ code: "seat_purchase_payment_failed",+ }),+ );++ renderWithI18n(<BillingTab />);+ await user.click(screen.getByRole("button", { name: "Add seats" }));+ await user.click(+ await screen.findByRole("button", { name: "Add 1 seat" }),+ );++ expect(+ await screen.findByText(+ "Payment could not be completed. Update the payment method in Stripe, then request a new quote.",+ ),+ ).toBeInTheDocument();+ });++ it("stops seat purchase polling after two minutes", () => {+ vi.useFakeTimers();+ Object.assign(mocks.summary, {+ activeSeatPurchase: {+ requestId: "seat-request-pending",+ targetSeats: 7,+ status: "pending",+ expiresAt: "2030-01-01T00:15:00Z",+ },+ });+ try {+ renderWithI18n(<BillingTab />);+ expect(screen.getByText("Seat purchase processing")).toBeInTheDocument();++ act(() => vi.advanceTimersByTime(2 * 60_000));++ expect(+ screen.getByText("Seat confirmation is taking longer than expected"),+ ).toBeInTheDocument();+ const formattedExpiry = new Intl.DateTimeFormat("en", {+ dateStyle: "medium",+ timeStyle: "short",+ }).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.`,+ ),+ ).toBeInTheDocument();+ const summaryOptions = mocks.useQuery.mock.calls+ .map(([options]) => options)+ .filter(+ (options) =>+ options.queryKey?.[options.queryKey.length - 1] === "summary",+ )+ .at(-1);+ expect(+ summaryOptions.refetchInterval({ state: { data: mocks.summary } }),+ ).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it("does not promise an unlock time for a submitted seat purchase", () => {+ vi.useFakeTimers();+ Object.assign(mocks.summary, {+ activeSeatPurchase: {+ requestId: "seat-request-submitted",+ targetSeats: 7,+ status: "submitted",+ expiresAt: null,+ },+ });+ try {+ renderWithI18n(<BillingTab />);+ act(() => vi.advanceTimersByTime(2 * 60_000));++ expect(+ screen.getByText(+ "Automatic checking has stopped. The purchase may still complete; check again later or contact support before starting another purchase.",+ ),+ ).toBeInTheDocument();+ } finally {+ vi.useRealTimers();+ }});it("uses completed and reserved runs for the quota decision", () => {@@ -718,7 +1063,7 @@ describe("BillingTab", () => {expect(screen.getByText("Some seat details are unavailable"),).toBeInTheDocument();- expect(screen.getAllByText("Unavailable")).toHaveLength(2);+ expect(screen.getAllByText("Unavailable")).toHaveLength(4);},);@@ -779,7 +1124,7 @@ describe("BillingTab", () => {renderWithI18n(<BillingTab />);expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();- expect(screen.getByText("Unavailable")).toBeInTheDocument();+ expect(screen.getAllByText("Unavailable").length).toBeGreaterThan(0);expect(screen.getByText("Open the Billing Portal to update your payment method. The plan badge above shows the access currently available.",diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex e22db95596..a0da05a4b3 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -8,14 +8,17 @@ import {CreditCard,ExternalLink,Loader2,+ Plus,RefreshCw,ShieldCheck,} from "lucide-react";-import { ApiError } from "@multica/core/api";+import { ApiError, errorCode } from "@multica/core/api";import { autopilotQuotaUsageOptions } from "@multica/core/autopilots";import {useCreateWorkspaceSubscriptionCheckout,useCreateWorkspaceSubscriptionPortal,+ usePreviewWorkspaceSeatPurchase,+ usePurchaseWorkspaceSeats,useReconcileWorkspaceSubscriptionSeats,workspaceSubscriptionEntitlementsOptions,workspaceSubscriptionPricesOptions,@@ -25,7 +28,11 @@ import { useFeatureEnabled } from "@multica/core/config";import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";import { useCurrentMember } from "@multica/core/permissions";import { useCurrentWorkspace } from "@multica/core/paths";-import type { WorkspaceSubscriptionInterval } from "@multica/core/types";+import type {+ PurchaseWorkspaceSeatsRequest,+ WorkspaceSeatPurchasePreview,+ WorkspaceSubscriptionInterval,+} from "@multica/core/types";import {Alert,AlertDescription,@@ -43,6 +50,15 @@ import {} from "@multica/ui/components/ui/alert-dialog";import { Badge } from "@multica/ui/components/ui/badge";import { Button } from "@multica/ui/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import { Input } from "@multica/ui/components/ui/input";import {Progress,ProgressLabel,@@ -65,6 +81,8 @@ import {} from "./billing-state";const CHECKOUT_SYNC_TIMEOUT_MS = 30_000;+const SEAT_PURCHASE_POLL_TIMEOUT_MS = 2 * 60_000;+const SEAT_PURCHASE_PREVIEW_DEBOUNCE_MS = 800;const STRIPE_ZERO_DECIMAL_CURRENCIES = new Set(["BIF",@@ -250,6 +268,16 @@ function BillingTabContent() {const [interval, setInterval] =useState<WorkspaceSubscriptionInterval>("month");const [checkoutConfirmOpen, setCheckoutConfirmOpen] = useState(false);+ const [seatPurchaseOpen, setSeatPurchaseOpen] = useState(false);+ const [additionalSeatsInput, setAdditionalSeatsInput] = useState("1");+ const [seatPreview, setSeatPreview] =+ useState<WorkspaceSeatPurchasePreview | null>(null);+ const [seatPreviewRevision, setSeatPreviewRevision] = useState(0);+ const [seatPurchaseError, setSeatPurchaseError] = useState<string | null>(+ null,+ );+ const [seatPurchasePollingTimedOut, setSeatPurchasePollingTimedOut] =+ useState(false);const [actionError, setActionError] = useState<string | null>(null);const [portalUnavailable, setPortalUnavailable] = useState(false);const [reconcileMessage, setReconcileMessage] = useState<string | null>(null);@@ -263,11 +291,25 @@ function BillingTabContent() {key: string;} | null>(null);const portalIntentKeyRef = useRef<string | null>(null);+ const seatPurchaseIntentRef = useRef<{+ wsId: string;+ key: string;+ preview: WorkspaceSeatPurchasePreview;+ request: PurchaseWorkspaceSeatsRequest;+ } | null>(null);+ const seatPreviewInputRef = useRef("");const consumedCallbackKeyRef = useRef<string | null>(null);useEffect(() => {checkoutIntentRef.current = null;portalIntentKeyRef.current = null;+ seatPurchaseIntentRef.current = null;+ seatPreviewInputRef.current = "";+ setSeatPurchaseOpen(false);+ setSeatPreview(null);+ setSeatPreviewRevision(0);+ setSeatPurchaseError(null);+ setSeatPurchasePollingTimedOut(false);setPortalUnavailable(false);setActionError(null);setReconcileMessage(null);@@ -323,8 +365,31 @@ function BillingTabContent() {entitlementQuery.dataUpdatedAt >= returnObservedAt;const summaryQuery = useQuery({...workspaceSubscriptionSummaryOptions(wsId),- refetchInterval: isSyncingCheckout ? 2_000 : false,+ // Checkout activation and seat additions both finish asynchronously in a+ // Stripe webhook. Seat polling is bounded so a lost webhook cannot keep a+ // browser polling forever.+ refetchInterval: (query) =>+ isSyncingCheckout ||+ (query.state.data?.activeSeatPurchase &&+ !seatPurchasePollingTimedOut)+ ? 2_000+ : false,});+ const activeSeatPurchaseRequestId =+ summaryQuery.data?.activeSeatPurchase?.requestId ?? null;++ useEffect(() => {+ if (!activeSeatPurchaseRequestId) {+ setSeatPurchasePollingTimedOut(false);+ return;+ }+ setSeatPurchasePollingTimedOut(false);+ const timeout = window.setTimeout(+ () => setSeatPurchasePollingTimedOut(true),+ SEAT_PURCHASE_POLL_TIMEOUT_MS,+ );+ return () => window.clearTimeout(timeout);+ }, [activeSeatPurchaseRequestId]);const summaryUnavailable =summaryQuery.isError ||(!summaryQuery.isPending && summaryQuery.data == null);@@ -342,8 +407,84 @@ 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;const refetchSummary = summaryQuery.refetch;+ const previewSeatPurchase = previewSeatPurchaseMutation.mutateAsync;++ useEffect(() => {+ 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 requestKey = `${wsId}:${value}:${currentSeats ?? ""}:${purchaseVersion ?? ""}:${seatPreviewRevision}`;+ seatPreviewInputRef.current = requestKey;+ const intent = seatPurchaseIntentRef.current;+ if (+ intent?.wsId === wsId &&+ intent.request.additionalSeats === additionalSeats &&+ intent.request.expectedCurrentSeats === currentSeats &&+ intent.request.expectedPurchaseVersion === purchaseVersion+ ) {+ setSeatPreview(intent.preview);+ setSeatPurchaseError(null);+ return;+ }+ seatPurchaseIntentRef.current = null;+ setSeatPreview(null);+ if (+ !Number.isSafeInteger(additionalSeats) ||+ additionalSeats < 1 ||+ currentSeats === null ||+ purchaseVersion === null ||+ currentSeats + additionalSeats > 10_000+ ) {+ return;+ }++ const timeout = window.setTimeout(() => {+ void previewSeatPurchase({ additionalSeats })+ .then((preview) => {+ if (seatPreviewInputRef.current !== requestKey) return;+ if (+ !preview ||+ preview.additionalSeats !== additionalSeats ||+ preview.currentSeats !== currentSeats ||+ preview.purchaseVersion !== purchaseVersion ||+ preview.resultingSeats !== currentSeats + additionalSeats+ ) {+ setSeatPurchaseError(+ t(($) => $.workspace.seat_purchase.preview_unreadable),+ );+ return;+ }+ setSeatPreview(preview);+ setSeatPurchaseError(null);+ })+ .catch((error: unknown) => {+ if (seatPreviewInputRef.current !== requestKey) return;+ setSeatPurchaseError(+ error instanceof ApiError &&+ error.status === 409 &&+ errorCode(error) === "seat_purchase_in_progress"+ ? t(($) => $.workspace.seat_purchase.in_progress)+ : t(($) => $.workspace.seat_purchase.preview_failed),+ );+ });+ }, SEAT_PURCHASE_PREVIEW_DEBOUNCE_MS);+ return () => window.clearTimeout(timeout);+ }, [+ additionalSeatsInput,+ previewSeatPurchase,+ seatPurchaseOpen,+ seatPreviewRevision,+ summaryQuery.data?.billedSeats,+ summaryQuery.data?.purchaseVersion,+ t,+ wsId,+ ]);useEffect(() => {if (isSyncingCheckout && isCheckoutProConfirmed) {@@ -504,6 +645,115 @@ function BillingTabContent() {}};+ const handleSeatPurchase = async () => {+ const confirmedPreview = seatPreview;+ if (!confirmedPreview) return;+ setSeatPurchaseError(null);+ const request: PurchaseWorkspaceSeatsRequest = {+ additionalSeats: confirmedPreview.additionalSeats,+ expectedCurrentSeats: confirmedPreview.currentSeats,+ expectedPurchaseVersion: confirmedPreview.purchaseVersion,+ acceptedProrationAmount: confirmedPreview.prorationAmount,+ currency: confirmedPreview.currency,+ idempotencyKey: "",+ };+ const existing = seatPurchaseIntentRef.current;+ const key =+ existing?.wsId === wsId &&+ existing.request.additionalSeats === request.additionalSeats &&+ existing.request.expectedCurrentSeats === request.expectedCurrentSeats &&+ existing.request.expectedPurchaseVersion ===+ request.expectedPurchaseVersion &&+ existing.request.acceptedProrationAmount ===+ request.acceptedProrationAmount &&+ existing.request.currency === request.currency+ ? existing.key+ : createIdempotencyKey("workspace-seat-purchase", wsId).slice(0, 200);+ request.idempotencyKey = key;+ seatPurchaseIntentRef.current = {+ wsId,+ key,+ preview: confirmedPreview,+ request,+ };+ try {+ const response = await purchaseSeatsMutation.mutateAsync(request);+ if (+ !response ||+ response.currentSeats !== confirmedPreview.currentSeats ||+ response.additionalSeats !== confirmedPreview.additionalSeats ||+ response.resultingSeats !== confirmedPreview.resultingSeats ||+ response.currency !== confirmedPreview.currency+ ) {+ setSeatPurchaseError(+ t(($) => $.workspace.seat_purchase.purchase_unreadable),+ );+ return;+ }+ seatPurchaseIntentRef.current = null;+ seatPreviewInputRef.current = "";+ setSeatPurchaseOpen(false);+ setSeatPreview(null);+ setReconcileMessage(+ t(($) => $.workspace.seat_purchase.submitted, {+ count: response.resultingSeats,+ }),+ );+ await Promise.all([entitlementQuery.refetch(), summaryQuery.refetch()]);+ } catch (error) {+ if (error instanceof ApiError && error.status === 409) {+ const purchaseErrorCode = errorCode(error);+ seatPurchaseIntentRef.current = null;+ setSeatPreview(null);+ if (purchaseErrorCode === "seat_purchase_in_progress") {+ setSeatPurchaseError(+ t(($) => $.workspace.seat_purchase.in_progress),+ );+ await summaryQuery.refetch();+ return;+ }+ setSeatPurchaseError(t(($) => $.workspace.seat_purchase.quote_changed));+ await summaryQuery.refetch();+ setSeatPreviewRevision((revision) => revision + 1);+ return;+ }+ if (error instanceof ApiError && error.status === 402) {+ seatPurchaseIntentRef.current = null;+ setSeatPreview(null);+ setSeatPurchaseError(+ t(($) => $.workspace.seat_purchase.payment_failed),+ );+ return;+ }+ if (error instanceof ApiError && error.status === 403) {+ seatPurchaseIntentRef.current = null;+ reportActionError(+ error,+ t(($) => $.workspace.seat_purchase.purchase_failed),+ );+ return;+ }+ setSeatPurchaseError(+ t(($) => $.workspace.seat_purchase.purchase_failed),+ );+ }+ };++ const handleSeatPurchaseOpenChange = (open: boolean) => {+ if (!open && purchaseSeatsMutation.isPending) return;+ setSeatPurchaseOpen(open);+ if (!open) return;+ setSeatPurchaseError(null);+ const intent = seatPurchaseIntentRef.current;+ if (intent?.wsId === wsId) {+ setAdditionalSeatsInput(String(intent.request.additionalSeats));+ setSeatPreview(intent.preview);+ return;+ }+ setAdditionalSeatsInput("1");+ setSeatPreview(null);+ };+if (entitlementQuery.isPending) {return (<SettingsTab@@ -568,8 +818,29 @@ function BillingTabContent() {(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 availableSeats =+ billedSeats === null || billedSeats === undefined+ ? null+ : Math.max(0, billedSeats - usedSeats - reservedSeats);+ const activeSeatPurchase = summaryQuery.data?.activeSeatPurchase ?? null;+ const activeSeatPurchaseExpiry = formatDateTime(+ activeSeatPurchase?.expiresAt ?? null,+ locale,+ );+ const canAddSeats =+ canManage &&+ hasManagedSubscription &&+ (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,quotaUsageQuery.data,@@ -584,7 +855,8 @@ function BillingTabContent() {const isMutating =checkoutMutation.isPending ||portalMutation.isPending ||- reconcileMutation.isPending;+ reconcileMutation.isPending ||+ purchaseSeatsMutation.isPending;const selectedPrice = pricesQuery.data?.[interval] ?? null;const formattedUnitPrice = selectedPrice? formatStripeMinorAmount(@@ -606,6 +878,20 @@ function BillingTabContent() {const hasDisplayableEstimatedTotal =hasDisplayableUnitPrice && formattedEstimatedTotal !== null;const canRetryPrice = !pricesQuery.isLoading && selectedPrice === null;+ const formattedSeatProration = seatPreview+ ? formatStripeMinorAmount(+ seatPreview.prorationAmount,+ seatPreview.currency,+ locale,+ )+ : null;+ const formattedNextSeatInvoice = seatPreview+ ? formatStripeMinorAmount(+ seatPreview.nextInvoiceAmount,+ seatPreview.currency,+ locale,+ )+ : null;return (<SettingsTab@@ -1117,6 +1403,34 @@ function BillingTabContent() {<AlertDescription>{reconcileMessage}</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><SettingsRowlabel={t(($) => $.workspace.seats.human_members)}@@ -1124,8 +1438,8 @@ function BillingTabContent() {><div className="flex flex-col gap-2 sm:items-end"><span className="tabular-nums">- {t(($) => $.workspace.current.member_count, {- count: actualSeats,+ {t(($) => $.workspace.seats.seat_count, {+ count: usedSeats,})}</span>{canManage && hasManagedSubscription ? (@@ -1162,10 +1476,67 @@ function BillingTabContent() {<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: billedSeats,+ count: availableSeats,})}</span>)}@@ -1206,6 +1577,141 @@ function BillingTabContent() {</SettingsCard></SettingsSection>+ <Dialog+ open={seatPurchaseOpen}+ onOpenChange={handleSeatPurchaseOpenChange}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>+ {t(($) => $.workspace.seat_purchase.title)}+ </DialogTitle>+ <DialogDescription>+ {t(($) => $.workspace.seat_purchase.description)}+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <div className="space-y-2">+ <label+ className="text-body font-medium"+ htmlFor="workspace-additional-seats"+ >+ {t(($) => $.workspace.seat_purchase.additional_label)}+ </label>+ <Input+ id="workspace-additional-seats"+ className="h-11"+ type="number"+ inputMode="numeric"+ min={1}+ max={+ billedSeats === null || billedSeats === undefined+ ? 10_000+ : 10_000 - billedSeats+ }+ step={1}+ value={additionalSeatsInput}+ disabled={purchaseSeatsMutation.isPending}+ onChange={(event) => {+ setAdditionalSeatsInput(event.currentTarget.value);+ setSeatPurchaseError(null);+ }}+ />+ <p className="text-caption text-muted-foreground">+ {t(($) => $.workspace.seat_purchase.additional_hint)}+ </p>+ </div>+ {previewSeatPurchaseMutation.isPending ? (+ <div+ className="flex items-center gap-2 text-body text-muted-foreground"+ role="status"+ >+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ {t(($) => $.workspace.seat_purchase.preview_loading)}+ </div>+ ) : null}+ {seatPurchaseError ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.seat_purchase.error_title)}+ </AlertTitle>+ <AlertDescription>{seatPurchaseError}</AlertDescription>+ </Alert>+ ) : null}+ {seatPreview &&+ formattedSeatProration !== null &&+ formattedNextSeatInvoice !== null ? (+ <div className="space-y-3 rounded-lg border border-surface-border p-4">+ <div className="flex items-center justify-between gap-4 text-body">+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seat_purchase.seats_after)}+ </span>+ <span className="font-medium tabular-nums">+ {t(($) => $.workspace.seats.seat_count, {+ count: seatPreview.resultingSeats,+ })}+ </span>+ </div>+ <div className="flex items-center justify-between gap-4 text-body">+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seat_purchase.charge_today)}+ </span>+ <span className="font-medium tabular-nums">+ {formattedSeatProration}+ </span>+ </div>+ <div className="flex items-center justify-between gap-4 text-body">+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seat_purchase.next_invoice)}+ </span>+ <span className="font-medium tabular-nums">+ {formattedNextSeatInvoice}+ </span>+ </div>+ <p className="text-caption leading-5 text-muted-foreground">+ {t(($) => $.workspace.seat_purchase.tax_notice)}+ </p>+ </div>+ ) : null}+ </div>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ className="h-11"+ disabled={purchaseSeatsMutation.isPending}+ onClick={() => handleSeatPurchaseOpenChange(false)}+ >+ {t(($) => $.workspace.actions.cancel)}+ </Button>+ <Button+ type="button"+ className="h-11"+ disabled={+ !seatPreview ||+ formattedSeatProration === null ||+ formattedNextSeatInvoice === null ||+ previewSeatPurchaseMutation.isPending ||+ purchaseSeatsMutation.isPending+ }+ onClick={() => void handleSeatPurchase()}+ >+ {purchaseSeatsMutation.isPending ? (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ ) : (+ <Plus />+ )}+ {seatPreview+ ? t(($) => $.workspace.seat_purchase.confirm, {+ count: seatPreview.additionalSeats,+ })+ : t(($) => $.workspace.actions.add_seats)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+<AlertDialogopen={checkoutConfirmOpen}onOpenChange={handleCheckoutConfirmOpenChange}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex b46c2df444..d66beafd5e 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1721,6 +1721,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Group(func(r chi.Router) {r.Use(middleware.RequireWorkspaceRole(queries, "owner", "admin"))r.Post("/checkout-sessions", h.CreateCloudWorkspaceSubscriptionCheckout)+ r.Post("/seats/purchase-preview", h.PreviewCloudWorkspaceSubscriptionSeatPurchase)+ r.Post("/seats/purchases", h.PurchaseCloudWorkspaceSubscriptionSeats)r.Post("/seats/reconcile", h.ReconcileCloudWorkspaceSubscriptionSeats)r.Post("/portal-sessions", h.CreateCloudWorkspaceSubscriptionPortal)})diff --git a/server/internal/handler/cloud_billing.go b/server/internal/handler/cloud_billing.goindex 57ed7cba9d..582291704d 100644--- a/server/internal/handler/cloud_billing.go+++ b/server/internal/handler/cloud_billing.go@@ -48,6 +48,8 @@ const stripeSignatureHeader = "Stripe-Signature"const idempotencyKeyHeader = "Idempotency-Key"const maxCloudSubscriptionIdempotencyKeyLength = 255+const maxCloudSubscriptionSeatPurchaseIdempotencyKeyLength = 200+const maxCloudSubscriptionSeats = 10_000type cloudSubscriptionCheckoutRequest struct {Interval string `json:"interval"`@@ -64,6 +66,19 @@ type cloudSubscriptionCheckoutUpstreamRequest struct {CustomerEmail string `json:"customer_email,omitempty"`}+type cloudSubscriptionSeatPurchasePreviewRequest struct {+ AdditionalSeats int `json:"additional_seats"`+}++type cloudSubscriptionSeatPurchaseRequest struct {+ AdditionalSeats int `json:"additional_seats"`+ ExpectedCurrentSeats int `json:"expected_current_seats"`+ ExpectedPurchaseVersion int64 `json:"expected_purchase_version"`+ AcceptedProrationAmount int64 `json:"accepted_proration_amount"`+ Currency string `json:"currency"`+ IdempotencyKey string `json:"idempotency_key,omitempty"`+}+// requireCloudSubscriptionWorkspace is the handler-level backstop behind the// router's RequireWorkspaceMember / RequireWorkspaceRole middleware. Keeping// the check here makes a future route refactor fail closed instead of exposing@@ -238,6 +253,92 @@ func (h *Handler) ReconcileCloudWorkspaceSubscriptionSeats(w http.ResponseWriterh.proxyCloudSubscription(w, r, http.MethodPost, "/api/v1/subscriptions/"+workspaceID+"/seats/reconcile", userID, nil, nil)}+// PreviewCloudWorkspaceSubscriptionSeatPurchase accepts only an additive seat+// count. Cloud reads the authoritative current quantity and returns Stripe's+// estimated proration plus the next full recurring invoice.+func (h *Handler) PreviewCloudWorkspaceSubscriptionSeatPurchase(w http.ResponseWriter, r *http.Request) {+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")+ if !ok {+ return+ }+ body, ok := readCloudRuntimeJSONBody(w, r)+ if !ok {+ return+ }+ var in cloudSubscriptionSeatPurchasePreviewRequest+ if err := json.Unmarshal(body, &in); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if in.AdditionalSeats < 1 || in.AdditionalSeats > maxCloudSubscriptionSeats {+ writeError(w, http.StatusBadRequest, "additional_seats must be within 1..10000")+ return+ }+ upstreamBody, err := json.Marshal(in)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to build seat purchase preview")+ return+ }+ h.proxyCloudSubscription(w, r, http.MethodPost,+ "/api/v1/subscriptions/"+workspaceID+"/seats/purchase-preview", userID, upstreamBody, nil)+}++// PurchaseCloudWorkspaceSubscriptionSeats forwards a user-confirmed quote.+// The allowlisted body omits any client workspace or absolute target quantity;+// Cloud repeats the quote and owns concurrency, idempotency, and Stripe writes.+func (h *Handler) PurchaseCloudWorkspaceSubscriptionSeats(w http.ResponseWriter, r *http.Request) {+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")+ if !ok {+ return+ }+ body, ok := readCloudRuntimeJSONBody(w, r)+ if !ok {+ return+ }+ var in cloudSubscriptionSeatPurchaseRequest+ if err := json.Unmarshal(body, &in); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ if in.AdditionalSeats < 1 || in.ExpectedCurrentSeats < 1 ||+ in.AdditionalSeats > maxCloudSubscriptionSeats ||+ in.ExpectedCurrentSeats > maxCloudSubscriptionSeats-in.AdditionalSeats ||+ in.ExpectedPurchaseVersion < 1 || in.AcceptedProrationAmount < 0 || !isASCIICurrency(in.Currency) {+ writeError(w, http.StatusBadRequest, "invalid seat purchase confirmation")+ return+ }+ key, ok := requireCloudSubscriptionIdempotencyKey(w, r, in.IdempotencyKey)+ if !ok {+ return+ }+ if len(key) > maxCloudSubscriptionSeatPurchaseIdempotencyKeyLength {+ writeError(w, http.StatusBadRequest, "seat purchase idempotency key must be at most 200 bytes")+ return+ }+ in.Currency = strings.ToLower(in.Currency)+ in.IdempotencyKey = key+ upstreamBody, err := json.Marshal(in)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to build seat purchase request")+ return+ }+ h.proxyCloudSubscription(w, r, http.MethodPost,+ "/api/v1/subscriptions/"+workspaceID+"/seats/purchases", userID, upstreamBody,+ http.Header{idempotencyKeyHeader: []string{key}})+}++func isASCIICurrency(value string) bool {+ if len(value) != 3 {+ return false+ }+ for _, char := range value {+ if (char < 'a' || char > 'z') && (char < 'A' || char > 'Z') {+ return false+ }+ }+ return true+}+func (h *Handler) CreateCloudWorkspaceSubscriptionPortal(w http.ResponseWriter, r *http.Request) {workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")if !ok {diff --git a/server/internal/handler/cloud_billing_test.go b/server/internal/handler/cloud_billing_test.goindex f5aaecbd04..e52992a256 100644--- a/server/internal/handler/cloud_billing_test.go+++ b/server/internal/handler/cloud_billing_test.go@@ -450,6 +450,98 @@ func TestCreateCloudWorkspaceSubscriptionCheckoutAcceptsHeaderIdempotencyKey(t *}}+func TestCloudWorkspaceSeatPurchaseForwardsOnlyAdditiveConfirmation(t *testing.T) {+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)+ proxy := &fakeCloudRuntimeProxy{enabled: true, resp: &cloudruntime.Response{StatusCode: http.StatusAccepted, Body: []byte(`{"status":"submitted"}`)}}+ useCloudRuntimeProxy(t, proxy)+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/seats/purchases", map[string]any{+ "workspace_id": "00000000-0000-0000-0000-000000000001",+ "target_seats": 999,+ "additional_seats": 2,+ "expected_current_seats": 5,+ "expected_purchase_version": 9,+ "accepted_proration_amount": 425,+ "currency": "USD",+ "idempotency_key": "seat-request-1",+ }), "admin")+ w := httptest.NewRecorder()+ testHandler.PurchaseCloudWorkspaceSubscriptionSeats(w, req)++ if w.Code != http.StatusAccepted || proxy.req.Path != "/api/v1/subscriptions/"+testWorkspaceID+"/seats/purchases" {+ t.Fatalf("status=%d path=%s body=%s", w.Code, proxy.req.Path, w.Body.String())+ }+ var body map[string]any+ if err := json.Unmarshal(proxy.req.Body, &body); err != nil {+ t.Fatal(err)+ }+ if _, ok := body["workspace_id"]; ok {+ t.Fatalf("client workspace leaked upstream: %v", body)+ }+ if _, ok := body["target_seats"]; ok {+ t.Fatalf("absolute target leaked upstream: %v", body)+ }+ if body["additional_seats"] != float64(2) || body["currency"] != "usd" || body["idempotency_key"] != "seat-request-1" {+ t.Fatalf("upstream body=%v", body)+ }+ if proxy.req.Headers.Get(idempotencyKeyHeader) != "seat-request-1" {+ t.Fatalf("upstream idempotency=%q", proxy.req.Headers.Get(idempotencyKeyHeader))+ }+}++func TestCloudWorkspaceSeatPurchasePreviewUsesAuthoritativePath(t *testing.T) {+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)+ proxy := &fakeCloudRuntimeProxy{enabled: true, resp: &cloudruntime.Response{StatusCode: http.StatusOK, Body: []byte(`{"resulting_seats":7}`)}}+ useCloudRuntimeProxy(t, proxy)+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/seats/purchase-preview", map[string]any{+ "additional_seats": 2, "workspace_id": "00000000-0000-0000-0000-000000000002", "target_seats": 999,+ }), "owner")+ w := httptest.NewRecorder()+ testHandler.PreviewCloudWorkspaceSubscriptionSeatPurchase(w, req)++ if w.Code != http.StatusOK || proxy.req.Path != "/api/v1/subscriptions/"+testWorkspaceID+"/seats/purchase-preview" {+ t.Fatalf("status=%d path=%s body=%s", w.Code, proxy.req.Path, w.Body.String())+ }+ if string(proxy.req.Body) != `{"additional_seats":2}` {+ t.Fatalf("upstream body=%s", proxy.req.Body)+ }+}++func TestCloudWorkspaceSeatPurchaseRejectsInvalidOrUnauthorizedRequests(t *testing.T) {+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)+ tests := []struct {+ name string+ role string+ body map[string]any+ header string+ }{+ {name: "member", role: "member", body: map[string]any{"additional_seats": 1}},+ {name: "absolute overflow", role: "owner", body: map[string]any{"additional_seats": 2, "expected_current_seats": 9999, "expected_purchase_version": 1, "accepted_proration_amount": 0, "currency": "usd", "idempotency_key": "key"}},+ {name: "bad currency", role: "owner", body: map[string]any{"additional_seats": 1, "expected_current_seats": 5, "expected_purchase_version": 1, "accepted_proration_amount": 0, "currency": "u$d", "idempotency_key": "key"}},+ {name: "long key", role: "owner", body: map[string]any{"additional_seats": 1, "expected_current_seats": 5, "expected_purchase_version": 1, "accepted_proration_amount": 0, "currency": "usd"}, header: strings.Repeat("a", 201)},+ }+ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ proxy := &fakeCloudRuntimeProxy{enabled: true}+ useCloudRuntimeProxy(t, proxy)+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/seats/purchases", tc.body), tc.role)+ if tc.header != "" {+ req.Header.Set(idempotencyKeyHeader, tc.header)+ }+ w := httptest.NewRecorder()+ testHandler.PurchaseCloudWorkspaceSubscriptionSeats(w, req)+ if tc.role == "member" && w.Code != http.StatusForbidden {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if tc.role != "member" && w.Code != http.StatusBadRequest {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if proxy.called {+ t.Fatal("invalid request reached upstream")+ }+ })+ }+}+func TestCloudWorkspaceSubscriptionWritesRequireManagerRole(t *testing.T) {withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)proxy := &fakeCloudRuntimeProxy{enabled: true}