Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6344: Show billing summary and autopilot quota usage (#7218)
Multica Eve722bde9d1818
diff --git a/packages/core/autopilots/index.ts b/packages/core/autopilots/index.tsindex f720976715..9feefdc3c9 100644--- a/packages/core/autopilots/index.ts+++ b/packages/core/autopilots/index.ts@@ -1,5 +1,6 @@export {autopilotKeys,+ autopilotQuotaUsageOptions,autopilotListOptions,autopilotDetailOptions,autopilotRunsOptions,diff --git a/packages/core/autopilots/queries.ts b/packages/core/autopilots/queries.tsindex c3fb139dd4..c2277c3b05 100644--- a/packages/core/autopilots/queries.ts+++ b/packages/core/autopilots/queries.ts@@ -3,6 +3,7 @@ import { api } from "../api";export const autopilotKeys = {all: (wsId: string) => ["autopilots", wsId] as const,+ usage: (wsId: string) => [...autopilotKeys.all(wsId), "usage"] as const,list: (wsId: string) => [...autopilotKeys.all(wsId), "list"] as const,detail: (wsId: string, id: string) =>[...autopilotKeys.all(wsId), "detail", id] as const,@@ -18,6 +19,16 @@ export const autopilotKeys = {[...autopilotKeys.all(wsId), "cron-preview", expr, tz] as const,};+export function autopilotQuotaUsageOptions(wsId: string) {+ return queryOptions({+ queryKey: autopilotKeys.usage(wsId),+ queryFn: () => api.getAutopilotQuotaUsage(),+ enabled: wsId.length > 0,+ staleTime: 30_000,+ refetchOnWindowFocus: true,+ });+}+export function autopilotListOptions(wsId: string) {return queryOptions({queryKey: autopilotKeys.list(wsId),diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex cd40346c0c..4b5eabf32d 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -81,6 +81,10 @@"trialing": "Trialing","past_due": "Past due","canceled": "Canceled",+ "incomplete": "Incomplete",+ "incomplete_expired": "Setup expired",+ "paused": "Paused",+ "unpaid": "Unpaid","unknown": "Unknown status"},"load_failed": {@@ -89,6 +93,7 @@},"actions": {"retry": "Retry",+ "retry_autopilots": "Retry automation usage","upgrade": "Upgrade to Pro","manage": "Manage billing","refresh_seats": "Refresh seats",@@ -121,7 +126,23 @@},"past_due": {"title": "Payment needs attention",- "description": "Open the Billing Portal to update your payment method and keep Pro access."+ "description": "Open the Billing Portal to update your payment method. The plan badge above shows the access currently available.",+ "grace_description": "Update your payment method by {{date}} to keep Pro access."+ },+ "subscription_notice": {+ "canceling_title": "Cancellation is scheduled",+ "canceling_description": "This subscription is scheduled to cancel on {{date}}. The plan badge above shows the access currently enforced.",+ "canceling_description_without_date": "This subscription is scheduled to cancel at the end of its current period.",+ "incomplete_title": "Subscription setup is incomplete",+ "incomplete_description": "Open billing management to finish or review the payment setup.",+ "incomplete_expired_title": "Subscription setup expired",+ "incomplete_expired_description": "The previous payment setup expired without activating Pro. Start a new upgrade when ready.",+ "paused_title": "Subscription is paused",+ "paused_description": "Open billing management to review the pause and available recovery options.",+ "unpaid_title": "Subscription is unpaid",+ "unpaid_description": "Open billing management to resolve the unpaid balance.",+ "canceled_title": "Subscription is canceled",+ "canceled_description": "The entitlement badge above shows the plan currently enforced for this workspace."},"read_only": {"title": "Read-only billing access",@@ -135,6 +156,8 @@"members_description": "Agents and pending invitations are not counted as seats.","member_count_one": "{{count}} member","member_count_other": "{{count}} members",+ "billing_interval": "Billing interval",+ "billing_interval_description": "The interval stored for the active subscription.","period_end": "Current period ends","period_end_description": "The date reported by the current subscription snapshot."},@@ -161,19 +184,42 @@},"limits": {"title": "Usage and limits",- "description": "Current limits are shown without inventing usage totals the server does not provide yet.",+ "description": "Limits come from the current entitlement. Automation usage comes from server quota accounting.","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"+ "unavailable": "Unavailable",+ "per_month": "{{count}} / month",+ "usage_loading": "Loading automation usage",+ "usage_label": "Automation quota usage",+ "current_usage": "Current usage",+ "reached": "Limit reached",+ "usage_total": "{{total}} / {{limit}}",+ "usage_breakdown": "{{used}} completed · {{reserved}} in progress",+ "resets_at": "Resets {{date}}",+ "usage_unavailable": "Usage is temporarily unavailable"},"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.",+ "pending": "Scheduled seat quantity",+ "pending_description": "A lower quantity that cloud billing reports for the next period.",+ "seat_count_one": "{{count}} seat",+ "seat_count_other": "{{count}} seats",+ "pending_with_date_one": "{{count}} seat from {{date}}",+ "pending_with_date_other": "{{count}} seats from {{date}}",+ "none_pending": "No scheduled change",+ "not_subscribed": "No active subscription",+ "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.","updated": "Seats refreshed","reconciled": "Current members: {{actual}} · billed seats: {{billed}}"},diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex b573eb66dd..92bd2f2806 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -81,6 +81,10 @@"trialing": "トライアル中","past_due": "支払い遅延","canceled": "キャンセル済み",+ "incomplete": "未完了",+ "incomplete_expired": "設定期限切れ",+ "paused": "一時停止中",+ "unpaid": "未払い","unknown": "不明なステータス"},"load_failed": {@@ -89,6 +93,7 @@},"actions": {"retry": "再試行",+ "retry_autopilots": "自動化の使用量を再取得","upgrade": "Pro にアップグレード","manage": "請求を管理","refresh_seats": "席数を更新",@@ -121,7 +126,23 @@},"past_due": {"title": "お支払い方法の確認が必要です",- "description": "Pro を継続するには Billing Portal でお支払い方法を更新してください。"+ "description": "Billing Portal でお支払い方法を更新してください。上のプランバッジには現在利用できるアクセス権が表示されます。",+ "grace_description": "Pro を継続するには {{date}} までにお支払い方法を更新してください。"+ },+ "subscription_notice": {+ "canceling_title": "キャンセルが予定されています",+ "canceling_description": "このサブスクリプションは {{date}} にキャンセルされる予定です。上のプランバッジには現在適用中のアクセス権が表示されます。",+ "canceling_description_without_date": "このサブスクリプションは現在の期間終了時にキャンセルされる予定です。",+ "incomplete_title": "サブスクリプション設定が未完了です",+ "incomplete_description": "請求管理を開き、お支払い設定を完了または確認してください。",+ "incomplete_expired_title": "サブスクリプション設定の期限が切れました",+ "incomplete_expired_description": "以前のお支払い設定は Pro を有効化せず期限切れになりました。必要なときに再度アップグレードしてください。",+ "paused_title": "サブスクリプションは一時停止中です",+ "paused_description": "請求管理を開き、一時停止と再開方法を確認してください。",+ "unpaid_title": "サブスクリプションは未払いです",+ "unpaid_description": "請求管理を開き、未払い残高を解消してください。",+ "canceled_title": "サブスクリプションはキャンセル済みです",+ "canceled_description": "上のプランバッジは、このワークスペースに現在適用されているプランを示します。"},"read_only": {"title": "請求情報の閲覧のみ",@@ -134,6 +155,8 @@"members": "ユーザー席","members_description": "エージェントと保留中の招待は席数に含まれません。","member_count_other": "{{count}}名",+ "billing_interval": "請求期間",+ "billing_interval_description": "有効なサブスクリプションに保存されている請求期間です。","period_end": "現在の期間終了日","period_end_description": "現在のサブスクリプション情報で報告された日付です。"},@@ -159,19 +182,40 @@},"limits": {"title": "使用量と上限",- "description": "サーバーがまだ提供していない使用済み件数を 0 とせず、現在の上限のみ表示します。",+ "description": "上限は現在の entitlement、自動化の使用量はサーバーのクォータ集計に基づきます。","issues": "最近のタスク","issues_description": "Free では最近アクティブなタスクを利用できます。Pro には件数制限がありません。","autopilots": "成功した自動化","autopilots_description": "Free の上限は UTC の暦月ごとにリセットされます。Pro は無制限です。","unlimited": "無制限",- "per_month": "月 {{count}} 回"+ "unavailable": "利用できません",+ "per_month": "月 {{count}} 回",+ "usage_loading": "自動化の使用量を読み込み中",+ "usage_label": "自動化クォータの使用量",+ "current_usage": "現在の使用量",+ "reached": "上限に達しました",+ "usage_total": "{{total}} / {{limit}}",+ "usage_breakdown": "完了 {{used}} · 実行中 {{reserved}}",+ "resets_at": "{{date}} にリセット",+ "usage_unavailable": "使用量は一時的に利用できません"},"seats": {"title": "席数","description": "現在のユーザーメンバーはそれぞれ Pro の 1 席として数えられます。エージェントと保留中の招待は含まれません。","human_members": "現在のユーザーメンバー","human_members_description": "メンバー変更後に更新すると、Cloud Billing が Stripe の quantity を照合します。",+ "billed": "請求席数",+ "billed_description": "Stripe 請求に現在保存されている席数です。",+ "pending": "変更予定の席数",+ "pending_description": "Cloud Billing が次の期間に対して報告した、より少ない席数です。",+ "seat_count_other": "{{count}}席",+ "pending_with_date_other": "{{date}} から {{count}}席",+ "none_pending": "予定された変更はありません",+ "not_subscribed": "有効なサブスクリプションはありません",+ "unavailable": "利用できません",+ "summary_loading": "サブスクリプションの席数詳細を読み込み中",+ "summary_unavailable_title": "一部の席数詳細を利用できません",+ "summary_unavailable_description": "現在のプランは表示できますが、請求席数と変更予定の席数を読み込めませんでした。","updated": "席数を更新しました","reconciled": "現在のメンバー: {{actual}} · 請求席数: {{billed}}"},diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 9cd2db22d8..c3fd89f3af 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -81,6 +81,10 @@"trialing": "체험 중","past_due": "결제 연체","canceled": "취소됨",+ "incomplete": "미완료",+ "incomplete_expired": "설정 만료",+ "paused": "일시 중지됨",+ "unpaid": "미결제","unknown": "알 수 없는 상태"},"load_failed": {@@ -89,6 +93,7 @@},"actions": {"retry": "다시 시도",+ "retry_autopilots": "자동화 사용량 다시 시도","upgrade": "Pro로 업그레이드","manage": "결제 관리","refresh_seats": "좌석 새로고침",@@ -121,7 +126,23 @@},"past_due": {"title": "결제 정보를 확인해야 합니다",- "description": "Pro 이용을 유지하려면 Billing Portal에서 결제 수단을 업데이트하세요."+ "description": "Billing Portal에서 결제 수단을 업데이트하세요. 위의 요금제 배지는 현재 이용 가능한 액세스를 표시합니다.",+ "grace_description": "Pro 이용을 유지하려면 {{date}}까지 결제 수단을 업데이트하세요."+ },+ "subscription_notice": {+ "canceling_title": "구독 취소가 예정되어 있습니다",+ "canceling_description": "이 구독은 {{date}}에 취소될 예정입니다. 위의 플랜 배지는 현재 적용 중인 액세스를 표시합니다.",+ "canceling_description_without_date": "이 구독은 현재 결제 기간 종료 시 취소될 예정입니다.",+ "incomplete_title": "구독 설정이 완료되지 않았습니다",+ "incomplete_description": "결제 관리를 열어 결제 설정을 완료하거나 확인하세요.",+ "incomplete_expired_title": "구독 설정이 만료되었습니다",+ "incomplete_expired_description": "이전 결제 설정은 Pro를 활성화하지 못한 채 만료되었습니다. 필요할 때 다시 업그레이드하세요.",+ "paused_title": "구독이 일시 중지되었습니다",+ "paused_description": "결제 관리를 열어 일시 중지 상태와 복구 방법을 확인하세요.",+ "unpaid_title": "구독이 미결제 상태입니다",+ "unpaid_description": "결제 관리를 열어 미결제 잔액을 해결하세요.",+ "canceled_title": "구독이 취소되었습니다",+ "canceled_description": "위 요금제 배지는 이 워크스페이스에 현재 적용되는 요금제를 보여 줍니다."},"read_only": {"title": "결제 정보 읽기 전용",@@ -134,6 +155,8 @@"members": "사용자 좌석","members_description": "에이전트와 대기 중인 초대는 좌석에 포함되지 않습니다.","member_count_other": "멤버 {{count}}명",+ "billing_interval": "결제 주기",+ "billing_interval_description": "활성 구독에 저장된 결제 주기입니다.","period_end": "현재 결제 기간 종료일","period_end_description": "현재 구독 정보에 보고된 날짜입니다."},@@ -159,19 +182,40 @@},"limits": {"title": "사용량 및 한도",- "description": "서버가 아직 제공하지 않는 사용량을 0으로 표시하지 않고 현재 한도만 보여 줍니다.",+ "description": "한도는 현재 entitlement에서, 자동화 사용량은 서버 쿼터 집계에서 가져옵니다.","issues": "최근 태스크","issues_description": "Free에서는 최근 활성 태스크를 이용할 수 있습니다. Pro에는 범위 제한이 없습니다.","autopilots": "성공한 자동화","autopilots_description": "Free 한도는 UTC 기준 매월 초기화됩니다. Pro는 무제한입니다.","unlimited": "무제한",- "per_month": "월 {{count}}회"+ "unavailable": "사용할 수 없음",+ "per_month": "월 {{count}}회",+ "usage_loading": "자동화 사용량 불러오는 중",+ "usage_label": "자동화 쿼터 사용량",+ "current_usage": "현재 사용량",+ "reached": "한도 도달",+ "usage_total": "{{total}} / {{limit}}",+ "usage_breakdown": "완료 {{used}} · 진행 중 {{reserved}}",+ "resets_at": "{{date}}에 초기화",+ "usage_unavailable": "사용량을 일시적으로 불러올 수 없습니다"},"seats": {"title": "좌석","description": "현재 사용자 멤버 한 명당 Pro 좌석 하나로 계산됩니다. 에이전트와 대기 중인 초대는 포함되지 않습니다.","human_members": "현재 사용자 멤버","human_members_description": "멤버 변경 후 새로고침하면 Cloud Billing이 Stripe quantity를 조정합니다.",+ "billed": "결제 좌석",+ "billed_description": "Stripe 결제에 현재 저장된 좌석 수입니다.",+ "pending": "예정 좌석 수",+ "pending_description": "Cloud Billing이 다음 결제 기간에 대해 보고한 더 적은 좌석 수입니다.",+ "seat_count_other": "좌석 {{count}}개",+ "pending_with_date_other": "{{date}}부터 좌석 {{count}}개",+ "none_pending": "예정된 변경 없음",+ "not_subscribed": "활성 구독 없음",+ "unavailable": "사용할 수 없음",+ "summary_loading": "구독 좌석 상세 정보 불러오는 중",+ "summary_unavailable_title": "일부 좌석 상세 정보를 불러올 수 없습니다",+ "summary_unavailable_description": "현재 요금제는 계속 표시되지만 결제 좌석과 예정 좌석 수를 불러오지 못했습니다.","updated": "좌석 새로고침됨","reconciled": "현재 멤버: {{actual}} · 결제 좌석: {{billed}}"},diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex d040ed3253..1f4e964f43 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -81,6 +81,10 @@"trialing": "试用中","past_due": "付款逾期","canceled": "已取消",+ "incomplete": "未完成",+ "incomplete_expired": "开通已过期",+ "paused": "已暂停",+ "unpaid": "未付款","unknown": "未知状态"},"load_failed": {@@ -89,6 +93,7 @@},"actions": {"retry": "重试",+ "retry_autopilots": "重试加载自动化用量","upgrade": "升级到 Pro","manage": "管理账单","refresh_seats": "刷新席位",@@ -121,7 +126,23 @@},"past_due": {"title": "付款信息需要处理",- "description": "打开 Billing Portal 更新付款方式,以继续使用 Pro。"+ "description": "打开 Billing Portal 更新付款方式。上方的套餐徽章显示当前可用权限。",+ "grace_description": "请在 {{date}} 前更新付款方式,以继续使用 Pro。"+ },+ "subscription_notice": {+ "canceling_title": "订阅已安排取消",+ "canceling_description": "此订阅计划于 {{date}} 取消。上方的套餐徽章显示当前实际生效的权限。",+ "canceling_description_without_date": "这个订阅将在当前周期结束时取消。",+ "incomplete_title": "订阅开通尚未完成",+ "incomplete_description": "打开账单管理,完成或检查付款设置。",+ "incomplete_expired_title": "订阅开通已过期",+ "incomplete_expired_description": "上一次付款设置未能启用 Pro 且已过期,需要时请重新发起升级。",+ "paused_title": "订阅已暂停",+ "paused_description": "打开账单管理,查看暂停原因和可用的恢复方式。",+ "unpaid_title": "订阅款项尚未支付",+ "unpaid_description": "打开账单管理处理未支付款项。",+ "canceled_title": "订阅已取消",+ "canceled_description": "上方套餐徽标显示这个工作区当前实际生效的套餐。"},"read_only": {"title": "账单只读权限",@@ -134,6 +155,8 @@"members": "成员席位","members_description": "智能体和待接受的邀请不计入席位。","member_count_other": "{{count}} 位成员",+ "billing_interval": "付款周期",+ "billing_interval_description": "当前订阅保存的付款周期。","period_end": "当前周期结束时间","period_end_description": "当前订阅快照报告的日期。"},@@ -159,19 +182,40 @@},"limits": {"title": "用量与限额",- "description": "这里仅显示当前套餐限额,不会把服务端尚未提供的已用量伪装成 0。",+ "description": "限额来自当前 entitlement,自动化用量来自服务端额度统计。","issues": "最近活跃的任务","issues_description": "Free 可访问最近活跃的任务;Pro 没有窗口限制。","autopilots": "成功的自动化执行","autopilots_description": "Free 限额按 UTC 自然月重置;Pro 不限次数。","unlimited": "不限",- "per_month": "每月 {{count}} 次"+ "unavailable": "暂不可用",+ "per_month": "每月 {{count}} 次",+ "usage_loading": "正在加载自动化用量",+ "usage_label": "自动化额度用量",+ "current_usage": "当前用量",+ "reached": "已达到限额",+ "usage_total": "{{total}} / {{limit}}",+ "usage_breakdown": "已完成 {{used}} · 进行中 {{reserved}}",+ "resets_at": "{{date}} 重置",+ "usage_unavailable": "用量暂时不可用"},"seats": {"title": "席位","description": "每位当前成员都会计为一个 Pro 席位,智能体和待接受的邀请不计。","human_members": "当前成员","human_members_description": "成员变化后刷新,通知 Cloud Billing 对账 Stripe quantity。",+ "billed": "计费席位",+ "billed_description": "Stripe 账单当前保存的席位数量。",+ "pending": "待生效席位",+ "pending_description": "Cloud Billing 报告的下一周期较低席位数量。",+ "seat_count_other": "{{count}} 个席位",+ "pending_with_date_other": "{{date}} 起 {{count}} 个席位",+ "none_pending": "没有待生效变更",+ "not_subscribed": "没有有效订阅",+ "unavailable": "不可用",+ "summary_loading": "正在加载订阅席位详情",+ "summary_unavailable_title": "部分席位详情不可用",+ "summary_unavailable_description": "当前套餐仍会显示,但暂时无法加载计费席位和待生效席位。","updated": "席位已刷新","reconciled": "当前成员:{{actual}} · 计费席位:{{billed}}"},diff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.tsnew file mode 100644index 0000000000..c1dc9a18d8--- /dev/null+++ b/packages/views/settings/components/billing-state.test.ts@@ -0,0 +1,174 @@+// @vitest-environment node++import { describe, expect, it } from "vitest";+import type {+ AutopilotQuotaUsage,+ WorkspaceSubscriptionEntitlements,+ WorkspaceSubscriptionSummary,+} from "@multica/core/types";+import {+ canPurchaseWorkspaceSubscription,+ hasManagedWorkspaceSubscription,+ resolveAutopilotUsage,+} from "./billing-state";++const freeEntitlements: WorkspaceSubscriptionEntitlements = {+ workspaceId: "workspace-1",+ plan: "free",+ status: "inactive",+ seats: 3,+ issueWindow: 17,+ autopilotRuns: 7,+ currentPeriodEnd: null,+ snapshotExpiresAt: null,+ version: 1,+};++const quotaUsage: AutopilotQuotaUsage = {+ action: "enforce",+ used: 3,+ reserved: 2,+ limit: 7,+ period_start: "2030-01-01T00:00:00Z",+ period_end: "2030-02-01T00:00:00Z",+ reset_at: "2030-02-01T00:00:00Z",+ blocked_counts: {},+};++describe("resolveAutopilotUsage", () => {+ it("counts reserved runs toward progress and the reached decision", () => {+ expect(+ resolveAutopilotUsage(freeEntitlements, quotaUsage, false, false),+ ).toEqual({+ kind: "metered",+ used: 3,+ reserved: 2,+ total: 5,+ limit: 7,+ progress: 500 / 7,+ reached: false,+ resetAt: "2030-02-01T00:00:00Z",+ });++ expect(+ resolveAutopilotUsage(+ freeEntitlements,+ { ...quotaUsage, used: 5 },+ false,+ false,+ ),+ ).toMatchObject({ total: 7, reached: true, progress: 100 });+ });++ it("shows Pro as unlimited from entitlement even when usage is unavailable", () => {+ expect(+ resolveAutopilotUsage(+ { ...freeEntitlements, plan: "pro", autopilotRuns: null },+ undefined,+ true,+ true,+ ),+ ).toEqual({ kind: "unlimited" });+ });++ it("does not turn missing or disabled limited usage into zero or unlimited", () => {+ expect(+ resolveAutopilotUsage(freeEntitlements, undefined, true, false),+ ).toEqual({ kind: "unavailable" });+ expect(+ resolveAutopilotUsage(+ freeEntitlements,+ {+ ...quotaUsage,+ action: "off",+ used: null,+ reserved: null,+ limit: null,+ reset_at: null,+ },+ false,+ false,+ ),+ ).toEqual({ kind: "unavailable" });+ });++ it("keeps authoritative metered usage independent of entitlement unlimited", () => {+ expect(+ resolveAutopilotUsage(+ { ...freeEntitlements, plan: "pro", autopilotRuns: null },+ quotaUsage,+ false,+ false,+ ),+ ).toMatchObject({ kind: "metered", total: 5, limit: 7 });+ });++ it("does not derive unlimited when the entitlement fact is not trusted", () => {+ expect(+ resolveAutopilotUsage(+ { ...freeEntitlements, plan: "pro", autopilotRuns: null },+ undefined,+ true,+ false,+ ),+ ).toEqual({ kind: "unavailable" });+ });+});++describe("billing subscription state", () => {+ it("prefers subscription facts and keeps safe compatibility fallbacks", () => {+ const summary = {+ entitlement: freeEntitlements,+ billingInterval: null,+ actualSeats: 3,+ billedSeats: null,+ pendingSeatQuantity: null,+ cancelAtPeriodEnd: false,+ graceUntil: null,+ hasStripeCustomer: true,+ } satisfies WorkspaceSubscriptionSummary;++ expect(hasManagedWorkspaceSubscription(freeEntitlements, summary)).toBe(+ true,+ );+ expect(+ hasManagedWorkspaceSubscription(+ { ...freeEntitlements, status: "incomplete_expired" },+ undefined,+ ),+ ).toBe(true);+ expect(hasManagedWorkspaceSubscription(freeEntitlements, undefined)).toBe(+ false,+ );+ });++ it.each([+ ["inactive", true],+ ["canceled", true],+ ["incomplete_expired", true],+ ["active", false],+ ["trialing", false],+ ["past_due", false],+ ["incomplete", false],+ ["paused", false],+ ["unpaid", false],+ ["future_status", false],+ ])("allows a Free workspace in %s to purchase: %s", (status, expected) => {+ expect(+ canPurchaseWorkspaceSubscription({+ ...freeEntitlements,+ status,+ }),+ ).toBe(expected);+ });++ it("never offers Checkout while Pro is currently enforced", () => {+ expect(+ canPurchaseWorkspaceSubscription({+ ...freeEntitlements,+ plan: "pro",+ status: "active",+ }),+ ).toBe(false);+ });+});diff --git a/packages/views/settings/components/billing-state.ts b/packages/views/settings/components/billing-state.tsnew file mode 100644index 0000000000..8838f01469--- /dev/null+++ b/packages/views/settings/components/billing-state.ts@@ -0,0 +1,123 @@+import type {+ AutopilotQuotaUsage,+ WorkspaceSubscriptionEntitlements,+ WorkspaceSubscriptionSummary,+} from "@multica/core/types";++export type AutopilotUsageView =+ | { kind: "unlimited" }+ | { kind: "unavailable" }+ | {+ kind: "metered";+ used: number;+ reserved: number;+ total: number;+ limit: number;+ progress: number;+ reached: boolean;+ resetAt: string;+ };++/**+ * Quota admission counts completed and reserved runs. Keep reserved work+ * visible so the progress bar matches the server's blocking decision. A+ * complete metered response is authoritative independently of entitlement+ * state; only the unlimited fallback comes from the entitlement response.+ */+export function resolveAutopilotUsage(+ entitlements: WorkspaceSubscriptionEntitlements,+ usage: AutopilotQuotaUsage | undefined,+ failed: boolean,+ allowEntitlementUnlimited: boolean,+): AutopilotUsageView {+ if (!failed && usage !== undefined && usage.action !== "off") {+ const { used, reserved, limit, reset_at: resetAt } = usage;+ if (+ used !== null &&+ reserved !== null &&+ limit !== null &&+ resetAt !== null &&+ used >= 0 &&+ reserved >= 0 &&+ limit >= 0 &&+ Number.isFinite(used) &&+ Number.isFinite(reserved) &&+ Number.isFinite(limit)+ ) {+ const total = used + reserved;+ const reached = total >= limit;+ const progress =+ limit === 0+ ? 100+ : Math.min(100, Math.max(0, (total / limit) * 100));++ return {+ kind: "metered",+ used,+ reserved,+ total,+ limit,+ progress,+ reached,+ resetAt,+ };+ }+ }++ if (+ allowEntitlementUnlimited &&+ entitlements.plan === "pro" &&+ entitlements.autopilotRuns === null+ ) {+ return { kind: "unlimited" };+ }++ return { kind: "unavailable" };+}++const MANAGED_SUBSCRIPTION_STATUSES = new Set([+ "active",+ "trialing",+ "past_due",+ "canceled",+ "incomplete",+ "incomplete_expired",+ "paused",+ "unpaid",+]);++const PURCHASABLE_SUBSCRIPTION_STATUSES = new Set([+ "inactive",+ "canceled",+ "incomplete_expired",+]);++/**+ * Summary facts are primary. Plan and status are compatibility fallbacks so+ * an older or temporarily unavailable summary does not hide the recovery UI.+ */+export function hasManagedWorkspaceSubscription(+ entitlements: WorkspaceSubscriptionEntitlements,+ summary: WorkspaceSubscriptionSummary | null | undefined,+): boolean {+ return (+ summary?.hasStripeCustomer === true ||+ summary?.billedSeats !== null && summary?.billedSeats !== undefined ||+ entitlements.plan === "pro" ||+ MANAGED_SUBSCRIPTION_STATUSES.has(entitlements.status)+ );+}++/**+ * Checkout creates a new subscription. Cloud accepts an existing record only+ * after cancellation or incomplete setup expiry; every other known status may+ * still represent a live or recoverable subscription and stays in Portal.+ */+export function canPurchaseWorkspaceSubscription(+ entitlements: WorkspaceSubscriptionEntitlements,+): boolean {+ return (+ entitlements.plan === "free" &&+ PURCHASABLE_SUBSCRIPTION_STATUSES.has(entitlements.status)+ );+}diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex a2c949ba45..6a47cb8a87 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -12,6 +12,8 @@ const mocks = vi.hoisted(() => ({portal: vi.fn(),reconcile: vi.fn(),refetch: vi.fn(),+ refetchSummary: vi.fn(),+ refetchUsage: vi.fn(),refetchPrices: vi.fn(),openExternal: vi.fn(),role: "owner" as "owner" | "admin" | "member",@@ -33,17 +35,46 @@ const mocks = vi.hoisted(() => ({pricesLoading: false,pricesFetching: false,pricesError: false,+ summaryPending: false,+ summaryFetching: false,+ summaryError: false,+ summaryMalformed: false,+ usagePending: false,+ usageFetching: false,+ usageError: false,+ entitlementsDataUpdatedAt: 0,+ entitlementsFetchedAfterMount: false,entitlements: {workspaceId: "workspace-1",plan: "free",status: "inactive",seats: 3,- issueWindow: 1000,- autopilotRuns: 100,+ issueWindow: 17,+ autopilotRuns: 7,currentPeriodEnd: null as string | null,snapshotExpiresAt: null as string | null,version: 0,},+ summary: {+ entitlement: null as never,+ billingInterval: null as "month" | "year" | null,+ actualSeats: 3,+ billedSeats: null as number | null,+ pendingSeatQuantity: null as number | null,+ cancelAtPeriodEnd: false,+ graceUntil: null as string | null,+ hasStripeCustomer: false,+ },+ usage: {+ action: "enforce" as "off" | "observe" | "enforce",+ used: 3 as number | null,+ reserved: 2 as number | null,+ limit: 7 as number | null,+ period_start: "2030-01-01T00:00:00Z" as string | null,+ period_end: "2030-02-01T00:00:00Z" as string | null,+ reset_at: "2030-02-01T00:00:00Z" as string | null,+ blocked_counts: {} as Record<string, number> | null,+ },}));vi.mock("@tanstack/react-query", () => ({@@ -57,6 +88,9 @@ vi.mock("@multica/core/billing", () => ({workspaceSubscriptionPricesOptions: (wsId: string) => ({queryKey: ["workspace-subscriptions", wsId, "prices"],}),+ workspaceSubscriptionSummaryOptions: (wsId: string) => ({+ queryKey: ["workspace-subscriptions", wsId, "summary"],+ }),useCreateWorkspaceSubscriptionCheckout: () => ({mutateAsync: mocks.checkout,isPending: false,@@ -71,6 +105,12 @@ vi.mock("@multica/core/billing", () => ({}),}));+vi.mock("@multica/core/autopilots", () => ({+ autopilotQuotaUsageOptions: (wsId: string) => ({+ queryKey: ["autopilots", wsId, "usage"],+ }),+}));+vi.mock("@multica/core/paths", () => ({useCurrentWorkspace: () => ({id: mocks.workspaceId,@@ -125,16 +165,45 @@ describe("BillingTab", () => {mocks.pricesLoading = false;mocks.pricesFetching = false;mocks.pricesError = false;+ mocks.summaryPending = false;+ mocks.summaryFetching = false;+ mocks.summaryError = false;+ mocks.summaryMalformed = false;+ mocks.usagePending = false;+ mocks.usageFetching = false;+ mocks.usageError = false;+ mocks.entitlementsDataUpdatedAt = 0;+ mocks.entitlementsFetchedAfterMount = false;Object.assign(mocks.entitlements, {plan: "free",status: "inactive",seats: 3,- issueWindow: 1000,- autopilotRuns: 100,+ issueWindow: 17,+ autopilotRuns: 7,currentPeriodEnd: null,snapshotExpiresAt: null,version: 0,});+ Object.assign(mocks.summary, {+ entitlement: mocks.entitlements,+ billingInterval: null,+ actualSeats: 3,+ billedSeats: null,+ pendingSeatQuantity: null,+ cancelAtPeriodEnd: false,+ graceUntil: null,+ hasStripeCustomer: false,+ });+ Object.assign(mocks.usage, {+ action: "enforce",+ used: 3,+ reserved: 2,+ limit: 7,+ period_start: "2030-01-01T00:00:00Z",+ period_end: "2030-02-01T00:00:00Z",+ reset_at: "2030-02-01T00:00:00Z",+ blocked_counts: {},+ });mocks.useQuery.mockImplementation((options: unknown) => {const queryKey = (options as { queryKey?: readonly unknown[] }).queryKey;if (queryKey?.[queryKey.length - 1] === "prices") {@@ -146,8 +215,32 @@ describe("BillingTab", () => {refetch: mocks.refetchPrices,};}+ if (queryKey?.[queryKey.length - 1] === "summary") {+ return {+ data: mocks.summaryError+ ? undefined+ : mocks.summaryMalformed+ ? null+ : mocks.summary,+ isPending: mocks.summaryPending,+ isFetching: mocks.summaryFetching,+ isError: mocks.summaryError,+ refetch: mocks.refetchSummary,+ };+ }+ if (queryKey?.[queryKey.length - 1] === "usage") {+ return {+ data: mocks.usageError ? undefined : mocks.usage,+ isPending: mocks.usagePending,+ isFetching: mocks.usageFetching,+ isError: mocks.usageError,+ refetch: mocks.refetchUsage,+ };+ }return {data: mocks.entitlements,+ dataUpdatedAt: mocks.entitlementsDataUpdatedAt,+ isFetchedAfterMount: mocks.entitlementsFetchedAfterMount,isPending: false,isError: false,refetch: mocks.refetch,@@ -186,8 +279,9 @@ describe("BillingTab", () => {renderWithI18n(<BillingTab />);expect(screen.getByRole("heading", { name: "Billing" })).toBeInTheDocument();- expect(screen.getByText("1,000")).toBeInTheDocument();- expect(screen.getByText("100 / month")).toBeInTheDocument();+ expect(screen.getByText("17")).toBeInTheDocument();+ expect(screen.getByText("5 / 7")).toBeInTheDocument();+ expect(screen.getByText("3 completed · 2 in progress")).toBeInTheDocument();expect(screen.getByText("$10.00 per human seat")).toBeInTheDocument();expect(screen.getByText("Estimated monthly total: $30.00"),@@ -297,10 +391,21 @@ describe("BillingTab", () => {queryKey: ["workspace-subscriptions", "workspace-2", "prices"],}),);+ expect(mocks.useQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ queryKey: ["workspace-subscriptions", "workspace-2", "summary"],+ }),+ );+ expect(mocks.useQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ queryKey: ["autopilots", "workspace-2", "usage"],+ }),+ );});it("shows the unit price without a zero estimated total when seats are unavailable", () => {mocks.entitlements.seats = 0;+ mocks.summary.actualSeats = 0;renderWithI18n(<BillingTab />);@@ -457,6 +562,65 @@ describe("BillingTab", () => {}});+ it("keeps Checkout syncing until Pro is fetched after the return callback", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2030-01-01T00:00:00Z"));+ navigationState.search = "tab=billing&result=success&session_id=cs_test_1";+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ });+ mocks.entitlementsDataUpdatedAt = Date.now() - 1;+ mocks.entitlementsFetchedAfterMount = true;+ try {+ renderWithI18n(<BillingTab />);++ expect(+ screen.getByText("Activating your subscription"),+ ).toBeInTheDocument();+ expect(screen.queryByText("Pro is active")).not.toBeInTheDocument();+ expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();+ expect(screen.getByText("Unavailable")).toBeInTheDocument();+ expect(screen.getByText("5 / 7")).toBeInTheDocument();+ expect(mocks.useQuery).toHaveBeenCalledWith(+ expect.objectContaining({ refetchInterval: 2_000 }),+ );+ } finally {+ vi.useRealTimers();+ }+ });++ it("confirms Pro after an entitlement fetch newer than the return callback", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2030-01-01T00:00:00Z"));+ navigationState.search = "tab=billing&result=success&session_id=cs_test_1";+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ });+ Object.assign(mocks.usage, {+ action: "off",+ used: null,+ reserved: null,+ limit: null,+ reset_at: null,+ });+ mocks.entitlementsDataUpdatedAt = Date.now() + 1;+ mocks.entitlementsFetchedAfterMount = true;+ try {+ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Pro is active")).toBeInTheDocument();+ expect(screen.getAllByText("Unlimited")).toHaveLength(2);+ } finally {+ vi.useRealTimers();+ }+ });+it("keeps plan facts visible but hides subscription mutations from members", () => {mocks.role = "member";@@ -473,6 +637,186 @@ describe("BillingTab", () => {).not.toBeInTheDocument();});+ it("renders authoritative subscription seat facts", () => {+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "active",+ issueWindow: null,+ autopilotRuns: null,+ currentPeriodEnd: "2030-02-01T00:00:00Z",+ });+ Object.assign(mocks.usage, {+ action: "off",+ used: null,+ reserved: null,+ limit: null,+ reset_at: null,+ });+ Object.assign(mocks.summary, {+ billingInterval: "month",+ actualSeats: 4,+ billedSeats: 5,+ pendingSeatQuantity: 4,+ hasStripeCustomer: true,+ });++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Monthly")).toBeInTheDocument();+ expect(screen.getByText("5 seats")).toBeInTheDocument();+ expect(screen.getByText(/4 seats from Feb 1, 2030/)).toBeInTheDocument();+ expect(screen.getAllByText("4 members")).toHaveLength(2);+ });++ it("uses completed and reserved runs for the quota decision", () => {+ Object.assign(mocks.usage, { used: 5, reserved: 2, limit: 7 });++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Limit reached")).toBeInTheDocument();+ expect(screen.getByText("7 / 7")).toBeInTheDocument();+ expect(screen.getByText("5 completed · 2 in progress")).toBeInTheDocument();+ });++ it("does not render missing limited usage as zero or unlimited", async () => {+ const user = userEvent.setup();+ Object.assign(mocks.usage, {+ action: "off",+ used: null,+ reserved: null,+ limit: null,+ reset_at: null,+ });++ renderWithI18n(<BillingTab />);++ expect(+ screen.getByText("Usage is temporarily unavailable"),+ ).toBeInTheDocument();+ expect(screen.getByText("7 / month")).toBeInTheDocument();+ expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();+ expect(screen.queryByText(/0 \/ 7/)).not.toBeInTheDocument();++ await user.click(+ screen.getByRole("button", { name: "Retry automation usage" }),+ );+ expect(mocks.refetchUsage).toHaveBeenCalledOnce();+ });++ it.each([+ ["request fails", true, false],+ ["response is malformed", false, true],+ ])(+ "keeps plan facts visible when the subscription summary %s",+ (_case, isError, isMalformed) => {+ mocks.summaryError = isError;+ mocks.summaryMalformed = isMalformed;++ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Free")).toBeInTheDocument();+ expect(+ screen.getByText("Some seat details are unavailable"),+ ).toBeInTheDocument();+ expect(screen.getAllByText("Unavailable")).toHaveLength(2);+ },+ );++ it.each([+ ["incomplete", "Subscription setup is incomplete"],+ ["incomplete_expired", "Subscription setup expired"],+ ["paused", "Subscription is paused"],+ ["unpaid", "Subscription is unpaid"],+ ["canceled", "Subscription is canceled"],+ ])("renders a recovery notice for %s", (status, title) => {+ mocks.entitlements.status = status;++ renderWithI18n(<BillingTab />);++ expect(screen.getByText(title)).toBeInTheDocument();+ });++ it("shows grace and scheduled-cancellation dates from subscription facts", () => {+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "past_due",+ currentPeriodEnd: "2030-03-01T00:00:00Z",+ snapshotExpiresAt: "2030-02-15T00:00:00Z",+ });+ Object.assign(mocks.summary, {+ graceUntil: "2030-02-15T00:00:00Z",+ cancelAtPeriodEnd: true,+ hasStripeCustomer: true,+ });++ renderWithI18n(<BillingTab />);++ expect(+ screen.getByText(/Update your payment method by Feb 15, 2030/),+ ).toBeInTheDocument();+ expect(screen.getByText("Cancellation is scheduled")).toBeInTheDocument();+ expect(+ screen.getByText(/subscription is scheduled to cancel on Mar 1, 2030/),+ ).toBeInTheDocument();+ });++ it("stops deriving Pro access after the summary grace deadline", () => {+ Object.assign(mocks.entitlements, {+ plan: "pro",+ status: "past_due",+ issueWindow: null,+ autopilotRuns: null,+ });+ mocks.summary.graceUntil = "2000-01-01T00:00:00Z";+ Object.assign(mocks.usage, {+ action: "off",+ used: null,+ reserved: null,+ limit: null,+ reset_at: null,+ });++ renderWithI18n(<BillingTab />);++ expect(screen.queryByText("Unlimited")).not.toBeInTheDocument();+ expect(screen.getByText("Unavailable")).toBeInTheDocument();+ expect(+ screen.getByText(+ "Open the Billing Portal to update your payment method. The plan badge above shows the access currently available.",+ ),+ ).toBeInTheDocument();+ expect(screen.queryByText(/keep Pro access/)).not.toBeInTheDocument();+ });++ it("keeps cancellation and pending-seat dates on one summary snapshot", () => {+ Object.assign(mocks.entitlements, {+ plan: "free",+ currentPeriodEnd: "2030-03-01T00:00:00Z",+ });+ Object.assign(mocks.summary, {+ entitlement: {+ ...mocks.entitlements,+ currentPeriodEnd: "2030-04-01T00:00:00Z",+ },+ pendingSeatQuantity: 4,+ cancelAtPeriodEnd: true,+ hasStripeCustomer: true,+ });++ renderWithI18n(<BillingTab />);++ expect(+ screen.getByText(/subscription is scheduled to cancel on Apr 1, 2030/),+ ).toBeInTheDocument();+ expect(screen.getByText(/4 seats from Apr 1, 2030/)).toBeInTheDocument();+ expect(screen.getByText("Apr 1, 2030")).toBeInTheDocument();+ expect(screen.queryByText("Mar 1, 2030")).not.toBeInTheDocument();+ expect(+ screen.queryByText(/subscription is scheduled to cancel on Mar 1, 2030/),+ ).not.toBeInTheDocument();+ expect(screen.queryByText(/Pro remains available/)).not.toBeInTheDocument();+ });+it("shows Pro management and unlimited limits without a second Checkout", () => {Object.assign(mocks.entitlements, {plan: "pro",@@ -482,6 +826,13 @@ describe("BillingTab", () => {currentPeriodEnd: "2026-09-13T00:00:00Z",version: 3,});+ Object.assign(mocks.usage, {+ action: "off",+ used: null,+ reserved: null,+ limit: null,+ reset_at: null,+ });renderWithI18n(<BillingTab />);@@ -500,33 +851,55 @@ describe("BillingTab", () => {);});- 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,- });+ it.each(["canceled", "incomplete_expired"])(+ "keeps management and self-service repurchase available for %s Free",+ (status) => {+ Object.assign(mocks.entitlements, {+ plan: "free",+ status,+ currentPeriodEnd: "2026-09-13T00:00:00Z",+ version: 4,+ });+ Object.assign(mocks.summary, {+ billedSeats: 3,+ hasStripeCustomer: true,+ });- renderWithI18n(<BillingTab />);+ renderWithI18n(<BillingTab />);- expect(- screen.getByRole("button", { name: "Manage billing" }),- ).toBeInTheDocument();- });+ expect(+ screen.getByRole("button", { name: "Manage billing" }),+ ).toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Upgrade to Pro" }),+ ).toBeInTheDocument();+ expect(mocks.useQuery).toHaveBeenCalledWith(+ expect.objectContaining({+ queryKey: ["workspace-subscriptions", "workspace-1", "prices"],+ enabled: true,+ }),+ );+ },+ );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",+ snapshotExpiresAt: null,version: 4,});+ mocks.summary.graceUntil = "2000-01-01T00:00:00Z";renderWithI18n(<BillingTab />);expect(screen.getByText("Payment needs attention")).toBeInTheDocument();- expect(screen.queryByText("Sep 1, 2026")).not.toBeInTheDocument();+ expect(+ screen.getByText(+ "Open the Billing Portal to update your payment method. The plan badge above shows the access currently available.",+ ),+ ).toBeInTheDocument();+ expect(screen.queryByText(/keep Pro access/)).not.toBeInTheDocument();expect(screen.getByRole("button", { name: "Manage billing" }),).toBeInTheDocument();diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex 00e16f59ec..e22db95596 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -12,12 +12,14 @@ import {ShieldCheck,} from "lucide-react";import { ApiError } from "@multica/core/api";+import { autopilotQuotaUsageOptions } from "@multica/core/autopilots";import {useCreateWorkspaceSubscriptionCheckout,useCreateWorkspaceSubscriptionPortal,useReconcileWorkspaceSubscriptionSeats,workspaceSubscriptionEntitlementsOptions,workspaceSubscriptionPricesOptions,+ workspaceSubscriptionSummaryOptions,} from "@multica/core/billing";import { useFeatureEnabled } from "@multica/core/config";import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";@@ -41,6 +43,11 @@ 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 {+ Progress,+ ProgressLabel,+ ProgressValue,+} from "@multica/ui/components/ui/progress";import { Skeleton } from "@multica/ui/components/ui/skeleton";import { useLocale, useT } from "../../i18n";import { useNavigation } from "../../navigation";@@ -51,6 +58,11 @@ import {SettingsSection,SettingsTab,} from "./settings-layout";+import {+ canPurchaseWorkspaceSubscription,+ hasManagedWorkspaceSubscription,+ resolveAutopilotUsage,+} from "./billing-state";const CHECKOUT_SYNC_TIMEOUT_MS = 30_000;@@ -109,6 +121,16 @@ function formatDate(value: string | null, locale: string): string | null {return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(date);}+function formatDateTime(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",+ timeStyle: "short",+ }).format(date);+}+/*** Stripe API amounts use its own minor-unit contract: two decimals by default,* an explicit zero-decimal list, five three-decimal currencies, and ISK/UGX in@@ -166,9 +188,13 @@ function statusBadgeVariant(case "trialing":return "default";case "past_due":+ case "incomplete":+ case "unpaid":return "destructive";case "inactive":case "canceled":+ case "incomplete_expired":+ case "paused":return "secondary";default:return "outline";@@ -209,11 +235,18 @@ function BillingTabContent() {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;+ observedAt: number | null;+ }>(() => ({+ workspaceId: wsId || null,+ result: returnResultParam,+ observedAt: returnResultParam === "success" ? Date.now() : null,+ }));+ const returnStateMatchesWorkspace =+ returnState.workspaceId === null || returnState.workspaceId === wsId;+ const returnResult = returnStateMatchesWorkspace ? returnState.result : null;+ const returnObservedAt = returnStateMatchesWorkspace+ ? returnState.observedAt+ : null;const [interval, setInterval] =useState<WorkspaceSubscriptionInterval>("month");const [checkoutConfirmOpen, setCheckoutConfirmOpen] = useState(false);@@ -246,7 +279,11 @@ function BillingTabContent() {useEffect(() => {if (!callbackKey || consumedCallbackKeyRef.current === callbackKey) return;consumedCallbackKeyRef.current = callbackKey;- setReturnState({ workspaceId: wsId || null, result: returnResultParam });+ setReturnState({+ workspaceId: wsId || null,+ result: returnResultParam,+ observedAt: returnResultParam === "success" ? Date.now() : null,+ });if (returnResultParam === "cancel") checkoutIntentRef.current = null;const params = new URLSearchParams(navigation.searchParams);@@ -278,11 +315,26 @@ function BillingTabContent() {refetchInterval: isSyncingCheckout ? 2_000 : false,});const entitlements = entitlementQuery.data;- const canUpgrade =- entitlements?.plan === "free" &&- entitlements.status !== "active" &&- entitlements.status !== "trialing" &&- entitlements.status !== "past_due";+ const isCheckoutProConfirmed =+ returnResult === "success" &&+ returnObservedAt !== null &&+ entitlements?.plan === "pro" &&+ entitlementQuery.isFetchedAfterMount &&+ entitlementQuery.dataUpdatedAt >= returnObservedAt;+ const summaryQuery = useQuery({+ ...workspaceSubscriptionSummaryOptions(wsId),+ refetchInterval: isSyncingCheckout ? 2_000 : false,+ });+ const summaryUnavailable =+ summaryQuery.isError ||+ (!summaryQuery.isPending && summaryQuery.data == null);+ const quotaUsageQuery = useQuery(autopilotQuotaUsageOptions(wsId));+ const hasManagedSubscription = entitlements+ ? hasManagedWorkspaceSubscription(entitlements, summaryQuery.data)+ : false;+ const canUpgrade = entitlements+ ? canPurchaseWorkspaceSubscription(entitlements)+ : false;const pricesQuery = useQuery({...workspaceSubscriptionPricesOptions(wsId),enabled: wsId.length > 0 && canUpgrade,@@ -291,26 +343,28 @@ function BillingTabContent() {const portalMutation = useCreateWorkspaceSubscriptionPortal(wsId);const reconcileMutation = useReconcileWorkspaceSubscriptionSeats(wsId);const refetchEntitlements = entitlementQuery.refetch;+ const refetchSummary = summaryQuery.refetch;useEffect(() => {- if (isSyncingCheckout && entitlements?.plan === "pro") {+ if (isSyncingCheckout && isCheckoutProConfirmed) {setIsSyncingCheckout(false);setSyncTimedOut(false);checkoutIntentRef.current = null;}- }, [entitlements?.plan, isSyncingCheckout]);+ }, [isCheckoutProConfirmed, 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 graceUntil = summaryQuery.data?.graceUntil;+ if (!graceUntil) return;+ const graceUntilMs = new Date(graceUntil).getTime();+ if (Number.isNaN(graceUntilMs)) return;+ const delay = Math.max(0, graceUntilMs - Date.now()) + 100;const timeout = window.setTimeout(() => {void refetchEntitlements();+ void refetchSummary();}, Math.min(delay, 2_147_000_000));return () => window.clearTimeout(timeout);- }, [entitlements?.snapshotExpiresAt, refetchEntitlements]);+ }, [refetchEntitlements, refetchSummary, summaryQuery.data?.graceUntil]);const planLabel = (plan: string) => {switch (plan) {@@ -335,6 +389,14 @@ function BillingTabContent() {return t(($) => $.workspace.status.past_due);case "canceled":return t(($) => $.workspace.status.canceled);+ case "incomplete":+ return t(($) => $.workspace.status.incomplete);+ case "incomplete_expired":+ return t(($) => $.workspace.status.incomplete_expired);+ case "paused":+ return t(($) => $.workspace.status.paused);+ case "unpaid":+ return t(($) => $.workspace.status.unpaid);default:return t(($) => $.workspace.status.unknown);}@@ -381,7 +443,7 @@ function BillingTabContent() {if (error instanceof ApiError && error.status === 409) {checkoutIntentRef.current = null;setActionError(t(($) => $.workspace.errors.already_subscribed));- await entitlementQuery.refetch();+ await Promise.all([entitlementQuery.refetch(), summaryQuery.refetch()]);return;}reportActionError(error, t(($) => $.workspace.errors.checkout_failed));@@ -414,7 +476,7 @@ function BillingTabContent() {portalIntentKeyRef.current = null;setPortalUnavailable(true);setActionError(t(($) => $.workspace.errors.portal_unavailable));- await entitlementQuery.refetch();+ await Promise.all([entitlementQuery.refetch(), summaryQuery.refetch()]);return;}reportActionError(error, t(($) => $.workspace.errors.portal_failed));@@ -436,6 +498,7 @@ function BillingTabContent() {billed: response.billedSeats,}),);+ await Promise.all([entitlementQuery.refetch(), summaryQuery.refetch()]);} catch (error) {reportActionError(error, t(($) => $.workspace.errors.reconcile_failed));}@@ -486,13 +549,38 @@ function BillingTabContent() {);}- const periodEnd = formatDate(entitlements.currentPeriodEnd, locale);- const isPro = entitlements.plan === "pro";- const hasManagedSubscription =- isPro ||- entitlements.status === "active" ||- entitlements.status === "trialing" ||- entitlements.status === "past_due";+ const summaryPeriodEnd = formatDate(+ summaryQuery.data?.entitlement.currentPeriodEnd ?? null,+ locale,+ );+ const graceUntilValue = summaryQuery.data?.graceUntil ?? null;+ const graceUntil = formatDate(graceUntilValue, locale);+ const graceUntilMs = graceUntilValue+ ? new Date(graceUntilValue).getTime()+ : Number.NaN;+ const hasActiveProGrace =+ entitlements.plan === "pro" &&+ entitlements.status === "past_due" &&+ Number.isFinite(graceUntilMs) &&+ graceUntilMs > Date.now();+ const canUseEntitlementUnlimited =+ entitlements.plan === "pro" &&+ (entitlements.status !== "past_due" || hasActiveProGrace) &&+ (returnResult !== "success" || isCheckoutProConfirmed);+ const actualSeats = summaryQuery.data?.actualSeats ?? entitlements.seats;+ const billedSeats = summaryQuery.data?.billedSeats;+ const pendingSeatQuantity = summaryQuery.data?.pendingSeatQuantity;+ const quotaUsage = resolveAutopilotUsage(+ entitlements,+ quotaUsageQuery.data,+ quotaUsageQuery.isError,+ canUseEntitlementUnlimited,+ );+ const quotaResetAt =+ quotaUsage.kind === "metered"+ ? formatDateTime(quotaUsage.resetAt, locale)+ : null;+ const numberFormatter = new Intl.NumberFormat(locale);const isMutating =checkoutMutation.isPending ||portalMutation.isPending ||@@ -506,9 +594,9 @@ function BillingTabContent() {): null;const formattedEstimatedTotal =- selectedPrice && entitlements.seats > 0- ? formatStripeMinorAmount(- selectedPrice.unitAmount * entitlements.seats,+ selectedPrice && actualSeats > 0+ ? formatStripeMinorAmount(+ selectedPrice.unitAmount * actualSeats,selectedPrice.currency,locale,)@@ -546,7 +634,7 @@ function BillingTabContent() {{returnResult === "success" ? (<Alert>- {isPro ? (+ {isCheckoutProConfirmed ? (<CheckCircle2 />) : (<Loader2@@ -558,12 +646,12 @@ function BillingTabContent() {/>)}<AlertTitle>- {isPro+ {isCheckoutProConfirmed? t(($) => $.workspace.return.active_title): t(($) => $.workspace.return.syncing_title)}</AlertTitle><AlertDescription>- {isPro+ {isCheckoutProConfirmed? t(($) => $.workspace.return.active_description): syncTimedOut? t(($) => $.workspace.return.timeout_description)@@ -572,12 +660,104 @@ function BillingTabContent() {</Alert>) : null}+ {summaryQuery.data?.cancelAtPeriodEnd ? (+ <Alert>+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.subscription_notice.canceling_title)}+ </AlertTitle>+ <AlertDescription>+ {summaryPeriodEnd+ ? t(+ ($) =>+ $.workspace.subscription_notice.canceling_description,+ { date: summaryPeriodEnd },+ )+ : t(+ ($) =>+ $.workspace.subscription_notice+ .canceling_description_without_date,+ )}+ </AlertDescription>+ </Alert>+ ) : null}+{entitlements.status === "past_due" ? (<Alert variant="destructive"><AlertCircle /><AlertTitle>{t(($) => $.workspace.past_due.title)}</AlertTitle><AlertDescription>- {t(($) => $.workspace.past_due.description)}+ {hasActiveProGrace && graceUntil+ ? t(($) => $.workspace.past_due.grace_description, {+ date: graceUntil,+ })+ : t(($) => $.workspace.past_due.description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {entitlements.status === "incomplete" ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.subscription_notice.incomplete_title)}+ </AlertTitle>+ <AlertDescription>+ {t(($) => $.workspace.subscription_notice.incomplete_description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {entitlements.status === "incomplete_expired" ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>+ {t(+ ($) => $.workspace.subscription_notice.incomplete_expired_title,+ )}+ </AlertTitle>+ <AlertDescription>+ {t(+ ($) =>+ $.workspace.subscription_notice+ .incomplete_expired_description,+ )}+ </AlertDescription>+ </Alert>+ ) : null}++ {entitlements.status === "paused" ? (+ <Alert>+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.subscription_notice.paused_title)}+ </AlertTitle>+ <AlertDescription>+ {t(($) => $.workspace.subscription_notice.paused_description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {entitlements.status === "unpaid" ? (+ <Alert variant="destructive">+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.subscription_notice.unpaid_title)}+ </AlertTitle>+ <AlertDescription>+ {t(($) => $.workspace.subscription_notice.unpaid_description)}+ </AlertDescription>+ </Alert>+ ) : null}++ {entitlements.status === "canceled" ? (+ <Alert>+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.subscription_notice.canceled_title)}+ </AlertTitle>+ <AlertDescription>+ {t(($) => $.workspace.subscription_notice.canceled_description)}</AlertDescription></Alert>) : null}@@ -621,16 +801,30 @@ function BillingTabContent() {><span className="tabular-nums">{t(($) => $.workspace.current.member_count, {- count: entitlements.seats,+ count: actualSeats,})}</span></SettingsRow>- {periodEnd ? (+ {summaryQuery.data?.billingInterval ? (+ <SettingsRow+ label={t(($) => $.workspace.current.billing_interval)}+ description={t(+ ($) => $.workspace.current.billing_interval_description,+ )}+ >+ <span>+ {summaryQuery.data.billingInterval === "month"+ ? t(($) => $.workspace.upgrade.monthly)+ : t(($) => $.workspace.upgrade.yearly)}+ </span>+ </SettingsRow>+ ) : null}+ {summaryPeriodEnd ? (<SettingsRowlabel={t(($) => $.workspace.current.period_end)}description={t(($) => $.workspace.current.period_end_description)}>- <span className="tabular-nums">{periodEnd}</span>+ <span className="tabular-nums">{summaryPeriodEnd}</span></SettingsRow>) : null}</SettingsCard>@@ -668,7 +862,7 @@ function BillingTabContent() {<div className="space-y-2"><p className="text-body font-medium">{t(($) => $.workspace.upgrade.pro_for_team, {- count: entitlements.seats,+ count: actualSeats,})}</p>{pricesQuery.isLoading ? (@@ -792,23 +986,93 @@ function BillingTabContent() {><span className="tabular-nums">{entitlements.issueWindow === null- ? t(($) => $.workspace.limits.unlimited)- : new Intl.NumberFormat(locale).format(- entitlements.issueWindow,- )}+ ? canUseEntitlementUnlimited+ ? t(($) => $.workspace.limits.unlimited)+ : t(($) => $.workspace.limits.unavailable)+ : numberFormatter.format(entitlements.issueWindow)}</span></SettingsRow><SettingsRowlabel={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,+ {quotaUsage.kind === "unlimited" ? (+ <span className="tabular-nums">+ {t(($) => $.workspace.limits.unlimited)}+ </span>+ ) : quotaUsageQuery.isPending ? (+ <div+ className="w-full max-w-72 space-y-2 motion-reduce:[&_[data-slot=skeleton]]:animate-none"+ role="status"+ aria-label={t(($) => $.workspace.limits.usage_loading)}+ >+ <Skeleton className="h-5 w-full" />+ <Skeleton className="h-4 w-2/3" />+ </div>+ ) : quotaUsage.kind === "metered" ? (+ <div className="w-full max-w-72 space-y-2">+ <Progress+ value={quotaUsage.progress}+ aria-label={t(($) => $.workspace.limits.usage_label)}+ >+ <ProgressLabel>+ {quotaUsage.reached+ ? t(($) => $.workspace.limits.reached)+ : t(($) => $.workspace.limits.current_usage)}+ </ProgressLabel>+ <ProgressValue>+ {() =>+ t(($) => $.workspace.limits.usage_total, {+ total: numberFormatter.format(quotaUsage.total),+ limit: numberFormatter.format(quotaUsage.limit),+ })+ }+ </ProgressValue>+ </Progress>+ <p className="text-caption text-muted-foreground tabular-nums">+ {t(($) => $.workspace.limits.usage_breakdown, {+ used: numberFormatter.format(quotaUsage.used),+ reserved: numberFormatter.format(quotaUsage.reserved),})}- </span>+ </p>+ {quotaResetAt ? (+ <p className="text-caption text-muted-foreground tabular-nums">+ {t(($) => $.workspace.limits.resets_at, {+ date: quotaResetAt,+ })}+ </p>+ ) : null}+ </div>+ ) : (+ <div className="flex flex-col gap-2 sm:items-end">+ {entitlements.autopilotRuns !== null ? (+ <span className="tabular-nums">+ {t(($) => $.workspace.limits.per_month, {+ count: entitlements.autopilotRuns,+ })}+ </span>+ ) : null}+ <span className="text-caption text-muted-foreground">+ {t(($) => $.workspace.limits.usage_unavailable)}+ </span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ aria-label={t(($) => $.workspace.actions.retry_autopilots)}+ aria-busy={quotaUsageQuery.isFetching}+ disabled={quotaUsageQuery.isFetching}+ onClick={() => void quotaUsageQuery.refetch()}+ >+ {quotaUsageQuery.isFetching ? (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ ) : (+ <RefreshCw />+ )}+ {t(($) => $.workspace.actions.retry)}+ </Button>+ </div>+ )}</SettingsRow></SettingsCard></SettingsSection>@@ -817,6 +1081,35 @@ function BillingTabContent() {title={t(($) => $.workspace.seats.title)}description={t(($) => $.workspace.seats.description)}>+ {summaryUnavailable ? (+ <Alert className="mb-3">+ <AlertCircle />+ <AlertTitle>+ {t(($) => $.workspace.seats.summary_unavailable_title)}+ </AlertTitle>+ <AlertDescription>+ <p>+ {t(($) => $.workspace.seats.summary_unavailable_description)}+ </p>+ <Button+ className="mt-3"+ type="button"+ variant="outline"+ size="sm"+ aria-busy={summaryQuery.isFetching}+ disabled={summaryQuery.isFetching}+ onClick={() => void summaryQuery.refetch()}+ >+ {summaryQuery.isFetching ? (+ <Loader2 className="animate-spin motion-reduce:animate-none" />+ ) : (+ <RefreshCw />+ )}+ {t(($) => $.workspace.actions.retry)}+ </Button>+ </AlertDescription>+ </Alert>+ ) : null}{reconcileMessage ? (<Alert className="mb-3"><CheckCircle2 />@@ -832,7 +1125,7 @@ function BillingTabContent() {<div className="flex flex-col gap-2 sm:items-end"><span className="tabular-nums">{t(($) => $.workspace.current.member_count, {- count: entitlements.seats,+ count: actualSeats,})}</span>{canManage && hasManagedSubscription ? (@@ -852,6 +1145,64 @@ function BillingTabContent() {) : null}</div></SettingsRow>+ <SettingsRow+ label={t(($) => $.workspace.seats.billed)}+ description={t(($) => $.workspace.seats.billed_description)}+ >+ {summaryQuery.isPending ? (+ <Skeleton+ className="h-5 w-20 motion-reduce:animate-none"+ aria-label={t(($) => $.workspace.seats.summary_loading)}+ />+ ) : summaryUnavailable ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.unavailable)}+ </span>+ ) : billedSeats === null || billedSeats === undefined ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.not_subscribed)}+ </span>+ ) : (+ <span className="tabular-nums">+ {t(($) => $.workspace.seats.seat_count, {+ count: billedSeats,+ })}+ </span>+ )}+ </SettingsRow>+ <SettingsRow+ label={t(($) => $.workspace.seats.pending)}+ description={t(($) => $.workspace.seats.pending_description)}+ >+ {summaryQuery.isPending ? (+ <Skeleton+ className="h-5 w-28 motion-reduce:animate-none"+ aria-label={t(($) => $.workspace.seats.summary_loading)}+ />+ ) : summaryUnavailable ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.unavailable)}+ </span>+ ) : pendingSeatQuantity === null ||+ pendingSeatQuantity === undefined ? (+ <span className="text-muted-foreground">+ {t(($) => $.workspace.seats.none_pending)}+ </span>+ ) : summaryPeriodEnd ? (+ <span className="tabular-nums">+ {t(($) => $.workspace.seats.pending_with_date, {+ count: pendingSeatQuantity,+ date: summaryPeriodEnd,+ })}+ </span>+ ) : (+ <span className="tabular-nums">+ {t(($) => $.workspace.seats.seat_count, {+ count: pendingSeatQuantity,+ })}+ </span>+ )}+ </SettingsRow></SettingsCard></SettingsSection>@@ -870,7 +1221,7 @@ function BillingTabContent() {interval === "month"? t(($) => $.workspace.upgrade.monthly): t(($) => $.workspace.upgrade.yearly),- count: entitlements.seats,+ count: actualSeats,})}</AlertDialogDescription></AlertDialogHeader>