Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5852: add workspace Billing settings UI (#6908)
Multica Evecc8e020f80a7
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 356a2b3edc..f0a3a241ad 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -188,6 +188,10 @@ import type {WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrices,+ CreateWorkspaceSubscriptionCheckoutRequest,+ CreateWorkspaceSubscriptionCheckoutResponse,+ WorkspaceSubscriptionSeatReconcileResult,+ CreateWorkspaceSubscriptionPortalResponse,} from "../types";import type { OnboardingCompletionPath } from "../onboarding/types";import type {@@ -293,6 +297,9 @@ import {WorkspaceSubscriptionEntitlementsSchema,WorkspaceSubscriptionSummarySchema,WorkspaceSubscriptionPricesSchema,+ CreateWorkspaceSubscriptionCheckoutResponseSchema,+ WorkspaceSubscriptionSeatReconcileResultSchema,+ CreateWorkspaceSubscriptionPortalResponseSchema,DingTalkInstallationSchema,DingTalkGroupRouteSchema,ListDingTalkGroupRoutesResponseSchema,@@ -1606,6 +1613,66 @@ export class ApiClient {);}+ async createWorkspaceSubscriptionCheckout(+ data: CreateWorkspaceSubscriptionCheckoutRequest,+ ): Promise<CreateWorkspaceSubscriptionCheckoutResponse | null> {+ const res = await this.fetchRaw(+ "/api/cloud-subscriptions/checkout-sessions",+ {+ method: "POST",+ body: JSON.stringify({+ interval: data.interval,+ idempotency_key: data.idempotencyKey,+ ...(data.customerEmail+ ? { customer_email: data.customerEmail }+ : {}),+ }),+ extraHeaders: {+ "Content-Type": "application/json",+ "Idempotency-Key": data.idempotencyKey,+ },+ },+ );+ const raw = (await res.json()) as unknown;+ return parseWithFallback<CreateWorkspaceSubscriptionCheckoutResponse | null>(+ raw,+ CreateWorkspaceSubscriptionCheckoutResponseSchema,+ null,+ { endpoint: "POST /api/cloud-subscriptions/checkout-sessions" },+ );+ }++ async reconcileWorkspaceSubscriptionSeats(): Promise<+ WorkspaceSubscriptionSeatReconcileResult | null+ > {+ const res = await this.fetchRaw("/api/cloud-subscriptions/seats/reconcile", {+ method: "POST",+ });+ const raw = (await res.json()) as unknown;+ return parseWithFallback<WorkspaceSubscriptionSeatReconcileResult | null>(+ raw,+ WorkspaceSubscriptionSeatReconcileResultSchema,+ null,+ { endpoint: "POST /api/cloud-subscriptions/seats/reconcile" },+ );+ }++ async createWorkspaceSubscriptionPortal(+ idempotencyKey: string,+ ): Promise<CreateWorkspaceSubscriptionPortalResponse | null> {+ const res = await this.fetchRaw("/api/cloud-subscriptions/portal-sessions", {+ method: "POST",+ extraHeaders: { "Idempotency-Key": idempotencyKey },+ });+ const raw = (await res.json()) as unknown;+ return parseWithFallback<CreateWorkspaceSubscriptionPortalResponse | null>(+ raw,+ CreateWorkspaceSubscriptionPortalResponseSchema,+ null,+ { endpoint: "POST /api/cloud-subscriptions/portal-sessions" },+ );+ }+async deleteRuntime(runtimeId: string): Promise<void> {await this.fetch(`/api/runtimes/${runtimeId}`, { method: "DELETE" });}diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.tsindex b98a361161..4358804604 100644--- a/packages/core/api/schema.test.ts+++ b/packages/core/api/schema.test.ts@@ -676,6 +676,132 @@ describe("ApiClient schema fallback", () => {url: "",});});++ it("parses workspace entitlements into camelCase without fabricating Free", async () => {+ stubFetchJson({+ workspace_id: "workspace-1",+ plan: "pro",+ status: "active",+ seats: 4,+ issue_window: null,+ autopilot_runs: null,+ current_period_end: "2026-09-13T00:00:00Z",+ snapshot_expires_at: null,+ version: 7,+ });+ const client = new ApiClient("https://api.example.test");++ await expect(+ client.getWorkspaceSubscriptionEntitlements(),+ ).resolves.toEqual({+ workspaceId: "workspace-1",+ plan: "pro",+ status: "active",+ seats: 4,+ issueWindow: null,+ autopilotRuns: null,+ currentPeriodEnd: "2026-09-13T00:00:00Z",+ snapshotExpiresAt: null,+ version: 7,+ });++ stubFetchJson({ plan: "free", seats: "unknown" });+ await expect(client.getWorkspaceSubscriptionEntitlements()).resolves.toBeNull();+ });++ it("accepts an empty workspace entitlement snapshot", async () => {+ stubFetchJson({+ workspace_id: "workspace-1",+ plan: "free",+ status: "inactive",+ seats: 0,+ issue_window: 1000,+ autopilot_runs: 100,+ snapshot_expires_at: null,+ version: 0,+ });+ const client = new ApiClient("https://api.example.test");++ await expect(+ client.getWorkspaceSubscriptionEntitlements(),+ ).resolves.toMatchObject({ seats: 0, plan: "free" });+ });++ it("sends the Checkout idempotency key in the header and body", async () => {+ stubFetchJson(+ {+ request_id: "request-1",+ session_id: "cs_test_1",+ url: "https://checkout.stripe.com/test-session",+ },+ 201,+ );+ const client = new ApiClient("https://api.example.test");++ await expect(+ client.createWorkspaceSubscriptionCheckout({+ interval: "year",+ idempotencyKey: "checkout-intent-1",+ }),+ ).resolves.toEqual({+ requestId: "request-1",+ sessionId: "cs_test_1",+ url: "https://checkout.stripe.com/test-session",+ });++ const fetchMock = vi.mocked(fetch);+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit & {+ headers: Record<string, string>;+ };+ expect(init.headers["Idempotency-Key"]).toBe("checkout-intent-1");+ expect(JSON.parse(String(init.body))).toEqual({+ interval: "year",+ idempotency_key: "checkout-intent-1",+ });+ });++ it("rejects unreadable or non-HTTPS Stripe URLs at the schema boundary", async () => {+ stubFetchJson(+ {+ request_id: "request-1",+ session_id: "cs_test_1",+ url: "javascript:alert(1)",+ },+ 201,+ );+ const client = new ApiClient("https://api.example.test");++ await expect(+ client.createWorkspaceSubscriptionCheckout({+ interval: "month",+ idempotencyKey: "checkout-intent-1",+ }),+ ).resolves.toBeNull();++ stubFetchJson({ url: 123 });+ await expect(+ client.createWorkspaceSubscriptionPortal("portal-intent-1"),+ ).resolves.toBeNull();+ });++ it("parses seat reconciliation into camelCase", async () => {+ stubFetchJson({+ workspace_id: "workspace-1",+ billed_seats: 5,+ actual_seats: 4,+ action: "scheduled_decrease",+ });+ const client = new ApiClient("https://api.example.test");++ await expect(+ client.reconcileWorkspaceSubscriptionSeats(),+ ).resolves.toEqual({+ workspaceId: "workspace-1",+ billedSeats: 5,+ actualSeats: 4,+ action: "scheduled_decrease",+ });+ });});});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 5b94446f0c..826a326c4a 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -25,6 +25,9 @@ import type {WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPrices,+ CreateWorkspaceSubscriptionCheckoutResponse,+ WorkspaceSubscriptionSeatReconcileResult,+ CreateWorkspaceSubscriptionPortalResponse,CronPreviewResponse,DingTalkGroupRoute,DingTalkInstallation,@@ -2178,6 +2181,15 @@ export const EMPTY_CREATE_BILLING_PORTAL_SESSION_RESPONSE: CreateBillingPortalSeconst WorkspaceSubscriptionIntervalSchema = z.enum(["month", "year"]);+// Stripe hosts Checkout and Portal, so those URLs leave the app. `z.string()+// .url()` is not enough on its own — `new URL("javascript:...")` parses — and+// the caller hands this value to location.assign, so the scheme is pinned here.+const StripeHostedURLSchema = z.string().url().refine(+ (value) => value.startsWith("https://"),+ { message: "Stripe hosted URL must use HTTPS" },+);++export const WorkspaceSubscriptionEntitlementsSchema = z.object({workspace_id: z.string(),@@ -2273,6 +2285,49 @@ export const WorkspaceSubscriptionPricesSchema = z}),);+export const CreateWorkspaceSubscriptionCheckoutResponseSchema = z+ .object({+ request_id: z.string(),+ session_id: z.string(),+ url: StripeHostedURLSchema,+ })+ .loose()+ .transform(+ (value): CreateWorkspaceSubscriptionCheckoutResponse => ({+ requestId: value.request_id,+ sessionId: value.session_id,+ url: value.url,+ }),+ );++export const WorkspaceSubscriptionSeatReconcileResultSchema = z+ .object({+ workspace_id: z.string(),+ billed_seats: z.number().int().nonnegative(),+ actual_seats: z.number().int().nonnegative(),+ action: z.string(),+ })+ .loose()+ .transform(+ (value): WorkspaceSubscriptionSeatReconcileResult => ({+ workspaceId: value.workspace_id,+ billedSeats: value.billed_seats,+ actualSeats: value.actual_seats,+ action: value.action,+ }),+ );++export const CreateWorkspaceSubscriptionPortalResponseSchema = z+ .object({+ url: StripeHostedURLSchema,+ })+ .loose()+ .transform(+ (value): CreateWorkspaceSubscriptionPortalResponse => ({+ url: value.url,+ }),+ );+// ---------------------------------------------------------------------------// Runtime model discovery (`POST /api/runtimes/:id/models`,// `GET /api/runtimes/:id/models/:requestId`). Both endpoints return the samediff --git a/packages/core/billing/index.ts b/packages/core/billing/index.tsindex 03d1544ff8..c48edd4189 100644--- a/packages/core/billing/index.ts+++ b/packages/core/billing/index.ts@@ -1,3 +1,4 @@export * from "./queries";export * from "./mutations";export * from "./workspace-subscription-queries";+export * from "./workspace-subscription-mutations";diff --git a/packages/core/billing/workspace-subscription-mutations.ts b/packages/core/billing/workspace-subscription-mutations.tsnew file mode 100644index 0000000000..8353cb15e1--- /dev/null+++ b/packages/core/billing/workspace-subscription-mutations.ts@@ -0,0 +1,42 @@+import { useMutation, useQueryClient } from "@tanstack/react-query";+import { api } from "../api";+import type { CreateWorkspaceSubscriptionCheckoutRequest } from "../types";+import { workspaceSubscriptionKeys } from "./workspace-subscription-queries";++export function useCreateWorkspaceSubscriptionCheckout(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (data: CreateWorkspaceSubscriptionCheckoutRequest) =>+ api.createWorkspaceSubscriptionCheckout(data),+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: workspaceSubscriptionKeys.entitlements(wsId),+ });+ },+ });+}++export function useReconcileWorkspaceSubscriptionSeats(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: () => api.reconcileWorkspaceSubscriptionSeats(),+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: workspaceSubscriptionKeys.entitlements(wsId),+ });+ },+ });+}++export function useCreateWorkspaceSubscriptionPortal(wsId: string) {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: (idempotencyKey: string) =>+ api.createWorkspaceSubscriptionPortal(idempotencyKey),+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: workspaceSubscriptionKeys.entitlements(wsId),+ });+ },+ });+}diff --git a/packages/core/feature-flags/index.ts b/packages/core/feature-flags/index.tsindex 338037fe5d..aa53378a6a 100644--- a/packages/core/feature-flags/index.ts+++ b/packages/core/feature-flags/index.ts@@ -18,6 +18,7 @@ export { FeatureFlagService } from "./service";export { StaticProvider } from "./static-provider";export { ChainProvider } from "./chain-provider";export {+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,COMPOSIO_MCP_APPS_FLAG,PLUGINS_V1_FLAG,PRIVATE_PLUGINS_V1_FLAG,diff --git a/packages/core/feature-flags/keys.ts b/packages/core/feature-flags/keys.tsindex b613a55632..3648f9d232 100644--- a/packages/core/feature-flags/keys.ts+++ b/packages/core/feature-flags/keys.ts@@ -1,3 +1,5 @@export const COMPOSIO_MCP_APPS_FLAG = "composio_mcp_apps";export const PLUGINS_V1_FLAG = "plugins_v1";+export const BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG =+ "billing_workspace_subscriptions";export const PRIVATE_PLUGINS_V1_FLAG = "private_plugins_v1";diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex 9fbb610cd7..51748b58fe 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -245,3 +245,26 @@ export interface WorkspaceSubscriptionPrices {month: WorkspaceSubscriptionPrice;year: WorkspaceSubscriptionPrice;}++export interface CreateWorkspaceSubscriptionCheckoutRequest {+ interval: WorkspaceSubscriptionInterval;+ idempotencyKey: string;+ customerEmail?: string;+}++export interface CreateWorkspaceSubscriptionCheckoutResponse {+ requestId: string;+ sessionId: string;+ url: string;+}++export interface WorkspaceSubscriptionSeatReconcileResult {+ workspaceId: string;+ billedSeats: number;+ actualSeats: number;+ action: string;+}++export interface CreateWorkspaceSubscriptionPortalResponse {+ url: string;+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 17731a2ef6..fef7d8f2f5 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -285,4 +285,8 @@ export type {WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPrices,+ CreateWorkspaceSubscriptionCheckoutRequest,+ CreateWorkspaceSubscriptionCheckoutResponse,+ WorkspaceSubscriptionSeatReconcileResult,+ CreateWorkspaceSubscriptionPortalResponse,} from "./billing";diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 2f181ab3e6..53ef0fd176 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -66,6 +66,118 @@"row_meta": "{{date}} · stripe: {{checkout}}","stripe_empty": "—"},+ "workspace": {+ "title": "Billing",+ "description": "Manage this workspace's plan, limits, human seats, and Stripe billing.",+ "loading": "Loading workspace billing",+ "plan": {+ "free": "Free",+ "pro": "Pro",+ "unknown": "Unknown plan"+ },+ "status": {+ "inactive": "Inactive",+ "active": "Active",+ "trialing": "Trialing",+ "past_due": "Past due",+ "canceled": "Canceled",+ "unknown": "Unknown status"+ },+ "load_failed": {+ "title": "Billing is temporarily unavailable",+ "description": "We couldn't read a trustworthy subscription snapshot. Your plan has not been changed."+ },+ "actions": {+ "retry": "Retry",+ "upgrade": "Upgrade to Pro",+ "manage": "Manage billing",+ "refresh_seats": "Refresh seats",+ "cancel": "Cancel",+ "continue_to_stripe": "Continue to Stripe"+ },+ "errors": {+ "action_title": "Billing action failed",+ "temporarily_unavailable": "Billing is temporarily unavailable. Retry in a moment.",+ "permission_changed": "Your workspace role no longer allows this action. Refresh the page to see your current access.",+ "checkout_response": "Checkout could not open because the server response was unreadable. Retry without changing your selected interval.",+ "already_subscribed": "This workspace already has a subscription. The current plan has been refreshed.",+ "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."+ },+ "return": {+ "cancel_title": "Checkout canceled",+ "cancel_description": "No plan change was made.",+ "portal_title": "Billing details refreshed",+ "portal_description": "The latest subscription snapshot is shown below.",+ "syncing_title": "Activating your subscription",+ "syncing_description": "Payment is complete. We're waiting for Stripe to confirm the plan change.",+ "timeout_description": "Payment was received, but the subscription is still syncing. Refresh this page in a moment.",+ "active_title": "Pro is active",+ "active_description": "This workspace now has Pro access."+ },+ "past_due": {+ "title": "Payment needs attention",+ "description": "Open the Billing Portal to update your payment method and keep Pro access."+ },+ "read_only": {+ "title": "Read-only billing access",+ "description": "You can view the workspace plan and limits. Only owners and admins can purchase or manage a subscription."+ },+ "current": {+ "title": "Current plan",+ "plan": "Workspace plan",+ "plan_description": "The entitlement currently enforced for this workspace.",+ "members": "Human members",+ "members_description": "Agents and pending invitations are not counted as seats.",+ "member_count_one": "{{count}} member",+ "member_count_other": "{{count}} members",+ "period_end": "Current period ends",+ "period_end_description": "The date reported by the current subscription snapshot."+ },+ "upgrade": {+ "title": "Upgrade to Pro",+ "description": "Choose a billing interval, then confirm the current seats and final amount in Stripe Checkout.",+ "interval_label": "Billing interval",+ "monthly": "Monthly",+ "yearly": "Yearly",+ "pro_for_team_one": "Pro for {{count}} human seat",+ "pro_for_team_other": "Pro for {{count}} human seats",+ "price_at_checkout": "The server re-counts human members before purchase. Stripe Checkout shows the authoritative per-seat price and total before you pay."+ },+ "management": {+ "title": "Subscription management",+ "description": "Stripe securely manages payment methods, invoices, and cancellation.",+ "portal": "Stripe Billing Portal",+ "portal_description": "Open Stripe to manage this workspace's subscription.",+ "portal_unavailable": "No Stripe Billing Portal is available for this workspace."+ },+ "limits": {+ "title": "Usage and limits",+ "description": "Current limits are shown without inventing usage totals the server does not provide yet.",+ "issues": "Recent tasks",+ "issues_description": "Free keeps the most recently active tasks available. Pro has no window limit.",+ "autopilots": "Successful automations",+ "autopilots_description": "The Free allowance resets each UTC calendar month. Pro is unlimited.",+ "unlimited": "Unlimited",+ "per_month": "{{count}} / month"+ },+ "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.",+ "updated": "Seats refreshed",+ "reconciled": "Current members: {{actual}} · billed seats: {{billed}}"+ },+ "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."+ }+ },"shared": {"request_failed": "Request failed","refresh": "Refresh",diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 8d815bb55c..cce0d5f689 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -183,7 +183,8 @@"labels": "Labels","properties": "Properties","quick_actions": "Quick Actions",- "plugins": "Plugins"+ "plugins": "Plugins",+ "billing": "Billing"}},"plugins": {diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex a133c208ef..56b6b57757 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -66,6 +66,116 @@"row_meta": "{{date}} · stripe: {{checkout}}","stripe_empty": "—"},+ "workspace": {+ "title": "請求とプラン",+ "description": "このワークスペースのプラン、上限、ユーザー席、Stripe 請求を管理します。",+ "loading": "ワークスペースの請求情報を読み込み中",+ "plan": {+ "free": "Free",+ "pro": "Pro",+ "unknown": "不明なプラン"+ },+ "status": {+ "inactive": "未契約",+ "active": "有効",+ "trialing": "トライアル中",+ "past_due": "支払い遅延",+ "canceled": "キャンセル済み",+ "unknown": "不明なステータス"+ },+ "load_failed": {+ "title": "請求サービスは一時的に利用できません",+ "description": "信頼できるサブスクリプション情報を取得できませんでした。プランは変更されていません。"+ },+ "actions": {+ "retry": "再試行",+ "upgrade": "Pro にアップグレード",+ "manage": "請求を管理",+ "refresh_seats": "席数を更新",+ "cancel": "キャンセル",+ "continue_to_stripe": "Stripe に進む"+ },+ "errors": {+ "action_title": "請求操作に失敗しました",+ "temporarily_unavailable": "請求サービスは一時的に利用できません。しばらくしてから再試行してください。",+ "permission_changed": "現在のワークスペース権限ではこの操作を実行できません。ページを更新して権限を確認してください。",+ "checkout_response": "サーバー応答を読み取れないため Checkout を開けませんでした。選択した期間を変えずに再試行してください。",+ "already_subscribed": "このワークスペースにはすでにサブスクリプションがあります。現在のプランを更新しました。",+ "checkout_failed": "Checkout を作成できませんでした。しばらくしてから再試行してください。",+ "portal_response": "サーバー応答を読み取れないため Billing Portal を開けませんでした。",+ "portal_unavailable": "このワークスペースでは Billing Portal を利用できません。現在のプランを更新しました。",+ "portal_failed": "Billing Portal を開けませんでした。しばらくしてから再試行してください。",+ "reconcile_response": "席数は更新されましたが、結果を読み取れませんでした。ページを再読み込みして確認してください。",+ "reconcile_failed": "席数を更新できませんでした。メンバー変更は保存済みで、定期照合は引き続き再試行されます。"+ },+ "return": {+ "cancel_title": "Checkout をキャンセルしました",+ "cancel_description": "プランは変更されていません。",+ "portal_title": "請求情報を更新しました",+ "portal_description": "最新のサブスクリプション情報を下に表示しています。",+ "syncing_title": "サブスクリプションを有効化しています",+ "syncing_description": "支払いが完了しました。Stripe によるプラン変更の確認を待っています。",+ "timeout_description": "支払いは受領済みですが、サブスクリプションは同期中です。しばらくしてからページを更新してください。",+ "active_title": "Pro が有効になりました",+ "active_description": "このワークスペースで Pro を利用できます。"+ },+ "past_due": {+ "title": "お支払い方法の確認が必要です",+ "description": "Pro を継続するには Billing Portal でお支払い方法を更新してください。"+ },+ "read_only": {+ "title": "請求情報の閲覧のみ",+ "description": "ワークスペースのプランと上限を確認できます。サブスクリプションの購入と管理は owner と admin のみ実行できます。"+ },+ "current": {+ "title": "現在のプラン",+ "plan": "ワークスペースプラン",+ "plan_description": "このワークスペースに現在適用されている entitlement です。",+ "members": "ユーザー席",+ "members_description": "エージェントと保留中の招待は席数に含まれません。",+ "member_count_other": "{{count}}名",+ "period_end": "現在の期間終了日",+ "period_end_description": "現在のサブスクリプション情報で報告された日付です。"+ },+ "upgrade": {+ "title": "Pro にアップグレード",+ "description": "請求期間を選び、Stripe Checkout で現在の席数と最終金額を確認します。",+ "interval_label": "請求期間",+ "monthly": "月払い",+ "yearly": "年払い",+ "pro_for_team_other": "{{count}}席で Pro を利用",+ "price_at_checkout": "購入前にサーバーがユーザーメンバーを再集計します。お支払い前に Stripe Checkout で正式な席単価と合計金額を確認できます。"+ },+ "management": {+ "title": "サブスクリプション管理",+ "description": "お支払い方法、請求書、キャンセルは Stripe で安全に管理されます。",+ "portal": "Stripe Billing Portal",+ "portal_description": "Stripe でこのワークスペースのサブスクリプションを管理します。",+ "portal_unavailable": "このワークスペースで利用できる Stripe Billing Portal はありません。"+ },+ "limits": {+ "title": "使用量と上限",+ "description": "サーバーがまだ提供していない使用済み件数を 0 とせず、現在の上限のみ表示します。",+ "issues": "最近のタスク",+ "issues_description": "Free では最近アクティブなタスクを利用できます。Pro には件数制限がありません。",+ "autopilots": "成功した自動化",+ "autopilots_description": "Free の上限は UTC の暦月ごとにリセットされます。Pro は無制限です。",+ "unlimited": "無制限",+ "per_month": "月 {{count}} 回"+ },+ "seats": {+ "title": "席数",+ "description": "現在のユーザーメンバーはそれぞれ Pro の 1 席として数えられます。エージェントと保留中の招待は含まれません。",+ "human_members": "現在のユーザーメンバー",+ "human_members_description": "メンバー変更後に更新すると、Cloud Billing が Stripe の quantity を照合します。",+ "updated": "席数を更新しました",+ "reconciled": "現在のメンバー: {{actual}} · 請求席数: {{billed}}"+ },+ "confirm": {+ "title": "Stripe Checkout に進みますか?",+ "description": "請求期間: {{interval}}。現在のユーザーメンバー: {{count}}。Stripe が席数を再集計し、お支払い前に最終金額を表示します。"+ }+ },"shared": {"request_failed": "リクエストに失敗しました","refresh": "更新",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 4fc24dfe53..fe4d7d4fe7 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -183,7 +183,8 @@"labels": "ラベル","properties": "プロパティ","quick_actions": "クイックアクション",- "plugins": "Plugins"+ "plugins": "Plugins",+ "billing": "請求とプラン"}},"plugins": {diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 82f87e1a68..dab75184df 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -66,6 +66,116 @@"row_meta": "{{date}} · stripe: {{checkout}}","stripe_empty": "—"},+ "workspace": {+ "title": "결제 및 요금제",+ "description": "이 워크스페이스의 요금제, 한도, 사용자 좌석 및 Stripe 결제를 관리합니다.",+ "loading": "워크스페이스 결제 정보 불러오는 중",+ "plan": {+ "free": "Free",+ "pro": "Pro",+ "unknown": "알 수 없는 요금제"+ },+ "status": {+ "inactive": "비활성",+ "active": "활성",+ "trialing": "체험 중",+ "past_due": "결제 연체",+ "canceled": "취소됨",+ "unknown": "알 수 없는 상태"+ },+ "load_failed": {+ "title": "결제 서비스를 일시적으로 사용할 수 없습니다",+ "description": "신뢰할 수 있는 구독 정보를 불러오지 못했습니다. 요금제는 변경되지 않았습니다."+ },+ "actions": {+ "retry": "다시 시도",+ "upgrade": "Pro로 업그레이드",+ "manage": "결제 관리",+ "refresh_seats": "좌석 새로고침",+ "cancel": "취소",+ "continue_to_stripe": "Stripe로 이동"+ },+ "errors": {+ "action_title": "결제 작업 실패",+ "temporarily_unavailable": "결제 서비스를 일시적으로 사용할 수 없습니다. 잠시 후 다시 시도하세요.",+ "permission_changed": "현재 워크스페이스 역할로는 이 작업을 수행할 수 없습니다. 페이지를 새로고침해 현재 권한을 확인하세요.",+ "checkout_response": "서버 응답을 읽을 수 없어 Checkout을 열지 못했습니다. 선택한 결제 주기를 유지하고 다시 시도하세요.",+ "already_subscribed": "이 워크스페이스에는 이미 구독이 있습니다. 현재 요금제를 새로고침했습니다.",+ "checkout_failed": "Checkout을 만들지 못했습니다. 잠시 후 다시 시도하세요.",+ "portal_response": "서버 응답을 읽을 수 없어 Billing Portal을 열지 못했습니다.",+ "portal_unavailable": "이 워크스페이스에서는 Billing Portal을 사용할 수 없습니다. 현재 요금제를 새로고침했습니다.",+ "portal_failed": "Billing Portal을 열지 못했습니다. 잠시 후 다시 시도하세요.",+ "reconcile_response": "좌석은 새로고침되었지만 결과를 읽지 못했습니다. 페이지를 다시 불러와 현재 수를 확인하세요.",+ "reconcile_failed": "좌석을 새로고침하지 못했습니다. 멤버 변경은 저장되었으며 정기 조정이 계속 재시도됩니다."+ },+ "return": {+ "cancel_title": "Checkout 취소됨",+ "cancel_description": "요금제는 변경되지 않았습니다.",+ "portal_title": "결제 정보 새로고침됨",+ "portal_description": "아래에 최신 구독 정보를 표시합니다.",+ "syncing_title": "구독 활성화 중",+ "syncing_description": "결제가 완료되었습니다. Stripe의 요금제 변경 확인을 기다리고 있습니다.",+ "timeout_description": "결제는 접수되었지만 구독이 아직 동기화 중입니다. 잠시 후 페이지를 새로고침하세요.",+ "active_title": "Pro 활성화됨",+ "active_description": "이 워크스페이스에서 이제 Pro를 사용할 수 있습니다."+ },+ "past_due": {+ "title": "결제 정보를 확인해야 합니다",+ "description": "Pro 이용을 유지하려면 Billing Portal에서 결제 수단을 업데이트하세요."+ },+ "read_only": {+ "title": "결제 정보 읽기 전용",+ "description": "워크스페이스 요금제와 한도를 볼 수 있습니다. 구독 구매와 관리는 owner와 admin만 할 수 있습니다."+ },+ "current": {+ "title": "현재 요금제",+ "plan": "워크스페이스 요금제",+ "plan_description": "이 워크스페이스에 현재 적용되는 entitlement입니다.",+ "members": "사용자 좌석",+ "members_description": "에이전트와 대기 중인 초대는 좌석에 포함되지 않습니다.",+ "member_count_other": "멤버 {{count}}명",+ "period_end": "현재 결제 기간 종료일",+ "period_end_description": "현재 구독 정보에 보고된 날짜입니다."+ },+ "upgrade": {+ "title": "Pro로 업그레이드",+ "description": "결제 주기를 선택한 다음 Stripe Checkout에서 현재 좌석과 최종 금액을 확인하세요.",+ "interval_label": "결제 주기",+ "monthly": "월간",+ "yearly": "연간",+ "pro_for_team_other": "사용자 좌석 {{count}}개에 Pro 적용",+ "price_at_checkout": "구매 전에 서버가 사용자 멤버를 다시 계산합니다. 결제 전 Stripe Checkout에서 공식 좌석당 가격과 총액을 확인할 수 있습니다."+ },+ "management": {+ "title": "구독 관리",+ "description": "결제 수단, 청구서 및 구독 취소는 Stripe에서 안전하게 관리됩니다.",+ "portal": "Stripe Billing Portal",+ "portal_description": "Stripe에서 이 워크스페이스의 구독을 관리합니다.",+ "portal_unavailable": "이 워크스페이스에서 사용할 수 있는 Stripe Billing Portal이 없습니다."+ },+ "limits": {+ "title": "사용량 및 한도",+ "description": "서버가 아직 제공하지 않는 사용량을 0으로 표시하지 않고 현재 한도만 보여 줍니다.",+ "issues": "최근 태스크",+ "issues_description": "Free에서는 최근 활성 태스크를 이용할 수 있습니다. Pro에는 범위 제한이 없습니다.",+ "autopilots": "성공한 자동화",+ "autopilots_description": "Free 한도는 UTC 기준 매월 초기화됩니다. Pro는 무제한입니다.",+ "unlimited": "무제한",+ "per_month": "월 {{count}}회"+ },+ "seats": {+ "title": "좌석",+ "description": "현재 사용자 멤버 한 명당 Pro 좌석 하나로 계산됩니다. 에이전트와 대기 중인 초대는 포함되지 않습니다.",+ "human_members": "현재 사용자 멤버",+ "human_members_description": "멤버 변경 후 새로고침하면 Cloud Billing이 Stripe quantity를 조정합니다.",+ "updated": "좌석 새로고침됨",+ "reconciled": "현재 멤버: {{actual}} · 결제 좌석: {{billed}}"+ },+ "confirm": {+ "title": "Stripe Checkout으로 이동할까요?",+ "description": "결제 주기: {{interval}}. 현재 사용자 멤버: {{count}}. Stripe가 좌석을 다시 계산하고 결제 전에 최종 금액을 표시합니다."+ }+ },"shared": {"request_failed": "요청 실패","refresh": "새로고침",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 229ca5f19e..ec25c0d244 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -183,7 +183,8 @@"labels": "레이블","properties": "속성","quick_actions": "퀵 액션",- "plugins": "Plugins"+ "plugins": "Plugins",+ "billing": "결제 및 요금제"}},"plugins": {diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 9ad14cf2f5..a398b013a8 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -66,6 +66,116 @@"row_meta": "{{date}} · stripe: {{checkout}}","stripe_empty": "—"},+ "workspace": {+ "title": "账单与套餐",+ "description": "管理这个工作区的套餐、限额、成员席位和 Stripe 账单。",+ "loading": "正在加载工作区账单",+ "plan": {+ "free": "Free",+ "pro": "Pro",+ "unknown": "未知套餐"+ },+ "status": {+ "inactive": "未启用",+ "active": "活跃",+ "trialing": "试用中",+ "past_due": "付款逾期",+ "canceled": "已取消",+ "unknown": "未知状态"+ },+ "load_failed": {+ "title": "账单服务暂时不可用",+ "description": "暂时无法读取可信的订阅快照。你的套餐没有发生变化。"+ },+ "actions": {+ "retry": "重试",+ "upgrade": "升级到 Pro",+ "manage": "管理账单",+ "refresh_seats": "刷新席位",+ "cancel": "取消",+ "continue_to_stripe": "前往 Stripe"+ },+ "errors": {+ "action_title": "账单操作失败",+ "temporarily_unavailable": "账单服务暂时不可用,请稍后重试。",+ "permission_changed": "你的工作区角色已不允许执行此操作。刷新页面可查看当前权限。",+ "checkout_response": "服务端响应无法读取,无法打开 Checkout。请保留当前周期并重试。",+ "already_subscribed": "这个工作区已经有订阅,当前套餐已刷新。",+ "checkout_failed": "无法创建 Checkout,请稍后重试。",+ "portal_response": "服务端响应无法读取,无法打开 Billing Portal。",+ "portal_unavailable": "这个工作区暂时无法使用 Billing Portal,当前套餐已刷新。",+ "portal_failed": "无法打开 Billing Portal,请稍后重试。",+ "reconcile_response": "席位已刷新,但无法读取结果。请重新加载页面确认当前数量。",+ "reconcile_failed": "无法刷新席位。成员变更已保存,定期对账仍会继续重试。"+ },+ "return": {+ "cancel_title": "已取消 Checkout",+ "cancel_description": "套餐没有发生变化。",+ "portal_title": "账单信息已刷新",+ "portal_description": "下方显示最新的订阅快照。",+ "syncing_title": "正在启用订阅",+ "syncing_description": "付款已完成,正在等待 Stripe 确认套餐变化。",+ "timeout_description": "付款已收到,但订阅仍在同步。请稍后刷新页面。",+ "active_title": "Pro 已启用",+ "active_description": "这个工作区现在可以使用 Pro。"+ },+ "past_due": {+ "title": "付款信息需要处理",+ "description": "打开 Billing Portal 更新付款方式,以继续使用 Pro。"+ },+ "read_only": {+ "title": "账单只读权限",+ "description": "你可以查看工作区套餐和限额。只有 owner 和 admin 可以购买或管理订阅。"+ },+ "current": {+ "title": "当前套餐",+ "plan": "工作区套餐",+ "plan_description": "这个工作区当前生效的 entitlement。",+ "members": "成员席位",+ "members_description": "智能体和待接受的邀请不计入席位。",+ "member_count_other": "{{count}} 位成员",+ "period_end": "当前周期结束时间",+ "period_end_description": "当前订阅快照报告的日期。"+ },+ "upgrade": {+ "title": "升级到 Pro",+ "description": "选择付款周期,然后在 Stripe Checkout 确认当前席位和最终金额。",+ "interval_label": "付款周期",+ "monthly": "月付",+ "yearly": "年付",+ "pro_for_team_other": "为 {{count}} 个成员席位升级 Pro",+ "price_at_checkout": "购买前,服务端会重新统计成员。付款前,Stripe Checkout 会显示权威的单席位价格和总额。"+ },+ "management": {+ "title": "订阅管理",+ "description": "Stripe 会安全地管理付款方式、发票和取消订阅。",+ "portal": "Stripe Billing Portal",+ "portal_description": "前往 Stripe 管理这个工作区的订阅。",+ "portal_unavailable": "这个工作区暂时没有可用的 Stripe Billing Portal。"+ },+ "limits": {+ "title": "用量与限额",+ "description": "这里仅显示当前套餐限额,不会把服务端尚未提供的已用量伪装成 0。",+ "issues": "最近活跃的任务",+ "issues_description": "Free 可访问最近活跃的任务;Pro 没有窗口限制。",+ "autopilots": "成功的自动化执行",+ "autopilots_description": "Free 限额按 UTC 自然月重置;Pro 不限次数。",+ "unlimited": "不限",+ "per_month": "每月 {{count}} 次"+ },+ "seats": {+ "title": "席位",+ "description": "每位当前成员都会计为一个 Pro 席位,智能体和待接受的邀请不计。",+ "human_members": "当前成员",+ "human_members_description": "成员变化后刷新,通知 Cloud Billing 对账 Stripe quantity。",+ "updated": "席位已刷新",+ "reconciled": "当前成员:{{actual}} · 计费席位:{{billed}}"+ },+ "confirm": {+ "title": "前往 Stripe Checkout?",+ "description": "付款周期:{{interval}}。当前成员:{{count}}。Stripe 会重新统计席位,并在付款前显示最终金额。"+ }+ },"shared": {"request_failed": "请求失败","refresh": "刷新",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 12c876adc2..854cb7ed3e 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -183,7 +183,8 @@"labels": "标签","properties": "属性","quick_actions": "快捷操作",- "plugins": "Plugins"+ "plugins": "Plugins",+ "billing": "账单与套餐"}},"plugins": {diff --git a/packages/views/platform/open-external.ts b/packages/views/platform/open-external.tsindex 3d637ce987..9ef2340dcb 100644--- a/packages/views/platform/open-external.ts+++ b/packages/views/platform/open-external.ts@@ -7,13 +7,16 @@* `window.open(url, "_blank")` inside Electron would create a new renderer* window instead of handing the URL to the OS shell.*- * On web this falls back to `window.open` with the standard `noopener`+- * `noreferrer` flags, which is the same thing an `<a target="_blank">` would- * do but without requiring markup.+ * On web this defaults to `window.open` with the standard `noopener`++ * `noreferrer` flags. Callers that receive a URL after an async request can+ * choose `webTarget: "same-tab"` to avoid popup blocking.** SSR-safe: no-op if `window` is not defined.*/-export function openExternal(url: string): void {+export function openExternal(+ url: string,+ options?: { webTarget?: "new-tab" | "same-tab" },+): void {if (typeof window === "undefined") return;const desktopAPI = (window as unknown as {@@ -24,5 +27,13 @@ export function openExternal(url: string): void {void desktopAPI.openExternal(url);return;}+ // Async-created Stripe URLs are commonly returned after the original click+ // task has finished, so opening a new tab can be blocked as a popup. The+ // same-tab option keeps Checkout/Portal reliable on web while Electron still+ // hands the URL to the system browser above.+ if (options?.webTarget === "same-tab") {+ window.location.assign(url);+ return;+ }window.open(url, "_blank", "noopener,noreferrer");}diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxnew file mode 100644index 0000000000..c665eb413a--- /dev/null+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -0,0 +1,347 @@+import { act, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { ApiError } from "@multica/core/api";+import { configStore } from "@multica/core/config";+import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";+import { renderWithI18n } from "../../test/i18n";++const mocks = vi.hoisted(() => ({+ useQuery: vi.fn(),+ checkout: vi.fn(),+ portal: vi.fn(),+ reconcile: vi.fn(),+ refetch: vi.fn(),+ openExternal: vi.fn(),+ role: "owner" as "owner" | "admin" | "member",+ entitlements: {+ workspaceId: "workspace-1",+ plan: "free",+ status: "inactive",+ seats: 3,+ issueWindow: 1000,+ autopilotRuns: 100,+ currentPeriodEnd: null as string | null,+ snapshotExpiresAt: null as string | null,+ version: 0,+ },+}));++vi.mock("@tanstack/react-query", () => ({+ useQuery: (options: unknown) => mocks.useQuery(options),+}));++vi.mock("@multica/core/billing", () => ({+ workspaceSubscriptionEntitlementsOptions: (wsId: string) => ({+ queryKey: ["workspace-subscriptions", wsId, "entitlements"],+ }),+ useCreateWorkspaceSubscriptionCheckout: () => ({+ mutateAsync: mocks.checkout,+ isPending: false,+ }),+ useCreateWorkspaceSubscriptionPortal: () => ({+ mutateAsync: mocks.portal,+ isPending: false,+ }),+ useReconcileWorkspaceSubscriptionSeats: () => ({+ mutateAsync: mocks.reconcile,+ isPending: false,+ }),+}));++vi.mock("@multica/core/paths", () => ({+ useCurrentWorkspace: () => ({+ id: "workspace-1",+ slug: "acme",+ name: "Acme",+ }),+}));++vi.mock("@multica/core/permissions", () => ({+ useCurrentMember: () => ({ role: mocks.role, isLoading: false }),+}));++const navigationState = {+ search: "tab=billing",+ replace: vi.fn(),+};+vi.mock("../../navigation", () => ({+ useNavigation: () => ({+ pathname: "/acme/settings",+ searchParams: new URLSearchParams(navigationState.search),+ push: vi.fn(),+ replace: navigationState.replace,+ back: vi.fn(),+ getShareableUrl: vi.fn(),+ }),+}));++vi.mock("../../platform", () => ({ openExternal: mocks.openExternal }));++import { BillingTab } from "./billing-tab";++describe("BillingTab", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ navigationState.search = "tab=billing";+ mocks.role = "owner";+ Object.assign(mocks.entitlements, {+ plan: "free",+ status: "inactive",+ seats: 3,+ issueWindow: 1000,+ autopilotRuns: 100,+ currentPeriodEnd: null,+ snapshotExpiresAt: null,+ version: 0,+ });+ mocks.useQuery.mockReturnValue({+ data: mocks.entitlements,+ isPending: false,+ isError: false,+ refetch: mocks.refetch,+ });+ mocks.checkout.mockResolvedValue({+ requestId: "request-1",+ sessionId: "cs_test_1",+ url: "https://checkout.stripe.com/test-session",+ });+ mocks.portal.mockResolvedValue({+ url: "https://billing.stripe.com/test-session",+ });+ mocks.reconcile.mockResolvedValue({+ workspaceId: "workspace-1",+ billedSeats: 3,+ actualSeats: 3,+ action: "none",+ });+ configStore.getState().setFeatureFlags({+ [BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG]: true,+ });+ });++ it("renders nothing and issues no query when the feature flag is absent", () => {+ configStore.getState().setFeatureFlags({});++ const { container } = renderWithI18n(<BillingTab />);++ expect(container).toBeEmptyDOMElement();+ expect(mocks.useQuery).not.toHaveBeenCalled();+ });++ it("shows an honest Free plan without inventing prices or usage totals", () => {+ renderWithI18n(<BillingTab />);++ expect(screen.getByRole("heading", { name: "Billing" })).toBeInTheDocument();+ expect(screen.getByText("1,000")).toBeInTheDocument();+ expect(screen.getByText("100 / month")).toBeInTheDocument();+ expect(+ screen.getByText(/Stripe Checkout shows the authoritative per-seat price/),+ ).toBeInTheDocument();+ expect(screen.queryByText("$10")).not.toBeInTheDocument();+ });++ it("creates Checkout with a client idempotency key and opens Stripe externally", async () => {+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));++ await waitFor(() => {+ expect(mocks.checkout).toHaveBeenCalledTimes(1);+ });+ const request = mocks.checkout.mock.calls[0]?.[0] as {+ interval: string;+ idempotencyKey: string;+ };+ expect(request.interval).toBe("month");+ expect(request.idempotencyKey).toMatch(/^workspace-checkout-workspace-1-/);+ expect(mocks.openExternal).toHaveBeenCalledWith(+ "https://checkout.stripe.com/test-session",+ { webTarget: "same-tab" },+ );+ });++ it("reuses the Checkout idempotency key after an ambiguous failure", async () => {+ const user = userEvent.setup();+ mocks.checkout+ .mockRejectedValueOnce(new Error("network lost after submit"))+ .mockResolvedValueOnce({+ requestId: "request-1",+ sessionId: "cs_test_1",+ url: "https://checkout.stripe.com/test-session",+ });+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await screen.findByText("Billing action failed");++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));++ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(2));+ expect(mocks.checkout.mock.calls[1]?.[0].idempotencyKey).toBe(+ mocks.checkout.mock.calls[0]?.[0].idempotencyKey,+ );+ });++ it("starts a new Checkout intent after explicit cancellation", async () => {+ const user = userEvent.setup();+ mocks.checkout+ .mockRejectedValueOnce(new Error("network lost after submit"))+ .mockResolvedValueOnce({+ requestId: "request-2",+ sessionId: "cs_test_2",+ url: "https://checkout.stripe.com/test-session-2",+ });+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await screen.findByText("Billing action failed");++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Cancel" }));+ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));++ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(2));+ expect(mocks.checkout.mock.calls[1]?.[0].idempotencyKey).not.toBe(+ mocks.checkout.mock.calls[0]?.[0].idempotencyKey,+ );+ });++ it.each([+ [503, "Billing is temporarily unavailable. Retry in a moment."],+ [+ 403,+ "Your workspace role no longer allows this action. Refresh the page to see your current access.",+ ],+ ])("maps a %s Checkout response to actionable copy", async (status, copy) => {+ const user = userEvent.setup();+ mocks.checkout.mockRejectedValue(+ new ApiError("request failed", status, "Request Failed"),+ );+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));++ expect(await screen.findByText(copy)).toBeInTheDocument();+ });++ it("consumes cancel callback params once while preserving the active tab", () => {+ navigationState.search =+ "tab=billing&result=cancel&session_id=cs_test_1&source=email";++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Checkout canceled")).toBeInTheDocument();+ expect(navigationState.replace).toHaveBeenCalledOnce();+ expect(navigationState.replace).toHaveBeenCalledWith(+ "/acme/settings?tab=billing&source=email",+ );+ });++ it("polls after a success callback and surfaces a bounded sync timeout", () => {+ vi.useFakeTimers();+ navigationState.search = "tab=billing&result=success&session_id=cs_test_1";+ try {+ renderWithI18n(<BillingTab />);++ expect(+ screen.getByText("Activating your subscription"),+ ).toBeInTheDocument();+ expect(mocks.useQuery).toHaveBeenCalledWith(+ expect.objectContaining({ refetchInterval: 2_000 }),+ );+ expect(navigationState.replace).toHaveBeenCalledWith(+ "/acme/settings?tab=billing",+ );++ act(() => vi.advanceTimersByTime(30_000));++ expect(+ screen.getByText(+ "Payment was received, but the subscription is still syncing. Refresh this page in a moment.",+ ),+ ).toBeInTheDocument();+ expect(navigationState.replace).toHaveBeenCalledOnce();+ } finally {+ vi.useRealTimers();+ }+ });++ it("keeps plan facts visible but hides subscription mutations from members", () => {+ mocks.role = "member";++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Read-only billing access")).toBeInTheDocument();+ expect(screen.getAllByText("3 members")).toHaveLength(2);+ expect(+ screen.queryByRole("button", { name: "Upgrade to Pro" }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Refresh seats" }),+ ).not.toBeInTheDocument();+ });++ it("shows Pro management and unlimited limits without a second Checkout", () => {+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ currentPeriodEnd: "2026-09-13T00:00:00Z",+ version: 3,+ });++ renderWithI18n(<BillingTab />);++ expect(+ screen.getByRole("button", { name: "Manage billing" }),+ ).toBeInTheDocument();+ expect(screen.getAllByText("Unlimited")).toHaveLength(2);+ expect(+ screen.queryByRole("button", { name: "Upgrade to Pro" }),+ ).not.toBeInTheDocument();+ });++ it("keeps the billing portal available for a canceled Pro period", () => {+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "canceled",+ currentPeriodEnd: "2026-09-13T00:00:00Z",+ version: 4,+ });++ renderWithI18n(<BillingTab />);++ expect(+ screen.getByRole("button", { name: "Manage billing" }),+ ).toBeInTheDocument();+ });++ it("keeps payment recovery available when past-due grace has resolved to Free", () => {+ Object.assign(mocks.entitlements, {+ plan: "free",+ status: "past_due",+ snapshotExpiresAt: "2026-09-01T00:00:00Z",+ version: 4,+ });++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Payment needs attention")).toBeInTheDocument();+ expect(screen.queryByText("Sep 1, 2026")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Manage billing" }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Upgrade to Pro" }),+ ).not.toBeInTheDocument();+ });+});diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxnew file mode 100644index 0000000000..5893060d0b--- /dev/null+++ b/packages/views/settings/components/billing-tab.tsx@@ -0,0 +1,744 @@+"use client";++import { useEffect, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ AlertCircle,+ CheckCircle2,+ CreditCard,+ ExternalLink,+ Loader2,+ RefreshCw,+ ShieldCheck,+} from "lucide-react";+import { ApiError } from "@multica/core/api";+import {+ useCreateWorkspaceSubscriptionCheckout,+ useCreateWorkspaceSubscriptionPortal,+ useReconcileWorkspaceSubscriptionSeats,+ workspaceSubscriptionEntitlementsOptions,+} from "@multica/core/billing";+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 {+ Alert,+ AlertDescription,+ AlertTitle,+} from "@multica/ui/components/ui/alert";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@multica/ui/components/ui/alert-dialog";+import { Badge } from "@multica/ui/components/ui/badge";+import { Button } from "@multica/ui/components/ui/button";+import { Skeleton } from "@multica/ui/components/ui/skeleton";+import { useLocale, useT } from "../../i18n";+import { useNavigation } from "../../navigation";+import { openExternal } from "../../platform";+import {+ SettingsCard,+ SettingsRow,+ SettingsSection,+ SettingsTab,+} from "./settings-layout";++const CHECKOUT_SYNC_TIMEOUT_MS = 30_000;++type WorkspaceBillingReturnResult = "success" | "cancel" | "portal";++function parseReturnResult(+ value: string | null,+): WorkspaceBillingReturnResult | null {+ switch (value) {+ case "success":+ case "cancel":+ case "portal":+ return value;+ default:+ return null;+ }+}++function createIdempotencyKey(prefix: string, wsId: string): string {+ const suffix =+ globalThis.crypto?.randomUUID?.() ??+ `${Date.now()}-${Math.random().toString(36).slice(2)}`;+ return `${prefix}-${wsId}-${suffix}`.slice(0, 255);+}++function formatDate(value: string | null, locale: string): string | null {+ if (!value) return null;+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return null;+ return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(date);+}++function planBadgeVariant(plan: string): "default" | "secondary" | "outline" {+ if (plan === "pro") return "default";+ if (plan === "free") return "secondary";+ return "outline";+}++function statusBadgeVariant(+ status: string,+): "default" | "secondary" | "destructive" | "outline" {+ switch (status) {+ case "active":+ case "trialing":+ return "default";+ case "past_due":+ return "destructive";+ case "inactive":+ case "canceled":+ return "secondary";+ default:+ return "outline";+ }+}++/**+ * A second gate inside the tab keeps direct/test mounts fail-closed. The+ * Settings shell also omits this component and its navigation entry while the+ * flag is absent, so no subscription request is issued in either path.+ */+export function BillingTab() {+ const enabled = useFeatureEnabled(+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,+ false,+ );+ return enabled ? <BillingTabContent /> : null;+}++function BillingTabContent() {+ const { t } = useT("billing");+ const locale = useLocale();+ const navigation = useNavigation();+ const workspace = useCurrentWorkspace();+ const wsId = workspace?.id ?? "";+ const currentMember = useCurrentMember(wsId);+ const canManage =+ currentMember.role === "owner" || currentMember.role === "admin";+ const returnResultParam = parseReturnResult(+ navigation.searchParams.get("result"),+ );+ const returnSessionId = navigation.searchParams.get("session_id");+ const callbackKey =+ navigation.searchParams.has("result") ||+ navigation.searchParams.has("session_id")+ ? `${navigation.searchParams.get("result") ?? ""}:${returnSessionId ?? ""}`+ : null;+ const [returnState, setReturnState] = useState<{+ workspaceId: string | null;+ result: WorkspaceBillingReturnResult | null;+ }>({ workspaceId: wsId || null, result: returnResultParam });+ const returnResult =+ returnState.workspaceId === null || returnState.workspaceId === wsId+ ? returnState.result+ : null;+ const [interval, setInterval] =+ useState<WorkspaceSubscriptionInterval>("month");+ const [checkoutConfirmOpen, setCheckoutConfirmOpen] = useState(false);+ const [actionError, setActionError] = useState<string | null>(null);+ const [portalUnavailable, setPortalUnavailable] = useState(false);+ const [reconcileMessage, setReconcileMessage] = useState<string | null>(null);+ const [isSyncingCheckout, setIsSyncingCheckout] = useState(+ returnResult === "success",+ );+ const [syncTimedOut, setSyncTimedOut] = useState(false);+ const checkoutIntentRef = useRef<{+ wsId: string;+ interval: WorkspaceSubscriptionInterval;+ key: string;+ } | null>(null);+ const portalIntentKeyRef = useRef<string | null>(null);+ const consumedCallbackKeyRef = useRef<string | null>(null);++ useEffect(() => {+ checkoutIntentRef.current = null;+ portalIntentKeyRef.current = null;+ setPortalUnavailable(false);+ setActionError(null);+ setReconcileMessage(null);+ }, [wsId]);++ // Consume Stripe callback params once, then remove them with replace so a+ // refresh, copied URL, or settings-tab round trip cannot replay a banner or+ // restart subscription polling. Keep unrelated params, especially `tab`.+ useEffect(() => {+ if (!callbackKey || consumedCallbackKeyRef.current === callbackKey) return;+ consumedCallbackKeyRef.current = callbackKey;+ setReturnState({ workspaceId: wsId || null, result: returnResultParam });+ if (returnResultParam === "cancel") checkoutIntentRef.current = null;++ const params = new URLSearchParams(navigation.searchParams);+ params.delete("result");+ params.delete("session_id");+ const query = params.toString();+ navigation.replace(+ query ? `${navigation.pathname}?${query}` : navigation.pathname,+ );+ }, [callbackKey, navigation, returnResultParam, wsId]);++ useEffect(() => {+ if (returnResult !== "success") {+ setIsSyncingCheckout(false);+ setSyncTimedOut(false);+ return;+ }+ setIsSyncingCheckout(true);+ setSyncTimedOut(false);+ const timeout = window.setTimeout(() => {+ setIsSyncingCheckout(false);+ setSyncTimedOut(true);+ }, CHECKOUT_SYNC_TIMEOUT_MS);+ return () => window.clearTimeout(timeout);+ }, [returnResult, wsId]);++ const entitlementQuery = useQuery({+ ...workspaceSubscriptionEntitlementsOptions(wsId),+ refetchInterval: isSyncingCheckout ? 2_000 : false,+ });+ const checkoutMutation = useCreateWorkspaceSubscriptionCheckout(wsId);+ const portalMutation = useCreateWorkspaceSubscriptionPortal(wsId);+ const reconcileMutation = useReconcileWorkspaceSubscriptionSeats(wsId);+ const entitlements = entitlementQuery.data;+ const refetchEntitlements = entitlementQuery.refetch;++ useEffect(() => {+ if (isSyncingCheckout && entitlements?.plan === "pro") {+ setIsSyncingCheckout(false);+ setSyncTimedOut(false);+ checkoutIntentRef.current = null;+ }+ }, [entitlements?.plan, isSyncingCheckout]);++ useEffect(() => {+ const expiresAt = entitlements?.snapshotExpiresAt;+ if (!expiresAt) return;+ const expiresAtMs = new Date(expiresAt).getTime();+ if (Number.isNaN(expiresAtMs)) return;+ const delay = Math.max(0, expiresAtMs - Date.now()) + 100;+ const timeout = window.setTimeout(() => {+ void refetchEntitlements();+ }, Math.min(delay, 2_147_000_000));+ return () => window.clearTimeout(timeout);+ }, [entitlements?.snapshotExpiresAt, refetchEntitlements]);++ const planLabel = (plan: string) => {+ switch (plan) {+ case "free":+ return t(($) => $.workspace.plan.free);+ case "pro":+ return t(($) => $.workspace.plan.pro);+ default:+ return t(($) => $.workspace.plan.unknown);+ }+ };++ const statusLabel = (status: string) => {+ switch (status) {+ case "inactive":+ return t(($) => $.workspace.status.inactive);+ case "active":+ return t(($) => $.workspace.status.active);+ case "trialing":+ return t(($) => $.workspace.status.trialing);+ case "past_due":+ return t(($) => $.workspace.status.past_due);+ case "canceled":+ return t(($) => $.workspace.status.canceled);+ default:+ return t(($) => $.workspace.status.unknown);+ }+ };++ const reportActionError = (error: unknown, fallback: string) => {+ if (error instanceof ApiError && error.status === 503) {+ setActionError(t(($) => $.workspace.errors.temporarily_unavailable));+ return;+ }+ if (error instanceof ApiError && error.status === 403) {+ setActionError(t(($) => $.workspace.errors.permission_changed));+ return;+ }+ setActionError(fallback);+ };++ const handleCheckout = async () => {+ setActionError(null);+ const existing = checkoutIntentRef.current;+ const intent =+ existing?.wsId === wsId && existing.interval === interval+ ? existing+ : {+ wsId,+ interval,+ key: createIdempotencyKey("workspace-checkout", wsId),+ };+ checkoutIntentRef.current = intent;+ try {+ const response = await checkoutMutation.mutateAsync({+ interval,+ idempotencyKey: intent.key,+ });+ if (!response?.url) {+ setCheckoutConfirmOpen(false);+ setActionError(t(($) => $.workspace.errors.checkout_response));+ return;+ }+ setCheckoutConfirmOpen(false);+ openExternal(response.url, { webTarget: "same-tab" });+ } catch (error) {+ setCheckoutConfirmOpen(false);+ if (error instanceof ApiError && error.status === 409) {+ checkoutIntentRef.current = null;+ setActionError(t(($) => $.workspace.errors.already_subscribed));+ await entitlementQuery.refetch();+ return;+ }+ reportActionError(error, t(($) => $.workspace.errors.checkout_failed));+ }+ };++ const handleCheckoutConfirmOpenChange = (open: boolean) => {+ setCheckoutConfirmOpen(open);+ if (!open) checkoutIntentRef.current = null;+ };++ const handlePortal = async () => {+ setActionError(null);+ const key =+ portalIntentKeyRef.current ??+ createIdempotencyKey("workspace-portal", wsId);+ portalIntentKeyRef.current = key;+ try {+ const response = await portalMutation.mutateAsync(key);+ if (!response?.url) {+ setActionError(t(($) => $.workspace.errors.portal_response));+ return;+ }+ openExternal(response.url, { webTarget: "same-tab" });+ // A Portal URL is single-use. A later click is a new intent, while a+ // network failure above deliberately retains the key for safe retry.+ portalIntentKeyRef.current = null;+ } catch (error) {+ if (error instanceof ApiError && error.status === 404) {+ portalIntentKeyRef.current = null;+ setPortalUnavailable(true);+ setActionError(t(($) => $.workspace.errors.portal_unavailable));+ await entitlementQuery.refetch();+ return;+ }+ reportActionError(error, t(($) => $.workspace.errors.portal_failed));+ }+ };++ 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,+ }),+ );+ } catch (error) {+ reportActionError(error, t(($) => $.workspace.errors.reconcile_failed));+ }+ };++ if (entitlementQuery.isPending) {+ return (+ <SettingsTab+ title={t(($) => $.workspace.title)}+ description={t(($) => $.workspace.description)}+ >+ <SettingsCard>+ <div+ className="space-y-4 p-4 motion-reduce:[&_[data-slot=skeleton]]:animate-none"+ aria-label={t(($) => $.workspace.loading)}+ >+ <Skeleton className="h-5 w-40" />+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-2/3" />+ </div>+ </SettingsCard>+ </SettingsTab>+ );+ }++ if (entitlementQuery.isError || !entitlements) {+ return (+ <SettingsTab+ title={t(($) => $.workspace.title)}+ description={t(($) => $.workspace.description)}+ >+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>{t(($) => $.workspace.load_failed.title)}</AlertTitle>+ <AlertDescription>+ <p>{t(($) => $.workspace.load_failed.description)}</p>+ <Button+ className="mt-3 h-11"+ variant="outline"+ onClick={() => void entitlementQuery.refetch()}+ >+ <RefreshCw />+ {t(($) => $.workspace.actions.retry)}+ </Button>+ </AlertDescription>+ </Alert>+ </SettingsTab>+ );+ }++ const periodEnd = formatDate(entitlements.currentPeriodEnd, locale);+ const isFree = entitlements.plan === "free";+ const isPro = entitlements.plan === "pro";+ const hasManagedSubscription =+ isPro ||+ entitlements.status === "active" ||+ entitlements.status === "trialing" ||+ entitlements.status === "past_due";+ const isMutating =+ checkoutMutation.isPending ||+ portalMutation.isPending ||+ reconcileMutation.isPending;++ return (+ <SettingsTab+ title={t(($) => $.workspace.title)}+ description={t(($) => $.workspace.description)}+ >+ {returnResult === "cancel" ? (+ <Alert>+ <AlertCircle />+ <AlertTitle>{t(($) => $.workspace.return.cancel_title)}</AlertTitle>+ <AlertDescription>+ {t(($) => $.workspace.return.cancel_description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {returnResult === "portal" ? (+ <Alert>+ <CheckCircle2 />+ <AlertTitle>{t(($) => $.workspace.return.portal_title)}</AlertTitle>+ <AlertDescription>+ {t(($) => $.workspace.return.portal_description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {returnResult === "success" ? (+ <Alert>+ {isPro ? (+ <CheckCircle2 />+ ) : (+ <Loader2+ className={+ isSyncingCheckout+ ? "animate-spin motion-reduce:animate-none"+ : undefined+ }+ />+ )}+ <AlertTitle>+ {isPro+ ? t(($) => $.workspace.return.active_title)+ : t(($) => $.workspace.return.syncing_title)}+ </AlertTitle>+ <AlertDescription>+ {isPro+ ? t(($) => $.workspace.return.active_description)+ : syncTimedOut+ ? t(($) => $.workspace.return.timeout_description)+ : t(($) => $.workspace.return.syncing_description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {entitlements.status === "past_due" ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>{t(($) => $.workspace.past_due.title)}</AlertTitle>+ <AlertDescription>+ {t(($) => $.workspace.past_due.description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {!canManage && !currentMember.isLoading ? (+ <Alert>+ <ShieldCheck />+ <AlertTitle>{t(($) => $.workspace.read_only.title)}</AlertTitle>+ <AlertDescription>+ {t(($) => $.workspace.read_only.description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {actionError ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>{t(($) => $.workspace.errors.action_title)}</AlertTitle>+ <AlertDescription>{actionError}</AlertDescription>+ </Alert>+ ) : null}++ <SettingsSection title={t(($) => $.workspace.current.title)}>+ <SettingsCard>+ <SettingsRow+ label={t(($) => $.workspace.current.plan)}+ description={t(($) => $.workspace.current.plan_description)}+ >+ <div className="flex flex-wrap items-center gap-2 sm:justify-end">+ <Badge variant={planBadgeVariant(entitlements.plan)}>+ {planLabel(entitlements.plan)}+ </Badge>+ <Badge variant={statusBadgeVariant(entitlements.status)}>+ {statusLabel(entitlements.status)}+ </Badge>+ </div>+ </SettingsRow>+ <SettingsRow+ label={t(($) => $.workspace.current.members)}+ description={t(($) => $.workspace.current.members_description)}+ >+ <span className="tabular-nums">+ {t(($) => $.workspace.current.member_count, {+ count: entitlements.seats,+ })}+ </span>+ </SettingsRow>+ {periodEnd ? (+ <SettingsRow+ label={t(($) => $.workspace.current.period_end)}+ description={t(($) => $.workspace.current.period_end_description)}+ >+ <span className="tabular-nums">{periodEnd}</span>+ </SettingsRow>+ ) : null}+ </SettingsCard>+ </SettingsSection>++ {isFree && !hasManagedSubscription ? (+ <SettingsSection+ title={t(($) => $.workspace.upgrade.title)}+ description={t(($) => $.workspace.upgrade.description)}+ >+ <SettingsCard>+ <div className="space-y-5 p-4 sm:p-5">+ <div+ className="inline-flex w-full rounded-lg border border-surface-border p-1 sm:w-auto"+ role="group"+ aria-label={t(($) => $.workspace.upgrade.interval_label)}+ >+ {(["month", "year"] as const).map((value) => (+ <button+ key={value}+ type="button"+ aria-pressed={interval === value}+ className="min-h-11 flex-1 rounded-md px-4 text-body font-medium text-muted-foreground transition-[color,background-color,box-shadow] hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring aria-pressed:bg-surface-selected aria-pressed:text-surface-selected-foreground aria-pressed:shadow-sm sm:min-w-32"+ onClick={() => {+ setInterval(value);+ checkoutIntentRef.current = null;+ }}+ >+ {value === "month"+ ? t(($) => $.workspace.upgrade.monthly)+ : t(($) => $.workspace.upgrade.yearly)}+ </button>+ ))}+ </div>+ <div className="space-y-1">+ <p className="text-body font-medium">+ {t(($) => $.workspace.upgrade.pro_for_team, {+ count: entitlements.seats,+ })}+ </p>+ <p className="max-w-[65ch] text-caption leading-5 text-muted-foreground">+ {t(($) => $.workspace.upgrade.price_at_checkout)}+ </p>+ </div>+ {canManage ? (+ <Button+ className="h-11 w-full sm:w-auto"+ disabled={isMutating}+ onClick={() => setCheckoutConfirmOpen(true)}+ >+ <CreditCard />+ {t(($) => $.workspace.actions.upgrade)}+ </Button>+ ) : null}+ </div>+ </SettingsCard>+ </SettingsSection>+ ) : null}++ {hasManagedSubscription && canManage ? (+ <SettingsSection+ title={t(($) => $.workspace.management.title)}+ description={t(($) => $.workspace.management.description)}+ >+ <SettingsCard>+ <SettingsRow+ label={t(($) => $.workspace.management.portal)}+ description={+ portalUnavailable+ ? t(($) => $.workspace.management.portal_unavailable)+ : t(($) => $.workspace.management.portal_description)+ }+ >+ {!portalUnavailable ? (+ <Button+ className="h-11 w-full sm:w-auto"+ disabled={isMutating}+ onClick={() => void handlePortal()}+ >+ {portalMutation.isPending ? (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ ) : (+ <ExternalLink />+ )}+ {t(($) => $.workspace.actions.manage)}+ </Button>+ ) : null}+ </SettingsRow>+ </SettingsCard>+ </SettingsSection>+ ) : null}++ <SettingsSection+ title={t(($) => $.workspace.limits.title)}+ description={t(($) => $.workspace.limits.description)}+ >+ <SettingsCard>+ <SettingsRow+ label={t(($) => $.workspace.limits.issues)}+ description={t(($) => $.workspace.limits.issues_description)}+ >+ <span className="tabular-nums">+ {entitlements.issueWindow === null+ ? t(($) => $.workspace.limits.unlimited)+ : new Intl.NumberFormat(locale).format(+ entitlements.issueWindow,+ )}+ </span>+ </SettingsRow>+ <SettingsRow+ label={t(($) => $.workspace.limits.autopilots)}+ description={t(($) => $.workspace.limits.autopilots_description)}+ >+ <span className="tabular-nums">+ {entitlements.autopilotRuns === null+ ? t(($) => $.workspace.limits.unlimited)+ : t(($) => $.workspace.limits.per_month, {+ count: entitlements.autopilotRuns,+ })}+ </span>+ </SettingsRow>+ </SettingsCard>+ </SettingsSection>++ <SettingsSection+ title={t(($) => $.workspace.seats.title)}+ description={t(($) => $.workspace.seats.description)}+ >+ {reconcileMessage ? (+ <Alert className="mb-3">+ <CheckCircle2 />+ <AlertTitle>{t(($) => $.workspace.seats.updated)}</AlertTitle>+ <AlertDescription>{reconcileMessage}</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.current.member_count, {+ count: entitlements.seats,+ })}+ </span>+ {canManage && hasManagedSubscription ? (+ <Button+ className="h-11 w-full sm:w-auto"+ variant="outline"+ disabled={isMutating}+ onClick={() => void handleReconcile()}+ >+ {reconcileMutation.isPending ? (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ ) : (+ <RefreshCw />+ )}+ {t(($) => $.workspace.actions.refresh_seats)}+ </Button>+ ) : null}+ </div>+ </SettingsRow>+ </SettingsCard>+ </SettingsSection>++ <AlertDialog+ open={checkoutConfirmOpen}+ onOpenChange={handleCheckoutConfirmOpenChange}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t(($) => $.workspace.confirm.title)}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $.workspace.confirm.description, {+ interval:+ interval === "month"+ ? t(($) => $.workspace.upgrade.monthly)+ : t(($) => $.workspace.upgrade.yearly),+ count: entitlements.seats,+ })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel+ className="h-11"+ disabled={checkoutMutation.isPending}+ >+ {t(($) => $.workspace.actions.cancel)}+ </AlertDialogCancel>+ <AlertDialogAction+ className="h-11"+ disabled={checkoutMutation.isPending}+ onClick={() => void handleCheckout()}+ >+ {checkoutMutation.isPending ? (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ ) : (+ <ExternalLink />+ )}+ {t(($) => $.workspace.actions.continue_to_stripe)}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </SettingsTab>+ );+}diff --git a/packages/views/settings/components/index.ts b/packages/views/settings/components/index.tsindex 94cd6705df..718f5a01b4 100644--- a/packages/views/settings/components/index.ts+++ b/packages/views/settings/components/index.ts@@ -2,3 +2,4 @@ export { SettingsPage } from "./settings-page";export type { ExtraSettingsTab } from "./settings-page";export { PluginsTab } from "./plugins-tab";export { LabelsTab } from "./labels-tab";+export { BillingTab } from "./billing-tab";diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsxindex 02fec2f7b3..cfd6d2162d 100644--- a/packages/views/settings/components/settings-page.test.tsx+++ b/packages/views/settings/components/settings-page.test.tsx@@ -3,7 +3,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";import { configStore } from "@multica/core/config";-import { PLUGINS_V1_FLAG } from "@multica/core/feature-flags";+import {+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,+ PLUGINS_V1_FLAG,+} from "@multica/core/feature-flags";import { renderWithI18n } from "../../test/i18n";// This file tests the settings SHELL — the chrome around the tabs — so every@@ -28,6 +31,7 @@ vi.mock("./properties-tab", stub("PropertiesTab"));vi.mock("./quick-actions-tab", stub("QuickActionsTab"));vi.mock("./keyboard-shortcuts-tab", stub("KeyboardShortcutsTab"));vi.mock("./plugins-tab", stub("PluginsTab"));+vi.mock("./billing-tab", stub("BillingTab"));vi.mock("@multica/core/paths", () => ({useCurrentWorkspace: () => ({ name: "Acme" }),@@ -133,3 +137,29 @@ describe("SettingsPage Plugin feature flag", () => {expect(screen.getByText("PluginsTab")).toBeInTheDocument();});});++describe("SettingsPage workspace subscription feature flag", () => {+ it("hides Billing and falls back to Workspace General from a direct URL", () => {+ navigationState.search = "tab=billing";++ renderWithI18n(<SettingsPage />);++ expect(+ screen.queryByRole("tab", { name: "Billing" }),+ ).not.toBeInTheDocument();+ expect(screen.queryByText("BillingTab")).not.toBeInTheDocument();+ expect(screen.getByText("WorkspaceTab")).toBeInTheDocument();+ });++ it("shows and mounts Billing only when explicitly enabled", () => {+ navigationState.search = "tab=billing";+ configStore.getState().setFeatureFlags({+ [BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG]: true,+ });++ renderWithI18n(<SettingsPage />);++ expect(screen.getByRole("tab", { name: "Billing" })).toBeInTheDocument();+ expect(screen.getByText("BillingTab")).toBeInTheDocument();+ });+});diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsxindex a59048d021..dc5b5c063d 100644--- a/packages/views/settings/components/settings-page.tsx+++ b/packages/views/settings/components/settings-page.tsx@@ -17,13 +17,17 @@ import {ListTodo,Zap,Blocks,+ CreditCard,} from "lucide-react";import { GitHubMark } from "./github-mark";import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";import { useIsMobile } from "@multica/ui/hooks/use-mobile";import { useCurrentWorkspace } from "@multica/core/paths";import { useFeatureEnabled } from "@multica/core/config";-import { PLUGINS_V1_FLAG } from "@multica/core/feature-flags";+import {+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,+ PLUGINS_V1_FLAG,+} from "@multica/core/feature-flags";import { useNavigation } from "../../navigation";import { AccountTab } from "./account-tab";import { PreferencesTab } from "./preferences-tab";@@ -42,6 +46,7 @@ import { PropertiesTab } from "./properties-tab";import { QuickActionsTab } from "./quick-actions-tab";import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";import { PluginsTab } from "./plugins-tab";+import { BillingTab } from "./billing-tab";import { CollapsedNavTrigger } from "../../layout/page-header";import { useT } from "../../i18n";@@ -63,6 +68,7 @@ const WORKSPACE_TAB_KEYS = ["integrations","labs","members",+ "billing","labels","properties","quick_actions",@@ -75,6 +81,7 @@ const WORKSPACE_TAB_VALUES = {integrations: "integrations",labs: "labs",members: "members",+ billing: "billing",labels: "labels",properties: "properties",quick_actions: "quick-actions",@@ -87,6 +94,7 @@ const WORKSPACE_TAB_ICONS = {integrations: Plug,labs: FlaskConical,members: Users,+ billing: CreditCard,labels: Tags,properties: SlidersHorizontal,quick_actions: Zap,@@ -125,10 +133,19 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {const navigation = useNavigation();const isMobile = useIsMobile();const pluginsEnabled = useFeatureEnabled(PLUGINS_V1_FLAG, false);+ const billingEnabled = useFeatureEnabled(+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,+ false,+ );const visibleWorkspaceTabKeys = React.useMemo(- () => WORKSPACE_TAB_KEYS.filter((key) => key !== "plugins" || pluginsEnabled),- [pluginsEnabled],+ () =>+ WORKSPACE_TAB_KEYS.filter(+ (key) =>+ (key !== "plugins" || pluginsEnabled) &&+ (key !== "billing" || billingEnabled),+ ),+ [billingEnabled, pluginsEnabled],);// Whitelist of valid tab values; unknown ?tab=… values silently fall back to@@ -146,7 +163,9 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {const tabFromUrl = navigation.searchParams.get(TAB_QUERY_KEY);const candidateTab = tabFromUrl- ? LEGACY_WORKSPACE_TAB_REDIRECTS[tabFromUrl] ?? tabFromUrl+ ? tabFromUrl === "billing" && !billingEnabled+ ? "workspace"+ : LEGACY_WORKSPACE_TAB_REDIRECTS[tabFromUrl] ?? tabFromUrl: null;const activeTab =candidateTab && validTabs.has(candidateTab) ? candidateTab : DEFAULT_TAB;@@ -251,6 +270,9 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {<TabsContent value="integrations"><IntegrationsTab /></TabsContent><TabsContent value="labs"><LabsTab /></TabsContent><TabsContent value="members"><MembersTab /></TabsContent>+ {billingEnabled ? (+ <TabsContent value="billing"><BillingTab /></TabsContent>+ ) : null}<TabsContent value="labels"><LabelsTab /></TabsContent><TabsContent value="properties"><PropertiesTab /></TabsContent><TabsContent value="quick-actions"><QuickActionsTab /></TabsContent>