Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9488 feat: cap Free workspace members, exclude guests, upgrade and invite (#10957)
Multica Eve309cc9fe4400
diff --git a/apps/docs/content/docs/members-roles.fr.mdx b/apps/docs/content/docs/members-roles.fr.mdxindex d234a33a41..0f91a182dc 100644--- a/apps/docs/content/docs/members-roles.fr.mdx+++ b/apps/docs/content/docs/members-roles.fr.mdx@@ -41,7 +41,11 @@ La personne invitée accepte en se connectant avec cette adresse e-mail — aucuLe lien d'invitation n'apparaît que dans l'e-mail ; il n'existe aucun endroit dans le produit pour le consulter ou le copier. Si l'envoi de l'e-mail échoue, l'invitation existe tout de même — révoquez-la et envoyez-en une nouvelle.-Pour obtenir un lien à transmettre directement, générez-en un dans l'onglet **Liens de partage** de **Paramètres → Membres** en choisissant un rôle et une durée de validité. Toute personne qui a ce lien peut rejoindre l'espace de travail avec le rôle choisi, jusqu'à ce qu'il expire ou soit révoqué.+Pour obtenir un lien à transmettre directement, générez-en un dans l'onglet **Liens de partage** de **Paramètres → Membres** en choisissant un rôle et une durée de validité. Toute personne qui a ce lien peut rejoindre l'espace de travail avec le rôle choisi, jusqu'à ce qu'il expire ou soit révoqué, tant que l'espace de travail a une place de membre libre (voir ci-dessous).++### Limite de membres++Sur Multica Cloud, un espace de travail au forfait Free peut compter jusqu'à 5 membres. Chaque membre et chaque invitation en attente occupe une place ; les invités n'en occupent pas. Tant que la limite s'applique, une nouvelle invitation, une invitation acceptée ou un accès par lien de partage qui la dépasserait est refusé, jusqu'à ce qu'une place se libère (invitation révoquée ou membre retiré) ou que l'espace de travail passe à un forfait supérieur. Les membres existants ne sont jamais retirés. Quand l'espace de travail est complet, les administrateurs voient **Mettre à niveau et inviter** dans la fenêtre d'invitation : une fois le paiement effectué, **Paramètres → Facturation** propose d'envoyer l'invitation mise de côté. Avec Pro et Business, chaque membre occupe un siège payant. Les espaces de travail auto-hébergés n'ont pas de limite de membres.## Changer de rôlediff --git a/apps/docs/content/docs/members-roles.ja.mdx b/apps/docs/content/docs/members-roles.ja.mdxindex 7ae23dfeaf..cef156e6a5 100644--- a/apps/docs/content/docs/members-roles.ja.mdx+++ b/apps/docs/content/docs/members-roles.ja.mdx@@ -41,7 +41,11 @@ import { RolesDemo } from "@/components/demos/roles-demo";招待リンクはメールにのみ含まれ、プロダクトの画面にはそれを表示・コピーする場所がありません。メールの送信に失敗しても招待レコードは残るため、取り消してから送り直せます。-そのまま転送できるリンクが必要な場合は、**設定 → メンバー**の**共有リンク**でロールと有効期限を選んで生成します。リンクを受け取った人は、期限が切れるか取り消されるまで、選んだロールで参加できます。+そのまま転送できるリンクが必要な場合は、**設定 → メンバー**の**共有リンク**でロールと有効期限を選んで生成します。リンクを受け取った人は、期限が切れるか取り消されるまで、選んだロールで参加できます。ただし、ワークスペースにメンバーの空き枠がある場合に限ります(下記参照)。++### メンバー数の上限++Multica Cloud では、Free プランのワークスペースのメンバーは最大 5 人です。メンバーと保留中の招待がそれぞれ 1 枠を使い、ゲストは枠を使いません。上限が適用されている間は、上限を超える新しい招待、招待の承諾、共有リンクからの参加は拒否されます。枠が空く(招待を取り消す、メンバーを削除する)か、ワークスペースをアップグレードすると再び追加できます。既存のメンバーが削除されることはありません。ワークスペースが満員のとき、管理者には招待ダイアログに**アップグレードして招待**が表示されます。支払いが完了すると、**設定 → 請求とプラン**で保留中の招待を送信できます。Pro と Business では、メンバーごとに有料席が必要です。セルフホストのワークスペースにはメンバー数の上限はありません。## ロールの変更diff --git a/apps/docs/content/docs/members-roles.ko.mdx b/apps/docs/content/docs/members-roles.ko.mdxindex 8432359586..536ef1eb9e 100644--- a/apps/docs/content/docs/members-roles.ko.mdx+++ b/apps/docs/content/docs/members-roles.ko.mdx@@ -41,7 +41,11 @@ import { RolesDemo } from "@/components/demos/roles-demo";초대 링크는 이메일에만 표시되며 제품 화면에서 확인하거나 복사할 수 없습니다. 이메일 전송에 실패해도 초대 기록은 남으므로 취소한 뒤 다시 보낼 수 있습니다.-바로 전달할 수 있는 링크가 필요하면 **설정 → 멤버**의 **공유 링크**에서 역할과 유효 기간을 선택해 링크를 만드세요. 링크를 가진 사람은 링크가 만료되거나 취소될 때까지 선택한 역할로 참여할 수 있습니다.+바로 전달할 수 있는 링크가 필요하면 **설정 → 멤버**의 **공유 링크**에서 역할과 유효 기간을 선택해 링크를 만드세요. 링크를 가진 사람은 링크가 만료되거나 취소될 때까지 선택한 역할로 참여할 수 있습니다. 단, 워크스페이스에 빈 멤버 자리가 있어야 합니다(아래 참고).++### 멤버 수 한도++Multica Cloud에서 Free 요금제 워크스페이스는 멤버를 최대 5명까지 둘 수 있습니다. 멤버와 대기 중인 초대가 각각 한 자리를 차지하며, 게스트는 자리를 차지하지 않습니다. 한도가 적용되는 동안에는 한도를 넘는 새 초대, 초대 수락, 공유 링크를 통한 참여가 거부됩니다. 자리가 생기거나(초대 취소 또는 멤버 제거) 워크스페이스를 업그레이드하면 다시 추가할 수 있습니다. 기존 멤버는 제거되지 않습니다. 워크스페이스가 가득 차면 관리자는 초대 대화 상자에서 **업그레이드하고 초대**를 볼 수 있습니다. 결제가 완료되면 **설정 → 결제 및 요금제**에서 보류해 둔 초대를 보낼 수 있습니다. Pro와 Business에서는 멤버마다 유료 좌석이 필요합니다. 셀프 호스팅 워크스페이스에는 멤버 수 한도가 없습니다.## 역할 변경diff --git a/apps/docs/content/docs/members-roles.mdx b/apps/docs/content/docs/members-roles.mdxindex 2167fa8b0a..fd291645ff 100644--- a/apps/docs/content/docs/members-roles.mdx+++ b/apps/docs/content/docs/members-roles.mdx@@ -41,7 +41,11 @@ The invitee accepts by logging in with that email — no prior signup is needed.The invitation link appears only in the email; there is no place in the product to view or copy it. If the email fails to send, the invitation record still exists — revoke it and send a new one.-When you need a link you can pass along yourself, generate one under **Share links** in **Settings → Members** by choosing a role and an expiry. Anyone with the link can join with that role until it expires or is revoked.+When you need a link you can pass along yourself, generate one under **Share links** in **Settings → Members** by choosing a role and an expiry. Anyone with the link can join with that role until it expires or is revoked, as long as the workspace has a free member slot (see below).++### Member limit++On Multica Cloud, a workspace on the Free plan can have up to 5 members. Members and pending invitations each take a slot; guests take none. While the limit applies, a new invitation, an accepted invitation or a share-link join that would go past it is refused until a slot frees up (an invitation is revoked or a member removed) or the workspace upgrades. Existing members are never removed. When the workspace is full, admins see **Upgrade and invite** in the invite dialog: once the payment goes through, **Settings → Billing** offers to send the held invitation. On Pro and Business each member takes a paid seat. Self-hosted workspaces have no member limit.## Change rolesdiff --git a/apps/docs/content/docs/members-roles.zh-Hant.mdx b/apps/docs/content/docs/members-roles.zh-Hant.mdxindex 629e80af85..3bcddfb244 100644--- a/apps/docs/content/docs/members-roles.zh-Hant.mdx+++ b/apps/docs/content/docs/members-roles.zh-Hant.mdx@@ -41,7 +41,11 @@ import { RolesDemo } from "@/components/demos/roles-demo";邀請連結只出現在郵件裡,產品介面中沒有檢視或複製它的入口。郵件傳送失敗時邀請記錄仍然存在,可以撤銷後重新傳送。-需要一條能直接轉發的連結時,在**設定 → 成員**的**分享連結**中選擇角色和有效期後生成。拿到連結的人都可以以所選角色加入,直到連結過期或被撤銷。+需要一條能直接轉發的連結時,在**設定 → 成員**的**分享連結**中選擇角色和有效期後生成。拿到連結的人都可以以所選角色加入,直到連結過期或被撤銷;前提是工作區還有空餘的成員名額(見下文)。++### 成員上限++在 Multica Cloud 上,Free 套餐的工作區最多 5 位成員。成員和待接受的邀請各佔一個名額,訪客不佔。上限生效時,超出上限的新邀請、接受邀請和透過分享連結加入都會被拒絕,直到空出名額(撤回邀請或移除成員)或工作區升級。既有成員不會被移除。工作區滿員時,管理員會在邀請視窗裡看到**升級並邀請**:付款完成後,在**設定 → 帳單與套餐**裡可以發出這份邀請。Pro 和 Business 每位成員佔一個付費席位。自行部署的工作區沒有成員上限。## 調整角色diff --git a/apps/docs/content/docs/members-roles.zh.mdx b/apps/docs/content/docs/members-roles.zh.mdxindex 5da5babb50..ddeffb013c 100644--- a/apps/docs/content/docs/members-roles.zh.mdx+++ b/apps/docs/content/docs/members-roles.zh.mdx@@ -41,7 +41,11 @@ import { RolesDemo } from "@/components/demos/roles-demo";邀请链接只出现在邮件里,产品界面中没有查看或复制它的入口。邮件发送失败时邀请记录仍然存在,可以撤销后重新发送。-需要一条能直接转发的链接时,在**设置 → 成员**的**分享链接**中选择角色和有效期后生成。拿到链接的人都可以以所选角色加入,直到链接过期或被撤销。+需要一条能直接转发的链接时,在**设置 → 成员**的**分享链接**中选择角色和有效期后生成。拿到链接的人都可以以所选角色加入,直到链接过期或被撤销;前提是工作区还有空余的成员名额(见下文)。++### 成员上限++在 Multica Cloud 上,Free 套餐的工作区最多 5 位成员。成员和待接受的邀请各占一个名额,访客不占。上限生效时,超出上限的新邀请、接受邀请和通过分享链接加入都会被拒绝,直到空出名额(撤回邀请或移除成员)或工作区升级。已有成员不会被移除。工作区满员时,管理员会在邀请弹窗里看到**升级并邀请**:付款完成后,在**设置 → 账单与套餐**里可以发出这份邀请。Pro 和 Business 每位成员占一个付费席位。自部署的工作区没有成员上限。## 调整角色diff --git a/apps/web/app/join/page.test.tsx b/apps/web/app/join/page.test.tsxindex e3703ba323..121cbe51cf 100644--- a/apps/web/app/join/page.test.tsx+++ b/apps/web/app/join/page.test.tsx@@ -6,11 +6,12 @@ import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "@multica/views/locales/en/common.json";import enAuth from "@multica/views/locales/en/auth.json";import enSettings from "@multica/views/locales/en/settings.json";+import enInvite from "@multica/views/locales/en/invite.json";import { ApiError } from "@multica/core/api";import type { ReactNode } from "react";const TEST_RESOURCES = {- en: { common: enCommon, auth: enAuth, settings: enSettings },+ en: { common: enCommon, auth: enAuth, settings: enSettings, invite: enInvite },};function createWrapper() {@@ -245,4 +246,49 @@ describe("JoinPage", () => {);await waitFor(() => expect(screen.getByText(message)).toBeInTheDocument());});++ it("replaces the join action with the full state when the member limit refuses", async () => {+ const user = userEvent.setup();+ authStateRef.state.user = { id: "u1", email: "[email protected]" };+ mockJoinByShareLink.mockRejectedValue(+ new ApiError("server fallback", 403, "Forbidden", { code: "member_limit_reached" }),+ );++ render(<JoinPage />, { wrapper: createWrapper() });++ await user.click(+ await screen.findByRole("button", { name: "Join Workspace" }),+ );+ await waitFor(() =>+ expect(screen.getByRole("heading", { name: "Acme is full" })).toBeInTheDocument(),+ );+ expect(+ screen.getByText("Contact the person who invited you. This link works again once the workspace upgrades."),+ ).toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Join Workspace" })).not.toBeInTheDocument();++ // A slot frees up (an invitation revoked): the same page joins on retry.+ mockJoinByShareLink.mockResolvedValue({ workspace_id: "ws-1", workspace_slug: "acme" });+ await user.click(screen.getByRole("button", { name: "Try again" }));+ await waitFor(() => expect(screen.getByText("Joined!")).toBeInTheDocument());+ expect(mockJoinByShareLink).toHaveBeenCalledTimes(2);+ });++ it("shows a retry's own failure instead of the earlier full state", async () => {+ const user = userEvent.setup();+ authStateRef.state.user = { id: "u1", email: "[email protected]" };+ mockJoinByShareLink.mockRejectedValueOnce(+ new ApiError("server fallback", 403, "Forbidden", { code: "member_limit_reached" }),+ );+ render(<JoinPage />, { wrapper: createWrapper() });+ await user.click(await screen.findByRole("button", { name: "Join Workspace" }));+ await screen.findByRole("heading", { name: "Acme is full" });++ // The link was revoked in the meantime.+ mockJoinByShareLink.mockRejectedValueOnce(new Error("share link not found or expired"));+ await user.click(screen.getByRole("button", { name: "Try again" }));++ await waitFor(() => expect(screen.getByText("share link not found or expired")).toBeInTheDocument());+ expect(screen.queryByRole("heading", { name: "Acme is full" })).not.toBeInTheDocument();+ });});diff --git a/apps/web/app/join/page.tsx b/apps/web/app/join/page.tsxindex 4cfdf69932..b01e83113f 100644--- a/apps/web/app/join/page.tsx+++ b/apps/web/app/join/page.tsx@@ -8,10 +8,13 @@ import { Button } from "@multica/ui/components/ui/button";import { Card, CardContent } from "@multica/ui/components/ui/card";import { Badge } from "@multica/ui/components/ui/badge";import { useAuthStore } from "@multica/core/auth";+import { isMemberLimitReachedError } from "@multica/core/billing";import { workspaceKeys } from "@multica/core/workspace/queries";import type { ShareLinkInfo, Workspace } from "@multica/core/types";+import { useT } from "@multica/views/i18n";function JoinInner() {+ const { t } = useT("invite");const router = useRouter();const searchParams = useSearchParams();const code = searchParams.get("code");@@ -23,12 +26,15 @@ function JoinInner() {const [joining, setJoining] = useState(false);const [joinError, setJoinError] = useState<string | null>(null);const [joined, setJoined] = useState(false);+ // The workspace has no free member slot; the link works again once it+ // upgrades.+ const [workspaceFull, setWorkspaceFull] = useState(false);// Load the share-link preview once. No auth needed: this endpoint only// exposes the workspace name/slug and the inviter.useEffect(() => {if (!code) {- setInfoError("No invite code found. Please use a valid share link.");+ setInfoError(t(($) => $.join.no_code));return;}let cancelled = false;@@ -38,11 +44,12 @@ function JoinInner() {if (!cancelled) setInfo(data);}).catch(() => {- if (!cancelled) setInfoError("This invite link is invalid or has expired.");+ if (!cancelled) setInfoError(t(($) => $.join.invalid));});return () => {cancelled = true;};+ // eslint-disable-next-line react-hooks/exhaustive-deps -- load the preview once per code}, [code]);const handleJoin = () => {@@ -54,6 +61,8 @@ function JoinInner() {}setJoining(true);setJoinError(null);+ // A retry shows its own outcome: the link may have been revoked since.+ setWorkspaceFull(false);api.joinByShareLink(code).then(async (result) => {@@ -89,15 +98,19 @@ function JoinInner() {return;}setJoining(false);+ if (isMemberLimitReachedError(e)) {+ setWorkspaceFull(true);+ return;+ }if (code === "seat_capacity_full") {- setJoinError("All purchased member seats are in use. Ask a workspace admin to add a seat before trying again.");+ setJoinError(t(($) => $.join.seats_full));return;}if (code === "seat_capacity_unavailable") {- setJoinError("Member capacity could not be verified. Please try again.");+ setJoinError(t(($) => $.join.seats_unavailable));return;}- setJoinError(msg || "Failed to join the workspace. The link may have expired.");+ setJoinError(msg || t(($) => $.join.join_failed));});};@@ -107,40 +120,54 @@ function JoinInner() {<CardContent className="space-y-4 pt-6">{joined ? (<>- <h1 className="text-title-lg font-semibold text-center">Joined!</h1>- <p className="text-center text-muted-foreground">Redirecting to your workspace...</p>+ <h1 className="text-title-lg font-semibold text-center">{t(($) => $.join.joined_title)}</h1>+ <p className="text-center text-muted-foreground">{t(($) => $.join.redirecting)}</p></>) : infoError ? (<>- <h1 className="text-title-lg font-semibold text-center">Oops</h1>+ <h1 className="text-title-lg font-semibold text-center">{t(($) => $.join.error_title)}</h1><p className="text-center text-muted-foreground">{infoError}</p><div className="flex justify-center pt-2"><Button variant="outline" onClick={() => router.push("/")}>- Go Home+ {t(($) => $.join.go_home)}</Button></div></>) : !info ? (- <div className="py-6 text-center text-muted-foreground">Loading invite details...</div>+ <div className="py-6 text-center text-muted-foreground">{t(($) => $.join.loading)}</div>+ ) : workspaceFull ? (+ <>+ <h1 className="text-title-lg font-semibold text-center">+ {t(($) => $.join.full_title, { workspace: info.workspace_name })}+ </h1>+ <p className="text-center text-muted-foreground">{t(($) => $.join.full_description)}</p>+ {/* A slot can free up without the link changing (an invitation+ revoked, a member removed), so the join stays one click away. */}+ <div className="flex justify-center pt-2">+ <Button variant="outline" onClick={handleJoin} disabled={joining}>+ {joining ? t(($) => $.join.joining) : t(($) => $.join.retry)}+ </Button>+ </div>+ </>) : (<><h1 className="text-title-lg font-semibold text-center">- You're invited to {info.workspace_name}+ {t(($) => $.join.title, { workspace: info.workspace_name })}</h1>{info.creator_name && (<p className="text-center text-muted-foreground">- Invited by {info.creator_name}+ {t(($) => $.join.invited_by, { name: info.creator_name })}</p>)}<p className="flex items-center justify-center gap-2 text-center text-body text-muted-foreground">- <span>You'll join this workspace as</span>+ <span>{t(($) => $.join.join_as)}</span><Badge variant="outline">- {info.role === "admin" ? "Administrator" : "Member"}+ {info.role === "admin" ? t(($) => $.join.role_admin) : t(($) => $.join.role_member)}</Badge></p>{!user && (<p className="text-center text-body text-muted-foreground">- You'll need to log in to join this workspace.+ {t(($) => $.join.login_required)}</p>)}{joinError && (@@ -148,7 +175,11 @@ function JoinInner() {)}<div className="flex justify-center gap-2 pt-2"><Button onClick={handleJoin} disabled={joining}>- {joining ? "Joining..." : user ? "Join Workspace" : "Log In to Join"}+ {joining+ ? t(($) => $.join.joining)+ : user+ ? t(($) => $.join.join)+ : t(($) => $.join.log_in_to_join)}</Button></div></>@@ -159,9 +190,14 @@ function JoinInner() {);}+function JoinFallback() {+ const { t } = useT("invite");+ return <div className="flex min-h-screen items-center justify-center">{t(($) => $.join.loading)}</div>;+}+export default function JoinPage() {return (- <Suspense fallback={<div className="flex min-h-screen items-center justify-center">Loading...</div>}>+ <Suspense fallback={<JoinFallback />}><JoinInner /></Suspense>);diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 674402b39b..4d935d697d 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -285,6 +285,7 @@ import type {WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrices,WorkspaceFeatures,+ MemberLimit,CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,WorkspaceSubscriptionSeatReconcileResult,@@ -447,6 +448,7 @@ import {UNCONFIRMED_BATCH_UPDATE,WorkspaceSubscriptionPricesSchema,WorkspaceFeaturesSchema,+ MemberLimitSchema,CreateWorkspaceSubscriptionCheckoutResponseSchema,WorkspaceSubscriptionSeatReconcileResultSchema,WorkspaceSeatPurchasePreviewSchema,@@ -2647,6 +2649,18 @@ export class ApiClient {);}+ // The plan's member limit (MUL-9488). A response that cannot be read falls+ // back to no limit: the server still checks every admission.+ async getMemberLimit(workspaceId: string): Promise<MemberLimit> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/member-limit`);+ return parseWithFallback<MemberLimit>(+ raw,+ MemberLimitSchema,+ { action: "off", limit: null, members: null, pendingInvitations: null },+ { endpoint: "GET /api/workspaces/:id/member-limit" },+ );+ }+async getWorkspaceSubscriptionPrices(): Promise<WorkspaceSubscriptionPrices | null> {const raw = await this.fetch<unknown>("/api/cloud-subscriptions/prices");return parseWithFallback<WorkspaceSubscriptionPrices | null>(@@ -2668,6 +2682,9 @@ export class ApiClient {plan: data.plan,interval: data.interval,idempotency_key: data.idempotencyKey,+ ...(data.additionalSeats+ ? { additional_seats: data.additionalSeats }+ : {}),}),extraHeaders: {"Content-Type": "application/json",diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex ee65c86aa3..df1a8e18d3 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -38,6 +38,7 @@ import type {WorkspaceSubscriptionEntitlements,WorkspaceFeatureState,WorkspaceFeatures,+ MemberLimit,WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPlanPrices,@@ -3888,6 +3889,29 @@ export const WorkspaceFeaturesSchema = z}),);+// A limit that cannot be read, or an action from a newer server, reads as off:+// the server still checks every admission, so the worst case is a refusal+// shown after the attempt instead of before it.+export const MemberLimitSchema = z+ .object({+ action: z.enum(["off", "observe", "enforce"]).catch("off"),+ limit: z.number().int().nonnegative().nullable().catch(null).default(null),+ members: z.number().int().nonnegative().nullable().catch(null).default(null),+ pending_invitations: z.number().int().nonnegative().nullable().catch(null).default(null),+ })+ .loose()+ .transform(+ (value): MemberLimit =>+ value.action === "off" || value.limit === null+ ? { action: "off", limit: null, members: null, pendingInvitations: null }+ : {+ action: value.action,+ limit: value.limit,+ members: value.members ?? 0,+ pendingInvitations: value.pending_invitations ?? 0,+ },+ );+export const CreateWorkspaceSubscriptionCheckoutResponseSchema = z.object({request_id: z.string(),diff --git a/packages/core/billing/index.ts b/packages/core/billing/index.tsindex b7bd0218e8..c554bfde51 100644--- a/packages/core/billing/index.ts+++ b/packages/core/billing/index.ts@@ -6,3 +6,4 @@ export * from "./recovery";export * from "./paid-features";export * from "./trial";export * from "./trial-notice-store";+export * from "./member-limit";diff --git a/packages/core/billing/member-limit.test.ts b/packages/core/billing/member-limit.test.tsnew file mode 100644index 0000000000..783f0a94cf--- /dev/null+++ b/packages/core/billing/member-limit.test.ts@@ -0,0 +1,175 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";++import { ApiError } from "../api";+import { MemberLimitSchema } from "../api/schemas";+import type { MemberLimit, StorageAdapter } from "../types";+import {+ bindUpgradeInviteCheckout,+ clearUpgradeInvite,+ heldInvitesToOffer,+ isMemberLimitFull,+ isMemberLimitReachedError,+ listCheckoutHeldInvites,+ memberLimitKeys,+ readUpgradeInvite,+ saveUpgradeInvite,+ type HeldInvite,+} from "./member-limit";+import { workspaceKeys } from "../workspace/queries";++const OFF: MemberLimit = { action: "off", limit: null, members: null, pendingInvitations: null };++function memoryStorage(): StorageAdapter & { data: Map<string, string> } {+ const data = new Map<string, string>();+ return {+ data,+ getItem: (key) => data.get(key) ?? null,+ setItem: (key, value) => void data.set(key, value),+ removeItem: (key) => void data.delete(key),+ keys: () => [...data.keys()],+ };+}++describe("MemberLimitSchema", () => {+ it("reads an active limit with its counts", () => {+ expect(+ MemberLimitSchema.parse({ action: "enforce", limit: 5, members: 4, pending_invitations: 1 }),+ ).toEqual({ action: "enforce", limit: 5, members: 4, pendingInvitations: 1 });+ });++ it("reads off, an unknown action, or a limit without a value as no limit", () => {+ expect(MemberLimitSchema.parse({ action: "off" })).toEqual(OFF);+ expect(MemberLimitSchema.parse({ action: "block", limit: 5 })).toEqual(OFF);+ expect(MemberLimitSchema.parse({ action: "enforce", limit: "5" })).toEqual(OFF);+ });++ it("treats missing counts of an active limit as zero", () => {+ expect(MemberLimitSchema.parse({ action: "observe", limit: 5 })).toEqual({+ action: "observe",+ limit: 5,+ members: 0,+ pendingInvitations: 0,+ });+ });+});++describe("isMemberLimitFull", () => {+ const enforced = (members: number, pendingInvitations: number): MemberLimit => ({+ action: "enforce",+ limit: 5,+ members,+ pendingInvitations,+ });++ it("is full when members and pending invitations fill an enforced limit", () => {+ expect(isMemberLimitFull(enforced(4, 0))).toBe(false);+ expect(isMemberLimitFull(enforced(4, 1))).toBe(true);+ expect(isMemberLimitFull(enforced(7, 0))).toBe(true);+ });++ it("is never full while the limit is only observed, off, or unknown", () => {+ expect(isMemberLimitFull({ ...enforced(7, 0), action: "observe" })).toBe(false);+ expect(isMemberLimitFull(OFF)).toBe(false);+ expect(isMemberLimitFull(undefined)).toBe(false);+ });+});++describe("isMemberLimitReachedError", () => {+ it("matches only the member limit refusal", () => {+ expect(isMemberLimitReachedError(new ApiError("full", 403, "Forbidden", { code: "member_limit_reached" }))).toBe(true);+ expect(isMemberLimitReachedError(new ApiError("locked", 403, "Forbidden", { code: "feature_locked" }))).toBe(false);+ expect(isMemberLimitReachedError(new ApiError("full", 409, "Conflict", { code: "seat_capacity_full" }))).toBe(false);+ expect(isMemberLimitReachedError(new Error("member_limit_reached"))).toBe(false);+ });+});++describe("memberLimitKeys", () => {+ it("lives under the member list so a member change refetches it", () => {+ expect(memberLimitKeys.all("ws-1").slice(0, 3)).toEqual([...workspaceKeys.members("ws-1")]);+ });+});++describe("held upgrade invitations", () => {+ const now = Date.UTC(2026, 10, 19, 9);++ it("keeps each held invitation under its own token and drops only the one asked", () => {+ const storage = memoryStorage();+ const first = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" }, storage, now);+ const second = saveUpgradeInvite("acme", { email: "[email protected]", role: "admin" }, storage, now + 1);+ expect(first).not.toBe(second);+ expect(readUpgradeInvite("acme", first, storage, now + 60_000)).toMatchObject({ email: "[email protected]", role: "member", checkout: null });+ expect(readUpgradeInvite("other", first, storage, now + 60_000)).toBeNull();++ clearUpgradeInvite("acme", first, storage, now + 60_000);+ expect(readUpgradeInvite("acme", first, storage, now + 60_000)).toBeNull();+ expect(readUpgradeInvite("acme", second, storage, now + 60_000)).not.toBeNull();+ clearUpgradeInvite("acme", second, storage, now + 60_000);+ expect(storage.data.size).toBe(0);+ });++ it("binds a held invitation to its checkout and lists bound ones newest first", () => {+ const storage = memoryStorage();+ const waiting = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" }, storage, now);+ const older = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" }, storage, now + 1);+ const newer = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" }, storage, now + 2);+ bindUpgradeInviteCheckout("acme", older, { requestId: "req-1", baseVersion: 0 }, storage, now + 3);+ bindUpgradeInviteCheckout("acme", newer, { requestId: "req-2", baseVersion: 0 }, storage, now + 4);++ expect(listCheckoutHeldInvites("acme", storage, now + 5).map((h) => h.token)).toEqual([newer, older]);+ expect(readUpgradeInvite("acme", newer, storage, now + 5)?.checkout).toEqual({ requestId: "req-2", baseVersion: 0, boundAt: now + 4 });+ expect(readUpgradeInvite("acme", waiting, storage, now + 5)?.checkout).toBeNull();+ });++ // Stripe keeps a Checkout session payable for 24 hours; a held invitation+ // whose checkout started must outlive it, with time left to send it.+ it("keeps a held invitation for as long as its checkout can still be paid", () => {+ const storage = memoryStorage();+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" }, storage, now);+ bindUpgradeInviteCheckout("acme", token, { requestId: "req-1", baseVersion: 0 }, storage, now + 60_000);+ const hour = 60 * 60 * 1000;+ expect(readUpgradeInvite("acme", token, storage, now + 30 * hour)).not.toBeNull();+ expect(readUpgradeInvite("acme", token, storage, now + 49 * hour)).toBeNull();+ });++ it("drops abandoned or unreadable entries", () => {+ const storage = memoryStorage();+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "admin" }, storage, now);+ expect(readUpgradeInvite("acme", token, storage, now + 3 * 60 * 60 * 1000)).toBeNull();+ expect(storage.data.size).toBe(0);++ storage.setItem("multica:upgrade_invite:acme", "{not json");+ expect(listCheckoutHeldInvites("acme", storage, now)).toEqual([]);+ storage.setItem(+ "multica:upgrade_invite:acme",+ JSON.stringify({ invites: { t1: { email: "[email protected]", role: "owner", savedAt: now, checkout: null } } }),+ );+ expect(readUpgradeInvite("acme", "t1", storage, now)).toBeNull();+ expect(storage.data.size).toBe(0);+ });+});++describe("heldInvitesToOffer", () => {+ const held = (token: string, requestId: string | null, { baseVersion = 0, savedAt = 1 } = {}): HeldInvite => ({+ token,+ email: `${token}@acme.io`,+ role: "member",+ savedAt,+ checkout: requestId ? { requestId, baseVersion, boundAt: 10 } : null,+ });+ const paid = { version: 1, paid: true };++ it("waits until the plan is paid and changed after the invitation's checkout started", () => {+ // An incomplete first payment bumps the version but still reads as Free.+ expect(heldInvitesToOffer([held("a", "req-a")], { version: 1, paid: false })).toEqual([]);+ expect(heldInvitesToOffer([held("a", "req-a", { baseVersion: 1 })], paid)).toEqual([]);+ expect(heldInvitesToOffer([held("a", null)], paid)).toEqual([]);+ });++ it("offers every paid-for held invitation, newest first, for the person to pick", () => {+ // Paying for A while a newer B waits in another tab must still offer A.+ const older = held("a", "req-a", { savedAt: 1 });+ const newer = held("b", "req-b", { savedAt: 2 });+ expect(heldInvitesToOffer([older, newer], paid)).toEqual([newer, older]);+ });+});diff --git a/packages/core/billing/member-limit.ts b/packages/core/billing/member-limit.tsnew file mode 100644index 0000000000..46957afba9--- /dev/null+++ b/packages/core/billing/member-limit.ts@@ -0,0 +1,261 @@+import { queryOptions } from "@tanstack/react-query";+import { api, ApiError } from "../api";+import { defaultStorage } from "../platform/storage";+import type { MemberLimit, MemberRole, StorageAdapter } from "../types";+import { workspaceKeys } from "../workspace/queries";++/**+ * Member limit (MUL-9488).+ *+ * A Free workspace can have a limited number of members. Members and pending+ * invitations both take a slot; guests take none. The server checks every+ * invitation, invitation acceptance and share-link join; this module only+ * renders the limit ahead of that check and carries an invitation through an+ * upgrade.+ */+export const MEMBER_LIMIT_REACHED_CODE = "member_limit_reached";++export const memberLimitKeys = {+ /** Under `members`, so every member change also refetches the limit. */+ all: (wsId: string) => [...workspaceKeys.members(wsId), "limit"] as const,+};++/** Refetched on focus: an upgrade happens outside this tab, in Stripe. */+export function memberLimitOptions(wsId: string) {+ return queryOptions({+ queryKey: memberLimitKeys.all(wsId),+ queryFn: () => api.getMemberLimit(wsId),+ enabled: wsId.length > 0,+ staleTime: 30 * 1000,+ refetchOnWindowFocus: true,+ });+}++/**+ * Whether the next member would be refused. Only an enforced limit refuses;+ * an observed one admits everyone and stays invisible.+ */+export function isMemberLimitFull(limit: MemberLimit | null | undefined): boolean {+ if (!limit || limit.action !== "enforce" || limit.limit === null) return false;+ return (limit.members ?? 0) + (limit.pendingInvitations ?? 0) >= limit.limit;+}++/** The server refused a new member because the workspace is full. */+export function isMemberLimitReachedError(error: unknown): boolean {+ if (!(error instanceof ApiError) || error.status !== 403) return false;+ const body = error.body;+ return (+ typeof body === "object" &&+ body !== null &&+ (body as { code?: unknown }).code === MEMBER_LIMIT_REACHED_CODE+ );+}++/**+ * An invitation the member limit held back while its workspace upgrades.+ *+ * Members saves it under a token and opens Billing with that token. Billing+ * binds it to the checkout it creates for it. Once the plan is paid, Billing+ * offers it for sending (see heldInvitesToOffer); Members consumes it only+ * once it is sent.+ */+export interface UpgradeInvite {+ email: string;+ role: MemberRole;+}++export interface HeldInvite extends UpgradeInvite {+ token: string;+ savedAt: number;+ /** The checkout Billing created for this invitation, once it has. */+ checkout: HeldInviteCheckout | null;+}++export interface HeldInviteCheckout {+ /** The checkout request id Cloud returned. */+ requestId: string;+ /** The subscription version when the checkout started. */+ baseVersion: number;+ boundAt: number;+}++interface StoredHeldInvites {+ invites: Record<string, HeldInvite>;+}++// A held invitation whose checkout never started belongs to an abandoned+// upgrade after this long.+const UPGRADE_INVITE_TTL_MS = 2 * 60 * 60 * 1000;+// Once its checkout started it lives as long as Stripe can still take the+// payment (a Checkout session stays open 24 hours) plus a day to come back+// and send it.+const BOUND_UPGRADE_INVITE_TTL_MS = 48 * 60 * 60 * 1000;++function upgradeInviteKey(slug: string): string {+ return `multica:upgrade_invite:${slug}`;+}++function newToken(): string {+ return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;+}++function readStored(slug: string, storage: StorageAdapter, now: number): StoredHeldInvites {+ const empty: StoredHeldInvites = { invites: {} };+ const raw = storage.getItem(upgradeInviteKey(slug));+ if (!raw) return empty;+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ storage.removeItem(upgradeInviteKey(slug));+ return empty;+ }+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {+ storage.removeItem(upgradeInviteKey(slug));+ return empty;+ }+ const value = parsed as { invites?: unknown };+ const out: StoredHeldInvites = { invites: {} };+ if (typeof value.invites === "object" && value.invites !== null && !Array.isArray(value.invites)) {+ for (const [token, entry] of Object.entries(value.invites as Record<string, unknown>)) {+ const held = readHeld(token, entry, now);+ if (held) out.invites[token] = held;+ }+ }+ writeStored(slug, out, storage);+ return out;+}++function readHeld(token: string, value: unknown, now: number): HeldInvite | null {+ if (typeof value !== "object" || value === null) return null;+ const v = value as Partial<HeldInvite>;+ if (+ typeof v.email !== "string" ||+ v.email.trim() === "" ||+ (v.role !== "admin" && v.role !== "member") ||+ typeof v.savedAt !== "number" ||+ v.savedAt > now+ ) {+ return null;+ }+ const c = v.checkout;+ const checkout =+ c &&+ typeof c.requestId === "string" &&+ c.requestId !== "" &&+ typeof c.baseVersion === "number" &&+ typeof c.boundAt === "number"+ ? { requestId: c.requestId, baseVersion: c.baseVersion, boundAt: c.boundAt }+ : null;+ const expired = checkout+ ? now - checkout.boundAt > BOUND_UPGRADE_INVITE_TTL_MS+ : now - v.savedAt > UPGRADE_INVITE_TTL_MS;+ if (expired) return null;+ return { token, email: v.email, role: v.role, savedAt: v.savedAt, checkout };+}++function writeStored(slug: string, stored: StoredHeldInvites, storage: StorageAdapter): void {+ if (Object.keys(stored.invites).length === 0) {+ storage.removeItem(upgradeInviteKey(slug));+ return;+ }+ storage.setItem(upgradeInviteKey(slug), JSON.stringify(stored));+}++/** Holds an invitation and returns the token that names it. */+export function saveUpgradeInvite(+ slug: string,+ invite: UpgradeInvite,+ storage: StorageAdapter = defaultStorage,+ now: number = Date.now(),+): string {+ const stored = readStored(slug, storage, now);+ const token = newToken();+ stored.invites[token] = { token, email: invite.email, role: invite.role, savedAt: now, checkout: null };+ writeStored(slug, stored, storage);+ return token;+}++export function readUpgradeInvite(+ slug: string,+ token: string,+ storage: StorageAdapter = defaultStorage,+ now: number = Date.now(),+): HeldInvite | null {+ return readStored(slug, storage, now).invites[token] ?? null;+}++/** Records the checkout Billing created for a held invitation. */+export function bindUpgradeInviteCheckout(+ slug: string,+ token: string,+ checkout: Omit<HeldInviteCheckout, "boundAt">,+ storage: StorageAdapter = defaultStorage,+ now: number = Date.now(),+): void {+ const stored = readStored(slug, storage, now);+ const held = stored.invites[token];+ if (!held) return;+ stored.invites[token] = { ...held, checkout: { ...checkout, boundAt: now } };+ writeStored(slug, stored, storage);+}++/** Held invitations whose checkout has started, newest first. */+export function listCheckoutHeldInvites(+ slug: string,+ storage: StorageAdapter = defaultStorage,+ now: number = Date.now(),+): HeldInvite[] {+ return Object.values(readStored(slug, storage, now).invites)+ .filter((held) => held.checkout !== null)+ .sort((a, b) => b.savedAt - a.savedAt);+}++/** Drops one held invitation. */+export function clearUpgradeInvite(+ slug: string,+ token: string,+ storage: StorageAdapter = defaultStorage,+ now: number = Date.now(),+): void {+ const stored = readStored(slug, storage, now);+ delete stored.invites[token];+ writeStored(slug, stored, storage);+}++/** Drops every held invitation for email, once an invitation to it is out. */+export function clearUpgradeInvitesFor(+ slug: string,+ email: string,+ storage: StorageAdapter = defaultStorage,+ now: number = Date.now(),+): void {+ const stored = readStored(slug, storage, now);+ const normalized = email.trim().toLowerCase();+ for (const [token, held] of Object.entries(stored.invites)) {+ if (held.email.trim().toLowerCase() === normalized) delete stored.invites[token];+ }+ writeStored(slug, stored, storage);+}++/**+ * The held invitations to offer for sending now, newest first: those whose+ * checkout started on this client, once the plan is paid (an incomplete first+ * payment still reads as Free) and the subscription has changed since their+ * checkout started.+ *+ * They are only ever offered, never sent on their own, and all of them are+ * offered: nothing the client sees proves which checkout a plan change came+ * from (Desktop pays in the system browser and never sees the Stripe return,+ * another admin may have upgraded elsewhere, several checkouts can be open in+ * different tabs), so the person who held them picks.+ */+export function heldInvitesToOffer(+ held: HeldInvite[],+ subscription: { version: number; paid: boolean },+): HeldInvite[] {+ if (!subscription.paid) return [];+ return held+ .filter((h) => h.checkout !== null && subscription.version > h.checkout.baseVersion)+ .sort((a, b) => b.savedAt - a.savedAt);+}diff --git a/packages/core/platform/storage-cleanup.test.ts b/packages/core/platform/storage-cleanup.test.tsindex 3efc77e83a..46f0875c5a 100644--- a/packages/core/platform/storage-cleanup.test.ts+++ b/packages/core/platform/storage-cleanup.test.ts@@ -31,8 +31,9 @@ describe("clearWorkspaceStorage", () => {expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:activeSessionId:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica:chat:expanded:ws_123");expect(adapter.removeItem).toHaveBeenCalledWith("multica_navigation:ws_123");- // 8 non-draft keys, and no registered drafts in this test.- expect(adapter.removeItem).toHaveBeenCalledTimes(9);+ expect(adapter.removeItem).toHaveBeenCalledWith("multica:upgrade_invite:ws_123");+ // 10 non-draft keys, and no registered drafts in this test.+ expect(adapter.removeItem).toHaveBeenCalledTimes(10);});it("also clears registered draft keys via the registry", () => {@@ -57,8 +58,8 @@ describe("clearWorkspaceStorage", () => {expect(adapter.removeItem).toHaveBeenCalledWith("multica_test_draft:ws_123");// Globally-namespaced draft keys are removed without the slug suffix.expect(adapter.removeItem).toHaveBeenCalledWith("multica_test_global_draft");- // 8 non-draft keys + 2 registered draft keys.- expect(adapter.removeItem).toHaveBeenCalledTimes(11);+ // 10 non-draft keys + 2 registered draft keys.+ expect(adapter.removeItem).toHaveBeenCalledTimes(12);});});diff --git a/packages/core/platform/storage-cleanup.ts b/packages/core/platform/storage-cleanup.tsindex 359d681906..490a0ab221 100644--- a/packages/core/platform/storage-cleanup.ts+++ b/packages/core/platform/storage-cleanup.ts@@ -29,6 +29,9 @@ const WORKSPACE_SCOPED_KEYS = ["multica:chat:activeSessionId","multica:chat:expanded","multica_navigation",+ // An invitation held back by the member limit while its workspace upgrades+ // (billing/member-limit.ts). It carries the invitee's email.+ "multica:upgrade_invite",];/** Remove all workspace-scoped storage entries for the given workspace slug. */diff --git a/packages/core/realtime/use-realtime-sync-invitations.test.tsx b/packages/core/realtime/use-realtime-sync-invitations.test.tsxindex d3783ebb5d..f54ebe436e 100644--- a/packages/core/realtime/use-realtime-sync-invitations.test.tsx+++ b/packages/core/realtime/use-realtime-sync-invitations.test.tsx@@ -9,6 +9,7 @@ import { WSClient } from "../api/ws-client";import { createQueryClient } from "../query-client";import type { Invitation } from "../types";import { myInvitationListOptions, workspaceKeys } from "../workspace/queries";+import { memberLimitKeys } from "../billing/member-limit";import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";vi.mock("../platform/workspace-storage", () => ({@@ -277,3 +278,37 @@ it.each(["invitation:accepted", "invitation:declined"] as const)(}},);++// A declined invitation frees its member slot: an admin watching Members must+// not keep seeing the workspace as full (MUL-9488). Accepting already refreshes+// it through the member list, which the limit's key sits under.+it("refreshes the member limit when an invitation is declined", async () => {+ const qc = createQueryClient();+ const invalidate = vi.spyOn(qc, "invalidateQueries");+ setApiInstance({ listMyInvitations: vi.fn(async () => []) } as unknown as ApiClient);+ const handlers: Record<string, (payload: unknown, actorId?: string) => void> = {};+ const ws = {+ on: (e: string, handler: (payload: unknown) => void) => {+ handlers[e] = handler;+ return () => {+ delete handlers[e];+ };+ },+ onAny: () => () => {},+ onReconnect: () => () => {},+ } as unknown as WSClient;+ const stores = {+ authStore: { getState: () => ({ user: { id: "admin" } }) },+ } as unknown as RealtimeSyncStores;+ function Wrapper({ children }: { children: ReactNode }) {+ return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;+ }+ renderHook(() => useRealtimeSync(ws, stores), { wrapper: Wrapper });++ await act(async () => {+ handlers["invitation:declined"]!({ invitation_id: "inv-1" }, "invitee");+ });++ expect(invalidate).toHaveBeenCalledWith({ queryKey: memberLimitKeys.all("ws-1") });+ expect(memberLimitKeys.all("ws-1").slice(0, 3)).toEqual([...workspaceKeys.members("ws-1")]);+});diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 556a788cad..17db4fc4cd 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -70,6 +70,7 @@ import {notificationPreferenceKeys,} from "../notification-preferences/queries";import { workspaceKeys, workspaceListOptions } from "../workspace/queries";+import { memberLimitKeys } from "../billing/member-limit";import { isWorkspaceDeletePending } from "../workspace/pending-delete";import {showSystemNotification,@@ -1670,6 +1671,8 @@ export function useRealtimeSync(const currentWsId = getCurrentWsId();if (currentWsId) {qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });+ // A declined invitation frees its member slot.+ qc.invalidateQueries({ queryKey: memberLimitKeys.all(currentWsId) });}if (actorId === authStore.getState().user?.id) {qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex a8a11d6c24..d3596a5c81 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -330,6 +330,11 @@ export interface CreateWorkspaceSubscriptionCheckoutRequest {plan: WorkspaceSubscriptionPaidPlan;interval: WorkspaceSubscriptionInterval;idempotencyKey: string;+ /**+ * Seats to buy beyond the current members and pending invitations, so an+ * invitation held back by the Free member limit fits right after checkout.+ */+ additionalSeats?: number;}export interface CreateWorkspaceSubscriptionCheckoutResponse {@@ -445,3 +450,15 @@ export type WorkspaceFeatureState = "available" | "locked";export interface WorkspaceFeatures {features: Partial<Record<PaidFeature, WorkspaceFeatureState>>;}++/**+ * The plan's member limit (MUL-9488). `off` means no limit applies, which is+ * also every self-hosted workspace; the counts are null then. Members and+ * pending invitations both take a slot; guests take none.+ */+export interface MemberLimit {+ action: "off" | "observe" | "enforce";+ limit: number | null;+ members: number | null;+ pendingInvitations: number | null;+}diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 14d03e418a..1aff01dd8a 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -434,6 +434,7 @@ export type {PaidFeature,WorkspaceFeatureState,WorkspaceFeatures,+ MemberLimit,} from "./billing";export type { IssueWakeup, IssueWakeupInput, SystemWakeup, WorkspaceSystemWakeup, WakeupPreview, IssueWakeupSummaryRow, WakeupCondition, WakeupPausedReason, WakeupRun, PausedWakeup, WakeupSource } from "./issue-wakeup";diff --git a/packages/views/invitations/invitations-page.test.tsx b/packages/views/invitations/invitations-page.test.tsxindex abe6874b90..f67e7d1029 100644--- a/packages/views/invitations/invitations-page.test.tsx+++ b/packages/views/invitations/invitations-page.test.tsx@@ -64,7 +64,8 @@ vi.mock("@multica/core/auth", () => ({),}));-vi.mock("@multica/core/api", () => ({+vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),api: {getBaseUrl: () => "http://127.0.0.1:8080",acceptInvitation,@@ -76,6 +77,7 @@ vi.mock("@multica/core/api", () => ({},}));+import { ApiError } from "@multica/core/api";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../locales/en/common.json";import enInvite from "../locales/en/invite.json";@@ -241,6 +243,26 @@ describe("InvitationsPage", () => {expect(markOnboardingComplete).not.toHaveBeenCalled();});+ it("explains a join the workspace's member limit refused", async () => {+ listMyInvitations.mockResolvedValue([mkInvite("inv-1", "ws-1", "Acme")]);+ acceptInvitation.mockRejectedValue(+ new ApiError("server fallback", 403, "Forbidden", { code: "member_limit_reached" }),+ );+ renderPage();+ await waitFor(() => screen.getByText("Acme"));++ fireEvent.click(within(row("Acme")).getByRole("button", { name: "Join" }));++ await waitFor(() =>+ expect(+ screen.getByText(+ "Acme is full. Ask the person who invited you; you can join once the workspace upgrades.",+ ),+ ).toBeInTheDocument(),+ );+ expect(navigate).not.toHaveBeenCalled();+ });+it("pins and highlights the linked invitation for an onboarded user", async () => {auth.user = { onboarded_at: "2026-01-01T00:00:00Z" };const linked = mkInvite("inv-2", "ws-2", "Beta");diff --git a/packages/views/invitations/invitations-page.tsx b/packages/views/invitations/invitations-page.tsxindex 1033fad8b5..6b71cd1857 100644--- a/packages/views/invitations/invitations-page.tsx+++ b/packages/views/invitations/invitations-page.tsx@@ -3,6 +3,7 @@import { useState, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";import { api } from "@multica/core/api";+import { isMemberLimitReachedError } from "@multica/core/billing";import {myInvitationListOptions,workspaceListOptions,@@ -93,7 +94,16 @@ export function InvitationsPage({ invitationId, onBack }: InvitationsPageProps)const handleAccept = (invitation: Invitation) => {setError(null);accept.mutate(invitation, {- onError: (e) => setError(e instanceof Error ? e.message : t(($) => $.errors.accept_failed)),+ onError: (e) =>+ setError(+ isMemberLimitReachedError(e)+ ? t(($) => $.errors.member_limit_reached, {+ workspace: invitation.workspace_name || t(($) => $.list.workspace_fallback),+ })+ : e instanceof Error+ ? e.message+ : t(($) => $.errors.accept_failed),+ ),});};const handleDecline = (invitation: Invitation) => {diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex c86b8c1e52..854796c17b 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -135,7 +135,9 @@"usage_total": "{{total}} / {{limit}}","usage_breakdown": "{{used}} completed · {{reserved}} in progress","resets_at": "Resets {{date}}",- "usage_unavailable": "Usage is temporarily unavailable"+ "usage_unavailable": "Usage is temporarily unavailable",+ "members": "Members",+ "members_pending": "Pending invitations: {{pending}}"},"seats": {"title": "Seats",@@ -222,7 +224,16 @@},"confirm": {"title": "Continue to Stripe Checkout?",- "description": "Plan: {{plan}}. Billing interval: {{interval}}. Current human members: {{count}}. Stripe will re-count seats and show the final amount before payment."+ "description": "Plan: {{plan}}. Billing interval: {{interval}}. Current human members: {{count}}. Stripe will re-count seats and show the final amount before payment.",+ "held_invite": "One more paid seat is included for the invitation to {{email}}. Once the payment goes through, send it from Billing."+ },+ "held_invite": {+ "title": "The workspace is on {{plan}} now",+ "description": "You held back an invitation for {{email}} as {{role}} until the upgrade. Send it now?",+ "role_admin": "an admin",+ "role_member": "a member",+ "send": "Send invitation",+ "discard": "Discard"}},"return_page": {diff --git a/packages/views/locales/en/invite.json b/packages/views/locales/en/invite.jsonindex 6784cf8499..e5cf0d2fbf 100644--- a/packages/views/locales/en/invite.json+++ b/packages/views/locales/en/invite.json@@ -30,6 +30,31 @@},"errors": {"accept_failed": "Failed to accept invitation",- "decline_failed": "Failed to decline invitation"+ "decline_failed": "Failed to decline invitation",+ "member_limit_reached": "{{workspace}} is full. Ask the person who invited you; you can join once the workspace upgrades."+ },+ "join": {+ "no_code": "No invite code found. Please use a valid share link.",+ "invalid": "This invite link is invalid or has expired.",+ "joined_title": "Joined!",+ "redirecting": "Redirecting to your workspace...",+ "error_title": "Oops",+ "go_home": "Go Home",+ "loading": "Loading invite details...",+ "title": "You're invited to {{workspace}}",+ "invited_by": "Invited by {{name}}",+ "join_as": "You'll join this workspace as",+ "role_admin": "Administrator",+ "role_member": "Member",+ "login_required": "You'll need to log in to join this workspace.",+ "join": "Join Workspace",+ "joining": "Joining...",+ "log_in_to_join": "Log In to Join",+ "join_failed": "Failed to join the workspace. The link may have expired.",+ "seats_full": "All purchased member seats are in use. Ask a workspace admin to add a seat before trying again.",+ "seats_unavailable": "Member capacity could not be verified. Please try again.",+ "full_title": "{{workspace}} is full",+ "full_description": "Contact the person who invited you. This link works again once the workspace upgrades.",+ "retry": "Try again"}}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 8d41f83cee..b75b782d2c 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1647,7 +1647,20 @@"invitation_meta": "Sent {{sent}} · Expires {{expires}}","revoke_invitation_aria": "Revoke invitation for {{email}}","seats_used": "{{used}} of {{purchased}} seats used",- "manage_seats": "Manage seats"+ "manage_seats": "Manage seats",+ "member_limit_full_title": "This plan allows up to {{limit}} members. The workspace is full.",+ "member_limit_full_description": "Upgrade to Pro for unlimited members. Each member is a paid seat, and the upgrade includes one for this invitation. Or remove a member first.",+ "member_limit_full_description_pending": "Pending invitations take a slot too ({{pending}} now). Upgrade to Pro for unlimited members (each member is a paid seat, and the upgrade includes one for this invitation), or revoke an invitation or remove a member first.",+ "member_limit_usage": "{{used}} / {{limit}} members",+ "upgrade_and_invite": "Upgrade and invite",+ "toast_member_limit_reached": "The workspace is full. Upgrade to invite more members.",+ "member_limit_full_description_no_upgrade": "Revoke a pending invitation or remove a member to free a slot.",+ "toast_invalid_email": "Enter a valid email address.",+ "toast_already_member": "{{email}} is already a member of this workspace.",+ "toast_invitation_pending": "An invitation to {{email}} is already pending.",+ "toast_invite_check_unavailable": "Could not check existing members and invitations. Try again in a moment.",+ "member_limit_full_description_billing": "The workspace's subscription needs attention. Restore it in Billing to add members, or remove a member first.",+ "open_billing": "Open Billing"},"integrations": {"status_connected": "Connected",diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex f236e83b05..9cee88e23b 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -135,7 +135,9 @@"usage_total": "{{total}} / {{limit}}","usage_breakdown": "{{used}} completadas · {{reserved}} en curso","resets_at": "Se reinicia el {{date}}",- "usage_unavailable": "El uso no está disponible temporalmente"+ "usage_unavailable": "El uso no está disponible temporalmente",+ "members": "Miembros",+ "members_pending": "Invitaciones pendientes: {{pending}}"},"seats": {"title": "Puestos",@@ -222,7 +224,16 @@},"confirm": {"title": "¿Continuar a Stripe Checkout?",- "description": "Plan: {{plan}}. Intervalo de facturación: {{interval}}. Miembros humanos actuales: {{count}}. Stripe volverá a contar los puestos y mostrará el importe final antes del pago."+ "description": "Plan: {{plan}}. Intervalo de facturación: {{interval}}. Miembros humanos actuales: {{count}}. Stripe volverá a contar los puestos y mostrará el importe final antes del pago.",+ "held_invite": "Incluye un puesto de pago más para la invitación a {{email}}. Cuando se complete el pago, envíala desde Facturación."+ },+ "held_invite": {+ "title": "El espacio de trabajo ya está en {{plan}}",+ "description": "Guardaste una invitación para {{email}} como {{role}} hasta mejorar el plan. ¿La envías ahora?",+ "role_admin": "administrador",+ "role_member": "miembro",+ "send": "Enviar invitación",+ "discard": "Descartar"}},"return_page": {diff --git a/packages/views/locales/es/invite.json b/packages/views/locales/es/invite.jsonindex 3bda1e77b8..fbee2f2d5f 100644--- a/packages/views/locales/es/invite.json+++ b/packages/views/locales/es/invite.json@@ -30,6 +30,31 @@},"errors": {"accept_failed": "No se ha podido aceptar la invitación",- "decline_failed": "No se ha podido rechazar la invitación"+ "decline_failed": "No se ha podido rechazar la invitación",+ "member_limit_reached": "{{workspace}} está lleno. Habla con quien te invitó; podrás unirte cuando el espacio de trabajo mejore su plan."+ },+ "join": {+ "no_code": "No se encontró ningún código de invitación. Usa un enlace para compartir válido.",+ "invalid": "Este enlace de invitación no es válido o ha caducado.",+ "joined_title": "¡Te has unido!",+ "redirecting": "Redirigiendo a tu espacio de trabajo...",+ "error_title": "Vaya",+ "go_home": "Ir al inicio",+ "loading": "Cargando los detalles de la invitación...",+ "title": "Te han invitado a {{workspace}}",+ "invited_by": "Invitación de {{name}}",+ "join_as": "Te unirás a este espacio de trabajo como",+ "role_admin": "Administrador",+ "role_member": "Miembro",+ "login_required": "Tienes que iniciar sesión para unirte a este espacio de trabajo.",+ "join": "Unirse al espacio de trabajo",+ "joining": "Uniéndose...",+ "log_in_to_join": "Inicia sesión para unirte",+ "join_failed": "No se pudo unir al espacio de trabajo. Es posible que el enlace haya caducado.",+ "seats_full": "Todos los puestos de miembro comprados están en uso. Pide a un administrador del espacio de trabajo que añada un puesto antes de volver a intentarlo.",+ "seats_unavailable": "No se pudo verificar la capacidad de miembros. Inténtalo de nuevo.",+ "full_title": "{{workspace}} está lleno",+ "full_description": "Habla con quien te invitó. Este enlace volverá a funcionar cuando el espacio de trabajo mejore su plan.",+ "retry": "Volver a intentarlo"}}diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex dc08f14e2b..bb52028355 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -1647,7 +1647,20 @@"seats_used": "{{used}} de {{purchased}} puestos usados","share_links_description": "Cualquiera con el enlace puede unirse con el rol elegido hasta que caduque o lo revoques.","share_links_label": "Enlaces de invitación",- "you": "Tú"+ "you": "Tú",+ "member_limit_full_title": "Este plan permite hasta {{limit}} miembros. El espacio de trabajo está lleno.",+ "member_limit_full_description": "Pasa a Pro para tener miembros ilimitados. Cada miembro ocupa un puesto de pago, y la mejora incluye uno para esta invitación. O elimina antes a un miembro.",+ "member_limit_full_description_pending": "Las invitaciones pendientes también ocupan un lugar ({{pending}} ahora). Pasa a Pro para tener miembros ilimitados (cada miembro ocupa un puesto de pago, y la mejora incluye uno para esta invitación), o revoca antes una invitación o elimina a un miembro.",+ "member_limit_usage": "{{used}} / {{limit}} miembros",+ "upgrade_and_invite": "Mejorar e invitar",+ "toast_member_limit_reached": "El espacio de trabajo está lleno. Mejora el plan para invitar a más miembros.",+ "member_limit_full_description_no_upgrade": "Revoca una invitación pendiente o elimina a un miembro para liberar un lugar.",+ "toast_invalid_email": "Introduce una dirección de correo válida.",+ "toast_already_member": "{{email}} ya es miembro de este espacio de trabajo.",+ "toast_invitation_pending": "Ya hay una invitación pendiente para {{email}}.",+ "toast_invite_check_unavailable": "No se pudieron comprobar los miembros y las invitaciones actuales. Inténtalo de nuevo en un momento.",+ "member_limit_full_description_billing": "La suscripción del espacio de trabajo necesita atención. Restablécela en Facturación para añadir miembros, o elimina antes a un miembro.",+ "open_billing": "Abrir Facturación"},"integrations": {"status_connected": "Conectado",diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex 8d8a81277d..82dab2cabf 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -135,7 +135,9 @@"usage_total": "{{total}} / {{limit}}","usage_breakdown": "{{used}} terminées · {{reserved}} en cours","resets_at": "Réinitialisation {{date}}",- "usage_unavailable": "La consommation est temporairement indisponible"+ "usage_unavailable": "La consommation est temporairement indisponible",+ "members": "Membres",+ "members_pending": "Invitations en attente : {{pending}}"},"seats": {"title": "Sièges",@@ -222,7 +224,16 @@},"confirm": {"title": "Continuer vers Stripe Checkout ?",- "description": "Forfait : {{plan}}. Intervalle de facturation : {{interval}}. Membres humains actuels : {{count}}. Stripe recomptera les sièges et affichera le montant final avant le paiement."+ "description": "Forfait : {{plan}}. Intervalle de facturation : {{interval}}. Membres humains actuels : {{count}}. Stripe recomptera les sièges et affichera le montant final avant le paiement.",+ "held_invite": "Un siège payant supplémentaire est inclus pour l'invitation à {{email}}. Une fois le paiement effectué, envoyez-la depuis Facturation."+ },+ "held_invite": {+ "title": "L'espace de travail est maintenant en {{plan}}",+ "description": "Vous avez mis de côté une invitation pour {{email}} en tant que {{role}} jusqu'à la mise à niveau. L'envoyer maintenant ?",+ "role_admin": "administrateur",+ "role_member": "membre",+ "send": "Envoyer l'invitation",+ "discard": "Abandonner"}},"return_page": {diff --git a/packages/views/locales/fr/invite.json b/packages/views/locales/fr/invite.jsonindex ae2616bfe1..3d5642979d 100644--- a/packages/views/locales/fr/invite.json+++ b/packages/views/locales/fr/invite.json@@ -30,6 +30,31 @@},"errors": {"accept_failed": "Échec de l'acceptation de l'invitation",- "decline_failed": "Échec du refus de l'invitation"+ "decline_failed": "Échec du refus de l'invitation",+ "member_limit_reached": "{{workspace}} est complet. Contactez la personne qui vous a invité ; vous pourrez le rejoindre une fois son forfait mis à niveau."+ },+ "join": {+ "no_code": "Aucun code d'invitation trouvé. Utilisez un lien de partage valide.",+ "invalid": "Ce lien d'invitation n'est pas valide ou a expiré.",+ "joined_title": "C'est fait !",+ "redirecting": "Redirection vers votre espace de travail...",+ "error_title": "Oups",+ "go_home": "Retour à l'accueil",+ "loading": "Chargement de l'invitation...",+ "title": "Vous êtes invité à rejoindre {{workspace}}",+ "invited_by": "Invitation de {{name}}",+ "join_as": "Vous rejoindrez cet espace de travail en tant que",+ "role_admin": "Administrateur",+ "role_member": "Membre",+ "login_required": "Vous devez vous connecter pour rejoindre cet espace de travail.",+ "join": "Rejoindre l'espace de travail",+ "joining": "Adhésion...",+ "log_in_to_join": "Se connecter pour rejoindre",+ "join_failed": "Impossible de rejoindre l'espace de travail. Le lien a peut-être expiré.",+ "seats_full": "Tous les sièges achetés sont occupés. Demandez à un administrateur de l'espace de travail d'ajouter un siège avant de réessayer.",+ "seats_unavailable": "Impossible de vérifier la capacité en membres. Réessayez.",+ "full_title": "{{workspace}} est complet",+ "full_description": "Contactez la personne qui vous a invité. Ce lien fonctionnera de nouveau une fois le forfait de l'espace de travail mis à niveau.",+ "retry": "Réessayer"}}diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex ab7f103e96..805d93b5d7 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -1647,7 +1647,20 @@"invitation_meta": "Envoyée le {{sent}} · Expire le {{expires}}","revoke_invitation_aria": "Révoquer l'invitation de {{email}}","seats_used": "{{used}} sièges utilisés sur {{purchased}}",- "manage_seats": "Gérer les sièges"+ "manage_seats": "Gérer les sièges",+ "member_limit_full_title": "Ce forfait autorise jusqu'à {{limit}} membres. L'espace de travail est complet.",+ "member_limit_full_description": "Passez à Pro pour un nombre illimité de membres. Chaque membre occupe un siège payant, et la mise à niveau en inclut un pour cette invitation. Ou retirez d'abord un membre.",+ "member_limit_full_description_pending": "Les invitations en attente occupent aussi une place ({{pending}} actuellement). Passez à Pro pour un nombre illimité de membres (chaque membre occupe un siège payant, et la mise à niveau en inclut un pour cette invitation), ou révoquez d'abord une invitation ou retirez un membre.",+ "member_limit_usage": "{{used}} / {{limit}} membres",+ "upgrade_and_invite": "Mettre à niveau et inviter",+ "toast_member_limit_reached": "L'espace de travail est complet. Passez à un forfait supérieur pour inviter d'autres membres.",+ "member_limit_full_description_no_upgrade": "Révoquez une invitation en attente ou retirez un membre pour libérer une place.",+ "toast_invalid_email": "Saisissez une adresse e-mail valide.",+ "toast_already_member": "{{email}} est déjà membre de cet espace de travail.",+ "toast_invitation_pending": "Une invitation pour {{email}} est déjà en attente.",+ "toast_invite_check_unavailable": "Impossible de vérifier les membres et invitations existants. Réessayez dans un instant.",+ "member_limit_full_description_billing": "L'abonnement de l'espace de travail demande votre attention. Rétablissez-le dans Facturation pour ajouter des membres, ou retirez d'abord un membre.",+ "open_billing": "Ouvrir Facturation"},"integrations": {"status_connected": "Connecté",diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex 08525aa28c..e50e0007ff 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -134,7 +134,9 @@"usage_total": "{{total}} / {{limit}}","usage_breakdown": "完了 {{used}} · 実行中 {{reserved}}","resets_at": "{{date}} にリセット",- "usage_unavailable": "使用量は一時的に利用できません"+ "usage_unavailable": "使用量は一時的に利用できません",+ "members": "メンバー",+ "members_pending": "保留中の招待:{{pending}} 件"},"seats": {"title": "席数",@@ -216,7 +218,16 @@},"confirm": {"title": "Stripe Checkout に進みますか?",- "description": "プラン: {{plan}}。請求期間: {{interval}}。現在のユーザーメンバー: {{count}}。Stripe が席数を再集計し、お支払い前に最終金額を表示します。"+ "description": "プラン: {{plan}}。請求期間: {{interval}}。現在のユーザーメンバー: {{count}}。Stripe が席数を再集計し、お支払い前に最終金額を表示します。",+ "held_invite": "{{email}} への招待用に有料席が 1 席追加されます。支払いが完了したら、請求とプランから招待を送信してください。"+ },+ "held_invite": {+ "title": "ワークスペースは {{plan}} になりました",+ "description": "アップグレードまで保留していた {{email}} への招待({{role}})があります。今すぐ送信しますか?",+ "role_admin": "管理者",+ "role_member": "メンバー",+ "send": "招待を送信",+ "discard": "破棄"}},"return_page": {diff --git a/packages/views/locales/ja/invite.json b/packages/views/locales/ja/invite.jsonindex 4573e04ad1..b209407ef2 100644--- a/packages/views/locales/ja/invite.json+++ b/packages/views/locales/ja/invite.json@@ -30,6 +30,31 @@},"errors": {"accept_failed": "招待を承認できませんでした",- "decline_failed": "招待を辞退できませんでした"+ "decline_failed": "招待を辞退できませんでした",+ "member_limit_reached": "{{workspace}} はメンバーが上限に達しています。招待した人に連絡してください。ワークスペースがアップグレードされると参加できます。"+ },+ "join": {+ "no_code": "招待コードが見つかりません。有効な共有リンクを使ってください。",+ "invalid": "この招待リンクは無効か、期限が切れています。",+ "joined_title": "参加しました",+ "redirecting": "ワークスペースに移動しています...",+ "error_title": "エラー",+ "go_home": "ホームへ",+ "loading": "招待の詳細を読み込んでいます...",+ "title": "{{workspace}} に招待されています",+ "invited_by": "{{name}} からの招待",+ "join_as": "参加後のロール",+ "role_admin": "管理者",+ "role_member": "メンバー",+ "login_required": "このワークスペースに参加するにはログインが必要です。",+ "join": "ワークスペースに参加",+ "joining": "参加中...",+ "log_in_to_join": "ログインして参加",+ "join_failed": "ワークスペースに参加できませんでした。リンクの期限が切れている可能性があります。",+ "seats_full": "購入済みのメンバー席はすべて使用中です。ワークスペースの管理者に席の追加を依頼してから、もう一度お試しください。",+ "seats_unavailable": "メンバー枠を確認できませんでした。もう一度お試しください。",+ "full_title": "{{workspace}} はメンバーが上限に達しています",+ "full_description": "招待した人に連絡してください。ワークスペースがアップグレードされると、このリンクは再び使えます。",+ "retry": "もう一度試す"}}diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 98464a9566..9fc93254a1 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1632,7 +1632,20 @@"invitation_meta": "{{sent}} に送信 · {{expires}} に期限切れ","revoke_invitation_aria": "{{email}} への招待を取り消す","seats_used": "{{purchased}} 席中 {{used}} 席を使用",- "manage_seats": "席を管理"+ "manage_seats": "席を管理",+ "member_limit_full_title": "このプランのメンバー上限は {{limit}} 人で、上限に達しています",+ "member_limit_full_description": "Pro にアップグレードするとメンバー数は無制限です。メンバーごとに有料席が必要で、今回のアップグレードにはこの招待用の 1 席が含まれます。先にメンバーを削除することもできます。",+ "member_limit_full_description_pending": "保留中の招待も枠を使います(現在 {{pending}} 件)。Pro にアップグレードするとメンバー数は無制限です(メンバーごとに有料席が必要で、今回のアップグレードにはこの招待用の 1 席が含まれます)。先に招待を取り消すか、メンバーを削除することもできます。",+ "member_limit_usage": "{{used}} / {{limit}} 人",+ "upgrade_and_invite": "アップグレードして招待",+ "toast_member_limit_reached": "メンバーが上限に達しています。さらに招待するにはアップグレードしてください。",+ "member_limit_full_description_no_upgrade": "保留中の招待を取り消すか、メンバーを削除すると枠が空きます。",+ "toast_invalid_email": "有効なメールアドレスを入力してください。",+ "toast_already_member": "{{email}} はすでにこのワークスペースのメンバーです。",+ "toast_invitation_pending": "{{email}} への招待はすでに保留中です。",+ "toast_invite_check_unavailable": "既存のメンバーと招待を確認できませんでした。しばらくしてからもう一度お試しください。",+ "member_limit_full_description_billing": "ワークスペースのサブスクリプションに対応が必要です。請求とプランで復旧するとメンバーを追加できます。先にメンバーを削除することもできます。",+ "open_billing": "請求とプランを開く"},"integrations": {"status_connected": "接続済み",diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 576934580f..4d15fbbd25 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -134,7 +134,9 @@"usage_total": "{{total}} / {{limit}}","usage_breakdown": "완료 {{used}} · 진행 중 {{reserved}}","resets_at": "{{date}}에 초기화",- "usage_unavailable": "사용량을 일시적으로 불러올 수 없습니다"+ "usage_unavailable": "사용량을 일시적으로 불러올 수 없습니다",+ "members": "멤버",+ "members_pending": "대기 중인 초대: {{pending}}건"},"seats": {"title": "좌석",@@ -216,7 +218,16 @@},"confirm": {"title": "Stripe Checkout으로 이동할까요?",- "description": "요금제: {{plan}}. 결제 주기: {{interval}}. 현재 사용자 멤버: {{count}}. Stripe가 좌석을 다시 계산하고 결제 전에 최종 금액을 표시합니다."+ "description": "요금제: {{plan}}. 결제 주기: {{interval}}. 현재 사용자 멤버: {{count}}. Stripe가 좌석을 다시 계산하고 결제 전에 최종 금액을 표시합니다.",+ "held_invite": "{{email}}에게 보낼 초대를 위한 유료 좌석 1개가 추가됩니다. 결제가 완료되면 결제 및 요금제에서 초대를 보내세요."+ },+ "held_invite": {+ "title": "워크스페이스가 이제 {{plan}} 요금제입니다",+ "description": "업그레이드할 때까지 보류해 둔 {{email}} 초대({{role}})가 있습니다. 지금 보낼까요?",+ "role_admin": "관리자",+ "role_member": "멤버",+ "send": "초대 보내기",+ "discard": "버리기"}},"return_page": {diff --git a/packages/views/locales/ko/invite.json b/packages/views/locales/ko/invite.jsonindex 4c5641c5e3..8b595a91a6 100644--- a/packages/views/locales/ko/invite.json+++ b/packages/views/locales/ko/invite.json@@ -30,6 +30,31 @@},"errors": {"accept_failed": "초대를 수락하지 못했습니다",- "decline_failed": "초대를 거절하지 못했습니다"+ "decline_failed": "초대를 거절하지 못했습니다",+ "member_limit_reached": "{{workspace}}의 멤버 자리가 모두 찼습니다. 초대한 사람에게 문의하세요. 워크스페이스가 업그레이드되면 참가할 수 있습니다."+ },+ "join": {+ "no_code": "초대 코드를 찾을 수 없습니다. 유효한 공유 링크를 사용하세요.",+ "invalid": "유효하지 않거나 만료된 초대 링크입니다.",+ "joined_title": "참가했습니다",+ "redirecting": "워크스페이스로 이동하는 중...",+ "error_title": "문제가 발생했습니다",+ "go_home": "홈으로",+ "loading": "초대 정보를 불러오는 중...",+ "title": "{{workspace}}에 초대되었습니다",+ "invited_by": "초대한 사람: {{name}}",+ "join_as": "참가 후 역할",+ "role_admin": "관리자",+ "role_member": "멤버",+ "login_required": "이 워크스페이스에 참가하려면 로그인해야 합니다.",+ "join": "워크스페이스 참가",+ "joining": "참가하는 중...",+ "log_in_to_join": "로그인하고 참가",+ "join_failed": "워크스페이스에 참가하지 못했습니다. 링크가 만료되었을 수 있습니다.",+ "seats_full": "구매한 멤버 좌석이 모두 사용 중입니다. 워크스페이스 관리자에게 좌석 추가를 요청한 뒤 다시 시도하세요.",+ "seats_unavailable": "멤버 수용 인원을 확인하지 못했습니다. 다시 시도하세요.",+ "full_title": "{{workspace}}의 멤버 자리가 모두 찼습니다",+ "full_description": "초대한 사람에게 문의하세요. 워크스페이스가 업그레이드되면 이 링크를 다시 사용할 수 있습니다.",+ "retry": "다시 시도"}}diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 0d8ef13050..967311f987 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1375,7 +1375,20 @@"invitation_meta": "{{sent}} 발송 · {{expires}} 만료","revoke_invitation_aria": "{{email}}에 보낸 초대 취소","seats_used": "{{purchased}}석 중 {{used}}석 사용",- "manage_seats": "좌석 관리"+ "manage_seats": "좌석 관리",+ "member_limit_full_title": "이 요금제는 멤버를 최대 {{limit}}명까지 허용하며, 자리가 모두 찼습니다",+ "member_limit_full_description": "Pro로 업그레이드하면 멤버 수 제한이 없습니다. 멤버마다 유료 좌석이 필요하며, 이번 업그레이드에는 이 초대를 위한 좌석 1개가 포함됩니다. 먼저 멤버를 제거할 수도 있습니다.",+ "member_limit_full_description_pending": "대기 중인 초대도 자리를 차지합니다(현재 {{pending}}건). Pro로 업그레이드하면 멤버 수 제한이 없습니다(멤버마다 유료 좌석이 필요하며, 이번 업그레이드에는 이 초대를 위한 좌석 1개가 포함됩니다). 먼저 초대를 취소하거나 멤버를 제거할 수도 있습니다.",+ "member_limit_usage": "멤버 {{used}} / {{limit}}명",+ "upgrade_and_invite": "업그레이드하고 초대",+ "toast_member_limit_reached": "멤버 자리가 모두 찼습니다. 더 초대하려면 업그레이드하세요.",+ "member_limit_full_description_no_upgrade": "대기 중인 초대를 취소하거나 멤버를 제거하면 자리가 생깁니다.",+ "toast_invalid_email": "올바른 이메일 주소를 입력하세요.",+ "toast_already_member": "{{email}}은(는) 이미 이 워크스페이스의 멤버입니다.",+ "toast_invitation_pending": "{{email}}에게 보낸 초대가 이미 대기 중입니다.",+ "toast_invite_check_unavailable": "기존 멤버와 초대를 확인하지 못했습니다. 잠시 후 다시 시도하세요.",+ "member_limit_full_description_billing": "워크스페이스 구독에 조치가 필요합니다. 결제 및 요금제에서 구독을 복구하면 멤버를 추가할 수 있습니다. 먼저 멤버를 제거할 수도 있습니다.",+ "open_billing": "결제 및 요금제 열기"},"lark": {"section_title": "Lark",diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex 4e0b161a41..7b4dc9be93 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -137,7 +137,9 @@"usage_total": "{{total}} / {{limit}}","usage_breakdown": "{{used}} завершено · {{reserved}} в процессе","resets_at": "Сброс {{date}}",- "usage_unavailable": "Данные об использовании временно недоступны"+ "usage_unavailable": "Данные об использовании временно недоступны",+ "members": "Участники",+ "members_pending": "Ожидающие приглашения: {{pending}}"},"seats": {"title": "Места",@@ -234,7 +236,16 @@},"confirm": {"title": "Перейти к оформлению в Stripe Checkout?",- "description": "Тариф: {{plan}}. Интервал оплаты: {{interval}}. Текущее число участников-людей: {{count}}. Stripe пересчитает места и покажет итоговую сумму перед оплатой."+ "description": "Тариф: {{plan}}. Интервал оплаты: {{interval}}. Текущее число участников-людей: {{count}}. Stripe пересчитает места и покажет итоговую сумму перед оплатой.",+ "held_invite": "Включено ещё одно оплаченное место для приглашения {{email}}. Когда оплата пройдёт, отправьте приглашение в разделе «Биллинг»."+ },+ "held_invite": {+ "title": "Рабочее пространство теперь на тарифе {{plan}}",+ "description": "Вы отложили приглашение для {{email}} с ролью «{{role}}» до смены тарифа. Отправить его сейчас?",+ "role_admin": "администратор",+ "role_member": "участник",+ "send": "Отправить приглашение",+ "discard": "Отменить"}},"return_page": {diff --git a/packages/views/locales/ru/invite.json b/packages/views/locales/ru/invite.jsonindex ac58e7c513..62126494c6 100644--- a/packages/views/locales/ru/invite.json+++ b/packages/views/locales/ru/invite.json@@ -30,6 +30,31 @@},"errors": {"accept_failed": "Не удалось принять приглашение",- "decline_failed": "Не удалось отклонить приглашение"+ "decline_failed": "Не удалось отклонить приглашение",+ "member_limit_reached": "В {{workspace}} нет свободных мест. Свяжитесь с тем, кто вас пригласил: присоединиться можно будет после смены тарифа."+ },+ "join": {+ "no_code": "Код приглашения не найден. Используйте действующую ссылку.",+ "invalid": "Ссылка-приглашение недействительна или устарела.",+ "joined_title": "Готово!",+ "redirecting": "Переходим в рабочее пространство...",+ "error_title": "Что-то пошло не так",+ "go_home": "На главную",+ "loading": "Загружаем приглашение...",+ "title": "Вас пригласили в {{workspace}}",+ "invited_by": "Приглашение от {{name}}",+ "join_as": "Ваша роль в рабочем пространстве",+ "role_admin": "Администратор",+ "role_member": "Участник",+ "login_required": "Чтобы присоединиться к рабочему пространству, войдите в аккаунт.",+ "join": "Присоединиться",+ "joining": "Присоединение...",+ "log_in_to_join": "Войти и присоединиться",+ "join_failed": "Не удалось присоединиться к рабочему пространству. Возможно, срок действия ссылки истёк.",+ "seats_full": "Все купленные места заняты. Попросите администратора рабочего пространства добавить место и повторите попытку.",+ "seats_unavailable": "Не удалось проверить число свободных мест. Повторите попытку.",+ "full_title": "В {{workspace}} нет свободных мест",+ "full_description": "Свяжитесь с тем, кто вас пригласил. Ссылка снова заработает после смены тарифа.",+ "retry": "Повторить"}}diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 569372a120..ed3be85934 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -1676,7 +1676,20 @@"invitation_meta": "Отправлено {{sent}} · Истекает {{expires}}","revoke_invitation_aria": "Отозвать приглашение для {{email}}","seats_used": "Использовано мест: {{used}} из {{purchased}}",- "manage_seats": "Управление местами"+ "manage_seats": "Управление местами",+ "member_limit_full_title": "В этом тарифе не больше {{limit}} участников, и все места заняты",+ "member_limit_full_description": "Перейдите на Pro, чтобы снять ограничение на число участников. Каждый участник — это оплаченное место, и смена тарифа включает место для этого приглашения. Или сначала удалите участника.",+ "member_limit_full_description_pending": "Ожидающие приглашения тоже занимают место (сейчас: {{pending}}). Перейдите на Pro, чтобы снять ограничение (каждый участник — это оплаченное место, и смена тарифа включает место для этого приглашения), или сначала отзовите приглашение либо удалите участника.",+ "member_limit_usage": "Участников: {{used}} из {{limit}}",+ "upgrade_and_invite": "Сменить тариф и пригласить",+ "toast_member_limit_reached": "Все места заняты. Чтобы пригласить больше участников, смените тариф.",+ "member_limit_full_description_no_upgrade": "Отзовите ожидающее приглашение или удалите участника, чтобы освободить место.",+ "toast_invalid_email": "Введите корректный адрес электронной почты.",+ "toast_already_member": "{{email}} уже участник этого рабочего пространства.",+ "toast_invitation_pending": "Приглашение для {{email}} уже ожидает ответа.",+ "toast_invite_check_unavailable": "Не удалось проверить текущих участников и приглашения. Повторите попытку чуть позже.",+ "member_limit_full_description_billing": "Подписке рабочего пространства нужно внимание. Восстановите её в разделе «Биллинг», чтобы добавлять участников, или сначала удалите участника.",+ "open_billing": "Открыть «Биллинг»"},"integrations": {"status_connected": "Подключено",diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex 3b2076ed5f..a627c25c24 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -134,7 +134,9 @@"usage_total": "{{total}} / {{limit}}","usage_breakdown": "已完成 {{used}} · 进行中 {{reserved}}","resets_at": "{{date}} 重置",- "usage_unavailable": "用量暂时不可用"+ "usage_unavailable": "用量暂时不可用",+ "members": "成员",+ "members_pending": "待接受的邀请:{{pending}}"},"seats": {"title": "席位",@@ -216,7 +218,16 @@},"confirm": {"title": "前往 Stripe Checkout?",- "description": "套餐:{{plan}}。付款周期:{{interval}}。当前成员:{{count}}。Stripe 会重新统计席位,并在付款前显示最终金额。"+ "description": "套餐:{{plan}}。付款周期:{{interval}}。当前成员:{{count}}。Stripe 会重新统计席位,并在付款前显示最终金额。",+ "held_invite": "另含 1 个付费席位,留给发给 {{email}} 的邀请。付款完成后,在「账单与套餐」里发出这份邀请。"+ },+ "held_invite": {+ "title": "工作区已升级到 {{plan}}",+ "description": "你之前留下了一份邀请:以{{role}}身份邀请 {{email}},等升级后再发。现在发出吗?",+ "role_admin": "管理员",+ "role_member": "成员",+ "send": "发送邀请",+ "discard": "不发了"}},"return_page": {diff --git a/packages/views/locales/zh-Hans/invite.json b/packages/views/locales/zh-Hans/invite.jsonindex 6e176b7db5..a6fb47fdf2 100644--- a/packages/views/locales/zh-Hans/invite.json+++ b/packages/views/locales/zh-Hans/invite.json@@ -30,6 +30,31 @@},"errors": {"accept_failed": "接受邀请失败",- "decline_failed": "拒绝邀请失败"+ "decline_failed": "拒绝邀请失败",+ "member_limit_reached": "{{workspace}} 的成员已满。请联系邀请你的人,工作区升级后就能加入。"+ },+ "join": {+ "no_code": "没有找到邀请码,请使用有效的分享链接。",+ "invalid": "这个邀请链接无效或已过期。",+ "joined_title": "已加入",+ "redirecting": "正在进入工作区...",+ "error_title": "出错了",+ "go_home": "返回首页",+ "loading": "正在加载邀请信息...",+ "title": "你被邀请加入 {{workspace}}",+ "invited_by": "邀请人:{{name}}",+ "join_as": "加入后的角色",+ "role_admin": "管理员",+ "role_member": "成员",+ "login_required": "需要先登录才能加入这个工作区。",+ "join": "加入工作区",+ "joining": "加入中...",+ "log_in_to_join": "登录后加入",+ "join_failed": "加入工作区失败,链接可能已过期。",+ "seats_full": "已购买的成员席位都已用完。请联系工作区管理员增加席位后再试。",+ "seats_unavailable": "暂时无法核验成员席位,请稍后重试。",+ "full_title": "{{workspace}} 的成员已满",+ "full_description": "请联系邀请你的人。工作区升级后,这个链接会恢复可用。",+ "retry": "重试"}}diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex 3c6da882cb..e1ea80858c 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1632,7 +1632,20 @@"invitation_meta": "{{sent}} 发送 · {{expires}} 过期","revoke_invitation_aria": "撤销发给 {{email}} 的邀请","seats_used": "已用 {{used}} / {{purchased}} 个席位",- "manage_seats": "管理席位"+ "manage_seats": "管理席位",+ "member_limit_full_title": "当前套餐最多 {{limit}} 位成员,已满",+ "member_limit_full_description": "升级到 Pro 后成员不限。每位成员占一个付费席位,这次升级会为这份邀请多买一个。也可以先移除一位成员。",+ "member_limit_full_description_pending": "待接受的邀请也占名额(现有 {{pending}} 个)。升级到 Pro 后成员不限(每位成员占一个付费席位,这次升级会为这份邀请多买一个),也可以先撤回邀请或移除成员。",+ "member_limit_usage": "{{used}} / {{limit}} 位成员",+ "upgrade_and_invite": "升级并邀请",+ "toast_member_limit_reached": "工作区成员已满,升级后才能邀请更多成员。",+ "member_limit_full_description_no_upgrade": "撤回待接受的邀请或移除成员后,才能邀请新成员。",+ "toast_invalid_email": "请输入有效的邮箱地址。",+ "toast_already_member": "{{email}} 已经是这个工作区的成员。",+ "toast_invitation_pending": "已经有一封发给 {{email}} 的待接受邀请。",+ "toast_invite_check_unavailable": "暂时无法核对现有成员和邀请,请稍后再试。",+ "member_limit_full_description_billing": "工作区的订阅需要处理。到「账单与套餐」恢复订阅后才能加人,也可以先移除一位成员。",+ "open_billing": "打开账单与套餐"},"integrations": {"status_connected": "已连接",diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex 66087973d7..426d044186 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -134,7 +134,9 @@"usage_total": "{{total}} / {{limit}}","usage_breakdown": "已完成 {{used}} · 進行中 {{reserved}}","resets_at": "{{date}} 重置",- "usage_unavailable": "用量暫時不可用"+ "usage_unavailable": "用量暫時不可用",+ "members": "成員",+ "members_pending": "待接受的邀請:{{pending}}"},"seats": {"title": "席位",@@ -216,7 +218,16 @@},"confirm": {"title": "前往 Stripe Checkout?",- "description": "套餐:{{plan}}。付款週期:{{interval}}。當前成員:{{count}}。Stripe 會重新統計席位,並在付款前顯示最終金額。"+ "description": "套餐:{{plan}}。付款週期:{{interval}}。當前成員:{{count}}。Stripe 會重新統計席位,並在付款前顯示最終金額。",+ "held_invite": "另含 1 個付費席位,留給發給 {{email}} 的邀請。付款完成後,在「帳單與套餐」裡發出這份邀請。"+ },+ "held_invite": {+ "title": "工作區已升級到 {{plan}}",+ "description": "你之前留下了一份邀請:以{{role}}身分邀請 {{email}},等升級後再發。現在發出嗎?",+ "role_admin": "管理員",+ "role_member": "成員",+ "send": "發送邀請",+ "discard": "不發了"}},"return_page": {diff --git a/packages/views/locales/zh-Hant/invite.json b/packages/views/locales/zh-Hant/invite.jsonindex eb0e6bf469..9a41437fb1 100644--- a/packages/views/locales/zh-Hant/invite.json+++ b/packages/views/locales/zh-Hant/invite.json@@ -30,6 +30,31 @@},"errors": {"accept_failed": "接受邀請失敗",- "decline_failed": "拒絕邀請失敗"+ "decline_failed": "拒絕邀請失敗",+ "member_limit_reached": "{{workspace}} 的成員已滿。請聯絡邀請你的人,工作區升級後就能加入。"+ },+ "join": {+ "no_code": "找不到邀請碼,請使用有效的分享連結。",+ "invalid": "這個邀請連結無效或已過期。",+ "joined_title": "已加入",+ "redirecting": "正在進入工作區...",+ "error_title": "發生錯誤",+ "go_home": "返回首頁",+ "loading": "正在載入邀請資訊...",+ "title": "你被邀請加入 {{workspace}}",+ "invited_by": "邀請人:{{name}}",+ "join_as": "加入後的角色",+ "role_admin": "管理員",+ "role_member": "成員",+ "login_required": "需要先登入才能加入這個工作區。",+ "join": "加入工作區",+ "joining": "加入中...",+ "log_in_to_join": "登入後加入",+ "join_failed": "加入工作區失敗,連結可能已過期。",+ "seats_full": "已購買的成員席位都已用完。請聯絡工作區管理員增加席位後再試。",+ "seats_unavailable": "暫時無法核驗成員席位,請稍後重試。",+ "full_title": "{{workspace}} 的成員已滿",+ "full_description": "請聯絡邀請你的人。工作區升級後,這個連結會恢復可用。",+ "retry": "重試"}}diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 0e56c6d80f..38fc546539 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -1632,7 +1632,20 @@"invitation_meta": "{{sent}} 傳送 · {{expires}} 過期","revoke_invitation_aria": "撤銷發給 {{email}} 的邀請","seats_used": "已用 {{used}} / {{purchased}} 個席位",- "manage_seats": "管理席位"+ "manage_seats": "管理席位",+ "member_limit_full_title": "目前套餐最多 {{limit}} 位成員,已滿",+ "member_limit_full_description": "升級到 Pro 後成員不限。每位成員佔一個付費席位,這次升級會為這份邀請多買一個。也可以先移除一位成員。",+ "member_limit_full_description_pending": "待接受的邀請也佔名額(目前 {{pending}} 個)。升級到 Pro 後成員不限(每位成員佔一個付費席位,這次升級會為這份邀請多買一個),也可以先撤回邀請或移除成員。",+ "member_limit_usage": "{{used}} / {{limit}} 位成員",+ "upgrade_and_invite": "升級並邀請",+ "toast_member_limit_reached": "工作區成員已滿,升級後才能邀請更多成員。",+ "member_limit_full_description_no_upgrade": "撤回待接受的邀請或移除成員後,才能邀請新成員。",+ "toast_invalid_email": "請輸入有效的電子郵件地址。",+ "toast_already_member": "{{email}} 已經是這個工作區的成員。",+ "toast_invitation_pending": "已經有一封發給 {{email}} 的待接受邀請。",+ "toast_invite_check_unavailable": "暫時無法核對現有成員和邀請,請稍後再試。",+ "member_limit_full_description_billing": "工作區的訂閱需要處理。到「帳單與套餐」恢復訂閱後才能加人,也可以先移除一位成員。",+ "open_billing": "開啟帳單與套餐"},"integrations": {"status_connected": "已連線",diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex da720ae5c3..a152802644 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -6,10 +6,16 @@ import { configStore } from "@multica/core/config";import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";import type {AutopilotQuotaUsage,+ MemberLimit,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionPrices,WorkspaceSubscriptionSummary,} from "@multica/core/types";+import {+ bindUpgradeInviteCheckout,+ readUpgradeInvite,+ saveUpgradeInvite,+} from "@multica/core/billing";import { renderWithI18n } from "../../test/i18n";const mocks = vi.hoisted(() => ({@@ -28,6 +34,8 @@ const mocks = vi.hoisted(() => ({refetchPrices: vi.fn(),openExternal: vi.fn(),workspaceId: "workspace-1",+ invalidateQueries: vi.fn(() => Promise.resolve()),+ memberLimit: { action: "off", limit: null, members: null, pendingInvitations: null } as MemberLimit,prices: null as WorkspaceSubscriptionPrices | null,pricesLoading: false,pricesFetching: false,@@ -101,9 +109,12 @@ const mocks = vi.hoisted(() => ({vi.mock("@tanstack/react-query", () => ({useQuery: (options: unknown) => mocks.useQuery(options),+ useQueryClient: () => ({ invalidateQueries: mocks.invalidateQueries }),+ queryOptions: <T,>(options: T) => options,}));-vi.mock("@multica/core/billing", () => ({+vi.mock("@multica/core/billing", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/billing")>()),workspaceSubscriptionPricesOptions: (wsId: string) => ({queryKey: ["workspace-subscriptions", wsId, "prices"],}),@@ -157,13 +168,14 @@ vi.mock("@multica/core/paths", () => ({const navigationState = {search: "tab=billing",replace: vi.fn(),+ push: vi.fn(),};vi.mock("../../navigation", () => ({useNavigation: () => ({pathname: "/acme/settings",searchParams: new URLSearchParams(navigationState.search),hash: "",- push: vi.fn(),+ push: navigationState.push,replace: navigationState.replace,back: vi.fn(),getShareableUrl: vi.fn(),@@ -315,8 +327,13 @@ describe("BillingTab", () => {reset_at: "2030-02-01T00:00:00Z",blocked_counts: {},});+ localStorage.clear();+ mocks.memberLimit = { action: "off", limit: null, members: null, pendingInvitations: null };mocks.useQuery.mockImplementation((options: unknown) => {const queryKey = (options as { queryKey?: readonly unknown[] }).queryKey;+ if (queryKey?.[queryKey.length - 1] === "limit") {+ return { data: mocks.memberLimit, isPending: false, isError: false };+ }if (queryKey?.[queryKey.length - 1] === "prices") {return {data: mocks.prices,@@ -592,6 +609,257 @@ describe("BillingTab", () => {);});+ describe("member limit", () => {+ const upgraded = () => {+ Object.assign(mocks.entitlements, { plan: "pro", status: "active", version: 1 });+ mocks.summary.availableActions.checkout = false;+ mocks.summaryDataUpdatedAt = Date.now() + 1;+ mocks.summaryFetchedAfterMount = true;+ };+ const boundHeldInvite = (email: string, requestId: string) => {+ const token = saveUpgradeInvite("acme", { email, role: "member" });+ bindUpgradeInviteCheckout("acme", token, { requestId, baseVersion: 0 });+ return token;+ };+ const membersResume = (token: string) =>+ `/acme/settings?tab=members&invite=resume&held_invite=${token}`;++ it("opens the Pro checkout confirmation when Members asks for an upgrade", async () => {+ navigationState.search = "tab=billing&upgrade=pro";+ renderWithI18n(<BillingTab />);++ const confirm = await screen.findByRole("alertdialog");+ expect(confirm).toHaveTextContent("Plan: Pro");+ expect(navigationState.replace).toHaveBeenCalledWith("/acme/settings?tab=billing");+ });++ it("buys a seat for the held invitation and binds it to that checkout", async () => {+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" });+ navigationState.search = `tab=billing&upgrade=pro&held_invite=${token}`;+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ expect(await screen.findByRole("alertdialog")).toHaveTextContent(+ "One more paid seat is included for the invitation to [email protected]",+ );+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));++ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(1));+ expect(mocks.checkout.mock.calls[0]?.[0]).toMatchObject({ plan: "pro", additionalSeats: 1 });+ expect(readUpgradeInvite("acme", token)?.checkout).toMatchObject({ requestId: "request-1", baseVersion: 0 });+ });++ // Desktop: Stripe opens in the system browser, the person closes it and+ // upgrades again from the same page. That checkout is a plain one.+ it("makes the next checkout from the same page a plain one once the held one started", async () => {+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" });+ navigationState.search = `tab=billing&upgrade=pro&held_invite=${token}`;+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ await screen.findByRole("alertdialog");+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(1));++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ expect(screen.getByRole("alertdialog")).not.toHaveTextContent("One more paid seat");+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(2));++ const [held, plain] = mocks.checkout.mock.calls.map(([request]) => request);+ expect(plain).not.toHaveProperty("additionalSeats");+ expect(plain.idempotencyKey).not.toBe(held.idempotencyKey);+ });++ it("drops a cancelled held invitation, so a later upgrade buys no seat for it", async () => {+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" });+ navigationState.search = `tab=billing&upgrade=pro&held_invite=${token}`;+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ await screen.findByRole("alertdialog");+ await user.click(screen.getByRole("button", { name: "Cancel" }));+ expect(readUpgradeInvite("acme", token)).toBeNull();++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(1));+ expect(mocks.checkout.mock.calls[0]?.[0]).not.toHaveProperty("additionalSeats");+ });++ it("leaves other tabs' held invitations alone when an upgrade starts without one", async () => {+ const token = boundHeldInvite("[email protected]", "req-tab-a");+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));++ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(1));+ expect(mocks.checkout.mock.calls[0]?.[0]).not.toHaveProperty("additionalSeats");+ expect(readUpgradeInvite("acme", token)?.checkout?.requestId).toBe("req-tab-a");+ });++ it("waits for the paid plan: an incomplete payment still reads as Free", () => {+ const token = boundHeldInvite("[email protected]", "req-held");+ navigationState.search = "tab=billing&result=success&session_id=cs_test_1";+ Object.assign(mocks.entitlements, { plan: "free", status: "incomplete", version: 1 });+ mocks.summary.availableActions.checkout = false;+ renderWithI18n(<BillingTab />);++ expect(navigationState.push).not.toHaveBeenCalled();+ expect(screen.queryByRole("button", { name: "Send invitation" })).not.toBeInTheDocument();+ expect(readUpgradeInvite("acme", token)).not.toBeNull();+ });++ // Desktop pays in the system browser and never sees the return; another+ // admin may also have upgraded from elsewhere. Neither proves this+ // invitation's checkout was paid.+ it("asks before sending when no return ties the paid plan to the held checkout", async () => {+ const token = boundHeldInvite("[email protected]", "req-unverified");+ upgraded();+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ expect(navigationState.push).not.toHaveBeenCalled();+ expect(screen.getByText("The workspace is on Pro now")).toBeInTheDocument();+ expect(+ screen.getByText("You held back an invitation for [email protected] as a member until the upgrade. Send it now?"),+ ).toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Send invitation" }));+ expect(navigationState.push).toHaveBeenCalledWith(membersResume(token));+ });++ // Desktop: held checkout A, then plain checkout B, then A is paid in the+ // system browser. Nothing proves which was paid, so A stays on offer.+ it("keeps offering a held invitation a later plain checkout might have hidden", async () => {+ const token = boundHeldInvite("[email protected]", "req-a");+ const user = userEvent.setup();+ const view = renderWithI18n(<BillingTab />);+ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(1));+ view.unmount();++ upgraded();+ renderWithI18n(<BillingTab />);+ await user.click(screen.getByRole("button", { name: "Send invitation" }));+ expect(navigationState.push).toHaveBeenCalledWith(membersResume(token));+ });++ it("starts only plain checkouts from this page after a held checkout failed", async () => {+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" });+ navigationState.search = `tab=billing&upgrade=pro&held_invite=${token}`;+ mocks.checkout.mockRejectedValueOnce(new Error("timeout creating the Stripe session"));+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ await screen.findByRole("alertdialog");+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(1));++ await user.click(screen.getByRole("button", { name: "Upgrade to Pro" }));+ expect(screen.getByRole("alertdialog")).not.toHaveTextContent("One more paid seat");+ await user.click(screen.getByRole("button", { name: "Continue to Stripe" }));+ await waitFor(() => expect(mocks.checkout).toHaveBeenCalledTimes(2));+ expect(mocks.checkout.mock.calls[1]?.[0]).not.toHaveProperty("additionalSeats");+ });++ it("keeps the upgrade intent and its invitation while the summary cannot be read", () => {+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "admin" });+ navigationState.search = `tab=billing&upgrade=pro&held_invite=${token}`;+ mocks.summaryError = true;+ renderWithI18n(<BillingTab />);++ expect(navigationState.replace).not.toHaveBeenCalled();+ expect(readUpgradeInvite("acme", token)).toMatchObject({ email: "[email protected]", role: "admin" });+ });++ // Two tabs held A and B, B is newer; A's checkout is the one paid. Both+ // are offered, so the seat just bought can go to A.+ it("offers every paid-for held invitation so the person picks which to send", async () => {+ const a = boundHeldInvite("[email protected]", "req-a");+ boundHeldInvite("[email protected]", "req-b");+ navigationState.search = "tab=billing&result=success&session_id=cs_test_1";+ upgraded();+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ expect(screen.getByText(/invitation for omar@acme\.dev/)).toBeInTheDocument();+ const sarah = screen.getByText(/invitation for sarah@acme\.dev/).closest("li")!;+ await user.click(within(sarah).getByRole("button", { name: "Send invitation" }));+ expect(navigationState.push).toHaveBeenCalledWith(membersResume(a));+ });++ it("discards a held invitation the person no longer wants", async () => {+ const token = boundHeldInvite("[email protected]", "req-unverified");+ upgraded();+ const user = userEvent.setup();+ renderWithI18n(<BillingTab />);++ await user.click(screen.getByRole("button", { name: "Discard" }));++ expect(readUpgradeInvite("acme", token)).toBeNull();+ expect(navigationState.push).not.toHaveBeenCalled();+ expect(screen.queryByRole("button", { name: "Send invitation" })).not.toBeInTheDocument();+ });++ const heldCheckoutPollInterval = () => {+ const summaryOptions = mocks.useQuery.mock.calls+ .map(([options]) => options)+ .findLast((options) => options.queryKey?.[options.queryKey.length - 1] === "summary");+ return summaryOptions.refetchInterval({ state: { data: mocks.summary } });+ };++ it("stops polling a held checkout after two minutes and offers the invitation after a focus refresh", () => {+ vi.useFakeTimers();+ try {+ const token = boundHeldInvite("[email protected]", "req-desktop");+ const view = renderWithI18n(<BillingTab />);+ expect(heldCheckoutPollInterval()).toBe(5_000);+ expect(screen.queryByRole("button", { name: "Send invitation" })).not.toBeInTheDocument();++ act(() => vi.advanceTimersByTime(120_000));+ expect(heldCheckoutPollInterval()).toBe(false);+ expect(readUpgradeInvite("acme", token)).not.toBeNull();++ act(() => window.dispatchEvent(new Event("focus")));+ expect(mocks.refetchSummary).toHaveBeenCalledWith({ cancelRefetch: false });+ upgraded();+ view.rerender(<BillingTab />);+ expect(screen.getByRole("button", { name: "Send invitation" })).toBeInTheDocument();+ expect(navigationState.push).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it("does not restart fast polling when Billing opens with an older held checkout", () => {+ vi.useFakeTimers();+ try {+ const token = boundHeldInvite("[email protected]", "req-old");+ vi.advanceTimersByTime(25 * 60 * 60_000);+ renderWithI18n(<BillingTab />);++ expect(heldCheckoutPollInterval()).toBe(false);+ expect(mocks.refetchSummary).toHaveBeenCalledOnce();+ expect(readUpgradeInvite("acme", token)).not.toBeNull();+ } finally {+ vi.useRealTimers();+ }+ });++ it("shows members and pending invitations against the plan's limit", () => {+ mocks.memberLimit = { action: "observe", limit: 5, members: 4, pendingInvitations: 2 };+ renderWithI18n(<BillingTab />);++ expect(screen.getByText("Members")).toBeInTheDocument();+ expect(screen.getByText("6 / 5")).toBeInTheDocument();+ expect(screen.getByText("Pending invitations: 2")).toBeInTheDocument();+ });+ });+it("reuses the Checkout idempotency key after an ambiguous failure", async () => {const user = userEvent.setup();mocks.checkoutdiff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex db80b67bd4..65823ff595 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useRef, useState } from "react";-import { useQuery } from "@tanstack/react-query";+import { useQuery, useQueryClient } from "@tanstack/react-query";import {AlertCircle,ArrowDown,@@ -25,6 +25,14 @@ import {useReconcileWorkspaceSubscriptionSeats,usePreviewWorkspaceSeatPurchase,usePurchaseWorkspaceSeats,+ bindUpgradeInviteCheckout,+ clearUpgradeInvite,+ heldInvitesToOffer,+ listCheckoutHeldInvites,+ memberLimitKeys,+ memberLimitOptions,+ readUpgradeInvite,+ type HeldInvite,workspaceSubscriptionPricesOptions,workspaceSubscriptionSummaryOptions,} from "@multica/core/billing";@@ -37,6 +45,7 @@ import type {WorkspaceSeatPurchasePreview,WorkspaceSubscriptionInterval,WorkspaceSubscriptionPaidPlan,+ WorkspaceSubscriptionSummary,} from "@multica/core/types";import {Alert,@@ -95,12 +104,22 @@ import {} from "./billing-state";import { formatStripeMinorAmount } from "./billing-format";import { BillingTrialSection } from "./billing-trial-section";+import { settingsHref } from "./settings-navigation";export { formatStripeMinorAmount } from "./billing-format";const CHECKOUT_SYNC_TIMEOUT_MS = 30_000;+const HELD_CHECKOUT_POLL_TIMEOUT_MS = 2 * 60_000;const UPGRADE_SECTION_ANCHOR = "billing-upgrade";+function latestHeldCheckoutAt(invites: HeldInvite[]): number | null {+ return invites.reduce<number | null>(+ (latest, { checkout }) =>+ checkout ? Math.max(latest ?? checkout.boundAt, checkout.boundAt) : latest,+ null,+ );+}+/** Brings the plan cards into view, as a settings deep link would. */function scrollToUpgrade() {const target = document.querySelector<HTMLElement>(@@ -264,6 +283,7 @@ function BillingTabContent() {wsId: string;plan: WorkspaceSubscriptionPaidPlan;interval: WorkspaceSubscriptionInterval;+ heldToken: string | null;key: string;} | null>(null);const planChangeIntentRef = useRef<{@@ -285,6 +305,41 @@ function BillingTabContent() {attempts: number;} | null>(null);const consumedCallbackKeyRef = useRef<string | null>(null);+ const queryClient = useQueryClient();+ // The invitation Members held back for the checkout this page is about to+ // start ("Upgrade and invite"). Only that checkout buys a seat for it.+ const workspaceSlug = workspace?.slug ?? "";+ const [heldInvite, setHeldInvite] = useState<HeldInvite | null>(null);+ const [awaitingHeldCheckoutAt, setAwaitingHeldCheckoutAt] = useState<number | null>(null);+ const [heldCheckoutPollUntil, setHeldCheckoutPollUntil] = useState(0);+ useEffect(() => {+ setHeldInvite(null);+ setAwaitingHeldCheckoutAt(+ workspaceSlug ? latestHeldCheckoutAt(listCheckoutHeldInvites(workspaceSlug)) : null,+ );+ }, [workspaceSlug]);++ // Use the checkout timestamp so reopening Billing does not restart polling.+ // The invitation can still be sent after this window.+ useEffect(() => {+ const deadline =+ awaitingHeldCheckoutAt === null+ ? 0+ : awaitingHeldCheckoutAt + HELD_CHECKOUT_POLL_TIMEOUT_MS;+ const remaining = deadline - Date.now();+ if (remaining <= 0) {+ setHeldCheckoutPollUntil(0);+ return;+ }+ setHeldCheckoutPollUntil(deadline);+ const timeout = window.setTimeout(() => setHeldCheckoutPollUntil(0), remaining);+ return () => window.clearTimeout(timeout);+ }, [awaitingHeldCheckoutAt]);++ // Held invitations the paid plan may have bought a seat for, offered for+ // the person to send or discard.+ const [heldInvitesToConfirm, setHeldInvitesToConfirm] = useState<HeldInvite[]>([]);+ const memberLimitQuery = useQuery(memberLimitOptions(wsId));useEffect(() => {checkoutIntentRef.current = null;@@ -349,16 +404,29 @@ function BillingTabContent() {const summaryQuery = useQuery({...workspaceSubscriptionSummaryOptions(wsId),- // Checkout activation and seat additions both finish asynchronously in a- // Stripe webhook. Seat polling is bounded so a lost webhook cannot keep a- // browser polling forever.+ // Stripe webhooks may update the summary after the customer returns.refetchInterval: (query) =>isSyncingCheckout ||(query.state.data?.seatCapacity?.activePurchase &&!seatPurchasePollingTimedOut)? 2_000- : false,+ : heldCheckoutPollUntil > Date.now()+ ? 5_000+ : false,});+ const refetchSummary = summaryQuery.refetch;+ useEffect(() => {+ if (awaitingHeldCheckoutAt === null) return;+ // Electron can regain focus from the system browser without a visibility change.+ const refresh = () => {+ void refetchSummary({ cancelRefetch: false });+ };+ window.addEventListener("focus", refresh);+ // Reopening Billing after the polling window may still hit a fresh cache.+ if (Date.now() >= awaitingHeldCheckoutAt + HELD_CHECKOUT_POLL_TIMEOUT_MS) refresh();+ return () => window.removeEventListener("focus", refresh);+ }, [awaitingHeldCheckoutAt, refetchSummary]);+const entitlements = summaryQuery.data?.entitlement;// Checkout is done once paid seats are in effect. Neither the plan nor// Checkout going away proves it: a trial already reports Business, and a@@ -401,7 +469,6 @@ function BillingTabContent() {const previewPlanChangeMutation = usePreviewWorkspacePlanChange();const changePlanMutation = useChangeWorkspacePlan(wsId);const checkPlanChangeMutation = useReconcileWorkspaceSubscriptionSeats(wsId);- const refetchSummary = summaryQuery.refetch;const previewSeatPurchase = previewSeatPurchaseMutation.mutateAsync;const previewPlanChange = previewPlanChangeMutation.mutateAsync;@@ -622,6 +689,77 @@ function BillingTabContent() {}}, [isCheckoutConfirmed, isSyncingCheckout]);+ const sendHeldInvite = (held: HeldInvite) => {+ setHeldInvitesToConfirm([]);+ void queryClient.invalidateQueries({ queryKey: memberLimitKeys.all(wsId) });+ // The Stripe callback params are still in this render's URL; leaving+ // them on would replay the checkout banner the next time Billing opens.+ const params = new URLSearchParams(navigation.searchParams);+ params.delete("result");+ params.delete("session_id");+ navigation.push(+ `${settingsHref(navigation.pathname, params, "members")}&invite=resume&held_invite=${encodeURIComponent(held.token)}`,+ );+ };++ // A paid plan in effect: an incomplete first payment still reads as Free,+ // and a no-card trial is not a purchase.+ const subscriptionForHeldInvites = (summary: WorkspaceSubscriptionSummary) => ({+ version: summary.entitlement.version,+ paid:+ (summary.entitlement.plan === "pro" || summary.entitlement.plan === "business") &&+ summary.trial?.state !== "active",+ });++ // Bumped whenever held invitations change in storage, to re-read them.+ const [heldInvitesRevision, setHeldInvitesRevision] = useState(0);++ // Once the plan is paid, offer every held invitation it may have paid for,+ // for the person to send or discard. None is sent on its own (see+ // heldInvitesToOffer); reading the plan change rather than the Stripe return+ // is what lets Desktop, which pays in the system browser, get here too.+ useEffect(() => {+ const summary = summaryQuery.data;+ if (!summary || !workspaceSlug) return;+ const waiting = listCheckoutHeldInvites(workspaceSlug);+ const offers = heldInvitesToOffer(waiting, subscriptionForHeldInvites(summary));+ setAwaitingHeldCheckoutAt(offers.length === 0 ? latestHeldCheckoutAt(waiting) : null);+ setHeldInvitesToConfirm(offers);+ // eslint-disable-next-line react-hooks/exhaustive-deps -- re-check on each summary read+ }, [summaryQuery.dataUpdatedAt, workspaceSlug, heldInvitesRevision]);++ const discardHeldInvite = (held: HeldInvite) => {+ clearUpgradeInvite(workspaceSlug, held.token);+ setHeldInvitesRevision((revision) => revision + 1);+ };++ // Members links here with `?upgrade=pro` from a full invite dialog: open the+ // Pro checkout confirmation once the summary says checkout is available.+ // `held_invite` names the invitation that checkout is for. The intent waits+ // for a summary that can decide it: a failed read keeps it, and the email+ // and role with it, for the summary retry.+ const upgradeRequest = navigation.searchParams.get("upgrade");+ const heldInviteToken = navigation.searchParams.get("held_invite");+ useEffect(() => {+ const summary = summaryQuery.data;+ if (upgradeRequest === null || !summary) return;+ const params = new URLSearchParams(navigation.searchParams);+ params.delete("upgrade");+ params.delete("held_invite");+ navigation.replace(`${navigation.pathname}?${params.toString()}`);+ const held =+ heldInviteToken && workspaceSlug+ ? readUpgradeInvite(workspaceSlug, heldInviteToken)+ : null;+ if (upgradeRequest === "pro" && summary.availableActions.checkout === true) {+ setHeldInvite(held);+ openCheckoutConfirm("pro");+ } else if (held) {+ clearUpgradeInvite(workspaceSlug, held.token);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps -- consume the intent once the summary is known+ }, [upgradeRequest, summaryQuery.dataUpdatedAt]);+const planLabel = (plan: string) => {switch (plan) {case "free":@@ -683,15 +821,21 @@ function BillingTabContent() {const handleCheckout = async () => {setActionError(null);const existing = checkoutIntentRef.current;+ // A retry reuses the key only for the same checkout: same plan, interval+ // and held invitation (or none), so a plain upgrade never replays one that+ // bought a seat for an invitation.+ const heldToken = heldInvite?.token ?? null;const intent =existing?.wsId === wsId &&existing.plan === checkoutPlan &&- existing.interval === interval+ existing.interval === interval &&+ existing.heldToken === heldToken? existing: {wsId,plan: checkoutPlan,interval,+ heldToken,key: createIdempotencyKey("workspace-checkout", wsId),};checkoutIntentRef.current = intent;@@ -700,6 +844,7 @@ function BillingTabContent() {plan: intent.plan,interval: intent.interval,idempotencyKey: intent.key,+ ...(heldInvite ? { additionalSeats: 1 } : {}),});if (!response?.url) {setCheckoutConfirmOpen(false);@@ -707,9 +852,29 @@ function BillingTabContent() {return;}setCheckoutConfirmOpen(false);+ if (heldInvite && workspaceSlug) {+ bindUpgradeInviteCheckout(workspaceSlug, heldInvite.token, {+ requestId: response.requestId,+ baseVersion: summaryQuery.data?.entitlement.version ?? 0,+ });+ setAwaitingHeldCheckoutAt(Date.now());+ // The invitation now belongs to that checkout. Any later checkout+ // from this page (Desktop returns here after closing the browser) is+ // a plain one and buys no seat for it.+ setHeldInvite(null);+ checkoutIntentRef.current = null;+ }openExternal(response.url, { webTarget: "same-tab" });} catch (error) {setCheckoutConfirmOpen(false);+ // A failed checkout for a held invitation ends it here: the buttons on+ // this page only start plain checkouts, and the invitation is held+ // again from Members if it is still wanted.+ if (heldInvite && workspaceSlug) {+ clearUpgradeInvite(workspaceSlug, heldInvite.token);+ setHeldInvite(null);+ checkoutIntentRef.current = null;+ }if (error instanceof ApiError && error.status === 409) {checkoutIntentRef.current = null;setActionError(t(($) => $.workspace.errors.already_subscribed));@@ -722,7 +887,21 @@ function BillingTabContent() {const handleCheckoutConfirmOpenChange = (open: boolean) => {setCheckoutConfirmOpen(open);- if (!open) checkoutIntentRef.current = null;+ if (open) return;+ checkoutIntentRef.current = null;+ // Cancelled before any checkout: the held invitation goes with it, so a+ // later upgrade from this page does not buy a seat for it.+ if (heldInvite && !checkoutMutation.isPending && workspaceSlug) {+ clearUpgradeInvite(workspaceSlug, heldInvite.token);+ setHeldInvite(null);+ }+ };++ // The plan buttons always start a checkout of their own, never one for a+ // held invitation an earlier checkout from this page was opened for.+ const openPlainCheckoutConfirm = (plan: WorkspaceSubscriptionPaidPlan) => {+ setHeldInvite(null);+ openCheckoutConfirm(plan);};const openCheckoutConfirm = (plan: WorkspaceSubscriptionPaidPlan) => {@@ -1083,6 +1262,18 @@ function BillingTabContent() {? formatDateTime(quotaUsage.resetAt, locale): null;const numberFormatter = new Intl.NumberFormat(locale);+ // Members and pending invitations against the plan's member limit, shown+ // whenever Cloud applies one (observed or enforced).+ const memberLimitData = memberLimitQuery.data;+ const memberLimit =+ (memberLimitData?.action === "observe" || memberLimitData?.action === "enforce") &&+ memberLimitData.limit !== null+ ? {+ used: (memberLimitData.members ?? 0) + (memberLimitData.pendingInvitations ?? 0),+ limit: memberLimitData.limit,+ pending: memberLimitData.pendingInvitations ?? 0,+ }+ : null;const isMutating =checkoutMutation.isPending ||portalMutation.isPending ||@@ -1177,6 +1368,49 @@ function BillingTabContent() {title={t(($) => $.workspace.title)}scope="workspace">+ {heldInvitesToConfirm.length > 0 ? (+ <Alert>+ <Info />+ <AlertTitle>+ {t(($) => $.workspace.held_invite.title, {+ plan: planLabel(entitlements.plan),+ })}+ </AlertTitle>+ <ul className="col-start-2 mt-1 space-y-3">+ {heldInvitesToConfirm.map((held) => (+ <li key={held.token} className="space-y-2">+ <AlertDescription id={`held-invite-${held.token}`}>+ {t(($) => $.workspace.held_invite.description, {+ email: held.email,+ role:+ held.role === "admin"+ ? t(($) => $.workspace.held_invite.role_admin)+ : t(($) => $.workspace.held_invite.role_member),+ })}+ </AlertDescription>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ aria-describedby={`held-invite-${held.token}`}+ onClick={() => sendHeldInvite(held)}+ >+ {t(($) => $.workspace.held_invite.send)}+ </Button>+ <Button+ size="sm"+ variant="outline"+ aria-describedby={`held-invite-${held.token}`}+ onClick={() => discardHeldInvite(held)}+ >+ {t(($) => $.workspace.held_invite.discard)}+ </Button>+ </div>+ </li>+ ))}+ </ul>+ </Alert>+ ) : null}+{returnResult === "cancel" ? (<Alert><AlertCircle />@@ -1553,7 +1787,7 @@ function BillingTabContent() {className="h-11 w-full"variant={recommended ? "default" : "outline"}disabled={isMutating}- onClick={() => openCheckoutConfirm(plan)}+ onClick={() => openPlainCheckoutConfirm(plan)}><CreditCard />{t(($) => $.workspace.actions.upgrade_to, {@@ -1732,6 +1966,25 @@ function BillingTabContent() {</div>)}</SettingsRow>+ {memberLimit ? (+ <SettingsRow label={t(($) => $.workspace.limits.members)}>+ <div className="flex flex-col gap-1 sm:items-end">+ <span className="tabular-nums">+ {t(($) => $.workspace.limits.usage_total, {+ total: numberFormatter.format(memberLimit.used),+ limit: numberFormatter.format(memberLimit.limit),+ })}+ </span>+ {memberLimit.pending > 0 ? (+ <span className="text-caption text-muted-foreground tabular-nums">+ {t(($) => $.workspace.limits.members_pending, {+ pending: numberFormatter.format(memberLimit.pending),+ })}+ </span>+ ) : null}+ </div>+ </SettingsRow>+ ) : null}</SettingsCard></SettingsSection>@@ -2279,6 +2532,13 @@ function BillingTabContent() {: t(($) => $.workspace.upgrade.yearly),count: actualSeats,})}+ {heldInvite ? (+ <span className="mt-2 block">+ {t(($) => $.workspace.confirm.held_invite, {+ email: heldInvite.email,+ })}+ </span>+ ) : null}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>diff --git a/packages/views/settings/components/members-tab.test.tsx b/packages/views/settings/components/members-tab.test.tsxindex 3808375201..b41aedbf20 100644--- a/packages/views/settings/components/members-tab.test.tsx+++ b/packages/views/settings/components/members-tab.test.tsx@@ -7,6 +7,7 @@ import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flagimport { renderWithI18n } from "../../test/i18n";const mockCreateMember = vi.hoisted(() => vi.fn());+const mockRevokeInvitation = vi.hoisted(() => vi.fn());// The URL the settings router holds; `setSearch` stands in for navigation.const url = vi.hoisted(() => {const listeners = new Set<() => void>();@@ -28,23 +29,32 @@ const data = vi.hoisted(() => ({invitations: [] as Array<Record<string, unknown>>,shareLinks: [] as Array<Record<string, unknown>>,summary: null as Record<string, unknown> | null,+ memberLimit: null as Record<string, unknown> | null,+ invitationsLoaded: true,}));+const mockInvalidateQueries = vi.hoisted(() => vi.fn(() => Promise.resolve()));vi.mock("@tanstack/react-query", () => ({queryOptions: <T,>(opts: T) => opts,useQuery: (opts: { queryKey: unknown[] }) => {const key = JSON.stringify(opts.queryKey);- if (key.includes("invitations")) return { data: data.invitations };+ if (key.includes('"limit"')) return { data: data.memberLimit };+ if (key.includes("invitations")) {+ return data.invitationsLoaded+ ? { data: data.invitations, isSuccess: true }+ : { data: undefined, isSuccess: false };+ }if (key.includes("share-links")) return { data: data.shareLinks };- if (key.includes("members")) return { data: data.members };+ if (key.includes("members")) return { data: data.members, isSuccess: true };return { data: data.summary };},useQueryClient: () => ({- invalidateQueries: vi.fn(),+ invalidateQueries: mockInvalidateQueries,fetchQuery: vi.fn(),}),}));-vi.mock("@multica/core/billing", () => ({+vi.mock("@multica/core/billing", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/billing")>()),usePreviewWorkspaceSeatPurchase: () => ({ mutateAsync: vi.fn() }),usePurchaseWorkspaceSeats: () => ({ mutateAsync: vi.fn() }),workspaceSubscriptionSummaryOptions: (wsId: string) => ({@@ -57,7 +67,7 @@ vi.mock("@multica/core/paths", () => ({}));vi.mock("@multica/core/api", async (importOriginal) => ({...(await importOriginal<typeof import("@multica/core/api")>()),- api: { createMember: mockCreateMember },+ api: { createMember: mockCreateMember, revokeInvitation: mockRevokeInvitation },}));vi.mock("@multica/core/auth", () => {const state = { user: { id: "user-1" } };@@ -87,6 +97,9 @@ vi.mock("../../navigation", () => ({}));vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));+import { toast } from "sonner";+import { ApiError } from "@multica/core/api";+import { readUpgradeInvite, saveUpgradeInvite } from "@multica/core/billing";import { MembersTab } from "./members-tab";const member = (id: string, name: string, role: string) => ({@@ -102,6 +115,10 @@ const member = (id: string, name: string, role: string) => ({beforeEach(() => {vi.clearAllMocks();+ // clearAllMocks keeps implementations; a rejection set by one test must not+ // leak into the next.+ mockCreateMember.mockReset();+ mockRevokeInvitation.mockReset();url.set("tab=members");data.members = [member("user-1", "Ada Lovelace", "owner"),@@ -124,6 +141,9 @@ beforeEach(() => {];data.shareLinks = [];data.summary = null;+ data.memberLimit = null;+ data.invitationsLoaded = true;+ localStorage.clear();configStore.getState().setFeatureFlags({});});@@ -243,6 +263,213 @@ describe("MembersTab", () => {);});+ describe("member limit", () => {+ const LIMIT_KEY = ["workspaces", "ws-1", "members", "limit"];+ const enableBilling = () =>+ configStore.getState().setFeatureFlags({ [BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG]: true });+ const openInvite = async (user: ReturnType<typeof userEvent.setup>, email = "[email protected]") => {+ await user.click(screen.getByRole("button", { name: "Invite member" }));+ const dialog = await screen.findByRole("dialog", { name: "Invite member" });+ await user.type(within(dialog).getByRole("textbox", { name: "Email" }), email);+ return dialog;+ };++ it("turns a full enforced limit into upgrade and invite, holding the invitation for that checkout", async () => {+ enableBilling();+ data.memberLimit = { action: "enforce", limit: 5, members: 4, pendingInvitations: 1 };+ const user = userEvent.setup();+ renderWithI18n(<MembersTab />);++ const dialog = await openInvite(user);+ expect(within(dialog).getByRole("alert")).toHaveTextContent(+ "This plan allows up to 5 members. The workspace is full.",+ );+ expect(within(dialog).getByRole("alert")).toHaveTextContent("Pending invitations take a slot too (1 now)");+ expect(within(dialog).getByText("5 / 5 members")).toBeInTheDocument();+ expect(within(dialog).queryByRole("button", { name: "Invite" })).toBeNull();++ await user.click(within(dialog).getByRole("button", { name: "Upgrade and invite" }));++ expect(mockCreateMember).not.toHaveBeenCalled();+ const params = new URLSearchParams(url.get());+ expect(params.get("tab")).toBe("billing");+ expect(params.get("upgrade")).toBe("pro");+ const token = params.get("held_invite");+ expect(token).toBeTruthy();+ expect(readUpgradeInvite("acme", token!)).toMatchObject({ email: "[email protected]", role: "member", checkout: null });+ });++ it.each([+ ["not-an-email", "Enter a valid email address."],+ ["[email protected]", "[email protected] is already a member of this workspace."],+ ["[email protected]", "An invitation to [email protected] is already pending."],+ ])("does not start an upgrade for %s, which could not be invited after paying", async (email, message) => {+ enableBilling();+ data.memberLimit = { action: "enforce", limit: 5, members: 4, pendingInvitations: 1 };+ const user = userEvent.setup();+ renderWithI18n(<MembersTab />);++ const dialog = await openInvite(user, email);+ await user.click(within(dialog).getByRole("button", { name: "Upgrade and invite" }));++ expect(toast.error).toHaveBeenCalledWith(message);+ expect(new URLSearchParams(url.get()).get("tab")).toBe("members");+ expect(localStorage.getItem("multica:upgrade_invite:acme")).toBeNull();+ expect(screen.getByRole("dialog", { name: "Invite member" })).toBeInTheDocument();+ });++ it("waits for the invitation list before an upgrade can buy a seat", async () => {+ enableBilling();+ data.memberLimit = { action: "enforce", limit: 5, members: 4, pendingInvitations: 1 };+ data.invitationsLoaded = false;+ const user = userEvent.setup();+ renderWithI18n(<MembersTab />);++ const dialog = await openInvite(user, "[email protected]");+ const upgrade = within(dialog).getByRole("button", { name: "Upgrade and invite" });+ expect(upgrade).toBeDisabled();+ await user.click(upgrade);+ await user.keyboard("{Enter}");++ expect(new URLSearchParams(url.get()).get("tab")).toBe("members");+ expect(localStorage.getItem("multica:upgrade_invite:acme")).toBeNull();+ });++ it("offers no upgrade when Billing is off, only ways to free a slot", async () => {+ data.memberLimit = { action: "enforce", limit: 5, members: 5, pendingInvitations: 0 };+ const user = userEvent.setup();+ renderWithI18n(<MembersTab />);++ const dialog = await openInvite(user);+ expect(within(dialog).getByRole("alert")).toHaveTextContent(+ "Revoke a pending invitation or remove a member to free a slot.",+ );+ expect(within(dialog).queryByRole("button", { name: "Upgrade and invite" })).toBeNull();+ expect(within(dialog).getByRole("button", { name: "Invite" })).toBeDisabled();+ });++ it("stays out of the way while the limit is only observed", async () => {+ enableBilling();+ data.memberLimit = { action: "observe", limit: 5, members: 6, pendingInvitations: 0 };+ const user = userEvent.setup();+ renderWithI18n(<MembersTab />);++ const dialog = await openInvite(user);+ expect(within(dialog).queryByRole("alert")).toBeNull();+ expect(within(dialog).queryByText(/members$/)).toBeNull();+ await user.click(within(dialog).getByRole("button", { name: "Invite" }));+ await waitFor(() => expect(mockCreateMember).toHaveBeenCalled());+ });++ it("sends the held invitation Billing hands back and consumes only that one", async () => {+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "admin" });+ const other = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" });+ url.set(`tab=members&invite=resume&held_invite=${token}`);+ renderWithI18n(<MembersTab />);++ await waitFor(() =>+ expect(mockCreateMember).toHaveBeenCalledWith("ws-1", {+ email: "[email protected]",+ role: "admin",+ }),+ );+ await waitFor(() => expect(readUpgradeInvite("acme", token)).toBeNull());+ expect(mockCreateMember).toHaveBeenCalledTimes(1);+ // Another tab's held invitation is still waiting on its own checkout.+ expect(readUpgradeInvite("acme", other)).not.toBeNull();+ const params = new URLSearchParams(url.get());+ expect(params.has("invite")).toBe(false);+ expect(params.has("held_invite")).toBe(false);+ });++ // Right after the upgrade the server may still refuse on the Free policy+ // it re-read moments before payment; the send retries past that window.+ it("retries a held invitation the stale Free policy refused, then consumes it", async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ try {+ mockCreateMember+ .mockRejectedValueOnce(new ApiError("full", 403, "Forbidden", { code: "member_limit_reached" }))+ .mockResolvedValueOnce(undefined);+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" });+ url.set(`tab=members&invite=resume&held_invite=${token}`);+ renderWithI18n(<MembersTab />);++ await waitFor(() => expect(mockCreateMember).toHaveBeenCalledTimes(1));+ expect(readUpgradeInvite("acme", token)).not.toBeNull();+ await vi.advanceTimersByTimeAsync(6_000);+ await waitFor(() => expect(mockCreateMember).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(readUpgradeInvite("acme", token)).toBeNull());+ expect(toast.error).not.toHaveBeenCalled();+ } finally {+ vi.useRealTimers();+ }+ });++ it("keeps a held invitation that still cannot be sent, prefilled for another try", async () => {+ mockCreateMember.mockRejectedValue(new Error("nope"));+ const token = saveUpgradeInvite("acme", { email: "[email protected]", role: "member" });+ url.set(`tab=members&invite=resume&held_invite=${token}`);+ renderWithI18n(<MembersTab />);++ await waitFor(() => expect(mockCreateMember).toHaveBeenCalled());+ const dialog = screen.getByRole("dialog", { name: "Invite member" });+ expect(within(dialog).getByRole("textbox", { name: "Email" })).toHaveValue("[email protected]");+ expect(readUpgradeInvite("acme", token)).not.toBeNull();+ });++ it("sends a full workspace with a lapsed subscription to Billing, holding nothing", async () => {+ enableBilling();+ data.summary = { availableActions: { checkout: false } };+ data.memberLimit = { action: "enforce", limit: 5, members: 5, pendingInvitations: 0 };+ const user = userEvent.setup();+ renderWithI18n(<MembersTab />);++ const dialog = await openInvite(user);+ expect(within(dialog).getByRole("alert")).toHaveTextContent(+ "The workspace's subscription needs attention. Restore it in Billing to add members",+ );+ expect(within(dialog).queryByRole("button", { name: "Upgrade and invite" })).toBeNull();+ await user.click(within(dialog).getByRole("button", { name: "Open Billing" }));++ const params = new URLSearchParams(url.get());+ expect(params.get("tab")).toBe("billing");+ expect(params.has("upgrade")).toBe(false);+ expect(localStorage.getItem("multica:upgrade_invite:acme")).toBeNull();+ });++ it("refreshes the limit once a revoked invitation frees its slot", async () => {+ mockRevokeInvitation.mockResolvedValue(undefined);+ url.set("tab=members§ion=invitations");+ const user = userEvent.setup();+ renderWithI18n(<MembersTab />);++ await user.click(screen.getByRole("button", { name: "Revoke invitation for [email protected]" }));+ await user.click(await screen.findByRole("button", { name: "Confirm" }));++ await waitFor(() => expect(mockRevokeInvitation).toHaveBeenCalledWith("ws-1", "inv-1"));+ await waitFor(() => expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: LIMIT_KEY }));+ });++ it("refetches the limit when the server refuses a member past it", async () => {+ mockCreateMember.mockRejectedValue(+ new ApiError("full", 403, "Forbidden", { code: "member_limit_reached" }),+ );+ const user = userEvent.setup();+ renderWithI18n(<MembersTab />);++ const dialog = await openInvite(user);+ await user.click(within(dialog).getByRole("button", { name: "Invite" }));++ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith(+ "The workspace is full. Upgrade to invite more members.",+ ),+ );+ expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: LIMIT_KEY });+ expect(screen.getByRole("dialog", { name: "Invite member" })).toBeInTheDocument();+ });+ });+it("gives members a read-only view without invite or share-link controls", () => {data.members = [member("user-1", "Ada Lovelace", "member"),diff --git a/packages/views/settings/components/members-tab.tsx b/packages/views/settings/components/members-tab.tsxindex 05ddc93c7c..1c0d91c790 100644--- a/packages/views/settings/components/members-tab.tsx+++ b/packages/views/settings/components/members-tab.tsx@@ -41,6 +41,7 @@ import {DialogTitle,} from "@multica/ui/components/ui/dialog";import { Badge } from "@multica/ui/components/ui/badge";+import { Alert, AlertDescription, AlertTitle } from "@multica/ui/components/ui/alert";import {AlertDialog,AlertDialogContent,@@ -73,6 +74,14 @@ import { toast } from "sonner";import { useQuery, useQueryClient } from "@tanstack/react-query";import { useAuthStore } from "@multica/core/auth";import {+ clearUpgradeInvitesFor,+ isMemberLimitFull,+ isMemberLimitReachedError,+ memberLimitKeys,+ memberLimitOptions,+ readUpgradeInvite,+ saveUpgradeInvite,+ type UpgradeInvite,usePreviewWorkspaceSeatPurchase,usePurchaseWorkspaceSeats,workspaceSubscriptionSummaryOptions,@@ -109,6 +118,15 @@ import {const SEAT_PURCHASE_CONFIRM_TIMEOUT_MS = 2 * 60_000;+// Sending a held invitation right after its upgrade retries a member-limit+// refusal this many times, this far apart: past the server's five-second+// bound on re-reading Cloud's policy.+const HELD_INVITE_RETRIES = 2;+const HELD_INVITE_RETRY_MS = 6_000;++// Catches typos before an upgrade buys a seat for the invitation.+const INVITE_EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;+type MembersView = "members" | "invitations" | "links";type InviteSeatPurchase = {@@ -419,8 +437,13 @@ export function MembersTab() {const qc = useQueryClient();const wsId = useWorkspaceId();const navigation = useOptionalNavigation();- const { data: members = [] } = useQuery(memberListOptions(wsId));- const { data: invitations = [] } = useQuery(invitationListOptions(wsId));+ const memberListQuery = useQuery(memberListOptions(wsId));+ const invitationListQuery = useQuery(invitationListOptions(wsId));+ const members = memberListQuery.data ?? [];+ const invitations = invitationListQuery.data ?? [];+ // An upgrade buys a seat for the invitation, so it waits until both lists+ // have loaded and the invitation is known to be sendable.+ const inviteChecksReady = memberListQuery.isSuccess && invitationListQuery.isSuccess;const [inviteOpen, setInviteOpen] = useState(false);const [shareLinkOpen, setShareLinkOpen] = useState(false);@@ -481,26 +504,67 @@ export function MembersTab() {const canManageWorkspace = currentMember?.role === "owner" || currentMember?.role === "admin";// The Team panel's invite button links here with `?invite=1`; it waits for- // the member list so only managers get the dialog.- const inviteRequested = navigation?.searchParams.has("invite") ?? false;+ // the member list so only managers get the dialog. Billing links back with+ // `?invite=resume&held_invite=<token>` once the upgrade started for that+ // held invitation has gone through, and the invitation is sent.+ const inviteRequest = navigation?.searchParams.get("invite") ?? null;+ const heldInviteToken = navigation?.searchParams.get("held_invite") ?? null;useEffect(() => {- if (!inviteRequested || !navigation || !currentMember) return;- if (canManageWorkspace) setInviteOpen(true);+ if (inviteRequest === null || !navigation || !currentMember || !workspace) return;const params = new URLSearchParams(navigation.searchParams);params.delete("invite");+ params.delete("held_invite");navigation.replace(`${navigation.pathname}?${params}`);+ if (!canManageWorkspace) return;+ const held: UpgradeInvite | null =+ inviteRequest === "resume" && heldInviteToken+ ? readUpgradeInvite(workspace.slug, heldInviteToken)+ : null;+ setInviteOpen(true);+ if (!held) return;+ setInviteEmail(held.email);+ setInviteRole(held.role);+ // The held invitation is consumed only once it has been sent; if sending+ // still fails it stays prefilled here and held for another try.+ void qc+ .invalidateQueries({ queryKey: memberLimitKeys.all(wsId) })+ .then(() => inviteMember(held.email, held.role, { retryLimitRefusals: HELD_INVITE_RETRIES }));// eslint-disable-next-line react-hooks/exhaustive-deps -- consume the intent once the role is known- }, [inviteRequested, currentMember?.role]);+ }, [inviteRequest, heldInviteToken, currentMember?.role, workspace?.slug]);const isOwner = currentMember?.role === "owner";const ownerCount = members.filter((m) => m.role === "owner").length;// Only owners/admins may list share links; skip the request for plain// members (the server would 403) once the current member's role is known.const { data: shareLinks = [] } = useQuery(shareLinkListOptions(wsId, canManageWorkspace));const billingEnabled = useFeatureEnabled(BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG, false);- const seats = useQuery({+ const subscriptionSummary = useQuery({...workspaceSubscriptionSummaryOptions(wsId),enabled: billingEnabled && canManageWorkspace,- }).data?.seatCapacity;+ }).data;+ const seats = subscriptionSummary?.seatCapacity;+ const memberLimit = useQuery({+ ...memberLimitOptions(wsId),+ enabled: canManageWorkspace,+ }).data;+ // Only an enforced limit is shown; an observed one admits everyone.+ const enforcedMemberLimit =+ memberLimit?.action === "enforce" && memberLimit.limit !== null+ ? {+ used: (memberLimit.members ?? 0) + (memberLimit.pendingInvitations ?? 0),+ limit: memberLimit.limit,+ pending: memberLimit.pendingInvitations ?? 0,+ }+ : null;+ const inviteBlockedByMemberLimit = isMemberLimitFull(memberLimit);+ // Upgrading needs Billing; without it a full workspace can only free a slot.+ // A lapsed subscription (past due beyond grace) cannot start a new+ // checkout: it is restored in Billing, not upgraded.+ const subscriptionNeedsAttention =+ inviteBlockedByMemberLimit &&+ billingEnabled &&+ subscriptionSummary?.availableActions.checkout === false;+ const canUpgradeForInvite =+ inviteBlockedByMemberLimit && billingEnabled && !subscriptionNeedsAttention;const needle = memberQuery.trim().toLocaleLowerCase();const visibleMembers = needle? members.filter(@@ -514,6 +578,9 @@ export function MembersTab() {async (email: string, role: MemberRole) => {if (!workspace) return;await api.createMember(workspace.id, { email, role });+ // The invitation is out, however it was sent (directly, after an+ // upgrade, or after buying a seat): nothing held for it still waits.+ clearUpgradeInvitesFor(workspace.slug, email);setInviteEmail("");setInviteRole("member");await qc.invalidateQueries({@@ -524,15 +591,37 @@ export function MembersTab() {[qc, t, workspace, wsId],);- const handleInviteMember = async () => {- if (!workspace) return;- const email = inviteEmail.trim();- const role = inviteRole;+ // Resolves true once the invitation is sent. retryLimitRefusals retries a+ // member-limit refusal after HELD_INVITE_RETRY_MS: right after an upgrade+ // the server may still hold the Free policy it re-read moments before.+ const inviteMember = async (+ email: string,+ role: MemberRole,+ { retryLimitRefusals = 0 }: { retryLimitRefusals?: number } = {},+ ): Promise<boolean> => {+ if (!workspace) return false;setInviteLoading(true);try {- await sendInvitation(email, role);+ for (let attempt = 0; ; attempt++) {+ try {+ await sendInvitation(email, role);+ break;+ } catch (retryable) {+ if (!isMemberLimitReachedError(retryable) || attempt >= retryLimitRefusals) throw retryable;+ await new Promise((resolve) => setTimeout(resolve, HELD_INVITE_RETRY_MS));+ }+ }setInviteOpen(false);+ void qc.invalidateQueries({ queryKey: memberLimitKeys.all(wsId) });+ return true;} catch (e) {+ if (isMemberLimitReachedError(e)) {+ // The limit filled up after this dialog last read it. Refetch so the+ // dialog switches to its full state and offers the upgrade.+ await qc.invalidateQueries({ queryKey: memberLimitKeys.all(wsId) });+ toast.error(t(($) => $.members.toast_member_limit_reached));+ return false;+ }const code = errorCode(e);const capacityFailure = seatInvitationCapacityFailure(code);if (code === "seat_capacity_overcommitted") {@@ -567,7 +656,7 @@ export function MembersTab() {billingT(($) => $.workspace.seats.members_over_capacity_title),);}- return;+ return false;}if (capacityFailure === "full") {try {@@ -578,7 +667,7 @@ export function MembersTab() {toast.error(billingT(($) => $.workspace.seat_purchase.preview_unreadable),);- return;+ return false;}// Hand over to the purchase confirmation rather than stacking a// second modal on the invite dialog.@@ -599,22 +688,60 @@ export function MembersTab() {: billingT(($) => $.workspace.seat_purchase.preview_failed),);}- return;+ return false;}if (capacityFailure === "unavailable") {toast.error(t(($) => $.members.toast_seat_capacity_unavailable));- return;+ return false;}if (capacityFailure === "rate_limited") {toast.error(t(($) => $.members.toast_seat_capacity_rate_limited));- return;+ return false;}toast.error(e instanceof Error ? e.message : t(($) => $.members.toast_invitation_failed));+ return false;} finally {setInviteLoading(false);}};+ const handleInviteMember = () => inviteMember(inviteEmail.trim(), inviteRole);++ // Why an invitation could not be sent even after paying, checked before+ // the upgrade buys a seat for it. The server re-checks on send.+ const upgradeInviteProblem = (email: string): string | null => {+ if (!inviteChecksReady) {+ return t(($) => $.members.toast_invite_check_unavailable);+ }+ const normalized = email.toLowerCase();+ if (!INVITE_EMAIL_PATTERN.test(normalized)) {+ return t(($) => $.members.toast_invalid_email);+ }+ if (members.some((m) => m.email.toLowerCase() === normalized)) {+ return t(($) => $.members.toast_already_member, { email });+ }+ if (invitations.some((inv) => inv.invitee_email.toLowerCase() === normalized)) {+ return t(($) => $.members.toast_invitation_pending, { email });+ }+ return null;+ };++ // The workspace is full: hold the invitation while Billing runs checkout+ // for Pro, which sends it once the new plan is confirmed.+ const handleUpgradeAndInvite = () => {+ if (!workspace || !navigation) return;+ const email = inviteEmail.trim();+ const problem = upgradeInviteProblem(email);+ if (problem) {+ toast.error(problem);+ return;+ }+ const token = saveUpgradeInvite(workspace.slug, { email, role: inviteRole });+ setInviteOpen(false);+ const href = settingsHref(navigation.pathname, navigation.searchParams, "billing");+ navigation.push(`${href}&upgrade=pro&held_invite=${encodeURIComponent(token)}`);+ };+const handlePurchaseSeatAndInvite = async () => {if (!inviteSeatPurchase ||@@ -786,6 +913,8 @@ export function MembersTab() {try {await api.revokeInvitation(workspace.id, invitation.id);qc.invalidateQueries({ queryKey: workspaceKeys.invitations(wsId) });+ // A revoked invitation frees its member slot.+ qc.invalidateQueries({ queryKey: memberLimitKeys.all(wsId) });toast.success(t(($) => $.members.toast_invitation_revoked));} catch (e) {toast.error(e instanceof Error ? e.message : t(($) => $.members.toast_invitation_revoke_failed));@@ -930,6 +1059,14 @@ export function MembersTab() {onChange={setView}/><div className="flex min-w-0 items-center gap-3">+ {enforcedMemberLimit && !seats ? (+ <span className="shrink-0 text-caption text-muted-foreground tabular-nums">+ {t(($) => $.members.member_limit_usage, {+ used: enforcedMemberLimit.used,+ limit: enforcedMemberLimit.limit,+ })}+ </span>+ ) : null}{seats && billingEnabled ? (<span className="shrink-0 text-caption text-muted-foreground">{t(($) => $.members.seats_used, {@@ -1046,7 +1183,9 @@ export function MembersTab() {className="space-y-4"onSubmit={(event) => {event.preventDefault();- if (inviteEmail.trim()) void handleInviteMember();+ if (!inviteEmail.trim()) return;+ if (canUpgradeForInvite) handleUpgradeAndInvite();+ else if (!inviteBlockedByMemberLimit) void handleInviteMember();}}><div className="space-y-1.5">@@ -1087,22 +1226,73 @@ export function MembersTab() {</SelectContent></Select></div>- <DialogFooter>- <Button- type="button"- variant="outline"- onClick={() => setInviteOpen(false)}- disabled={inviteLoading}- >- {t(($) => $.members.confirm_cancel)}- </Button>- <Button- type="submit"- disabled={inviteLoading || !inviteEmail.trim()}- aria-busy={inviteLoading || undefined}- >- {inviteLoading ? t(($) => $.members.inviting) : t(($) => $.members.invite_button)}- </Button>+ {inviteBlockedByMemberLimit && enforcedMemberLimit ? (+ <Alert>+ <Users aria-hidden="true" />+ <AlertTitle>+ {t(($) => $.members.member_limit_full_title, { limit: enforcedMemberLimit.limit })}+ </AlertTitle>+ <AlertDescription>+ {!billingEnabled+ ? t(($) => $.members.member_limit_full_description_no_upgrade)+ : subscriptionNeedsAttention+ ? t(($) => $.members.member_limit_full_description_billing)+ : enforcedMemberLimit.pending > 0+ ? t(($) => $.members.member_limit_full_description_pending, {+ pending: enforcedMemberLimit.pending,+ })+ : t(($) => $.members.member_limit_full_description)}+ </AlertDescription>+ </Alert>+ ) : null}+ <DialogFooter className={enforcedMemberLimit ? "sm:items-center sm:justify-between" : undefined}>+ {enforcedMemberLimit ? (+ <span className="text-caption text-muted-foreground tabular-nums">+ {t(($) => $.members.member_limit_usage, {+ used: enforcedMemberLimit.used,+ limit: enforcedMemberLimit.limit,+ })}+ </span>+ ) : null}+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">+ <Button+ type="button"+ variant="outline"+ onClick={() => setInviteOpen(false)}+ disabled={inviteLoading}+ >+ {t(($) => $.members.confirm_cancel)}+ </Button>+ {subscriptionNeedsAttention ? (+ <Button+ type="button"+ disabled={!navigation}+ onClick={() => {+ if (!navigation) return;+ setInviteOpen(false);+ navigation.push(settingsHref(navigation.pathname, navigation.searchParams, "billing"));+ }}+ >+ {t(($) => $.members.open_billing)}+ </Button>+ ) : canUpgradeForInvite ? (+ <Button+ type="button"+ disabled={inviteLoading || !inviteEmail.trim() || !navigation || !inviteChecksReady}+ onClick={handleUpgradeAndInvite}+ >+ {t(($) => $.members.upgrade_and_invite)}+ </Button>+ ) : (+ <Button+ type="submit"+ disabled={inviteLoading || !inviteEmail.trim() || inviteBlockedByMemberLimit}+ aria-busy={inviteLoading || undefined}+ >+ {inviteLoading ? t(($) => $.members.inviting) : t(($) => $.members.invite_button)}+ </Button>+ )}+ </div></DialogFooter></form></DialogContent>diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 706d168afd..654b51429e 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1842,6 +1842,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Paid-feature states for read-only and upgrade UI; the// server enforces on every write regardless.r.Get("/features", h.GetWorkspaceFeatures)+ // The plan's member limit for upgrade UI; every admission+ // is checked on the server regardless.+ r.Get("/member-limit", h.GetMemberLimit)r.Post("/leave", h.LeaveWorkspace)r.Get("/invitations", h.ListWorkspaceInvitations)// Listing GitHub installations is member-visible so thediff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.mdindex dcb14878b4..289aeca5e4 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -58,6 +58,12 @@ Revision 4 (`features`) is safe in either order: an older consumer ignores`features`, and this consumer treats a policy without it as every feature`off`.+`gates.members` (revision 5) is optional and safe in either order too: an+older consumer ignores the unknown gate, and this consumer reads a policy+without it, or with a malformed one, as `members` `off` with reason+`gate_missing` or `gate_invalid`. Only that gate falls back; `autopilot_runs`+and the features keep their instructions. See [Member limit](#member-limit).+Responses tolerate unknown JSON fields and gates for additive compatibility.Unknown schema/action, malformed fields, a missing `autopilot_runs` gate, HTTPfailures, and timeouts fail open.@@ -121,6 +127,46 @@ structured localization; in-app quota views localize from `details`.Future consumers should depend on the small `Provider` interface. Tests can use`server/internal/entitlement/entitlementtest.Stub` without Cloud.+## Refreshing before a refusal++A consumer about to refuse an operation can call `Refresher.RefreshGate`+instead of trusting the cache. It fetches the policy again unless the cached+one arrived within the last five seconds, so a workspace that has just+upgraded is not refused on a policy cached before the upgrade, and repeated+refusals cost at most one Cloud request per workspace per five seconds. A+failed fetch answers exactly like `Gate`. The Cloud client implements it;+`entitlementtest.Stub` does too (`SetRefreshed`).++## Member limit++`members` caps the members of a workspace on a plan with a member limit+(Free). It carries a `limit` and no period: it is a ceiling on headcount, not+a budget that resets. Cloud sends it `off` for paid plans and trials, whose+seats are governed by purchased seat capacity (`server/internal/seatcapacity`).++The handler checks it wherever a member is added+(`server/internal/handler/member_limit.go`):++| Operation | Counted against the limit |+| --- | --- |+| Create an invitation (`POST /api/workspaces/{id}/members`) | members + live pending invitations + 1 |+| Join by share link | the same, or members + 1 when the joiner holds a pending invitation |+| Accept an invitation | members + 1: the invitation already holds its slot |++Guests take no slot and are never checked. A refused invitation acceptance+leaves the invitation pending. Each path counts once before its side effects+(Cloud seat calls, rate-limit budgets), re-reading the policy with+`RefreshGate` before refusing, and again inside the transaction that writes+the member or invitation, under a per-workspace advisory lock taken before any+row lock; the second count decides races for the last slot. `enforce` refuses+with `403 member_limit_reached`. Attempts are recorded in+`entitlement_limit_overage` under gate `members`, grouped by UTC calendar month+since the gate has no period of its own.++Clients read `GET /api/workspaces/{id}/member-limit` (member-readable), which+returns `action` and, while a limit applies, `limit`, `members` and+`pending_invitations`.+## Paid featuresA paid feature is restricted for a workspace whose plan does not include it.diff --git a/server/internal/entitlement/cache.go b/server/internal/entitlement/cache.goindex 027b45c574..2b6d417322 100644--- a/server/internal/entitlement/cache.go+++ b/server/internal/entitlement/cache.go@@ -16,7 +16,10 @@ type policySnapshot struct {subscriptionVersion int64cloudValidUntil time.Timegates map[GateName]Gate- features map[FeatureName]featureEntry+ // gateReasons holds why an optional gate fell back to off (missing or+ // malformed); a gate Cloud sent correctly has no entry.+ gateReasons map[GateName]Reason+ features map[FeatureName]featureEntry}// featureEntry is one normalized paid feature. A feature Cloud did not send,@@ -27,8 +30,11 @@ type featureEntry struct {}type cacheEntry struct {- hasPolicy bool- policy policySnapshot+ hasPolicy bool+ policy policySnapshot+ // receivedAt is when the policy arrived; a forced refresh reuses a policy+ // younger than minForcedRefreshAge instead of fetching again.+ receivedAt time.TimefreshUntil time.TimestaleUntil time.TimeretryAfter time.Timediff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.goindex 94ad2e12e9..7bdc7f0d30 100644--- a/server/internal/entitlement/client.go+++ b/server/internal/entitlement/client.go@@ -23,6 +23,10 @@ const (defaultFailureRetry = 5 * time.SecondmaxPolicyTTL = 5 * time.MinutemaxResponseBodySize = 64 << 10+ // minForcedRefreshAge bounds RefreshGate: a policy received this recently+ // is already current, so repeated rejections cost no more Cloud requests+ // than one per workspace in this window.+ minForcedRefreshAge = 5 * time.Second)var (@@ -56,6 +60,7 @@ type Client struct {var (_ Provider = (*Client)(nil)+ _ Refresher = (*Client)(nil)_ FeatureProvider = (*Client)(nil))@@ -114,6 +119,27 @@ func (c *Client) Gate(ctx context.Context, workspaceID uuid.UUID, name GateName)return c.recordDecision(name, decisionFromEntry(entry, name, reason, stale))}+// RefreshGate fetches the workspace's policy again unless the cached one+// arrived within minForcedRefreshAge, then resolves the gate from it. When+// that fetch fails it answers exactly like Gate, from the cache or fail-open.+func (c *Client) RefreshGate(ctx context.Context, workspaceID uuid.UUID, name GateName) Decision {+ if !c.Enabled() || workspaceID == uuid.Nil || !name.valid() {+ return c.Gate(ctx, workspaceID, name)+ }+ entry, refreshed, err := c.refreshShared(ctx, workspaceID, "force:"+workspaceID.String(),+ func(cached cacheEntry, now time.Time) bool {+ return cached.hasPolicy && now.Before(cached.freshUntil) && now.Sub(cached.receivedAt) < minForcedRefreshAge+ })+ if err != nil {+ return c.Gate(ctx, workspaceID, name)+ }+ reason := ReasonCacheFresh+ if refreshed {+ reason = ReasonRefreshed+ }+ return c.recordDecision(name, decisionFromEntry(entry, name, reason, false))+}+// Feature resolves one paid feature from the same cached policy as Gate, so// reading both costs at most one Cloud request per workspace.func (c *Client) Feature(ctx context.Context, workspaceID uuid.UUID, name FeatureName) FeatureDecision {@@ -187,14 +213,29 @@ type refreshResult struct {}func (c *Client) refresh(ctx context.Context, workspaceID uuid.UUID) (cacheEntry, bool, error) {+ return c.refreshShared(ctx, workspaceID, workspaceID.String(), func(cached cacheEntry, now time.Time) bool {+ return cached.hasPolicy && now.Before(cached.freshUntil)+ })+}++// refreshShared fetches the policy once per key for all concurrent callers.+// reuse decides whether the cached entry is current enough to skip the fetch.+// Forced refreshes use their own key so a normal caller already inside the+// shared call cannot hand them back the entry they meant to replace.+func (c *Client) refreshShared(+ ctx context.Context,+ workspaceID uuid.UUID,+ key string,+ reuse func(cached cacheEntry, now time.Time) bool,+) (cacheEntry, bool, error) {// A refresh is shared by all callers for this workspace, so its lifetime// cannot belong to whichever request happens to enter singleflight first.// Keep request-scoped values, but let the independent fetch timeout bound it.refreshCtx := context.WithoutCancel(ctx)- value, err, _ := c.refreshes.Do(workspaceID.String(), func() (any, error) {+ value, err, _ := c.refreshes.Do(key, func() (any, error) {now := c.now()if cached, ok := c.cache.get(workspaceID); ok {- if cached.hasPolicy && now.Before(cached.freshUntil) {+ if reuse(cached, now) {return refreshResult{entry: cached}, nil}if now.Before(cached.retryAfter) {@@ -216,6 +257,7 @@ func (c *Client) refresh(ctx context.Context, workspaceID uuid.UUID) (cacheEntryentry := cacheEntry{hasPolicy: true,policy: policy.snapshot,+ receivedAt: receivedAt,freshUntil: receivedAt.Add(ttl),staleUntil: receivedAt.Add(ttl).Add(c.staleGrace),}@@ -251,6 +293,37 @@ type wirePolicy struct {// wrong JSON type, cannot fail the decode of the whole policy and with it// the metered gates. normalizeFeatures parses it entry by entry.Features json.RawMessage `json:"features"`+ // undecodableGates names gates whose value had the wrong JSON shape.+ undecodableGates map[string]bool+}++// UnmarshalJSON decodes each gate on its own. A gate of the wrong JSON shape+// is marked undecodable instead of failing the whole response, so an optional+// gate falls back alone and cannot take autopilot_runs down with it.+func (p *wirePolicy) UnmarshalJSON(data []byte) error {+ type plain wirePolicy+ var envelope struct {+ plain+ // Shallower than plain.Gates, so it receives the "gates" key.+ Gates map[string]json.RawMessage `json:"gates"`+ }+ if err := json.Unmarshal(data, &envelope); err != nil {+ return err+ }+ *p = wirePolicy(envelope.plain)+ p.Gates = make(map[string]wireGate, len(envelope.Gates))+ for name, raw := range envelope.Gates {+ var gate wireGate+ if err := json.Unmarshal(raw, &gate); err != nil {+ if p.undecodableGates == nil {+ p.undecodableGates = make(map[string]bool)+ }+ p.undecodableGates[name] = true+ continue+ }+ p.Gates[name] = gate+ }+ return nil}type wireGate struct {@@ -316,15 +389,38 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {return fetchedPolicy{}, ErrInvalidPolicy}// Unknown gates are ignored for additive compatibility.- gates := make(map[GateName]Gate, 1)- for _, name := range []GateName{GateAutopilotRuns} {+ gates := make(map[GateName]Gate, 2)+ wireAutopilot, ok := wire.Gates[string(GateAutopilotRuns)]+ if !ok {+ return fetchedPolicy{}, ErrInvalidPolicy+ }+ autopilot, err := normalizeGate(GateAutopilotRuns, wireAutopilot)+ if err != nil {+ return fetchedPolicy{}, err+ }+ gates[GateAutopilotRuns] = autopilot+ // Gates added after autopilot_runs are optional and read on their own,+ // like features: a missing or malformed one is off for that gate alone, so+ // Cloud and Multica can deploy in either order and a bad value cannot turn+ // the autopilot quota off.+ gateReasons := make(map[GateName]Reason)+ for _, name := range []GateName{GateMembers} {+ if wire.undecodableGates[string(name)] {+ gates[name] = Gate{Action: ActionOff}+ gateReasons[name] = ReasonGateInvalid+ continue+ }wireGate, ok := wire.Gates[string(name)]if !ok {- return fetchedPolicy{}, ErrInvalidPolicy+ gates[name] = Gate{Action: ActionOff}+ gateReasons[name] = ReasonGateMissing+ continue}gate, err := normalizeGate(name, wireGate)if err != nil {- return fetchedPolicy{}, err+ gates[name] = Gate{Action: ActionOff}+ gateReasons[name] = ReasonGateInvalid+ continue}gates[name] = gate}@@ -334,6 +430,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {subscriptionVersion: wire.SubscriptionVersion,cloudValidUntil: wire.ValidUntil,gates: gates,+ gateReasons: gateReasons,features: normalizeFeatures(wire.Features),},validForSeconds: wire.ValidForSeconds,@@ -436,6 +533,9 @@ func normalizeNotificationPolicy(wire *wireNotificationPolicy) *NotificationPolifunc decisionFromEntry(entry cacheEntry, name GateName, reason Reason, stale bool) Decision {gate := cloneGate(entry.policy.gates[name])+ if fallback, ok := entry.policy.gateReasons[name]; ok {+ reason = fallback+ }if stale && gate.Action == ActionEnforce {gate.Action = ActionObserve}diff --git a/server/internal/entitlement/entitlementtest/stub.go b/server/internal/entitlement/entitlementtest/stub.goindex eb102e7b46..d5dc82e0a3 100644--- a/server/internal/entitlement/entitlementtest/stub.go+++ b/server/internal/entitlement/entitlementtest/stub.go@@ -18,22 +18,64 @@ type Call struct {type Stub struct {mu sync.RWMutexdecisions map[uuid.UUID]map[entitlement.GateName]entitlement.Decision+ refreshed map[uuid.UUID]map[entitlement.GateName]entitlement.Decisionfeatures map[uuid.UUID]map[entitlement.FeatureName]entitlement.FeatureDecisioncalls []Call+ refreshes []Call}var (_ entitlement.Provider = (*Stub)(nil)+ _ entitlement.Refresher = (*Stub)(nil)_ entitlement.FeatureProvider = (*Stub)(nil))func New() *Stub {return &Stub{decisions: make(map[uuid.UUID]map[entitlement.GateName]entitlement.Decision),+ refreshed: make(map[uuid.UUID]map[entitlement.GateName]entitlement.Decision),features: make(map[uuid.UUID]map[entitlement.FeatureName]entitlement.FeatureDecision),}}+// SetRefreshed fixes what RefreshGate returns, standing in for a policy Cloud+// changed after the cached one was read. Once RefreshGate has returned it,+// Gate returns it too, as the refreshed cache would.+func (s *Stub) SetRefreshed(workspaceID uuid.UUID, name entitlement.GateName, decision entitlement.Decision) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.refreshed[workspaceID] == nil {+ s.refreshed[workspaceID] = make(map[entitlement.GateName]entitlement.Decision)+ }+ decision.Reason = entitlement.ReasonStub+ s.refreshed[workspaceID][name] = cloneDecision(decision)+}++// RefreshGate returns the decision set with SetRefreshed, or the same+// decision as Gate when none was set.+func (s *Stub) RefreshGate(ctx context.Context, workspaceID uuid.UUID, name entitlement.GateName) entitlement.Decision {+ s.mu.Lock()+ s.refreshes = append(s.refreshes, Call{WorkspaceID: workspaceID, Gate: name})+ if decision, ok := s.refreshed[workspaceID][name]; ok {+ if s.decisions[workspaceID] == nil {+ s.decisions[workspaceID] = make(map[entitlement.GateName]entitlement.Decision)+ }+ s.decisions[workspaceID][name] = decision+ delete(s.refreshed[workspaceID], name)+ s.mu.Unlock()+ return cloneDecision(decision)+ }+ s.mu.Unlock()+ return s.Gate(ctx, workspaceID, name)+}++// Refreshes lists every RefreshGate call.+func (s *Stub) Refreshes() []Call {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return append([]Call(nil), s.refreshes...)+}+// SetFeature fixes one workspace's paid-feature decision. The Reason given is// kept, so tests can tell a configured observe from a stale downgrade.func (s *Stub) SetFeature(workspaceID uuid.UUID, name entitlement.FeatureName, decision entitlement.FeatureDecision) {diff --git a/server/internal/entitlement/members_gate_test.go b/server/internal/entitlement/members_gate_test.gonew file mode 100644index 0000000000..2c02029916--- /dev/null+++ b/server/internal/entitlement/members_gate_test.go@@ -0,0 +1,199 @@+package entitlement++import (+ "context"+ "net/http"+ "net/http/httptest"+ "sync/atomic"+ "testing"+ "time"++ "github.com/google/uuid"+)++func membersGate(action Action, limit int) wireGate {+ gate := wireGate{Action: string(action)}+ if action != ActionOff {+ gate.Limit = &limit+ }+ return gate+}++func TestMembersGateIsAPeriodlessCeiling(t *testing.T) {+ for _, action := range []Action{ActionOff, ActionObserve, ActionEnforce} {+ t.Run(string(action), func(t *testing.T) {+ server := httptest.NewServer(policyHandler(func(p *wirePolicy) {+ p.Gates[string(GateMembers)] = membersGate(action, 5)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)++ decision := client.Gate(context.Background(), uuid.New(), GateMembers)+ if decision.Gate.Action != action || decision.Reason != ReasonRefreshed {+ t.Fatalf("decision = %+v", decision)+ }+ if action == ActionOff {+ return+ }+ if decision.Gate.Limit == nil || *decision.Gate.Limit != 5 || decision.Gate.PeriodStart != nil {+ t.Fatalf("gate = %+v, want limit 5 without a period", decision.Gate)+ }+ })+ }+}++// Cloud and Multica deploy independently. A policy from a Cloud that does not+// send members yet, or sends it malformed, must leave members off without+// failing the autopilot quota open with it.+func TestMembersGateFailsOpenAlone(t *testing.T) {+ negative := -1+ tests := []struct {+ name string+ mutate func(*wirePolicy)+ reason Reason+ }{+ {"missing", func(*wirePolicy) {}, ReasonGateMissing},+ {"unknown action", func(p *wirePolicy) {+ p.Gates[string(GateMembers)] = wireGate{Action: "block"}+ }, ReasonGateInvalid},+ {"enforce without limit", func(p *wirePolicy) {+ p.Gates[string(GateMembers)] = wireGate{Action: string(ActionEnforce)}+ }, ReasonGateInvalid},+ {"negative limit", func(p *wirePolicy) {+ p.Gates[string(GateMembers)] = wireGate{Action: string(ActionEnforce), Limit: &negative}+ }, ReasonGateInvalid},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ server := httptest.NewServer(policyHandler(tt.mutate))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()++ members := client.Gate(context.Background(), workspaceID, GateMembers)+ if members.Gate.Action != ActionOff || members.Reason != tt.reason {+ t.Fatalf("members = %+v, want off/%s", members, tt.reason)+ }+ autopilot := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)+ if autopilot.Gate.Action != ActionEnforce || autopilot.Reason != ReasonCacheFresh {+ t.Fatalf("autopilot = %+v, want the enforced quota from the same policy", autopilot)+ }+ })+ }+}++// A members gate of the wrong JSON shape must not fail the decode of the+// whole policy: on a cold cache that would turn an enforced autopilot quota+// off. A malformed autopilot_runs gate still fails the policy open.+func TestMembersGateOfTheWrongShapeFailsOpenAlone(t *testing.T) {+ const autopilot = `"autopilot_runs": {"action": "enforce", "limit": 23,+ "period_start": "2026-08-01T00:00:00Z", "period_end": "2026-09-01T00:00:00Z",+ "reset_at": "2026-09-01T00:00:00Z"}`+ policy := func(gates string) string {+ return `{"schema_version": 1, "policy_revision": 5, "subscription_version": 0,+ "valid_until": "2030-01-01T00:00:00Z", "valid_for_seconds": 60,+ "gates": {` + gates + `}}`+ }+ for _, members := range []string{+ `"members": {"action": "enforce", "limit": "five"}`,+ `"members": ["enforce"]`,+ `"members": "enforce"`,+ } {+ t.Run(members, func(t *testing.T) {+ server := httptest.NewServer(bodyHandler(http.StatusOK, policy(autopilot+", "+members)))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()++ if got := client.Gate(context.Background(), workspaceID, GateMembers); got.Gate.Action != ActionOff || got.Reason != ReasonGateInvalid {+ t.Fatalf("members = %+v, want off/gate_invalid", got)+ }+ if got := client.Gate(context.Background(), workspaceID, GateAutopilotRuns); got.Gate.Action != ActionEnforce {+ t.Fatalf("autopilot = %+v, want the enforced quota", got)+ }+ })+ }++ server := httptest.NewServer(bodyHandler(http.StatusOK,+ policy(`"autopilot_runs": {"action": "enforce", "limit": "23"}, "members": {"action": "enforce", "limit": 5}`)))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ if got := client.Gate(context.Background(), uuid.New(), GateAutopilotRuns); got.Gate.Action != ActionOff || got.Reason != ReasonInvalidPolicy {+ t.Fatalf("malformed autopilot = %+v, want the whole policy failed open", got)+ }+}++func TestRefreshGateFetchesPastACurrentCache(t *testing.T) {+ clock := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)+ var calls atomic.Int64+ var action atomic.Value+ action.Store(ActionEnforce)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ calls.Add(1)+ policy := samplePolicy(5, calls.Load(), 60, ActionEnforce)+ policy.Gates[string(GateMembers)] = membersGate(action.Load().(Action), 5)+ writePolicy(t, w, policy)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ client.now = func() time.Time { return clock }+ workspaceID := uuid.New()++ if first := client.Gate(context.Background(), workspaceID, GateMembers); first.Gate.Action != ActionEnforce {+ t.Fatalf("first = %+v", first)+ }++ // The workspace upgrades; Cloud now turns the gate off.+ action.Store(ActionOff)+ clock = clock.Add(time.Second)+ recent := client.RefreshGate(context.Background(), workspaceID, GateMembers)+ if recent.Gate.Action != ActionEnforce || recent.Reason != ReasonCacheFresh || calls.Load() != 1 {+ t.Fatalf("recent = %+v, calls = %d; a policy younger than the refresh bound is reused", recent, calls.Load())+ }++ clock = clock.Add(minForcedRefreshAge)+ refreshed := client.RefreshGate(context.Background(), workspaceID, GateMembers)+ if refreshed.Gate.Action != ActionOff || refreshed.Reason != ReasonRefreshed || calls.Load() != 2 {+ t.Fatalf("refreshed = %+v, calls = %d", refreshed, calls.Load())+ }+ if cached := client.Gate(context.Background(), workspaceID, GateMembers); cached.Gate.Action != ActionOff || calls.Load() != 2 {+ t.Fatalf("cached = %+v, calls = %d; the refresh must replace the cache", cached, calls.Load())+ }+}++func TestRefreshGateFailureAnswersLikeGate(t *testing.T) {+ clock := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)+ var fail atomic.Bool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ if fail.Load() {+ w.WriteHeader(http.StatusServiceUnavailable)+ return+ }+ policy := samplePolicy(5, 1, 60, ActionEnforce)+ policy.Gates[string(GateMembers)] = membersGate(ActionEnforce, 5)+ writePolicy(t, w, policy)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ client.now = func() time.Time { return clock }+ workspaceID := uuid.New()++ client.Gate(context.Background(), workspaceID, GateMembers)+ fail.Store(true)+ clock = clock.Add(minForcedRefreshAge)+ decision := client.RefreshGate(context.Background(), workspaceID, GateMembers)+ if decision.Gate.Action != ActionEnforce || decision.Reason != ReasonCacheFresh {+ t.Fatalf("decision = %+v, want the still-fresh cached enforce", decision)+ }+}++func TestRefreshGateWithoutCloudIsOff(t *testing.T) {+ client, err := New(Config{})+ if err != nil {+ t.Fatalf("New: %v", err)+ }+ decision := client.RefreshGate(context.Background(), uuid.New(), GateMembers)+ if decision.Gate.Action != ActionOff || decision.Reason != ReasonDisabled {+ t.Fatalf("decision = %+v", decision)+ }+}diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.goindex 0b29b1a8a2..ede57b0dfd 100644--- a/server/internal/entitlement/types.go+++ b/server/internal/entitlement/types.go@@ -13,11 +13,14 @@ type GateName stringconst (GateAutopilotRuns GateName = "autopilot_runs"+ // GateMembers caps a workspace's members. Guests take no slot. It has no+ // period: the limit is a ceiling on headcount, not a budget that resets.+ GateMembers GateName = "members")func (n GateName) valid() bool {switch n {- case GateAutopilotRuns:+ case GateAutopilotRuns, GateMembers:return truedefault:return false@@ -53,6 +56,10 @@ const (// without touching the rest of an otherwise valid policy.ReasonFeatureMissing Reason = "feature_missing"ReasonFeatureInvalid Reason = "feature_invalid"+ // ReasonGateMissing and ReasonGateInvalid fail one optional gate open the+ // same way, leaving autopilot_runs and the features untouched.+ ReasonGateMissing Reason = "gate_missing"+ ReasonGateInvalid Reason = "gate_invalid")// Gate is the effective instruction for one generic enforcement point. Limits@@ -92,6 +99,14 @@ type Provider interface {Gate(ctx context.Context, workspaceID uuid.UUID, name GateName) Decision}+// Refresher re-reads one gate ahead of its cached lifetime. A consumer calls+// it only right before rejecting, so a plan change made moments ago (an+// upgrade that was just paid for) is not refused on a policy cached before it.+// A Provider without it rejects on the cached decision.+type Refresher interface {+ RefreshGate(ctx context.Context, workspaceID uuid.UUID, name GateName) Decision+}+// FeatureName is a stable paid-feature key. Unlike a GateName it meters// nothing: it says whether a workspace may add to the feature's configuration.type FeatureName stringdiff --git a/server/internal/handler/cloud_billing.go b/server/internal/handler/cloud_billing.goindex 5b8dde3dba..06bb0515e4 100644--- a/server/internal/handler/cloud_billing.go+++ b/server/internal/handler/cloud_billing.go@@ -3,6 +3,7 @@ package handlerimport ("encoding/json""errors"+ "fmt""io""net/http""strings"@@ -63,16 +64,25 @@ type cloudSubscriptionCheckoutRequest struct {Plan string `json:"plan"`Interval string `json:"interval"`IdempotencyKey string `json:"idempotency_key,omitempty"`+ // AdditionalSeats buys seats beyond the current members and pending+ // invitations, so an invitation the Free member limit held back fits+ // right after checkout (MUL-9488).+ AdditionalSeats int `json:"additional_seats,omitempty"`}+// maxCheckoutAdditionalSeats bounds the extra seats one checkout may add. The+// invite dialog sends one invitation at a time; Cloud enforces its own total.+const maxCheckoutAdditionalSeats = 100+// This is an intentional allowlist: additive cloud fields are not forwarded// until the main repository explicitly reviews and adds them here.type cloudSubscriptionCheckoutUpstreamRequest struct {- WorkspaceID string `json:"workspace_id"`- Plan string `json:"plan"`- Interval string `json:"interval"`- IdempotencyKey string `json:"idempotency_key,omitempty"`- CustomerEmail string `json:"customer_email,omitempty"`+ WorkspaceID string `json:"workspace_id"`+ Plan string `json:"plan"`+ Interval string `json:"interval"`+ IdempotencyKey string `json:"idempotency_key,omitempty"`+ CustomerEmail string `json:"customer_email,omitempty"`+ AdditionalSeats int `json:"additional_seats,omitempty"`}type cloudSubscriptionPlanChangePreviewRequest struct {@@ -240,6 +250,10 @@ func (h *Handler) CreateCloudWorkspaceSubscriptionCheckout(w http.ResponseWriterwriteError(w, http.StatusBadRequest, "interval must be month or year")return}+ if in.AdditionalSeats < 0 || in.AdditionalSeats > maxCheckoutAdditionalSeats {+ writeError(w, http.StatusBadRequest, fmt.Sprintf("additional_seats must be between 0 and %d", maxCheckoutAdditionalSeats))+ return+ }idempotencyKey, ok := requireCloudSubscriptionIdempotencyKey(w, r, in.IdempotencyKey)if !ok {return@@ -259,11 +273,12 @@ func (h *Handler) CreateCloudWorkspaceSubscriptionCheckout(w http.ResponseWriterreturn}upstreamBody, err := json.Marshal(cloudSubscriptionCheckoutUpstreamRequest{- WorkspaceID: workspaceID,- Plan: in.Plan,- Interval: in.Interval,- IdempotencyKey: idempotencyKey,- CustomerEmail: customerEmail,+ WorkspaceID: workspaceID,+ Plan: in.Plan,+ Interval: in.Interval,+ IdempotencyKey: idempotencyKey,+ CustomerEmail: customerEmail,+ AdditionalSeats: in.AdditionalSeats,})if err != nil {writeError(w, http.StatusInternalServerError, "failed to build subscription request")diff --git a/server/internal/handler/cloud_billing_test.go b/server/internal/handler/cloud_billing_test.goindex d2c8f6f365..3ba9af09af 100644--- a/server/internal/handler/cloud_billing_test.go+++ b/server/internal/handler/cloud_billing_test.go@@ -9,6 +9,7 @@ import ("strings""testing"+ "github.com/google/uuid""github.com/multica-ai/multica/server/internal/cloudruntime""github.com/multica-ai/multica/server/internal/featureflags""github.com/multica-ai/multica/server/internal/middleware"@@ -410,6 +411,65 @@ func TestCreateCloudWorkspaceSubscriptionCheckoutInjectsAuthoritativeWorkspaceAn}}+// An upgrade started from a full invite dialog buys a seat for the invitation+// it holds back (MUL-9488). The count is forwarded within bounds; a plain+// checkout sends none.+func TestCreateCloudWorkspaceSubscriptionCheckoutForwardsAdditionalSeats(t *testing.T) {+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)+ checkout := func(body map[string]any) (*httptest.ResponseRecorder, *fakeCloudRuntimeProxy) {+ proxy := &fakeCloudRuntimeProxy{+ enabled: true,+ resp: &cloudruntime.Response{+ StatusCode: http.StatusCreated,+ Body: []byte(`{"url":"https://checkout.stripe.test/session"}`),+ },+ }+ useCloudRuntimeProxy(t, proxy)+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/checkout-sessions", body), "owner")+ w := httptest.NewRecorder()+ testHandler.CreateCloudWorkspaceSubscriptionCheckout(w, req)+ return w, proxy+ }+ base := func(extra map[string]any) map[string]any {+ body := map[string]any{"plan": "pro", "interval": "year", "idempotency_key": "checkout-seats-" + uuid.NewString()}+ for key, value := range extra {+ body[key] = value+ }+ return body+ }++ w, proxy := checkout(base(map[string]any{"additional_seats": 1}))+ if w.Code != http.StatusCreated {+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())+ }+ var upstream map[string]any+ if err := json.Unmarshal(proxy.req.Body, &upstream); err != nil {+ t.Fatalf("decode upstream body: %v", err)+ }+ if upstream["additional_seats"] != float64(1) {+ t.Fatalf("upstream additional_seats = %v, want 1", upstream["additional_seats"])+ }++ w, proxy = checkout(base(nil))+ if w.Code != http.StatusCreated {+ t.Fatalf("plain checkout status = %d", w.Code)+ }+ upstream = nil+ if err := json.Unmarshal(proxy.req.Body, &upstream); err != nil {+ t.Fatalf("decode upstream body: %v", err)+ }+ if _, ok := upstream["additional_seats"]; ok {+ t.Fatalf("plain checkout forwarded additional_seats: %v", upstream)+ }++ for _, seats := range []int{-1, maxCheckoutAdditionalSeats + 1} {+ w, proxy = checkout(base(map[string]any{"additional_seats": seats}))+ if w.Code != http.StatusBadRequest || proxy.called {+ t.Fatalf("additional_seats %d: status = %d, upstream = %q; want 400 without a Cloud call", seats, w.Code, proxy.req.Path)+ }+ }+}+func TestCreateCloudWorkspaceSubscriptionCheckoutFailsWhenPayerCannotBeResolved(t *testing.T) {withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)proxy := &fakeCloudRuntimeProxy{enabled: true}diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.goindex 5738e020a8..308087edeb 100644--- a/server/internal/handler/invitation.go+++ b/server/internal/handler/invitation.go@@ -145,6 +145,21 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {return}+ memberLimit, err := h.memberLimitFor(r.Context(), requester.WorkspaceID, role, false)+ if err != nil {+ if errors.Is(err, errMemberLimitReached) {+ // Like a full seat ledger, a full workspace admits nobody until its+ // members or plan change, so repeated attempts spend the actor+ // budget only.+ h.consumeInvitationActorAdmission(r, admission)+ writeMemberLimitReached(w)+ return+ }+ slog.Warn("member limit check failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)+ writeError(w, http.StatusInternalServerError, "failed to create invitation")+ return+ }+invitationID := uuid.New()expiresAt := time.Now().Add(7 * 24 * time.Hour)if err := h.reserveInvitationCapacity(r.Context(), uuid.UUID(requester.WorkspaceID.Bytes), invitationID, expiresAt); err != nil {@@ -171,7 +186,8 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {ExpiresAt: pgtype.Timestamptz{Time: expiresAt, Valid: true},}var inv db.WorkspaceInvitation- if h.seatCapacityEnabled() {+ var limitAdmission memberLimitAdmission+ if h.seatCapacityEnabled() || memberLimit.active() {tx, txErr := h.TxStarter.Begin(r.Context())if txErr != nil {h.compensateCapacityIntent(r.Context(), invitationID)@@ -180,8 +196,14 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {}defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)- inv, err = qtx.CreateInvitation(r.Context(), createParams)+ err = memberLimit.lock(r.Context(), qtx)+ if err == nil {+ limitAdmission, err = memberLimit.admit(r.Context(), qtx)+ }if err == nil {+ inv, err = qtx.CreateInvitation(r.Context(), createParams)+ }+ if err == nil && h.seatCapacityEnabled() {err = qtx.DeleteSeatCapacityIntentForAction(r.Context(), db.DeleteSeatCapacityIntentForActionParams{OperationToken: uuidToPG(invitationID), Action: seatcapacity.ActionReserveInvitation,})@@ -197,8 +219,15 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {} else {inv, err = h.Queries.CreateInvitation(r.Context(), createParams)}+ if err == nil || errors.Is(err, errMemberLimitReached) {+ limitAdmission.record(r.Context())+ }if err != nil {h.compensateCapacityIntent(r.Context(), invitationID)+ if errors.Is(err, errMemberLimitReached) {+ writeMemberLimitReached(w)+ return+ }if isUniqueViolation(err) {writeError(w, http.StatusConflict, "invitation already pending for this email")return@@ -506,6 +535,17 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusGone, "invitation has expired")return}+ // The invitation already holds its slot. A refusal leaves it pending, so+ // the invitee can still accept once the workspace upgrades.+ memberLimit, err := h.memberLimitFor(r.Context(), inv.WorkspaceID, inv.Role, true)+ if err != nil {+ if errors.Is(err, errMemberLimitReached) {+ writeMemberLimitReached(w)+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to accept invitation")+ return+ }capacityActive, err := h.beginCapacityConsume(r.Context(), uuid.UUID(inv.WorkspaceID.Bytes), uuid.UUID(inv.ID.Bytes), uuid.UUID(inv.ID.Bytes), uuid.UUID(user.ID.Bytes))if err != nil {writeSeatCapacityError(w, err)@@ -521,12 +561,27 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ if err := memberLimit.lock(r.Context(), qtx); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to accept invitation")+ return+ }accepted, err := qtx.AcceptInvitation(r.Context(), inv.ID)if err != nil {writeError(w, http.StatusInternalServerError, "failed to accept invitation")return}+ limitAdmission, err := memberLimit.admit(r.Context(), qtx)+ if err != nil {+ _ = tx.Rollback(r.Context())+ if errors.Is(err, errMemberLimitReached) {+ limitAdmission.record(r.Context())+ writeMemberLimitReached(w)+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to accept invitation")+ return+ }member, err := qtx.CreateMember(r.Context(), db.CreateMemberParams{WorkspaceID: accepted.WorkspaceID,@@ -568,6 +623,7 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to accept invitation")return}+ limitAdmission.record(r.Context())if capacityActive {h.confirmCapacityIntent(r.Context(), uuid.UUID(accepted.WorkspaceID.Bytes), uuid.UUID(accepted.ID.Bytes), uuid.UUID(member.ID.Bytes))}diff --git a/server/internal/handler/member_limit.go b/server/internal/handler/member_limit.gonew file mode 100644index 0000000000..5adfcdeb2a--- /dev/null+++ b/server/internal/handler/member_limit.go@@ -0,0 +1,251 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/service"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Member limit (MUL-9488).+//+// Cloud caps the members of a workspace on the Free plan through the+// "members" gate. Every path that adds a member checks it:+//+// - Creating an invitation or joining by share link counts members plus+// live pending invitations, because each pending invitation already holds+// a slot it can still turn into a member.+// - Accepting an invitation counts members only: its own invitation is the+// slot it holds.+//+// Guests take no slot and are never checked. Paid plans get the gate off and+// keep using purchased seats (seat_capacity.go). Off skips the check without+// reading anything, which is also the self-hosted behavior.+//+// A path checks twice. Before its side effects (Cloud seat calls, rate-limit+// budgets) it counts without a lock, so a full workspace is refused early,+// and re-reads Cloud's policy before refusing. Inside the transaction that+// writes the member or invitation it takes the workspace's admission lock+// first, before any row lock, and counts again; that second count is the one+// that holds when two admissions race for the last slot.++const memberLimitReachedCode = "member_limit_reached"++var errMemberLimitReached = errors.New("workspace has reached its member limit")++// guestRole takes no member slot (MUL-9420).+const guestRole = "guest"++func roleTakesMemberSlot(role string) bool { return role != guestRole }++// memberLimit is one admission's member-limit decision, read before its+// transaction so no Cloud call runs while the admission lock is held.+type memberLimit struct {+ overages service.EntitlementOverages+ workspaceID pgtype.UUID+ // reserved is set when the member takes the slot its own pending+ // invitation already holds.+ reserved bool+ decision entitlement.Decision+}++// memberLimitFor reads the gate for one admission and refuses it early when+// it is enforced and already over the limit. A refusal is recorded and+// returned as errMemberLimitReached.+func (h *Handler) memberLimitFor(ctx context.Context, workspaceID pgtype.UUID, role string, reserved bool) (memberLimit, error) {+ m := memberLimit{+ overages: service.EntitlementOverages{Queries: h.Queries},+ workspaceID: workspaceID,+ reserved: reserved,+ decision: entitlement.Decision{Gate: entitlement.Gate{Action: entitlement.ActionOff}},+ }+ if h.Entitlements == nil || !workspaceID.Valid || !roleTakesMemberSlot(role) {+ return m, nil+ }+ m.decision = h.Entitlements.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateMembers)+ if !m.active() || m.decision.Gate.Action != entitlement.ActionEnforce {+ return m, nil+ }+ slots, err := h.Queries.CountWorkspaceMemberSlots(ctx, workspaceID)+ if err != nil {+ return m, err+ }+ if !m.exceeds(slots) {+ return m, nil+ }+ // About to refuse: re-read the policy so a workspace that has just+ // upgraded is not refused on a policy cached before the upgrade.+ if refresher, ok := h.Entitlements.(entitlement.Refresher); ok {+ m.decision = refresher.RefreshGate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateMembers)+ if !m.active() || m.decision.Gate.Action != entitlement.ActionEnforce || !m.exceeds(slots) {+ return m, nil+ }+ }+ m.overLimit(slots).record(ctx)+ return m, errMemberLimitReached+}++func (m memberLimit) active() bool {+ action := m.decision.Gate.Action+ return (action == entitlement.ActionObserve || action == entitlement.ActionEnforce) &&+ m.decision.Gate.Limit != nil+}++func (m memberLimit) limit() int64 { return int64(*m.decision.Gate.Limit) }++// attempted is the slot count once this admission is made, counting itself.+func (m memberLimit) attempted(slots db.CountWorkspaceMemberSlotsRow) int64 {+ if m.reserved {+ return slots.Members + 1+ }+ return slots.Members + slots.PendingInvitations + 1+}++func (m memberLimit) exceeds(slots db.CountWorkspaceMemberSlotsRow) bool {+ return m.attempted(slots) > m.limit()+}++// lock serializes the workspace's member admissions until tx ends. Take it+// first in the transaction, before any row lock, so every admission path+// acquires its locks in the same order.+func (m memberLimit) lock(ctx context.Context, q *db.Queries) error {+ if !m.active() {+ return nil+ }+ return q.LockWorkspaceMemberAdmission(ctx, m.workspaceID)+}++// admit counts under the lock taken by lock. Within the limit it returns+// nothing to record. Over it, observe admits and enforce returns+// errMemberLimitReached; either way the returned admission records the+// attempt once the transaction has ended.+func (m memberLimit) admit(ctx context.Context, q *db.Queries) (memberLimitAdmission, error) {+ if !m.active() {+ return memberLimitAdmission{}, nil+ }+ slots, err := q.CountWorkspaceMemberSlots(ctx, m.workspaceID)+ if err != nil {+ return memberLimitAdmission{}, err+ }+ if !m.exceeds(slots) {+ return memberLimitAdmission{}, nil+ }+ admission := m.overLimit(slots)+ if m.decision.Gate.Action == entitlement.ActionEnforce {+ return admission, errMemberLimitReached+ }+ return admission, nil+}++func (m memberLimit) overLimit(slots db.CountWorkspaceMemberSlotsRow) memberLimitAdmission {+ start, end := memberLimitPeriod(time.Now())+ return memberLimitAdmission{overages: m.overages, attempt: &service.LimitExceededAttempt{+ WorkspaceID: m.workspaceID,+ Gate: entitlement.GateMembers,+ Action: m.decision.Gate.Action,+ PeriodStart: start,+ PeriodEnd: end,+ Limit: m.limit(),+ AttemptedUsage: m.attempted(slots),+ }}+}++// memberLimitPeriod groups member-limit attempts by UTC calendar month. The+// gate itself has no period; the month only buckets the over-limit records,+// so rollout reach reads the same way as the monthly autopilot quota.+func memberLimitPeriod(now time.Time) (time.Time, time.Time) {+ now = now.UTC()+ start := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)+ return start, start.AddDate(0, 1, 0)+}++// memberLimitAdmission is an over-limit attempt waiting to be recorded.+type memberLimitAdmission struct {+ overages service.EntitlementOverages+ attempt *service.LimitExceededAttempt+}++// record stores the attempt, if any. Call it after the transaction has+// ended: committed for an observed admission, rolled back for a refusal.+// Recording is best-effort and never changes the outcome.+func (a memberLimitAdmission) record(ctx context.Context) {+ if a.attempt != nil {+ a.overages.Record(ctx, *a.attempt)+ }+}++func writeMemberLimitReached(w http.ResponseWriter) {+ writeErrorCode(w, http.StatusForbidden, memberLimitReachedCode,+ "This workspace has reached its plan's member limit. Upgrade the plan to add more members.")+}++// MemberLimitResponse is the member limit as clients render it. action is off+// when no limit applies, including self-hosted deployments; limit, members and+// pending_invitations are present only while a limit applies. Guests are not+// counted.+type MemberLimitResponse struct {+ Action string `json:"action"`+ Limit *int64 `json:"limit,omitempty"`+ Members *int64 `json:"members,omitempty"`+ PendingInvitations *int64 `json:"pending_invitations,omitempty"`+}++// GetMemberLimit — GET /api/workspaces/{id}/member-limit+//+// Member-readable, like the member and invitation lists it counts. Clients+// use it to show the limit before an invitation is refused; the server checks+// every admission regardless.+func (h *Handler) GetMemberLimit(w http.ResponseWriter, r *http.Request) {+ wsID := workspaceIDFromURL(r, "id")+ if _, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found"); !ok {+ return+ }+ workspaceID, ok := parseUUIDOrBadRequest(w, wsID, "workspace id")+ if !ok {+ return+ }+ resp := MemberLimitResponse{Action: string(entitlement.ActionOff)}+ if h.Entitlements != nil {+ decision := h.Entitlements.Gate(r.Context(), uuid.UUID(workspaceID.Bytes), entitlement.GateMembers)+ m := memberLimit{workspaceID: workspaceID, decision: decision}+ if m.active() {+ slots, err := h.Queries.CountWorkspaceMemberSlots(r.Context(), workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load member limit")+ return+ }+ // Before telling the client the workspace is full, re-read the+ // policy as an admission would: right after an upgrade the cached+ // one is still Free's, and the client would offer an upgrade the+ // workspace already has.+ if m.decision.Gate.Action == entitlement.ActionEnforce && m.exceeds(slots) {+ if refresher, ok := h.Entitlements.(entitlement.Refresher); ok {+ m.decision = refresher.RefreshGate(r.Context(), uuid.UUID(workspaceID.Bytes), entitlement.GateMembers)+ decision = m.decision+ }+ }+ }+ if m.active() {+ slots, err := h.Queries.CountWorkspaceMemberSlots(r.Context(), workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load member limit")+ return+ }+ limit := m.limit()+ resp = MemberLimitResponse{+ Action: string(decision.Gate.Action),+ Limit: &limit,+ Members: &slots.Members,+ PendingInvitations: &slots.PendingInvitations,+ }+ }+ }+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/member_limit_test.go b/server/internal/handler/member_limit_test.gonew file mode 100644index 0000000000..79715e5541--- /dev/null+++ b/server/internal/handler/member_limit_test.go@@ -0,0 +1,359 @@+package handler++import (+ "fmt"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"+ "time"++ "github.com/google/uuid"++ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// memberLimitWorkspace is a workspace of its own, so its member and+// invitation counts belong to the test alone. The test user owns it, and+// members adds that many more plain members.+func memberLimitWorkspace(t *testing.T, members int) string {+ t.Helper()+ suffix := uuid.NewString()[:8]+ workspaceID := dbfx.Workspace(t, "Member limit "+suffix, "member-limit-"+suffix)+ dbfx.Cleanup(t, `DELETE FROM workspace_invitation WHERE workspace_id = $1`, workspaceID)+ dbfx.Cleanup(t, `DELETE FROM workspace_share_link WHERE workspace_id = $1`, workspaceID)+ dbfx.Cleanup(t, `DELETE FROM member WHERE workspace_id = $1`, workspaceID)+ dbfx.Cleanup(t, `DELETE FROM entitlement_limit_overage WHERE workspace_id = $1`, workspaceID)+ dbfx.Member(t, workspaceID, testUserID, "owner")+ for i := 0; i < members; i++ {+ userID := dbfx.User(t, fmt.Sprintf("Member limit %s %d", suffix, i), fmt.Sprintf("member-limit-%s-%[email protected]", suffix, i))+ dbfx.Member(t, workspaceID, userID, "member")+ }+ return workspaceID+}++// useMemberLimit points the shared handler at a stub whose members gate in+// workspaceID has action and limit.+func useMemberLimit(t *testing.T, workspaceID string, action entitlement.Action, limit int) *entitlementtest.Stub {+ t.Helper()+ stub := entitlementtest.New()+ stub.Set(uuid.MustParse(workspaceID), entitlement.GateMembers, memberLimitDecision(action, limit))+ prior := testHandler.Entitlements+ testHandler.Entitlements = stub+ t.Cleanup(func() { testHandler.Entitlements = prior })+ return stub+}++func memberLimitDecision(action entitlement.Action, limit int) entitlement.Decision {+ gate := entitlement.Gate{Action: action}+ if action != entitlement.ActionOff {+ gate.Limit = &limit+ }+ return entitlement.Decision{Gate: gate}+}++func pendingInvitation(t *testing.T, workspaceID, email, userID string) string {+ t.Helper()+ cols := testutil.Cols{+ "workspace_id": workspaceID,+ "inviter_id": testUserID,+ "invitee_email": email,+ "role": "member",+ "status": "pending",+ "expires_at": testutil.Raw("now() + interval '1 day'"),+ }+ if userID != "" {+ cols["invitee_user_id"] = userID+ }+ return dbfx.Insert(t, "workspace_invitation", cols)+}++type memberLimitOverage struct {+ limit, peak, observed, enforced int64+}++func memberLimitOverageOf(t *testing.T, workspaceID string) memberLimitOverage {+ t.Helper()+ var o memberLimitOverage+ dbfx.QueryRow(t, `+ SELECT COALESCE(MAX(limit_value), 0), COALESCE(MAX(peak_usage), 0),+ COALESCE(SUM(observed_count), 0), COALESCE(SUM(enforced_count), 0)+ FROM entitlement_limit_overage+ WHERE workspace_id = $1 AND gate = 'members'`, workspaceID).+ Scan(&o.limit, &o.peak, &o.observed, &o.enforced)+ return o+}++func wantMemberLimitReached(t *testing.T, resp *testutil.Response) {+ t.Helper()+ var body struct {+ Code string `json:"code"`+ }+ resp.Want(http.StatusForbidden).JSON(&body)+ if body.Code != memberLimitReachedCode {+ t.Fatalf("code = %q, want %q", body.Code, memberLimitReachedCode)+ }+}++func inviteToWorkspace(t *testing.T, workspaceID, email string) *testutil.Response {+ t.Helper()+ req := newRequest(http.MethodPost, "/api/workspaces/"+workspaceID+"/members", CreateMemberRequest{Email: email, Role: "member"})+ req.Header.Set("X-Workspace-ID", workspaceID)+ return testutil.Call(t, testHandler.CreateInvitation, withURLParam(req, "id", workspaceID))+}++func invitationCount(t *testing.T, workspaceID string) int {+ t.Helper()+ return dbfx.Count(t, `SELECT count(*) FROM workspace_invitation WHERE workspace_id = $1`, workspaceID)+}++// A full workspace (owner + 4 members under a limit of 5) is handled by the+// gate's action: off admits without recording, observe admits and records,+// enforce refuses and records without writing the invitation.+func TestCreateInvitationUnderEachMemberLimitAction(t *testing.T) {+ for _, tc := range []struct {+ action entitlement.Action+ want int+ record memberLimitOverage+ }{+ {entitlement.ActionOff, http.StatusCreated, memberLimitOverage{}},+ {entitlement.ActionObserve, http.StatusCreated, memberLimitOverage{limit: 5, peak: 6, observed: 1}},+ {entitlement.ActionEnforce, http.StatusForbidden, memberLimitOverage{limit: 5, peak: 6, enforced: 1}},+ } {+ t.Run(string(tc.action), func(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 4)+ useMemberLimit(t, workspaceID, tc.action, 5)++ resp := inviteToWorkspace(t, workspaceID, "sixth-"+uuid.NewString()+"@multica.ai")+ if tc.want == http.StatusForbidden {+ wantMemberLimitReached(t, resp)+ if n := invitationCount(t, workspaceID); n != 0 {+ t.Fatalf("refused invitation wrote %d rows", n)+ }+ } else {+ resp.Want(tc.want)+ }+ if got := memberLimitOverageOf(t, workspaceID); got != tc.record {+ t.Fatalf("overage = %+v, want %+v", got, tc.record)+ }+ })+ }+}++func TestCreateInvitationWithinMemberLimitRecordsNothing(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 3)+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)++ inviteToWorkspace(t, workspaceID, "fifth-"+uuid.NewString()+"@multica.ai").Want(http.StatusCreated)+ if got := memberLimitOverageOf(t, workspaceID); got != (memberLimitOverage{}) {+ t.Fatalf("overage = %+v, want none", got)+ }+}++// A pending invitation already holds a slot, so it counts against a new one.+func TestCreateInvitationCountsPendingInvitations(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 3)+ pendingInvitation(t, workspaceID, "pending-"+uuid.NewString()+"@multica.ai", "")+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)++ wantMemberLimitReached(t, inviteToWorkspace(t, workspaceID, "sixth-"+uuid.NewString()+"@multica.ai"))+}++// Accepting takes the slot the invitation holds: 4 members plus this+// invitation fit a limit of 5 even though another invitation is pending, and+// a refusal leaves the invitation pending for after an upgrade.+func TestAcceptInvitationTakesTheSlotItHolds(t *testing.T) {+ for _, tc := range []struct {+ name string+ members int+ want int+ }{+ {"fits", 3, http.StatusOK},+ {"full", 4, http.StatusForbidden},+ } {+ t.Run(tc.name, func(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, tc.members)+ email := "invitee-" + uuid.NewString() + "@multica.ai"+ userID := dbfx.User(t, "Member limit invitee", email)+ invitationID := pendingInvitation(t, workspaceID, email, userID)+ pendingInvitation(t, workspaceID, "other-"+uuid.NewString()+"@multica.ai", "")+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)++ req := newRequest(http.MethodPost, "/api/invitations/"+invitationID+"/accept", nil)+ req.Header.Set("X-User-ID", userID)+ resp := testutil.Call(t, testHandler.AcceptInvitation, withURLParam(req, "id", invitationID))+ if tc.want == http.StatusOK {+ resp.Want(http.StatusOK)+ return+ }+ wantMemberLimitReached(t, resp)+ if status, _ := invitationStatusOf(t, invitationID); status != "pending" {+ t.Fatalf("invitation status = %q, want pending", status)+ }+ if n := dbfx.Count(t, `SELECT count(*) FROM member WHERE workspace_id = $1 AND user_id = $2`, workspaceID, userID); n != 0 {+ t.Fatalf("refused accept created %d members", n)+ }+ })+ }+}++func joinWorkspaceByLink(t *testing.T, code, userID string) *testutil.Response {+ t.Helper()+ req := newRequest(http.MethodPost, "/api/share-links/join", JoinByShareLinkRequest{Code: code})+ req.Header.Set("X-User-ID", userID)+ return testutil.Call(t, testHandler.JoinByShareLink, req)+}++func TestJoinShareLinkRefusedWhenWorkspaceIsFull(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 4)+ link := createTestShareLink(t, workspaceID, "member", 5, 0)+ userID := dbfx.User(t, "Member limit joiner", "joiner-"+uuid.NewString()+"@multica.ai")+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)++ wantMemberLimitReached(t, joinWorkspaceByLink(t, link.Code, userID))+ if uses := dbfx.Count(t, `SELECT use_count FROM workspace_share_link WHERE id = $1`, link.ID); uses != 0 {+ t.Fatalf("refused join used the link %d times", uses)+ }+ if got := memberLimitOverageOf(t, workspaceID); got.enforced != 1 || got.peak != 6 {+ t.Fatalf("overage = %+v, want one enforced attempt at 6", got)+ }+}++// A joiner who was also invited by email takes the slot that invitation+// holds instead of a new one.+func TestJoinShareLinkTakesTheJoinersInvitationSlot(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 3)+ link := createTestShareLink(t, workspaceID, "member", 5, 0)+ email := "invited-joiner-" + uuid.NewString() + "@multica.ai"+ userID := dbfx.User(t, "Member limit invited joiner", email)+ invitationID := pendingInvitation(t, workspaceID, email, userID)+ pendingInvitation(t, workspaceID, "other-"+uuid.NewString()+"@multica.ai", "")+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)++ joinWorkspaceByLink(t, link.Code, userID).Want(http.StatusOK)+ if status, _ := invitationStatusOf(t, invitationID); status != "accepted" {+ t.Fatalf("invitation status = %q, want accepted", status)+ }+}++// A workspace that has just upgraded must not be refused on the policy cached+// before the upgrade: the handler re-reads it before refusing.+func TestMemberLimitRefreshesPolicyBeforeRefusing(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 4)+ stub := useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)+ stub.SetRefreshed(uuid.MustParse(workspaceID), entitlement.GateMembers, memberLimitDecision(entitlement.ActionOff, 0))++ inviteToWorkspace(t, workspaceID, "after-upgrade-"+uuid.NewString()+"@multica.ai").Want(http.StatusCreated)+ if refreshes := stub.Refreshes(); len(refreshes) != 1 || refreshes[0].Gate != entitlement.GateMembers {+ t.Fatalf("refreshes = %+v, want one members refresh", refreshes)+ }+ if got := memberLimitOverageOf(t, workspaceID); got != (memberLimitOverage{}) {+ t.Fatalf("overage = %+v, want none after the refreshed policy admitted it", got)+ }+}++// Two invitations racing for the last slot both pass the early check; the+// count under the workspace's admission lock lets exactly one through.+func TestConcurrentInvitationsTakeTheLastSlotOnce(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 3)+ useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)++ codes := make([]int, 2)+ var wg sync.WaitGroup+ start := make(chan struct{})+ for i := range codes {+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ <-start+ req := newRequest(http.MethodPost, "/api/workspaces/"+workspaceID+"/members", CreateMemberRequest{+ Email: fmt.Sprintf("race-%d-%[email protected]", i, uuid.NewString()), Role: "member",+ })+ req.Header.Set("X-Workspace-ID", workspaceID)+ rec := httptest.NewRecorder()+ testHandler.CreateInvitation(rec, withURLParam(req, "id", workspaceID))+ codes[i] = rec.Code+ }(i)+ }+ close(start)+ wg.Wait()++ created, refused := 0, 0+ for _, code := range codes {+ switch code {+ case http.StatusCreated:+ created+++ case http.StatusForbidden:+ refused+++ }+ }+ if created != 1 || refused != 1 {+ t.Fatalf("codes = %v, want one 201 and one 403", codes)+ }+ if n := invitationCount(t, workspaceID); n != 1 {+ t.Fatalf("invitations = %d, want 1", n)+ }+}++func TestGetMemberLimit(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 2)+ pendingInvitation(t, workspaceID, "pending-"+uuid.NewString()+"@multica.ai", "")++ get := func() MemberLimitResponse {+ req := newRequest(http.MethodGet, "/api/workspaces/"+workspaceID+"/member-limit", nil)+ req.Header.Set("X-Workspace-ID", workspaceID)+ var resp MemberLimitResponse+ testutil.Call(t, testHandler.GetMemberLimit, withURLParam(req, "id", workspaceID)).Want(http.StatusOK).JSON(&resp)+ return resp+ }++ if off := get(); off.Action != "off" || off.Limit != nil || off.Members != nil {+ t.Fatalf("without a provider = %+v, want off without counts", off)+ }+ useMemberLimit(t, workspaceID, entitlement.ActionObserve, 5)+ got := get()+ if got.Action != "observe" || got.Limit == nil || *got.Limit != 5 ||+ got.Members == nil || *got.Members != 3 || got.PendingInvitations == nil || *got.PendingInvitations != 1 {+ t.Fatalf("observed = %+v, want limit 5 with 3 members and 1 pending invitation", got)+ }+}++// A workspace that has just upgraded must not be reported full on the policy+// cached before the upgrade: the client would keep offering the upgrade.+func TestGetMemberLimitRefreshesBeforeReportingFull(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 4)+ stub := useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)+ stub.SetRefreshed(uuid.MustParse(workspaceID), entitlement.GateMembers, memberLimitDecision(entitlement.ActionOff, 0))++ req := newRequest(http.MethodGet, "/api/workspaces/"+workspaceID+"/member-limit", nil)+ req.Header.Set("X-Workspace-ID", workspaceID)+ var resp MemberLimitResponse+ testutil.Call(t, testHandler.GetMemberLimit, withURLParam(req, "id", workspaceID)).Want(http.StatusOK).JSON(&resp)+ if resp.Action != "off" || len(stub.Refreshes()) != 1 {+ t.Fatalf("resp = %+v, refreshes = %d; want the refreshed off policy", resp, len(stub.Refreshes()))+ }+}++// Within the server's five-second bound on re-reading Cloud, a refusal can+// still rest on the Free policy read just before payment. The held invitation+// survives that (the client retries after the bound); once the refreshed+// policy arrives the same invitation goes through.+func TestHeldInvitationGoesThroughOnceThePolicyCatchesUp(t *testing.T) {+ workspaceID := memberLimitWorkspace(t, 4)+ stub := useMemberLimit(t, workspaceID, entitlement.ActionEnforce, 5)+ email := "held-" + uuid.NewString() + "@multica.ai"++ wantMemberLimitReached(t, inviteToWorkspace(t, workspaceID, email))++ stub.SetRefreshed(uuid.MustParse(workspaceID), entitlement.GateMembers, memberLimitDecision(entitlement.ActionOff, 0))+ inviteToWorkspace(t, workspaceID, email).Want(http.StatusCreated)+}++func TestMemberLimitPeriodIsTheUTCMonth(t *testing.T) {+ start, end := memberLimitPeriod(time.Date(2026, 12, 31, 23, 30, 0, 0, time.FixedZone("UTC-5", -5*3600)))+ if !start.Equal(time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)) || !end.Equal(time.Date(2027, 2, 1, 0, 0, 0, 0, time.UTC)) {+ t.Fatalf("period = %s..%s", start, end)+ }+}diff --git a/server/internal/handler/share_link.go b/server/internal/handler/share_link.goindex e04f1eeaf9..660c57ac09 100644--- a/server/internal/handler/share_link.go+++ b/server/internal/handler/share_link.go@@ -300,6 +300,29 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {return}+ // A joiner who also holds a pending email invitation takes the slot that+ // invitation reserved, exactly as accepting it would.+ holdsInvitation := false+ if h.Entitlements != nil {+ _, pendingErr := h.Queries.GetPendingInvitationByEmail(r.Context(), db.GetPendingInvitationByEmailParams{+ WorkspaceID: linkPreview.WorkspaceID, InviteeEmail: strings.ToLower(user.Email),+ })+ if pendingErr != nil && !errors.Is(pendingErr, pgx.ErrNoRows) {+ writeError(w, http.StatusInternalServerError, "failed to join workspace")+ return+ }+ holdsInvitation = pendingErr == nil+ }+ memberLimit, err := h.memberLimitFor(r.Context(), linkPreview.WorkspaceID, linkPreview.Role, holdsInvitation)+ if err != nil {+ if errors.Is(err, errMemberLimitReached) {+ writeMemberLimitReached(w)+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to join workspace")+ return+ }+var capacityToken uuid.UUIDif h.seatCapacityEnabled() {capacityToken, err = h.beginShareJoinCapacity(r.Context(), uuid.UUID(linkPreview.WorkspaceID.Bytes), uuid.UUID(linkPreview.ID.Bytes), uuid.UUID(user.ID.Bytes))@@ -321,6 +344,11 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {defer tx.Rollback(r.Context())qtx := h.Queries.WithTx(tx)+ if err := memberLimit.lock(r.Context(), qtx); err != nil {+ h.compensateCapacityIntent(r.Context(), capacityToken)+ writeError(w, http.StatusInternalServerError, "failed to join workspace")+ return+ }link, err := qtx.ClaimShareLinkByID(r.Context(), linkPreview.ID)if err != nil {@@ -374,6 +402,22 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {return}+ // A joiner whose pending invitation was settled above takes the slot that+ // invitation held, as accepting it would; otherwise the join is a new slot.+ memberLimit.reserved = settledInvitationID.Valid+ limitAdmission, err := memberLimit.admit(r.Context(), qtx)+ if err != nil {+ _ = tx.Rollback(r.Context())+ h.compensateCapacityIntent(r.Context(), capacityToken)+ if errors.Is(err, errMemberLimitReached) {+ limitAdmission.record(r.Context())+ writeMemberLimitReached(w)+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to join workspace")+ return+ }+member, err := qtx.CreateMember(r.Context(), db.CreateMemberParams{WorkspaceID: link.WorkspaceID,UserID: user.ID,@@ -416,6 +460,7 @@ func (h *Handler) JoinByShareLink(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to join workspace")return}+ limitAdmission.record(r.Context())if capacityToken != uuid.Nil {h.confirmCapacityIntent(r.Context(), uuid.UUID(link.WorkspaceID.Bytes), capacityToken, uuid.UUID(member.ID.Bytes))}diff --git a/server/pkg/db/generated/member_limit.sql.go b/server/pkg/db/generated/member_limit.sql.gonew file mode 100644index 0000000000..290a6dea1b--- /dev/null+++ b/server/pkg/db/generated/member_limit.sql.go@@ -0,0 +1,53 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: member_limit.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const countWorkspaceMemberSlots = `-- name: CountWorkspaceMemberSlots :one+SELECT+ (SELECT count(*)+ FROM member m+ WHERE m.workspace_id = $1+ AND m.role <> 'guest')::bigint AS members,+ (SELECT count(*)+ FROM workspace_invitation wi+ WHERE wi.workspace_id = $1+ AND wi.status = 'pending'+ AND wi.expires_at > now()+ AND wi.role <> 'guest')::bigint AS pending_invitations+`++type CountWorkspaceMemberSlotsRow struct {+ Members int64 `json:"members"`+ PendingInvitations int64 `json:"pending_invitations"`+}++// Members and live pending invitations that take a member slot. Guests take+// none.+func (q *Queries) CountWorkspaceMemberSlots(ctx context.Context, workspaceID pgtype.UUID) (CountWorkspaceMemberSlotsRow, error) {+ row := q.db.QueryRow(ctx, countWorkspaceMemberSlots, workspaceID)+ var i CountWorkspaceMemberSlotsRow+ err := row.Scan(&i.Members, &i.PendingInvitations)+ return i, err+}++const lockWorkspaceMemberAdmission = `-- name: LockWorkspaceMemberAdmission :exec++SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':member_admission', 0))+`++// Member limit (entitlement gate "members").+// Serializes member-limit admissions within one workspace so the count and+// the write it guards see the same members and invitations.+func (q *Queries) LockWorkspaceMemberAdmission(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, lockWorkspaceMemberAdmission, workspaceID)+ return err+}diff --git a/server/pkg/db/queries/member_limit.sql b/server/pkg/db/queries/member_limit.sqlnew file mode 100644index 0000000000..ed65e932e4--- /dev/null+++ b/server/pkg/db/queries/member_limit.sql@@ -0,0 +1,21 @@+-- Member limit (entitlement gate "members").++-- name: LockWorkspaceMemberAdmission :exec+-- Serializes member-limit admissions within one workspace so the count and+-- the write it guards see the same members and invitations.+SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg('workspace_id')::uuid::text || ':member_admission', 0));++-- name: CountWorkspaceMemberSlots :one+-- Members and live pending invitations that take a member slot. Guests take+-- none.+SELECT+ (SELECT count(*)+ FROM member m+ WHERE m.workspace_id = sqlc.arg('workspace_id')+ AND m.role <> 'guest')::bigint AS members,+ (SELECT count(*)+ FROM workspace_invitation wi+ WHERE wi.workspace_id = sqlc.arg('workspace_id')+ AND wi.status = 'pending'+ AND wi.expires_at > now()+ AND wi.role <> 'guest')::bigint AS pending_invitations;