Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(billing): purchase a seat from the invite flow (#7538)
LinYushen60a55ec57b7b
diff --git a/.env.example b/.env.exampleindex 5d02ce9402..d9dcacfb64 100644--- a/.env.example+++ b/.env.example@@ -219,9 +219,6 @@ MULTICA_ENTITLEMENT_EMERGENCY_DISABLED=false# Keep disabled for self-hosting. The token must match Cloud's# billing.subscriptions.service_token_env secret.MULTICA_SUBSCRIPTION_CAPACITY_ENABLED=false-# Keep this true while pausing enforcement so previously recorded confirm and-# release intents continue draining. Enforcement=true implies worker=true.-MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED=falseMULTICA_SUBSCRIPTION_CAPACITY_URL=MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN=MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT=3sdiff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yamlindex 2e9fda1a3d..8e93c7da5a 100644--- a/deploy/helm/multica/templates/configmap.yaml+++ b/deploy/helm/multica/templates/configmap.yaml@@ -26,7 +26,6 @@ data:MULTICA_ENTITLEMENT_STALE_GRACE: {{ .Values.backend.config.entitlementPolicy.staleGrace | quote }}MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: {{ .Values.backend.config.entitlementPolicy.emergencyDisabled | quote }}MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: {{ .Values.backend.config.subscriptionCapacity.enabled | quote }}- MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED: {{ .Values.backend.config.subscriptionCapacity.workerEnabled | quote }}MULTICA_SUBSCRIPTION_CAPACITY_URL: {{ .Values.backend.config.subscriptionCapacity.url | quote }}MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: {{ .Values.backend.config.subscriptionCapacity.timeout | quote }}GOOGLE_CLIENT_ID: {{ .Values.backend.config.googleClientId | quote }}diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex fe5cc44359..6288d060e7 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -154,9 +154,6 @@ backend:# enabled, put the matching service token in existingSecret.subscriptionCapacity:enabled: false- # Keep settlement running while enforcement is paused so durable- # confirm/release intents drain. enabled=true also starts the worker.- workerEnabled: falseurl: ""timeout: 3sgoogleClientId: ""diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 9ded8af82a..acf78fe5b3 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -116,7 +116,6 @@ services:MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: ${MULTICA_ENTITLEMENT_EMERGENCY_DISABLED:-false}# Managed seat capacity is also opt-in and stays off for self-hosting.MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: ${MULTICA_SUBSCRIPTION_CAPACITY_ENABLED:-false}- MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED: ${MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED:-false}MULTICA_SUBSCRIPTION_CAPACITY_URL: ${MULTICA_SUBSCRIPTION_CAPACITY_URL:-}MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN: ${MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN:-}MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: ${MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT:-3s}diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 7e500ef4fc..5f14166ad5 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -224,6 +224,7 @@"summary_unavailable_description": "The current plan is still shown, but purchased and scheduled seat quantities could not be loaded.","members_over_capacity_title": "Members exceed purchased seats","members_over_capacity_description": "This workspace has {{actual}} members but only {{purchased}} purchased seats. Add enough seats or remove members before sending more invitations.",+ "occupancy_over_capacity_description": "This workspace occupies {{occupied}} of {{purchased}} purchased seats ({{members}} members and {{reserved}} pending invitations). Add seats, remove a member, or revoke a pending invitation before inviting someone else.","updated": "Seat purchase submitted"},"seat_purchase": {diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 6bb61c381c..4312af6997 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1157,9 +1157,14 @@"inviting": "Inviting...","toast_invitation_sent": "Invitation sent","toast_invitation_failed": "Failed to send invitation",- "toast_seat_capacity_full": "All purchased member seats are in use. Add a seat before inviting someone else.","toast_seat_capacity_unavailable": "Member capacity could not be verified. Please try again.",- "add_seats_action": "Add seats",+ "seat_purchase_title": "Add a seat to send this invitation?",+ "seat_purchase_description": "No purchased seat is available for {{email}}. Review Stripe's estimate, then approve the purchase and invitation together.",+ "purchase_seat_and_invite": "Buy 1 seat and invite",+ "retry_seat_purchase": "Retry purchase",+ "seat_purchase_waiting": "Waiting for Stripe to confirm the new seat. Keep this page open so the invitation can be sent automatically; if you leave, the purchased seat remains and you can invite again later.",+ "seat_purchase_timeout": "The seat purchase was submitted, but confirmation is taking longer than expected. No invitation was sent. Retry the invitation after Billing shows an available seat.",+ "seat_purchase_capacity_taken": "The purchased seat is no longer available, so the invitation was not sent. Review current seats before trying again.","no_members": "No members found.","pending_title": "Pending invitations ({{count}})","pending_status": "Pending",diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex a8017f088c..da857f51c2 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -220,6 +220,7 @@"summary_unavailable_description": "現在のプランは表示できますが、購入済みの席数と変更予定の席数を読み込めませんでした。","members_over_capacity_title": "メンバー数が購入済みの席数を超えています","members_over_capacity_description": "このワークスペースには {{actual}} 人のメンバーがいますが、購入済みの席は {{purchased}} 席です。さらに招待する前に席を追加するか、メンバーを削除してください。",+ "occupancy_over_capacity_description": "このワークスペースは購入済み {{purchased}} 席に対して {{occupied}} 席を占有しています(メンバー {{members}} 人、保留中の招待 {{reserved}} 件)。さらに招待する前に席を追加する、メンバーを削除する、または保留中の招待を取り消してください。","updated": "席数の購入を送信しました"},"seat_purchase": {diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex d849636863..51dd22bf3b 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1154,9 +1154,14 @@"inviting": "招待中...","toast_invitation_sent": "招待を送信しました","toast_invitation_failed": "招待を送信できませんでした",- "toast_seat_capacity_full": "購入済みのメンバー席をすべて使用しています。新しいメンバーを招待する前に席を追加してください。","toast_seat_capacity_unavailable": "メンバー席を確認できませんでした。もう一度お試しください。",- "add_seats_action": "席を追加",+ "seat_purchase_title": "席を追加して招待を送信しますか?",+ "seat_purchase_description": "{{email}} に使用できる購入済みの席がありません。Stripe の見積もりを確認し、席の購入と招待をまとめて承認してください。",+ "purchase_seat_and_invite": "1 席を購入して招待",+ "retry_seat_purchase": "購入を再試行",+ "seat_purchase_waiting": "Stripe による新しい席の確認を待っています。招待を自動送信するには、このページを開いたままにしてください。ページを離れても購入済みの席は保持され、後で再度招待できます。",+ "seat_purchase_timeout": "席の購入は送信されましたが、確認に時間がかかっています。招待は送信されていません。請求画面に空き席が表示された後、もう一度招待してください。",+ "seat_purchase_capacity_taken": "購入した席はすでに利用できないため、招待は送信されませんでした。現在の席を確認してから再試行してください。","no_members": "メンバーが見つかりません。","pending_title": "保留中の招待({{count}})","pending_status": "保留中",diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 40be302ccb..88ea6a05d9 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -220,6 +220,7 @@"summary_unavailable_description": "현재 요금제는 계속 표시되지만 구매한 좌석과 예정 좌석 수를 불러오지 못했습니다.","members_over_capacity_title": "멤버 수가 구매한 좌석 수를 초과합니다","members_over_capacity_description": "이 워크스페이스에는 멤버가 {{actual}}명이지만 구매한 좌석은 {{purchased}}개입니다. 더 초대하기 전에 좌석을 추가하거나 멤버를 제거하세요.",+ "occupancy_over_capacity_description": "이 워크스페이스는 구매한 좌석 {{purchased}}개에 대해 {{occupied}}개를 점유하고 있습니다(멤버 {{members}}명, 대기 중인 초대 {{reserved}}건). 더 초대하기 전에 좌석을 추가하거나 멤버를 제거하거나 대기 중인 초대를 취소하세요.","updated": "좌석 구매를 제출했습니다"},"seat_purchase": {diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 58b2f53929..4d989409a6 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -892,9 +892,14 @@"inviting": "초대하는 중...","toast_invitation_sent": "초대를 보냈습니다","toast_invitation_failed": "초대를 보내지 못했습니다",- "toast_seat_capacity_full": "구매한 멤버 좌석을 모두 사용 중입니다. 새 멤버를 초대하기 전에 좌석을 추가하세요.","toast_seat_capacity_unavailable": "멤버 좌석을 확인할 수 없습니다. 다시 시도해 주세요.",- "add_seats_action": "좌석 추가",+ "seat_purchase_title": "좌석을 추가하고 초대를 보내시겠어요?",+ "seat_purchase_description": "{{email}}에 사용할 구매 좌석이 없습니다. Stripe 견적을 확인한 뒤 좌석 구매와 초대를 함께 승인하세요.",+ "purchase_seat_and_invite": "좌석 1개 구매 후 초대",+ "retry_seat_purchase": "구매 다시 시도",+ "seat_purchase_waiting": "Stripe의 새 좌석 확인을 기다리는 중입니다. 초대가 자동으로 전송되도록 이 페이지를 열어 두세요. 페이지를 벗어나도 구매한 좌석은 유지되며 나중에 다시 초대할 수 있습니다.",+ "seat_purchase_timeout": "좌석 구매가 제출되었지만 확인이 예상보다 오래 걸리고 있습니다. 초대는 전송되지 않았습니다. 결제 화면에 사용 가능한 좌석이 표시된 후 다시 초대하세요.",+ "seat_purchase_capacity_taken": "구매한 좌석을 더 이상 사용할 수 없어 초대가 전송되지 않았습니다. 현재 좌석을 확인한 후 다시 시도하세요.","no_members": "멤버를 찾을 수 없습니다.","pending_title": "대기 중인 초대 ({{count}})","pending_status": "대기 중",diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 4cb1d910e9..f01df0192b 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -220,6 +220,7 @@"summary_unavailable_description": "当前套餐仍会显示,但暂时无法加载已购席位和待生效席位。","members_over_capacity_title": "成员数超过已购席位","members_over_capacity_description": "当前工作区有 {{actual}} 名成员,但只购买了 {{purchased}} 个席位。继续邀请前,请补足席位或移除成员。",+ "occupancy_over_capacity_description": "当前工作区已占用 {{occupied}} 个席位,但只购买了 {{purchased}} 个({{members}} 名成员和 {{reserved}} 个待接受邀请)。继续邀请前,请补足席位、移除成员或撤销待接受邀请。","updated": "席位购买已提交"},"seat_purchase": {diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 9328666c0e..1a31b15d4c 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1154,9 +1154,14 @@"inviting": "邀请中...","toast_invitation_sent": "已发送邀请","toast_invitation_failed": "发送邀请失败",- "toast_seat_capacity_full": "已购买的成员席位已全部使用,请先增加席位再邀请新成员。","toast_seat_capacity_unavailable": "暂时无法核验成员席位,请稍后重试。",- "add_seats_action": "增加席位",+ "seat_purchase_title": "增加一个席位并发送邀请?",+ "seat_purchase_description": "当前没有可供 {{email}} 使用的已购席位。请核对 Stripe 报价,然后一次确认补购和邀请。",+ "purchase_seat_and_invite": "购买 1 个席位并邀请",+ "retry_seat_purchase": "重试购买",+ "seat_purchase_waiting": "正在等待 Stripe 确认新席位。请保持当前页面打开,以便确认后自动发送邀请;如果离开页面,已购席位仍会保留,之后可重新邀请。",+ "seat_purchase_timeout": "席位购买已提交,但确认时间超出预期。邀请尚未发送;请在“账单”显示有可用席位后重新邀请。",+ "seat_purchase_capacity_taken": "新购买的席位已不可用,因此没有发送邀请。请检查当前席位后重试。","no_members": "未找到成员。","pending_title": "待处理邀请({{count}})","pending_status": "待处理",diff --git a/packages/views/settings/components/billing-format.ts b/packages/views/settings/components/billing-format.tsnew file mode 100644index 0000000000..88b7ba95cf--- /dev/null+++ b/packages/views/settings/components/billing-format.ts@@ -0,0 +1,62 @@+const STRIPE_ZERO_DECIMAL_CURRENCIES = new Set([+ "BIF",+ "CLP",+ "DJF",+ "GNF",+ "JPY",+ "KMF",+ "KRW",+ "MGA",+ "PYG",+ "RWF",+ "VND",+ "VUV",+ "XAF",+ "XOF",+ "XPF",+]);+const STRIPE_TWO_DECIMAL_COMPAT_CURRENCIES = new Set(["ISK", "UGX"]);+const STRIPE_THREE_DECIMAL_CURRENCIES = new Set([+ "BHD",+ "JOD",+ "KWD",+ "OMR",+ "TND",+]);++/** Format a Stripe minor-unit amount without guessing currency precision. */+export function formatStripeMinorAmount(+ amount: number,+ currency: string,+ locale: string,+): string | null {+ if (!Number.isSafeInteger(amount) || amount < 0) return null;+ const normalizedCurrency = currency.trim().toUpperCase();+ if (!normalizedCurrency) return null;++ try {+ const fractionDigits = STRIPE_TWO_DECIMAL_COMPAT_CURRENCIES.has(+ normalizedCurrency,+ )+ ? 2+ : STRIPE_ZERO_DECIMAL_CURRENCIES.has(normalizedCurrency)+ ? 0+ : STRIPE_THREE_DECIMAL_CURRENCIES.has(normalizedCurrency)+ ? 3+ : 2;+ const majorAmount = amount / 10 ** fractionDigits;+ const showStripeFraction = !Number.isInteger(majorAmount);+ return new Intl.NumberFormat(locale, {+ style: "currency",+ currency: normalizedCurrency,+ ...(showStripeFraction+ ? {+ minimumFractionDigits: fractionDigits,+ maximumFractionDigits: fractionDigits,+ }+ : {}),+ }).format(majorAmount);+ } catch {+ return null;+ }+}diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex fc0e10643e..db8af322a0 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -79,37 +79,14 @@ import {hasWorkspaceBillingRelationship,resolveAutopilotUsage,} from "./billing-state";+import { formatStripeMinorAmount } from "./billing-format";++export { formatStripeMinorAmount } from "./billing-format";const CHECKOUT_SYNC_TIMEOUT_MS = 30_000;const SEAT_PURCHASE_POLL_TIMEOUT_MS = 2 * 60_000;const SEAT_PURCHASE_PREVIEW_DEBOUNCE_MS = 800;-const STRIPE_ZERO_DECIMAL_CURRENCIES = new Set([- "BIF",- "CLP",- "DJF",- "GNF",- "JPY",- "KMF",- "KRW",- "MGA",- "PYG",- "RWF",- "VND",- "VUV",- "XAF",- "XOF",- "XPF",-]);-const STRIPE_TWO_DECIMAL_COMPAT_CURRENCIES = new Set(["ISK", "UGX"]);-const STRIPE_THREE_DECIMAL_CURRENCIES = new Set([- "BHD",- "JOD",- "KWD",- "OMR",- "TND",-]);-type WorkspaceBillingReturnResult = "success" | "cancel" | "portal";function parseReturnResult(@@ -149,49 +126,6 @@ function formatDateTime(value: string | null, locale: string): string | null {}).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- * a backwards-compatible two-decimal representation. Intl localizes the- * already-converted major amount; it must not decide the divisor.- */-export function formatStripeMinorAmount(- amount: number,- currency: string,- locale: string,-): string | null {- if (!Number.isSafeInteger(amount) || amount < 0) return null;- const normalizedCurrency = currency.trim().toUpperCase();- if (!normalizedCurrency) return null;-- try {- const fractionDigits = STRIPE_TWO_DECIMAL_COMPAT_CURRENCIES.has(- normalizedCurrency,- )- ? 2- : STRIPE_ZERO_DECIMAL_CURRENCIES.has(normalizedCurrency)- ? 0- : STRIPE_THREE_DECIMAL_CURRENCIES.has(normalizedCurrency)- ? 3- : 2;- const majorAmount = amount / 10 ** fractionDigits;- const showStripeFraction = !Number.isInteger(majorAmount);- const formatter = new Intl.NumberFormat(locale, {- style: "currency",- currency: normalizedCurrency,- ...(showStripeFraction- ? {- minimumFractionDigits: fractionDigits,- maximumFractionDigits: fractionDigits,- }- : {}),- });- return formatter.format(majorAmount);- } catch {- return null;- }-}-function planBadgeVariant(plan: string): "default" | "secondary" | "outline" {if (plan === "pro") return "default";if (plan === "free") return "secondary";diff --git a/packages/views/settings/components/members-tab.tsx b/packages/views/settings/components/members-tab.tsxindex b42b200ab5..7cffa8835c 100644--- a/packages/views/settings/components/members-tab.tsx+++ b/packages/views/settings/components/members-tab.tsx@@ -1,10 +1,31 @@"use client";-import { useState } from "react";-import { Crown, Shield, User, Plus, MoreHorizontal, UserMinus, Clock, X, Mail, Link, Copy, Trash2 } from "lucide-react";+import { useCallback, useEffect, useRef, useState } from "react";+import {+ Clock,+ Copy,+ Crown,+ Link,+ Loader2,+ Mail,+ MoreHorizontal,+ Plus,+ Shield,+ Trash2,+ User,+ UserMinus,+ X,+} from "lucide-react";import { ActorAvatar } from "../../common/actor-avatar";import { useOptionalNavigation } from "../../navigation";-import type { MemberWithUser, MemberRole, Invitation, ShareLink } from "@multica/core/types";+import type {+ Invitation,+ MemberRole,+ MemberWithUser,+ PurchaseWorkspaceSeatsRequest,+ ShareLink,+ WorkspaceSeatPurchasePreview,+} from "@multica/core/types";import { Input } from "@multica/ui/components/ui/input";import { Button } from "@multica/ui/components/ui/button";import { Card, CardContent } from "@multica/ui/components/ui/card";@@ -39,12 +60,50 @@ import {import { toast } from "sonner";import { useQuery, useQueryClient } from "@tanstack/react-query";import { useAuthStore } from "@multica/core/auth";+import {+ usePreviewWorkspaceSeatPurchase,+ usePurchaseWorkspaceSeats,+ workspaceSubscriptionSummaryOptions,+} from "@multica/core/billing";import { useWorkspaceId } from "@multica/core/hooks";import { useCurrentWorkspace } from "@multica/core/paths";-import { memberListOptions, invitationListOptions, shareLinkListOptions, workspaceKeys } from "@multica/core/workspace/queries";+import {+ invitationListOptions,+ memberListOptions,+ shareLinkListOptions,+ workspaceKeys,+} from "@multica/core/workspace/queries";import { api, errorCode } from "@multica/core/api";-import { useT } from "../../i18n";+import { useLocale, useT } from "../../i18n";import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";+import { formatStripeMinorAmount } from "./billing-format";+import {+ isSingleSeatInvitePreview,+ purchasedSeatIsReadyForInvitation,+ seatPurchaseCanRetryWithSameQuote,+ seatPurchaseMatchesPreview,+} from "./seat-invite-purchase";++const SEAT_PURCHASE_CONFIRM_TIMEOUT_MS = 2 * 60_000;++type InviteSeatPurchase = {+ workspaceId: string;+ email: string;+ role: MemberRole;+ preview: WorkspaceSeatPurchasePreview;+ idempotencyKey: string;+ phase: "review" | "purchasing" | "waiting" | "inviting" | "error";+ submittedAt?: number;+ error?: string;+ retryable?: boolean;+};++function createSeatPurchaseKey(workspaceId: string): string {+ const suffix =+ globalThis.crypto?.randomUUID?.() ??+ `${Date.now()}-${Math.random().toString(36).slice(2)}`;+ return `invite-seat-${workspaceId}-${suffix}`.slice(0, 200);+}const ROLE_ICONS: Record<MemberRole, typeof Crown> = {owner: Crown,@@ -302,6 +361,8 @@ function ShareLinkRow({export function MembersTab() {const { t } = useT("settings");+ const { t: billingT } = useT("billing");+ const locale = useLocale();const roleConfig = useRoleLabels();const user = useAuthStore((s) => s.user);const workspace = useCurrentWorkspace();@@ -314,6 +375,9 @@ export function MembersTab() {const [inviteEmail, setInviteEmail] = useState("");const [inviteRole, setInviteRole] = useState<MemberRole>("member");const [inviteLoading, setInviteLoading] = useState(false);+ const [inviteSeatPurchase, setInviteSeatPurchase] =+ useState<InviteSeatPurchase | null>(null);+ const dispatchedInvitePurchaseKey = useRef<string | null>(null);const [memberActionId, setMemberActionId] = useState<string | null>(null);const [invitationActionId, setInvitationActionId] = useState<string | null>(null);const [shareLinkActionId, setShareLinkActionId] = useState<string | null>(null);@@ -326,6 +390,17 @@ export function MembersTab() {variant?: "destructive";onConfirm: () => Promise<void>;} | null>(null);+ const previewSeatPurchase = usePreviewWorkspaceSeatPurchase();+ const purchaseSeats = usePurchaseWorkspaceSeats(wsId);+ const seatPurchaseSummary = useQuery({+ ...workspaceSubscriptionSummaryOptions(wsId),+ enabled:+ inviteSeatPurchase?.phase === "waiting" &&+ inviteSeatPurchase.workspaceId === wsId,+ staleTime: 0,+ refetchInterval:+ inviteSeatPurchase?.phase === "waiting" ? 2_000 : false,+ });const currentMember = members.find((m) => m.user_id === user?.id) ?? null;const canManageWorkspace = currentMember?.role === "owner" || currentMember?.role === "admin";@@ -335,29 +410,90 @@ export function MembersTab() {// members (the server would 403) once the current member's role is known.const { data: shareLinks = [] } = useQuery(shareLinkListOptions(wsId, canManageWorkspace));+ const sendInvitation = useCallback(+ async (email: string, role: MemberRole) => {+ if (!workspace) return;+ await api.createMember(workspace.id, { email, role });+ setInviteEmail("");+ setInviteRole("member");+ await qc.invalidateQueries({+ queryKey: workspaceKeys.invitations(wsId),+ });+ toast.success(t(($) => $.members.toast_invitation_sent));+ },+ [qc, t, workspace, wsId],+ );+const handleInviteMember = async () => {if (!workspace) return;+ const email = inviteEmail.trim();+ const role = inviteRole;setInviteLoading(true);try {- await api.createMember(workspace.id, {- email: inviteEmail,- role: inviteRole,- });- setInviteEmail("");- setInviteRole("member");- qc.invalidateQueries({ queryKey: workspaceKeys.invitations(wsId) });- toast.success(t(($) => $.members.toast_invitation_sent));+ await sendInvitation(email, role);} catch (e) {const code = errorCode(e);+ if (code === "seat_capacity_overcommitted") {+ try {+ const summary = await qc.fetchQuery({+ ...workspaceSubscriptionSummaryOptions(wsId),+ staleTime: 0,+ });+ const capacity = summary?.seatCapacity;+ toast.error(+ billingT(($) => $.workspace.seats.members_over_capacity_title),+ capacity+ ? {+ description: billingT(+ ($) => $.workspace.seats.occupancy_over_capacity_description,+ {+ // Cloud refuses on used + reserved, so pending+ // invitations have to appear here: the most common+ // trigger is a first ledger snapshot whose member count+ // alone still fits inside the purchased seats.+ occupied: capacity.used + capacity.reserved,+ purchased: capacity.purchased,+ members: capacity.used,+ reserved: capacity.reserved,+ },+ ),+ }+ : undefined,+ );+ } catch {+ toast.error(+ billingT(($) => $.workspace.seats.members_over_capacity_title),+ );+ }+ return;+ }if (code === "seat_capacity_full") {- toast.error(t(($) => $.members.toast_seat_capacity_full), {- action: navigation- ? {- label: t(($) => $.members.add_seats_action),- onClick: () => navigation.push(`/${workspace.slug}/settings?tab=billing`),- }- : undefined,- });+ try {+ const preview = await previewSeatPurchase.mutateAsync({+ additionalSeats: 1,+ });+ if (!isSingleSeatInvitePreview(preview)) {+ toast.error(+ billingT(($) => $.workspace.seat_purchase.preview_unreadable),+ );+ return;+ }+ setInviteSeatPurchase({+ workspaceId: workspace.id,+ email,+ role,+ preview,+ idempotencyKey: createSeatPurchaseKey(workspace.id),+ phase: "review",+ });+ dispatchedInvitePurchaseKey.current = null;+ } catch (previewError) {+ toast.error(+ errorCode(previewError) === "seat_purchase_in_progress"+ ? billingT(($) => $.workspace.seat_purchase.in_progress)+ : billingT(($) => $.workspace.seat_purchase.preview_failed),+ );+ }return;}if (code === "seat_capacity_unavailable") {@@ -370,6 +506,151 @@ export function MembersTab() {}};+ const handlePurchaseSeatAndInvite = async () => {+ if (+ !inviteSeatPurchase ||+ (inviteSeatPurchase.phase !== "review" &&+ !(inviteSeatPurchase.phase === "error" && inviteSeatPurchase.retryable))+ ) {+ return;+ }+ const current = inviteSeatPurchase;+ if (!workspace || current.workspaceId !== workspace.id) {+ setInviteSeatPurchase(null);+ return;+ }+ setInviteSeatPurchase({+ ...current,+ phase: "purchasing",+ error: undefined,+ retryable: false,+ });+ const request: PurchaseWorkspaceSeatsRequest = {+ additionalSeats: current.preview.additionalSeats,+ expectedCurrentSeats: current.preview.currentSeats,+ expectedPurchaseVersion: current.preview.purchaseVersion,+ acceptedProrationAmount: current.preview.prorationAmount,+ currency: current.preview.currency,+ idempotencyKey: current.idempotencyKey,+ };+ try {+ const response = await purchaseSeats.mutateAsync(request);+ if (!seatPurchaseMatchesPreview(response, current.preview)) {+ setInviteSeatPurchase({+ ...current,+ phase: "error",+ error: billingT(+ ($) => $.workspace.seat_purchase.purchase_unreadable,+ ),+ retryable: true,+ });+ return;+ }+ const submittedAt = Date.now();+ setInviteSeatPurchase({+ ...current,+ phase: "waiting",+ submittedAt,+ error: undefined,+ retryable: false,+ });+ await qc.invalidateQueries({+ queryKey: workspaceSubscriptionSummaryOptions(wsId).queryKey,+ });+ } catch (error) {+ const code = errorCode(error);+ const message =+ code === "seat_purchase_payment_failed"+ ? billingT(($) => $.workspace.seat_purchase.payment_failed)+ : code === "seat_purchase_in_progress"+ ? billingT(($) => $.workspace.seat_purchase.in_progress)+ : code === "seat_quote_changed" || code === "seat_capacity_changed"+ ? billingT(($) => $.workspace.seat_purchase.quote_changed)+ : billingT(($) => $.workspace.seat_purchase.purchase_failed);+ setInviteSeatPurchase({+ ...current,+ phase: "error",+ error: message,+ retryable: seatPurchaseCanRetryWithSameQuote(code),+ });+ }+ };++ useEffect(() => {+ setInviteSeatPurchase((current) =>+ current && current.workspaceId !== wsId ? null : current,+ );+ }, [wsId]);++ useEffect(() => {+ const purchase = inviteSeatPurchase;+ if (+ purchase?.phase !== "waiting" ||+ purchase.workspaceId !== wsId ||+ purchase.submittedAt == null ||+ dispatchedInvitePurchaseKey.current === purchase.idempotencyKey ||+ !purchasedSeatIsReadyForInvitation(+ seatPurchaseSummary.data,+ purchase.preview,+ purchase.submittedAt,+ seatPurchaseSummary.dataUpdatedAt,+ )+ ) {+ return;+ }++ dispatchedInvitePurchaseKey.current = purchase.idempotencyKey;+ setInviteSeatPurchase({ ...purchase, phase: "inviting" });+ void sendInvitation(purchase.email, purchase.role)+ .then(() => setInviteSeatPurchase(null))+ .catch((error) => {+ const code = errorCode(error);+ setInviteSeatPurchase({+ ...purchase,+ phase: "error",+ retryable: false,+ error:+ code === "seat_capacity_full"+ ? t(($) => $.members.seat_purchase_capacity_taken)+ : code === "seat_capacity_unavailable"+ ? t(($) => $.members.toast_seat_capacity_unavailable)+ : error instanceof Error+ ? error.message+ : t(($) => $.members.toast_invitation_failed),+ });+ });+ }, [+ inviteSeatPurchase,+ seatPurchaseSummary.data,+ seatPurchaseSummary.dataUpdatedAt,+ sendInvitation,+ t,+ wsId,+ ]);++ useEffect(() => {+ if (+ inviteSeatPurchase?.phase !== "waiting" ||+ inviteSeatPurchase.submittedAt == null+ ) {+ return;+ }+ const elapsed = Date.now() - inviteSeatPurchase.submittedAt;+ const timeout = window.setTimeout(() => {+ setInviteSeatPurchase((current) =>+ current?.phase === "waiting"+ ? {+ ...current,+ phase: "error",+ error: t(($) => $.members.seat_purchase_timeout),+ retryable: false,+ }+ : current,+ );+ }, Math.max(0, SEAT_PURCHASE_CONFIRM_TIMEOUT_MS - elapsed));+ return () => window.clearTimeout(timeout);+ }, [inviteSeatPurchase?.phase, inviteSeatPurchase?.submittedAt, t]);+const handleRevokeInvitation = (invitation: Invitation) => {if (!workspace) return;setConfirmAction({@@ -653,6 +934,119 @@ export function MembersTab() {</SettingsSection>)}+ <AlertDialog+ open={inviteSeatPurchase !== null}+ onOpenChange={(open) => {+ if (+ !open &&+ (inviteSeatPurchase?.phase === "review" ||+ inviteSeatPurchase?.phase === "error")+ ) {+ setInviteSeatPurchase(null);+ }+ }}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {t(($) => $.members.seat_purchase_title)}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {inviteSeatPurchase?.phase === "review"+ ? t(($) => $.members.seat_purchase_description, {+ email: inviteSeatPurchase.email,+ })+ : inviteSeatPurchase?.phase === "error"+ ? inviteSeatPurchase.error+ : t(($) => $.members.seat_purchase_waiting)}+ </AlertDialogDescription>+ </AlertDialogHeader>++ {inviteSeatPurchase?.phase === "review" && (+ <div className="divide-y rounded-lg border text-body">+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <span className="text-muted-foreground">+ {billingT(($) => $.workspace.seat_purchase.seats_after)}+ </span>+ <span className="font-medium">+ {billingT(($) => $.workspace.seats.seat_count, {+ count: inviteSeatPurchase.preview.resultingSeats,+ })}+ </span>+ </div>+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <span className="text-muted-foreground">+ {billingT(($) => $.workspace.seat_purchase.charge_today)}+ </span>+ <span className="font-medium">+ {formatStripeMinorAmount(+ inviteSeatPurchase.preview.prorationAmount,+ inviteSeatPurchase.preview.currency,+ locale,+ ) ?? "—"}+ </span>+ </div>+ <div className="flex items-center justify-between gap-4 px-4 py-3">+ <span className="text-muted-foreground">+ {billingT(($) => $.workspace.seat_purchase.next_invoice)}+ </span>+ <span className="font-medium">+ {formatStripeMinorAmount(+ inviteSeatPurchase.preview.nextInvoiceAmount,+ inviteSeatPurchase.preview.currency,+ locale,+ ) ?? "—"}+ </span>+ </div>+ <p className="px-4 py-3 text-caption text-muted-foreground">+ {billingT(($) => $.workspace.seat_purchase.tax_notice)}+ </p>+ </div>+ )}++ {(inviteSeatPurchase?.phase === "purchasing" ||+ inviteSeatPurchase?.phase === "waiting" ||+ inviteSeatPurchase?.phase === "inviting") && (+ <div className="flex items-center gap-2 text-body text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" />+ {inviteSeatPurchase.phase === "inviting"+ ? t(($) => $.members.inviting)+ : t(($) => $.members.seat_purchase_waiting)}+ </div>+ )}++ <AlertDialogFooter>+ {(inviteSeatPurchase?.phase === "review" ||+ inviteSeatPurchase?.phase === "error") && (+ <AlertDialogCancel>+ {t(($) => $.members.confirm_cancel)}+ </AlertDialogCancel>+ )}+ {inviteSeatPurchase?.phase === "review" && (+ <AlertDialogAction+ onClick={(event) => {+ event.preventDefault();+ void handlePurchaseSeatAndInvite();+ }}+ >+ {t(($) => $.members.purchase_seat_and_invite)}+ </AlertDialogAction>+ )}+ {inviteSeatPurchase?.phase === "error" &&+ inviteSeatPurchase.retryable && (+ <AlertDialogAction+ onClick={(event) => {+ event.preventDefault();+ void handlePurchaseSeatAndInvite();+ }}+ >+ {t(($) => $.members.retry_seat_purchase)}+ </AlertDialogAction>+ )}+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+<AlertDialog open={!!confirmAction} onOpenChange={(v) => { if (!v) setConfirmAction(null); }}><AlertDialogContent><AlertDialogHeader>diff --git a/packages/views/settings/components/seat-invite-purchase.test.ts b/packages/views/settings/components/seat-invite-purchase.test.tsnew file mode 100644index 0000000000..69ece536a4--- /dev/null+++ b/packages/views/settings/components/seat-invite-purchase.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from "vitest";+import type {+ WorkspaceSeatPurchasePreview,+ WorkspaceSubscriptionSummary,+} from "@multica/core/types";+import {+ isSingleSeatInvitePreview,+ purchasedSeatIsReadyForInvitation,+ seatPurchaseCanRetryWithSameQuote,+ seatPurchaseMatchesPreview,+} from "./seat-invite-purchase";++const preview: WorkspaceSeatPurchasePreview = {+ currentSeats: 4,+ additionalSeats: 1,+ resultingSeats: 5,+ purchaseVersion: 7,+ currency: "usd",+ prorationAmount: 425,+ nextInvoiceAmount: 5_000,+ quotedAt: "2026-08-25T00:00:00Z",+};++function summary(purchased: number, available: number): WorkspaceSubscriptionSummary {+ return {+ entitlement: {+ workspaceId: "workspace-1",+ plan: "pro",+ status: "active",+ seats: purchased,+ issueWindow: null,+ autopilotRuns: null,+ currentPeriodEnd: null,+ snapshotExpiresAt: null,+ version: 1,+ },+ billingInterval: "month",+ humanMembers: 4,+ seatCapacity: {+ purchased,+ used: 4,+ reserved: purchased - 4 - available,+ available,+ version: 8,+ pendingQuantity: null,+ activePurchase: null,+ },+ cancelAtPeriodEnd: false,+ graceUntil: null,+ hasStripeCustomer: true,+ };+}++describe("invite seat purchase validation", () => {+ it("accepts only a coherent one-seat server preview", () => {+ expect(isSingleSeatInvitePreview(preview)).toBe(true);+ expect(+ isSingleSeatInvitePreview({ ...preview, resultingSeats: 6 }),+ ).toBe(false);+ expect(+ isSingleSeatInvitePreview({ ...preview, prorationAmount: -1 }),+ ).toBe(false);+ });++ it("requires the purchase response to match the accepted quote", () => {+ const response = {+ requestId: "request-1",+ currentSeats: 4,+ additionalSeats: 1,+ resultingSeats: 5,+ currency: "usd",+ prorationAmount: 425,+ nextInvoiceAmount: 5_000,+ status: "submitted" as const,+ };+ expect(seatPurchaseMatchesPreview(response, preview)).toBe(true);+ expect(+ seatPurchaseMatchesPreview({ ...response, resultingSeats: 6 }, preview),+ ).toBe(false);+ });++ it("reuses the idempotent quote only for retry-safe failures", () => {+ expect(seatPurchaseCanRetryWithSameQuote(undefined)).toBe(true);+ expect(seatPurchaseCanRetryWithSameQuote("seat_purchase_rate_limited")).toBe(+ true,+ );+ expect(seatPurchaseCanRetryWithSameQuote("seat_purchase_payment_failed")).toBe(+ false,+ );+ expect(seatPurchaseCanRetryWithSameQuote("seat_quote_changed")).toBe(false);+ expect(seatPurchaseCanRetryWithSameQuote("seat_capacity_changed")).toBe(false);+ expect(seatPurchaseCanRetryWithSameQuote("seat_purchase_in_progress")).toBe(+ false,+ );+ });++ it("retries the invitation only from a fresh summary with free capacity", () => {+ expect(purchasedSeatIsReadyForInvitation(summary(5, 1), preview, 100, 101)).toBe(true);+ expect(purchasedSeatIsReadyForInvitation(summary(5, 1), preview, 100, 99)).toBe(false);+ expect(purchasedSeatIsReadyForInvitation(summary(4, 0), preview, 100, 101)).toBe(false);+ expect(purchasedSeatIsReadyForInvitation(summary(5, 0), preview, 100, 101)).toBe(false);+ });+});diff --git a/packages/views/settings/components/seat-invite-purchase.ts b/packages/views/settings/components/seat-invite-purchase.tsnew file mode 100644index 0000000000..11fd457c14--- /dev/null+++ b/packages/views/settings/components/seat-invite-purchase.ts@@ -0,0 +1,58 @@+import type {+ PurchaseWorkspaceSeatsResponse,+ WorkspaceSeatPurchasePreview,+ WorkspaceSubscriptionSummary,+} from "@multica/core/types";++export function isSingleSeatInvitePreview(+ preview: WorkspaceSeatPurchasePreview | null | undefined,+): preview is WorkspaceSeatPurchasePreview {+ return Boolean(+ preview &&+ preview.additionalSeats === 1 &&+ preview.resultingSeats === preview.currentSeats + 1 &&+ Number.isSafeInteger(preview.prorationAmount) &&+ preview.prorationAmount >= 0 &&+ Number.isSafeInteger(preview.nextInvoiceAmount) &&+ preview.nextInvoiceAmount >= 0,+ );+}++export function seatPurchaseMatchesPreview(+ response: PurchaseWorkspaceSeatsResponse | null | undefined,+ preview: WorkspaceSeatPurchasePreview,+): response is PurchaseWorkspaceSeatsResponse {+ return Boolean(+ response &&+ response.currentSeats === preview.currentSeats &&+ response.additionalSeats === preview.additionalSeats &&+ response.resultingSeats === preview.resultingSeats &&+ response.currency === preview.currency,+ );+}++export function seatPurchaseCanRetryWithSameQuote(+ errorCode: string | undefined,+): boolean {+ return ![+ "seat_purchase_payment_failed",+ "seat_purchase_in_progress",+ "seat_quote_changed",+ "seat_capacity_changed",+ ].includes(errorCode ?? "");+}++export function purchasedSeatIsReadyForInvitation(+ summary: WorkspaceSubscriptionSummary | null | undefined,+ preview: WorkspaceSeatPurchasePreview,+ submittedAt: number,+ summaryUpdatedAt: number,+): boolean {+ const capacity = summary?.seatCapacity;+ return Boolean(+ summaryUpdatedAt >= submittedAt &&+ capacity &&+ capacity.purchased >= preview.resultingSeats &&+ capacity.available >= 1,+ );+}diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.shindex 1ef483b12a..5277a32592 100644--- a/scripts/helm-config.test.sh+++ b/scripts/helm-config.test.sh@@ -36,7 +36,6 @@ require_rendered_value "$default_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "truerequire_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_ENABLED: "false"'require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_URL: ""'require_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: "false"'-require_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED: "false"'require_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL: ""'require_rendered_value "$default_config" 'MULTICA_TASK_QUEUED_TTL: "2h"'require_rendered_value "$default_config" 'MULTICA_DATABASE_STARTUP_TIMEOUT: "3m"'@@ -87,12 +86,10 @@ capacity_config="$(helm template multica "$CHART_DIR" \--show-only templates/configmap.yaml \--set backend.config.subscriptionCapacity.enabled=true \- --set backend.config.subscriptionCapacity.workerEnabled=true \--set-string backend.config.subscriptionCapacity.url=https://multica-cloud.internal \--set-string backend.config.subscriptionCapacity.timeout=2s)"require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED: "true"'-require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED: "true"'require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL: "https://multica-cloud.internal"'require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: "2s"'reject_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN'diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex d4381cad2a..281a35cf01 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -421,14 +421,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bush.AutopilotService.Entitlements = entitlementClienth.AutopilotService.QuotaMetrics = opts.BusinessMetrics}- capacityEnforcementEnabled := envBool("MULTICA_SUBSCRIPTION_CAPACITY_ENABLED", false)- // Settlement remains independently enabled during an enforcement rollback- // so existing confirm/release intents keep draining. Enforcement always- // implies settlement; operators only need the separate flag when pausing- // new capacity admission.- capacityWorkerEnabled := capacityEnforcementEnabled || envBool("MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED", false)+ // This is deployment wiring, not a business mode: when connected, admission+ // and settlement both follow Cloud's single strict prepaid-seat policy.+ capacityEnabled := envBool("MULTICA_SUBSCRIPTION_CAPACITY_ENABLED", false)capacityClient, capacityErr := seatcapacity.New(seatcapacity.Config{- Enabled: capacityWorkerEnabled,+ Enabled: capacityEnabled,BaseURL: strings.TrimSpace(os.Getenv("MULTICA_SUBSCRIPTION_CAPACITY_URL")),ServiceToken: os.Getenv("MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN"),Timeout: envDuration("MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT", 3*time.Second),@@ -442,10 +439,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus} else {h.SeatCapacity = capacityClient}- h.SeatCapacityEnforcementEnabled = capacityEnforcementEnabledcapacityLocker := seatcapacity.NewWorkspaceLocker(pool)h.SeatCapacityLocker = capacityLocker- if capacityWorkerEnabled && h.SeatCapacity.Enabled() {+ if capacityEnabled && h.SeatCapacity.Enabled() {h.SeatCapacityWorker = seatcapacity.NewWorker(queries, h.SeatCapacity, capacityLocker, seatcapacity.WorkerConfig{Metrics: opts.SeatCapacityMetrics,})diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex fb4de4f3dd..0fd7a252ac 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -194,16 +194,15 @@ type Handler struct {Entitlements entitlement.Provider// SeatCapacity executes Cloud's pre-purchased human-seat protocol. Nil or// disabled preserves self-hosted behavior.- SeatCapacity seatcapacity.Executor- SeatCapacityEnforcementEnabled bool- SeatCapacityLocker seatcapacity.WorkspaceLocker- SeatCapacityWorker *seatcapacity.Worker- EmailService *service.EmailService- UpdateStore UpdateStore- ModelListStore ModelListStore- LocalSkillListStore LocalSkillListStore- LocalSkillImportStore LocalSkillImportStore- FeatureFlags *featureflag.Service+ SeatCapacity seatcapacity.Executor+ SeatCapacityLocker seatcapacity.WorkspaceLocker+ SeatCapacityWorker *seatcapacity.Worker+ EmailService *service.EmailService+ UpdateStore UpdateStore+ ModelListStore ModelListStore+ LocalSkillListStore LocalSkillListStore+ LocalSkillImportStore LocalSkillImportStore+ FeatureFlags *featureflag.Service// IssueStatusCatalog reads the workspace status catalog. Defaults to// Queries; a test can substitute a counting wrapper to assert HOW MANY// catalog reads a request performs, which is the only property thatdiff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.goindex 87c2ef088e..088e683a99 100644--- a/server/internal/handler/invitation.go+++ b/server/internal/handler/invitation.go@@ -109,7 +109,7 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to create invitation")return}- if h.seatCapacitySettlementEnabled() {+ if h.seatCapacityEnabled() {for _, expired := range expiredInvitations {if err := enqueueCapacityRelease(r.Context(), h.Queries, uuid.UUID(expired.WorkspaceID.Bytes), uuid.UUID(expired.ID.Bytes)); err != nil {writeError(w, http.StatusInternalServerError, "failed to release expired invitation capacity")@@ -129,18 +129,6 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {return}- // Consume every applicable budget only after validation and idempotency- // checks, but before the invitation row or email side effect is created.- if !h.admitInvitation(- w,- r,- uuidToString(requester.UserID),- uuidToString(requester.WorkspaceID),- email,- ) {- return- }-// Resolve invitee_user_id if the user already exists.var inviteeUserID pgtype.UUIDif existingUser.ID.Valid {@@ -154,6 +142,21 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {return}+ // Consume rate-limit budgets only after capacity is secured. A request that+ // must purchase a seat can then retry without spending the same invitation+ // budgets twice. If admission rejects, the durable capacity intent releases+ // the hold immediately or through the recovery worker.+ if !h.admitInvitation(+ w,+ r,+ uuidToString(requester.UserID),+ uuidToString(requester.WorkspaceID),+ email,+ ) {+ h.compensateCapacityIntent(r.Context(), invitationID)+ return+ }+createParams := db.CreateInvitationParams{ID: uuidToPG(invitationID), WorkspaceID: requester.WorkspaceID, InviterID: requester.UserID,InviteeEmail: email, InviteeUserID: inviteeUserID, Role: role,@@ -313,7 +316,7 @@ func (h *Handler) RevokeInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusNotFound, "invitation not found")return}- if h.seatCapacitySettlementEnabled() {+ if h.seatCapacityEnabled() {if err := enqueueCapacityRelease(r.Context(), qtx, uuid.UUID(inv.WorkspaceID.Bytes), uuid.UUID(inv.ID.Bytes)); err != nil {writeError(w, http.StatusInternalServerError, "failed to revoke invitation")return@@ -323,7 +326,7 @@ func (h *Handler) RevokeInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to revoke invitation")return}- if h.seatCapacitySettlementEnabled() {+ if h.seatCapacityEnabled() {h.compensateCapacityIntent(r.Context(), uuid.UUID(inv.ID.Bytes))}@@ -641,7 +644,7 @@ func (h *Handler) DeclineInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to decline invitation")return}- if h.seatCapacitySettlementEnabled() {+ if h.seatCapacityEnabled() {if err := enqueueCapacityRelease(r.Context(), qtx, uuid.UUID(inv.WorkspaceID.Bytes), uuid.UUID(inv.ID.Bytes)); err != nil {writeError(w, http.StatusInternalServerError, "failed to decline invitation")return@@ -651,7 +654,7 @@ func (h *Handler) DeclineInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to decline invitation")return}- if h.seatCapacitySettlementEnabled() {+ if h.seatCapacityEnabled() {h.compensateCapacityIntent(r.Context(), uuid.UUID(inv.ID.Bytes))}diff --git a/server/internal/handler/invitation_test.go b/server/internal/handler/invitation_test.goindex 7ce7e7f995..ddecf3bd34 100644--- a/server/internal/handler/invitation_test.go+++ b/server/internal/handler/invitation_test.go@@ -66,12 +66,9 @@ func (s *stubSeatCapacity) GetOperation(context.Context, uuid.UUID, uuid.UUID) (func useSeatCapacity(t *testing.T, executor seatcapacity.Executor) {t.Helper()previous := testHandler.SeatCapacity- previousEnforcement := testHandler.SeatCapacityEnforcementEnabledtestHandler.SeatCapacity = executor- testHandler.SeatCapacityEnforcementEnabled = truet.Cleanup(func() {testHandler.SeatCapacity = previous- testHandler.SeatCapacityEnforcementEnabled = previousEnforcement})}@@ -250,6 +247,38 @@ func TestCreateInvitation_BlocksWhenPurchasedCapacityIsFull(t *testing.T) {}}+func TestCreateInvitation_BlocksOvercommittedCapacityWithoutOfferingSingleSeatSemantics(t *testing.T) {+ clearInvitationsForTestWorkspace(t)+ capacity := &stubSeatCapacity{reserveErr: &seatcapacity.HTTPError{+ StatusCode: http.StatusConflict,+ Code: "capacity_overcommitted",+ }}+ useSeatCapacity(t, capacity)++ req := newRequest(http.MethodPost, "/api/workspaces/"+testWorkspaceID+"/members", CreateMemberRequest{+ Email: "[email protected]", Role: "member",+ })+ req = withURLParam(req, "id", testWorkspaceID)+ rec := httptest.NewRecorder()+ testHandler.CreateInvitation(rec, req)++ if rec.Code != http.StatusConflict {+ t.Fatalf("status = %d, want 409: %s", rec.Code, rec.Body.String())+ }+ var body struct {+ Code string `json:"code"`+ }+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ t.Fatal(err)+ }+ if body.Code != "seat_capacity_overcommitted" {+ t.Fatalf("code = %q, want seat_capacity_overcommitted", body.Code)+ }+ if capacity.reserveCalls != 1 {+ t.Fatalf("reserve calls = %d, want 1", capacity.reserveCalls)+ }+}+func TestCreateInvitation_CompensatesCapacityWhenCommitRollsBack(t *testing.T) {clearInvitationsForTestWorkspace(t)ctx := context.Background()@@ -350,8 +379,13 @@ func TestCreateInvitation_AllowsAfterExpiry(t *testing.T) {}}-func TestCreateInvitation_RateLimitChecksEveryGateBeforeWrite(t *testing.T) {+func TestCreateInvitation_RateLimitChecksEveryGateAfterCapacityReservation(t *testing.T) {clearInvitationsForTestWorkspace(t)+ if _, err := testPool.Exec(context.Background(), `DELETE FROM seat_capacity_outbox WHERE workspace_id = $1`, parseUUID(testWorkspaceID)); err != nil {+ t.Fatalf("clear capacity outbox: %v", err)+ }+ capacity := &stubSeatCapacity{reserveDecision: seatcapacity.Decision{Managed: true, Allowed: true}}+ useSeatCapacity(t, capacity)actor := &stubInvitationRateLimiter{allowed: false, retryAfter: 10 * time.Minute}workspace := &stubInvitationRateLimiter{allowed: true}recipient := &stubInvitationRateLimiter{allowed: false, retryAfter: 24 * time.Hour}@@ -426,6 +460,12 @@ func TestCreateInvitation_RateLimitChecksEveryGateBeforeWrite(t *testing.T) {if pendingCount != 0 {t.Fatalf("pending invitation count = %d, want 0 after rate limit rejection", pendingCount)}+ if capacity.reserveCalls != 1 || capacity.releaseCalls != 1 {+ t.Fatalf("capacity calls reserve=%d release=%d, want 1/1", capacity.reserveCalls, capacity.releaseCalls)+ }+ if intents := dbfx.Count(t, `SELECT count(*) FROM seat_capacity_outbox WHERE workspace_id = $1`, parseUUID(testWorkspaceID)); intents != 0 {+ t.Fatalf("capacity intents = %d, want 0 after compensated rate-limit rejection", intents)+ }}func TestCreateInvitation_RateLimiterFailureReturnsServiceUnavailable(t *testing.T) {diff --git a/server/internal/handler/seat_capacity.go b/server/internal/handler/seat_capacity.goindex 7c3fe9d5d6..5b2e043cd2 100644--- a/server/internal/handler/seat_capacity.go+++ b/server/internal/handler/seat_capacity.go@@ -15,17 +15,14 @@ import ()var (- errSeatCapacityFull = errors.New("no purchased member seats are available")- errSeatCapacityUnavailable = errors.New("seat capacity service is unavailable")+ errSeatCapacityFull = errors.New("no purchased member seats are available")+ errSeatCapacityOvercommitted = errors.New("workspace members exceed purchased seat capacity")+ errSeatCapacityUnavailable = errors.New("seat capacity service is unavailable"))const seatCapacityWorkspaceLockWait = 2 * time.Secondfunc (h *Handler) seatCapacityEnabled() bool {- return h != nil && h.SeatCapacityEnforcementEnabled && h.seatCapacitySettlementEnabled()-}--func (h *Handler) seatCapacitySettlementEnabled() bool {return h != nil && h.SeatCapacity != nil && h.SeatCapacity.Enabled()}@@ -72,6 +69,12 @@ func (h *Handler) reserveInvitationCapacity(ctx context.Context, workspaceID, in}decision, err := h.SeatCapacity.ReserveInvitation(ctx, workspaceID, invitationID, expiresAt)if err != nil {+ if seatcapacity.IsCapacityOvercommitted(err) {+ if deleteErr := deleteCapacityIntentForAction(ctx, q, invitationID, seatcapacity.ActionReserveInvitation); deleteErr != nil {+ return fmt.Errorf("discard overcommitted invitation capacity intent: %w", deleteErr)+ }+ return errSeatCapacityOvercommitted+ }h.compensateCapacityIntentLocked(ctx, q, invitationID)return fmt.Errorf("%w: %v", errSeatCapacityUnavailable, err)}@@ -79,8 +82,10 @@ func (h *Handler) reserveInvitationCapacity(ctx context.Context, workspaceID, inreturn deleteCapacityIntentForAction(ctx, q, invitationID, seatcapacity.ActionReserveInvitation)}if !decision.Allowed {- _ = deleteCapacityIntentForAction(ctx, q, invitationID, seatcapacity.ActionReserveInvitation)- if decision.Reason == "capacity_full" || decision.Reason == "denied" {+ if deleteErr := deleteCapacityIntentForAction(ctx, q, invitationID, seatcapacity.ActionReserveInvitation); deleteErr != nil {+ return fmt.Errorf("discard rejected invitation capacity intent: %w", deleteErr)+ }+ if decision.Reason == "capacity_full" {return errSeatCapacityFull}return fmt.Errorf("%w: reservation rejected in state %s", errSeatCapacityUnavailable, decision.Reason)@@ -95,10 +100,9 @@ func (h *Handler) reserveInvitationCapacity(ctx context.Context, workspaceID, in}func (h *Handler) beginCapacityConsume(ctx context.Context, workspaceID, token, invitationID, userID uuid.UUID) (bool, error) {- if !h.seatCapacitySettlementEnabled() {+ if !h.seatCapacityEnabled() {return false, nil}- enforced := h.seatCapacityEnabled()q, unlock, err := h.lockSeatCapacityWorkspace(ctx, workspaceID)if err != nil {return false, fmt.Errorf("%w: acquire workspace capacity lock: %v", errSeatCapacityUnavailable, err)@@ -113,25 +117,18 @@ func (h *Handler) beginCapacityConsume(ctx context.Context, workspaceID, token,}decision, err := h.SeatCapacity.Consume(ctx, workspaceID, token)if err != nil {- if !enforced {- if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionConsumeInvitation); deleteErr != nil {- return false, fmt.Errorf("discard unenforced invitation consume intent: %w", deleteErr)- }- return false, nil- }return false, fmt.Errorf("%w: %v", errSeatCapacityUnavailable, err)}if !decision.Managed {return false, deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionConsumeInvitation)}if !decision.Allowed {+ if expireErr := q.ExpireInvitationForCapacityRecovery(ctx, uuidToPG(invitationID)); expireErr != nil {+ return false, fmt.Errorf("expire invitation after rejected capacity consume: %w", expireErr)+ }if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionConsumeInvitation); deleteErr != nil {return false, fmt.Errorf("discard rejected invitation consume intent: %w", deleteErr)}- if !enforced {- return false, nil- }- _ = q.ExpireInvitationForCapacityRecovery(ctx, uuidToPG(invitationID))return false, errSeatCapacityFull}err = q.MarkSeatCapacityIntentDelivered(ctx, db.MarkSeatCapacityIntentDeliveredParams{@@ -160,13 +157,21 @@ func (h *Handler) beginShareJoinCapacity(ctx context.Context, workspaceID, sharetoken := uuid.UUID(intent.OperationToken.Bytes)decision, err := h.SeatCapacity.ClaimShareJoin(ctx, workspaceID, token)if err != nil {+ if seatcapacity.IsCapacityOvercommitted(err) {+ if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionClaimShareJoin); deleteErr != nil {+ return uuid.Nil, fmt.Errorf("discard overcommitted share-join capacity intent: %w", deleteErr)+ }+ return uuid.Nil, errSeatCapacityOvercommitted+ }return uuid.Nil, fmt.Errorf("%w: %v", errSeatCapacityUnavailable, err)}if !decision.Managed {return uuid.Nil, deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionClaimShareJoin)}if !decision.Allowed {- _ = deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionClaimShareJoin)+ if deleteErr := deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionClaimShareJoin); deleteErr != nil {+ return uuid.Nil, fmt.Errorf("discard rejected share-join capacity intent: %w", deleteErr)+ }return uuid.Nil, errSeatCapacityFull}if err := q.MarkSeatCapacityIntentDelivered(ctx, db.MarkSeatCapacityIntentDeliveredParams{@@ -209,7 +214,7 @@ func enqueueMemberCapacityRelease(ctx context.Context, q *db.Queries, workspaceI}func (h *Handler) confirmCapacityIntent(ctx context.Context, workspaceID, token, memberID uuid.UUID) {- if !h.seatCapacitySettlementEnabled() {+ if !h.seatCapacityEnabled() {return}q, unlock, err := h.lockSeatCapacityWorkspace(ctx, workspaceID)@@ -238,7 +243,7 @@ func (h *Handler) confirmCapacityIntent(ctx context.Context, workspaceID, token,}func (h *Handler) compensateCapacityIntent(ctx context.Context, token uuid.UUID) {- if !h.seatCapacitySettlementEnabled() {+ if !h.seatCapacityEnabled() {return}intent, err := h.Queries.GetSeatCapacityIntent(ctx, uuidToPG(token))@@ -271,7 +276,7 @@ func (h *Handler) compensateCapacityIntentLocked(ctx context.Context, q *db.Querreturn}decision, releaseErr := h.SeatCapacity.Release(ctx, uuid.UUID(intent.WorkspaceID.Bytes), token)- if (releaseErr == nil && (!decision.Managed || decision.Allowed || decision.Reason == "released" || decision.Reason == "denied")) || seatcapacity.IsNotFound(releaseErr) {+ if (releaseErr == nil && (!decision.Managed || decision.Allowed || decision.Reason == "released")) || seatcapacity.IsNotFound(releaseErr) {_ = deleteCapacityIntentForAction(ctx, q, token, seatcapacity.ActionRelease)return}@@ -282,7 +287,7 @@ func (h *Handler) compensateCapacityIntentLocked(ctx context.Context, q *db.Quer}func (h *Handler) settleMemberCapacityRelease(ctx context.Context, workspaceID, memberID uuid.UUID) {- if !h.seatCapacitySettlementEnabled() {+ if !h.seatCapacityEnabled() {return}q, unlock, err := h.lockSeatCapacityWorkspace(ctx, workspaceID)@@ -327,6 +332,8 @@ func recordCapacityFailure(ctx context.Context, q *db.Queries, token uuid.UUID,func writeSeatCapacityError(w http.ResponseWriter, err error) {switch {+ case errors.Is(err, errSeatCapacityOvercommitted):+ writeErrorCode(w, http.StatusConflict, "seat_capacity_overcommitted", "Workspace members exceed purchased seats. Add enough seats or remove members before adding another member.")case errors.Is(err, errSeatCapacityFull):writeErrorCode(w, http.StatusConflict, "seat_capacity_full", "No purchased member seats are available. Add seats in Billing before adding another member.")default:diff --git a/server/internal/handler/seat_capacity_test.go b/server/internal/handler/seat_capacity_test.goindex acaf7b9cd1..92f9313379 100644--- a/server/internal/handler/seat_capacity_test.go+++ b/server/internal/handler/seat_capacity_test.go@@ -210,13 +210,12 @@ func TestSeatCapacityIntentCannotRegressOrBeDeletedByStaleWorker(t *testing.T) {}}-func TestCapacitySettlementContinuesForInvitationWhileEnforcementIsPaused(t *testing.T) {+func TestCapacityConsumeRecordsDeliveredIntent(t *testing.T) {ctx := context.Background()workspaceID := uuid.UUID(parseUUID(testWorkspaceID).Bytes)token, userID := uuid.New(), uuid.New()executor := &stubSeatCapacity{}useSeatCapacity(t, executor)- testHandler.SeatCapacityEnforcementEnabled = falsepreviousLocker := testHandler.SeatCapacityLockertestHandler.SeatCapacityLocker = seatcapacity.NewWorkspaceLocker(testPool)t.Cleanup(func() {@@ -236,37 +235,36 @@ func TestCapacitySettlementContinuesForInvitationWhileEnforcementIsPaused(t *test.Fatal(err)}if intent.Action != seatcapacity.ActionConsumeInvitation || !intent.DeliveredAt.Valid {- t.Fatalf("paused-enforcement consume intent = %+v", intent)+ t.Fatalf("consume intent = %+v", intent)}}-func TestCapacityEnforcementPauseFailsOpenConsumeError(t *testing.T) {+func TestCapacityConsumeFailsClosedWhenCloudIsUnavailable(t *testing.T) {ctx := context.Background()workspaceID := uuid.UUID(parseUUID(testWorkspaceID).Bytes)token, userID := uuid.New(), uuid.New()executor := &stubSeatCapacity{consumeErr: errors.New("capacity service unavailable")}useSeatCapacity(t, executor)- testHandler.SeatCapacityEnforcementEnabled = falset.Cleanup(func() {_, _ = testPool.Exec(ctx, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, token)})active, err := testHandler.beginCapacityConsume(ctx, workspaceID, token, token, userID)- if err != nil {- t.Fatal(err)+ if !errors.Is(err, errSeatCapacityUnavailable) {+ t.Fatalf("consume error = %v, want errSeatCapacityUnavailable", err)}if active || executor.consumeCalls != 1 {t.Fatalf("active=%v consumeCalls=%d, want false/1", active, executor.consumeCalls)}- if intents := dbfx.Count(t, `SELECT count(*) FROM seat_capacity_outbox WHERE operation_token = $1`, uuidToPG(token)); intents != 0 {- t.Fatalf("capacity intents = %d, want 0 after fail-open", intents)+ if intents := dbfx.Count(t, `SELECT count(*) FROM seat_capacity_outbox WHERE operation_token = $1`, uuidToPG(token)); intents != 1 {+ t.Fatalf("capacity intents = %d, want 1 for recovery", intents)}}-func TestAcceptInvitationAllowsDeniedCapacityWhenEnforcementIsPaused(t *testing.T) {+func TestAcceptInvitationRejectsUnavailableReservedCapacity(t *testing.T) {ctx := context.Background()- email := "paused-capacity-invite-" + uuid.NewString() + "@multica.ai"- userID := dbfx.User(t, "Paused Capacity Invitee", email)+ email := "strict-capacity-invite-" + uuid.NewString() + "@multica.ai"+ userID := dbfx.User(t, "Strict Capacity Invitee", email)invitationID := dbfx.Insert(t, "workspace_invitation", testutil.Cols{"workspace_id": testWorkspaceID,"inviter_id": testUserID,@@ -279,29 +277,28 @@ func TestAcceptInvitationAllowsDeniedCapacityWhenEnforcementIsPaused(t *testing.dbfx.Cleanup(t, `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, parseUUID(testWorkspaceID), parseUUID(userID))dbfx.Cleanup(t, `DELETE FROM seat_capacity_outbox WHERE operation_token = $1`, parseUUID(invitationID))- denied := seatcapacity.Decision{Managed: true, Allowed: false, Reason: "capacity_full"}- executor := &stubSeatCapacity{consumeDecision: &denied}+ rejected := seatcapacity.Decision{Managed: true, Allowed: false, Reason: "capacity_full"}+ executor := &stubSeatCapacity{consumeDecision: &rejected}useSeatCapacity(t, executor)- testHandler.SeatCapacityEnforcementEnabled = falsereq := newRequest("POST", "/api/invitations/"+invitationID+"/accept", nil)req.Header.Set("X-User-ID", userID)req = withURLParam(req, "id", invitationID)rec := testutil.Call(t, testHandler.AcceptInvitation, req)- rec.Want(200)+ rec.Want(409)var invitationStatus stringif err := testPool.QueryRow(ctx, `SELECT status FROM workspace_invitation WHERE id = $1`, parseUUID(invitationID)).Scan(&invitationStatus); err != nil {t.Fatal(err)}- if invitationStatus != "accepted" {- t.Fatalf("invitation status = %q, want accepted", invitationStatus)+ if invitationStatus != "expired" {+ t.Fatalf("invitation status = %q, want expired", invitationStatus)}- if members := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, parseUUID(testWorkspaceID), parseUUID(userID)); members != 1 {- t.Fatalf("member count = %d, want 1", members)+ if members := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, parseUUID(testWorkspaceID), parseUUID(userID)); members != 0 {+ t.Fatalf("member count = %d, want 0", members)}if intents := dbfx.Count(t, `SELECT count(*) FROM seat_capacity_outbox WHERE operation_token = $1`, parseUUID(invitationID)); intents != 0 {- t.Fatalf("capacity intents = %d, want 0 after fail-open", intents)+ t.Fatalf("capacity intents = %d, want 0 after denial", intents)}if executor.consumeCalls != 1 {t.Fatalf("capacity consume calls = %d, want 1", executor.consumeCalls)diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 6ac2db640c..e2e2b6af74 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -1160,7 +1160,7 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {// disappear. Skipped for self-hosted/unmanaged deployments.name: "prepare seat capacity release",run: func() error {- if !h.seatCapacitySettlementEnabled() {+ if !h.seatCapacityEnabled() {return nil}if err := qtx.DeleteSeatCapacityConfirmIntentsForWorkspaceDeletion(ctx, requester.WorkspaceID); err != nil {diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.goindex 221be16d5e..cc0ea86962 100644--- a/server/internal/handler/workspace_revoke.go+++ b/server/internal/handler/workspace_revoke.go@@ -211,7 +211,7 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID// never followed by a failed member-delete (which would leave the user// still a member with a dead runtime), and a failed revoke never leaves// the user out of the workspace with a still-online runtime.- if h.seatCapacitySettlementEnabled() {+ if h.seatCapacityEnabled() {if err := enqueueMemberCapacityRelease(ctx, qtx, uuid.UUID(workspaceID.Bytes), uuid.UUID(memberID.Bytes)); err != nil {return empty, err}diff --git a/server/internal/seatcapacity/client.go b/server/internal/seatcapacity/client.goindex 2f246c3d55..176aec4a29 100644--- a/server/internal/seatcapacity/client.go+++ b/server/internal/seatcapacity/client.go@@ -72,7 +72,7 @@ type Executor interface {type unavailableExecutor struct{ err error }// NewUnavailable preserves fail-closed behavior when an operator explicitly-// enabled capacity enforcement with invalid configuration.+// enabled managed capacity with invalid configuration.func NewUnavailable(err error) Executor { return &unavailableExecutor{err: err} }func (u *unavailableExecutor) Enabled() bool { return true }@@ -258,3 +258,8 @@ func IsNotFound(err error) bool {var remote *HTTPErrorreturn errors.As(err, &remote) && remote.StatusCode == http.StatusNotFound}++func IsCapacityOvercommitted(err error) bool {+ var remote *HTTPError+ return errors.As(err, &remote) && remote.StatusCode == http.StatusConflict && remote.Code == "capacity_overcommitted"+}diff --git a/server/internal/seatcapacity/client_test.go b/server/internal/seatcapacity/client_test.goindex 493e753453..bceb0c05b9 100644--- a/server/internal/seatcapacity/client_test.go+++ b/server/internal/seatcapacity/client_test.go@@ -64,6 +64,16 @@ func TestClientRejectsRedirectAndDoesNotForwardCredential(t *testing.T) {}}+func TestIsCapacityOvercommittedRequiresCloudConflictCode(t *testing.T) {+ if !IsCapacityOvercommitted(&HTTPError{StatusCode: http.StatusConflict, Code: "capacity_overcommitted"}) {+ t.Fatal("capacity_overcommitted conflict was not recognized")+ }+ if IsCapacityOvercommitted(&HTTPError{StatusCode: http.StatusConflict, Code: "capacity_full"}) ||+ IsCapacityOvercommitted(&HTTPError{StatusCode: http.StatusServiceUnavailable, Code: "capacity_overcommitted"}) {+ t.Fatal("unrelated Cloud error was recognized as capacity overcommit")+ }+}+func TestDisabledClientPreservesLegacyBehavior(t *testing.T) {client, err := New(Config{})if err != nil {diff --git a/server/internal/seatcapacity/worker.go b/server/internal/seatcapacity/worker.goindex 3d8299fbfb..1672408fe1 100644--- a/server/internal/seatcapacity/worker.go+++ b/server/internal/seatcapacity/worker.go@@ -195,7 +195,7 @@ func (w *Worker) settle(ctx context.Context, intent db.SeatCapacityOutbox) errorif err != nil && !IsNotFound(err) {return err}- if err == nil && decision.Managed && !decision.Allowed && decision.Reason != "released" && decision.Reason != "denied" {+ if err == nil && decision.Managed && !decision.Allowed && decision.Reason != "released" {return errors.New("capacity release rejected in state " + decision.Reason)}return w.deleteCurrent(ctx, intent)@@ -225,7 +225,7 @@ func (w *Worker) recoverReserve(ctx context.Context, intent db.SeatCapacityOutboreturn errors.New("managed capacity operation response omitted operation")}switch decision.Operation.State {- case "denied", "released":+ case "released":return w.deleteCurrent(ctx, intent)case "reserved":invitationID := intent.InvitationID@@ -266,9 +266,11 @@ func (w *Worker) recoverConsuming(ctx context.Context, intent db.SeatCapacityOut// A concurrent request already committed and confirmed the member. A// stale consuming worker must not try to release that used seat.return w.deleteCurrent(ctx, intent)- case "denied", "released":+ case "released":if intent.Action == ActionConsumeInvitation && intent.InvitationID.Valid {- _ = w.queries.ExpireInvitationForCapacityRecovery(ctx, intent.InvitationID)+ if err := w.queries.ExpireInvitationForCapacityRecovery(ctx, intent.InvitationID); err != nil {+ return err+ }}return w.deleteCurrent(ctx, intent)case "consuming":