Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(billing): buy autopilot run add-ons when the quota is used up (MUL-9487) (#11042)

Multica Eveb17b13a83d3b
diff --git a/apps/docs/content/docs/autopilots.fr.mdx b/apps/docs/content/docs/autopilots.fr.mdx
index 6ae3ebf3f7..15ea27163a 100644
--- a/apps/docs/content/docs/autopilots.fr.mdx
+++ b/apps/docs/content/docs/autopilots.fr.mdx
@@ -30,6 +30,8 @@ Une automatisation est activée par défaut après l'enregistrement. **Exécuter
Sur Multica Cloud, **Exécuter maintenant** ne consomme aucune unité du quota d’automatisation quand un membre lance lui-même l’exécution. Il peut s’en servir même si le quota est épuisé. Les exécutions planifiées, celles déclenchées par webhook et celles qu’un agent lance pour un membre sont décomptées du quota.
+Une fois le quota épuisé, les exécutions décomptées sont ignorées jusqu’à sa réinitialisation au début du mois suivant. Sur Pro et Business, un propriétaire ou un administrateur peut aussi acheter des exécutions dans **Paramètres → Facturation** (10 $ les 1 000 exécutions, réglées sur la page de paiement Stripe et valables le mois en cours) ; sur Free, passer à un forfait supérieur augmente la limite. Les propriétaires, les administrateurs et le membre qui a créé l’automatisation reçoivent une notification dans la boîte de réception la première fois qu’une exécution est ignorée à chaque limite.
+
Voici une automatisation dont le mode de sortie est Créer une tâche. Cliquez sur **Exécuter maintenant**, ou avancez jusqu'à la prochaine exécution planifiée, et regardez-la créer une tâche, la confier à l'agent, puis terminer l'exécution.
<AutopilotDemo />
diff --git a/apps/docs/content/docs/autopilots.ja.mdx b/apps/docs/content/docs/autopilots.ja.mdx
index 418b616fee..495dbaf214 100644
--- a/apps/docs/content/docs/autopilots.ja.mdx
+++ b/apps/docs/content/docs/autopilots.ja.mdx
@@ -30,6 +30,8 @@ import { AutopilotDemo } from "@/components/demos/autopilot-demo";
Multica Cloud では、メンバーが**今すぐ実行**を選んでもワークスペースの自動化の利用枠は消費されず、枠を使い切った後も実行できます。スケジュールや Webhook による実行と、エージェントがメンバーに代わって開始した実行は利用枠にカウントされます。
+利用枠を使い切ると、カウント対象の実行は翌月初めのリセットまでスキップされます。Pro と Business では、所有者または管理者が**設定 → 請求とプラン**で実行回数を追加購入することもできます(1,000 回ごとに $10、Stripe の支払いページで支払い、当月のみ有効)。Free ではアップグレードすると上限が上がります。上限ごとに最初に実行がスキップされたとき、所有者、管理者、そのオートパイロットを作成したメンバーに受信トレイの通知が届きます。
+
下は出力モードが「タスクを作成」のオートパイロットです。**今すぐ実行**をクリックするか、次回の実行時刻まで早送りすると、タスクの作成、エージェントへの割り当て、実行の完了までを確認できます。
<AutopilotDemo />
diff --git a/apps/docs/content/docs/autopilots.ko.mdx b/apps/docs/content/docs/autopilots.ko.mdx
index 9ca5c70e34..e37aa28aa7 100644
--- a/apps/docs/content/docs/autopilots.ko.mdx
+++ b/apps/docs/content/docs/autopilots.ko.mdx
@@ -30,6 +30,8 @@ import { AutopilotDemo } from "@/components/demos/autopilot-demo";
Multica Cloud에서 멤버가 직접 누른 **지금 실행**은 워크스페이스의 자동화 할당량을 사용하지 않으며, 할당량을 모두 쓴 뒤에도 실행할 수 있습니다. 일정이나 Webhook으로 시작한 실행과 에이전트가 멤버를 대신해 시작한 실행은 할당량에 포함됩니다.
+할당량을 모두 쓰면 할당량에 포함되는 실행은 다음 달 초 초기화될 때까지 건너뜁니다. Pro와 Business에서는 소유자나 관리자가 **설정 → 결제 및 요금제**에서 실행 횟수를 추가 구매할 수도 있습니다(1,000회당 $10, Stripe 결제 페이지에서 결제, 이번 달만 유효). Free에서는 업그레이드하면 한도가 늘어납니다. 한도마다 처음으로 실행을 건너뛸 때 소유자, 관리자, 해당 오토파일럿을 만든 멤버가 받은편지함 알림을 받습니다.
+
아래는 출력 모드가 "태스크 생성"인 오토파일럿입니다. **지금 실행**을 클릭하거나 다음 실행 시간으로 건너뛰어, 태스크를 만들고 에이전트에게 맡긴 뒤 이번 실행이 완료되는 과정을 확인해 보세요.
<AutopilotDemo />
diff --git a/apps/docs/content/docs/autopilots.mdx b/apps/docs/content/docs/autopilots.mdx
index b6539558cd..86f87fb3cc 100644
--- a/apps/docs/content/docs/autopilots.mdx
+++ b/apps/docs/content/docs/autopilots.mdx
@@ -30,6 +30,8 @@ An autopilot is enabled by default after saving. **Run now** executes the full f
On Multica Cloud, a member’s **Run now** uses none of the workspace’s automation quota, even when the quota is exhausted. Scheduled runs, webhook runs, and runs an agent triggers on a member’s behalf count toward the quota.
+When the quota runs out, counted runs are skipped until the quota resets at the start of next month. On Pro and Business, an owner or admin can instead buy more runs in **Settings → Billing** ($10 per 1,000 runs, paid on Stripe's checkout page and valid for the current month); on Free, upgrading raises the limit. The owners and admins, and the member who created the autopilot, get an Inbox notice the first time a run is skipped at each limit.
+
Below is an autopilot whose execution mode is Create issue. Click **Run now**, or skip ahead to the next scheduled time, and watch it create an issue, hand it to the agent, and complete the run.
<AutopilotDemo />
diff --git a/apps/docs/content/docs/autopilots.zh-Hant.mdx b/apps/docs/content/docs/autopilots.zh-Hant.mdx
index 74185b3988..cda187ffb3 100644
--- a/apps/docs/content/docs/autopilots.zh-Hant.mdx
+++ b/apps/docs/content/docs/autopilots.zh-Hant.mdx
@@ -30,6 +30,8 @@ import { AutopilotDemo } from "@/components/demos/autopilot-demo";
在 Multica Cloud 上,成員親自點選**立即執行**不會消耗工作區的自動化配額,配額用完後也能執行。排程執行、Webhook 觸發的執行,以及 AI 代理代表成員觸發的執行都會計入配額。
+配額用完後,計入配額的執行會被跳過,直到下月初重置。Pro 和 Business 工作區的所有者或管理員也可以在**設定 → 帳單與套餐**裡加購($10 / 1,000 次,在 Stripe 付款頁面付款,當月有效);Free 工作區升級方案即可提高上限。每個上限第一次跳過執行時,所有者、管理員和建立這條自動化的成員會收到收件匣通知。
+
下面是一條輸出模式為"建立任務"的自動化。點**立即執行**,或者快進到下次執行時間,看它建立任務、交給 AI 代理,再到這次執行完成。
<AutopilotDemo />
diff --git a/apps/docs/content/docs/autopilots.zh.mdx b/apps/docs/content/docs/autopilots.zh.mdx
index d5e10518eb..16b3c59c22 100644
--- a/apps/docs/content/docs/autopilots.zh.mdx
+++ b/apps/docs/content/docs/autopilots.zh.mdx
@@ -30,6 +30,8 @@ import { AutopilotDemo } from "@/components/demos/autopilot-demo";
在 Multica Cloud 上,成员亲自点击**立即运行**不消耗工作区的自动化配额,配额用完时也可以运行。定时运行、Webhook 触发的运行,以及智能体代表成员触发的运行都会计入配额。
+配额用完后,计入配额的运行会被跳过,直到下月初重置。Pro 和 Business 工作区的所有者或管理员也可以在**设置 → 账单与套餐**里加购($10 / 1,000 次,在 Stripe 付款页面支付,当月有效);Free 工作区升级套餐即可提高上限。每个上限第一次跳过运行时,所有者、管理员和创建这条自动化的成员会收到收件箱通知。
+
下面是一条输出模式为"创建任务"的自动化。点**立即运行**,或者快进到下次运行时间,看它创建任务、交给智能体,再到这次运行完成。
<AutopilotDemo />
diff --git a/apps/mobile/app/(app)/[workspace]/inbox/[id].tsx b/apps/mobile/app/(app)/[workspace]/inbox/[id].tsx
index 2a2d3ec320..00729387a8 100644
--- a/apps/mobile/app/(app)/[workspace]/inbox/[id].tsx
+++ b/apps/mobile/app/(app)/[workspace]/inbox/[id].tsx
@@ -45,6 +45,20 @@ function BillingRecovery({
{t("detail.contact_admin")}
</Text>
);
+ case "autopilot_addon":
+ // Buying runs is a card payment; the app opens web Billing for it.
+ return billingUrl ? (
+ <Button
+ onPress={() => void Linking.openURL(billingUrl)}
+ accessibilityLabel={t("detail.buy_runs")}
+ >
+ <Text>{t("detail.buy_runs")}</Text>
+ </Button>
+ ) : (
+ <Text className="text-sm leading-5 text-muted-foreground">
+ {t("detail.buy_runs_web")}
+ </Text>
+ );
case "checkout":
case "portal":
case "billing":
@@ -91,6 +105,7 @@ export default function InboxNoticeDetail() {
const checkingConfig =
isQuotaNotice && !configQuery.data && configQuery.isFetching;
const recovery = resolveBillingRecovery({
+ autopilotAddon: true,
actions: summaryQuery.data?.availableActions,
billingEnabled: checkingConfig || billingEnabled,
loading:
diff --git a/apps/mobile/locales/en/inbox.json b/apps/mobile/locales/en/inbox.json
index 9efdc45b9c..acdcee6a72 100644
--- a/apps/mobile/locales/en/inbox.json
+++ b/apps/mobile/locales/en/inbox.json
@@ -39,9 +39,11 @@
"close": "Close notification",
"unavailable": "This notification is no longer available.",
"billing_disabled": "Billing changes are unavailable for this workspace. Contact your workspace administrator for help.",
- "contact_admin": "Ask a workspace owner or admin to review the billing options.",
+ "contact_admin": "Ask a workspace owner or admin to upgrade the plan or buy more runs.",
"review_billing": "Review billing options",
- "review_billing_web": "Open Multica on the web to review billing options."
+ "review_billing_web": "Open Multica on the web to review billing options.",
+ "buy_runs": "Buy more runs",
+ "buy_runs_web": "Open Multica on the web to buy more runs."
},
"type": {
"assigned": "Assigned",
@@ -86,8 +88,8 @@
"app_action_result": "App action result"
},
"body": {
- "autopilot_title_limit": "Autopilot \"{{title}}\" was not started because this workspace has reached its limit of {{limit}} runs for the current period. The allowance resets {{resetAt}}.",
- "autopilot_limit": "This workspace has reached its limit of {{limit}} autopilot runs for the current period. This execution was not started. The allowance resets {{resetAt}}.",
+ "autopilot_title_limit": "Autopilot \"{{title}}\" was not started because this workspace has reached its limit of {{limit}} runs for the current period. The allowance resets {{resetAt}}; a workspace owner or admin can also upgrade or buy more runs.",
+ "autopilot_limit": "This workspace has reached its limit of {{limit}} autopilot runs for the current period. This execution was not started. The allowance resets {{resetAt}}; a workspace owner or admin can also upgrade or buy more runs.",
"project_owner_joined": "{{name}} is a workspace owner and added themselves to this private project. They can now see its issues, comments, and attachments."
}
}
diff --git a/apps/mobile/locales/zh-Hans/inbox.json b/apps/mobile/locales/zh-Hans/inbox.json
index ec6a34372a..c955ecbc6d 100644
--- a/apps/mobile/locales/zh-Hans/inbox.json
+++ b/apps/mobile/locales/zh-Hans/inbox.json
@@ -39,9 +39,11 @@
"close": "关闭通知",
"unavailable": "此通知已不可用。",
"billing_disabled": "该工作区无法修改账单设置。请联系工作区管理员。",
- "contact_admin": "请让工作区所有者或管理员查看账单选项。",
+ "contact_admin": "请让工作区所有者或管理员升级套餐或加购执行次数。",
"review_billing": "查看账单选项",
- "review_billing_web": "在网页端打开 Multica 查看账单选项。"
+ "review_billing_web": "在网页端打开 Multica 查看账单选项。",
+ "buy_runs": "加购执行次数",
+ "buy_runs_web": "在网页端打开 Multica 加购执行次数。"
},
"type": {
"assigned": "已分配",
@@ -86,8 +88,8 @@
"app_action_result": "应用操作结果"
},
"body": {
- "autopilot_title_limit": "自动化 \"{{title}}\" 未启动,因为该工作区已达到当前周期 {{limit}} 次运行的上限。额度将在 {{resetAt}} 重置。",
- "autopilot_limit": "该工作区已达到当前周期 {{limit}} 次自动化运行的上限。此执行未启动。额度将在 {{resetAt}} 重置。",
+ "autopilot_title_limit": "自动化 \"{{title}}\" 未启动,因为该工作区已达到当前周期 {{limit}} 次运行的上限。额度将在 {{resetAt}} 重置;工作区所有者或管理员也可以升级套餐或加购执行次数。",
+ "autopilot_limit": "该工作区已达到当前周期 {{limit}} 次自动化运行的上限。此执行未启动。额度将在 {{resetAt}} 重置;工作区所有者或管理员也可以升级套餐或加购执行次数。",
"project_owner_joined": "{{name}} 是工作区所有者,已把自己加入这个私有项目,现在可以看到其中的任务、评论和附件。"
},
"actions.archive_completed": "归档已完成项",
@@ -97,5 +99,5 @@
"type.task_completed": "运行完成",
"type.task_failed": "运行失败",
"type.run_limit_blocked": "已达到上限,本次运行被阻止",
- "body.autopilot_title_limit": "自动化 \"{{title}}\" 未启动,因为该工作区已达到当前周期 {{limit}} 次运行的上限。额度将在 {{resetAt}} 重置。"
+ "body.autopilot_title_limit": "自动化 \"{{title}}\" 未启动,因为该工作区已达到当前周期 {{limit}} 次运行的上限。额度将在 {{resetAt}} 重置;工作区所有者或管理员也可以升级套餐或加购执行次数。"
}
diff --git a/apps/mobile/locales/zh-Hant/inbox.json b/apps/mobile/locales/zh-Hant/inbox.json
index eac88dffc2..baf4dd3f12 100644
--- a/apps/mobile/locales/zh-Hant/inbox.json
+++ b/apps/mobile/locales/zh-Hant/inbox.json
@@ -39,9 +39,11 @@
"close": "關閉通知",
"unavailable": "此通知已不可用。",
"billing_disabled": "該工作區無法修改帳單設定。請聯絡工作區管理員。",
- "contact_admin": "請讓工作區所有者或管理員檢視帳單選項。",
+ "contact_admin": "請讓工作區所有者或管理員升級方案或加購執行次數。",
"review_billing": "檢視帳單選項",
- "review_billing_web": "在網頁端開啟 Multica 檢視帳單選項。"
+ "review_billing_web": "在網頁端開啟 Multica 檢視帳單選項。",
+ "buy_runs": "加購執行次數",
+ "buy_runs_web": "在網頁端開啟 Multica 加購執行次數。"
},
"type": {
"assigned": "已分配",
@@ -86,8 +88,8 @@
"app_action_result": "應用操作結果"
},
"body": {
- "autopilot_title_limit": "自動化 \"{{title}}\" 未啟動,因為該工作區已達到當前週期 {{limit}} 次執行的上限。額度將在 {{resetAt}} 重置。",
- "autopilot_limit": "該工作區已達到當前週期 {{limit}} 次自動化執行的上限。此執行未啟動。額度將在 {{resetAt}} 重置。",
+ "autopilot_title_limit": "自動化 \"{{title}}\" 未啟動,因為該工作區已達到當前週期 {{limit}} 次執行的上限。額度將在 {{resetAt}} 重置;工作區所有者或管理員也可以升級方案或加購執行次數。",
+ "autopilot_limit": "該工作區已達到當前週期 {{limit}} 次自動化執行的上限。此執行未啟動。額度將在 {{resetAt}} 重置;工作區所有者或管理員也可以升級方案或加購執行次數。",
"project_owner_joined": "{{name}} 是工作區所有者,已把自己加入這個私有專案,現在可以看到其中的任務、評論和附件。"
},
"actions.archive_completed": "歸檔已完成項",
@@ -97,5 +99,5 @@
"type.task_completed": "執行完成",
"type.task_failed": "執行失敗",
"type.run_limit_blocked": "已達到上限,本次執行被阻止",
- "body.autopilot_title_limit": "自動化 \"{{title}}\" 未啟動,因為該工作區已達到當前週期 {{limit}} 次執行的上限。額度將在 {{resetAt}} 重置。"
+ "body.autopilot_title_limit": "自動化 \"{{title}}\" 未啟動,因為該工作區已達到當前週期 {{limit}} 次執行的上限。額度將在 {{resetAt}} 重置;工作區所有者或管理員也可以升級方案或加購執行次數。"
}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index f83ea1b75d..a94f772270 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -288,6 +288,9 @@ import type {
CreateBillingPortalSessionResponse,
WorkspaceSubscriptionSummary,
WorkspaceSubscriptionPrices,
+ CreateWorkspaceAutopilotAddonCheckoutRequest,
+ CreateWorkspaceAutopilotAddonCheckoutResponse,
+ WorkspaceAutopilotAddonCheckout,
WorkspaceFeatures,
MemberLimit,
StorageUsage,
@@ -454,6 +457,8 @@ import {
BatchUpdateIssuesResponseSchema,
UNCONFIRMED_BATCH_UPDATE,
WorkspaceSubscriptionPricesSchema,
+ CreateWorkspaceAutopilotAddonCheckoutResponseSchema,
+ WorkspaceAutopilotAddonCheckoutSchema,
WorkspaceFeaturesSchema,
MemberLimitSchema,
StorageUsageSchema,
@@ -2887,6 +2892,51 @@ export class ApiClient {
);
}
+ // Autopilot add-on packs (managers only), paid on Stripe Checkout. A
+ // non-2xx answer throws ApiError with Cloud's status: 409 not purchasable or
+ // price changed.
+ async createWorkspaceAutopilotAddonCheckout(
+ data: CreateWorkspaceAutopilotAddonCheckoutRequest,
+ ): Promise<CreateWorkspaceAutopilotAddonCheckoutResponse | null> {
+ const res = await this.fetchRaw(
+ "/api/cloud-subscriptions/autopilot-addon/checkout-sessions",
+ {
+ method: "POST",
+ body: JSON.stringify({
+ packs: data.packs,
+ expected_unit_amount: data.expectedUnitAmount,
+ currency: data.currency,
+ idempotency_key: data.idempotencyKey,
+ }),
+ extraHeaders: {
+ "Content-Type": "application/json",
+ "Idempotency-Key": data.idempotencyKey,
+ },
+ },
+ );
+ const raw = (await res.json()) as unknown;
+ return parseWithFallback<CreateWorkspaceAutopilotAddonCheckoutResponse | null>(
+ raw,
+ CreateWorkspaceAutopilotAddonCheckoutResponseSchema,
+ null,
+ { endpoint: "POST /api/cloud-subscriptions/autopilot-addon/checkout-sessions" },
+ );
+ }
+
+ async getWorkspaceAutopilotAddonCheckout(
+ sessionId: string,
+ ): Promise<WorkspaceAutopilotAddonCheckout | null> {
+ const raw = await this.fetch<unknown>(
+ `/api/cloud-subscriptions/autopilot-addon/checkout-sessions/${encodeURIComponent(sessionId)}`,
+ );
+ return parseWithFallback<WorkspaceAutopilotAddonCheckout | null>(
+ raw,
+ WorkspaceAutopilotAddonCheckoutSchema,
+ null,
+ { endpoint: "GET /api/cloud-subscriptions/autopilot-addon/checkout-sessions/:id" },
+ );
+ }
+
async deleteRuntime(runtimeId: string): Promise<void> {
await this.fetch(`/api/runtimes/${runtimeId}`, { method: "DELETE" });
}
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index c12449e4d6..7f2bc80302 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -1630,7 +1630,10 @@ describe("workspace subscription contract", () => {
purchaseSeats: false,
changePlan: true,
checkPlanChange: false,
+ // An older cloud sends no add-on action and no add-on summary.
+ purchaseAutopilotRuns: false,
});
+ expect(summary?.autopilotAddon).toBeNull();
expect(summary?.planChange).toBeNull();
expect(summary?.trial).toBeNull();
});
@@ -1661,6 +1664,56 @@ describe("workspace subscription contract", () => {
expect(malformed?.plan).toBe("pro");
});
+ it("reads the autopilot add-on action and this month's add-ons", async () => {
+ const base = {
+ entitlement,
+ billing_interval: "month",
+ human_members: 3,
+ seat_capacity: null,
+ cancel_at_period_end: false,
+ grace_until: null,
+ has_stripe_customer: true,
+ };
+ stubFetchJson({
+ ...base,
+ available_actions: {
+ checkout: false,
+ portal: true,
+ purchase_seats: true,
+ purchase_autopilot_runs: true,
+ },
+ autopilot_addon: {
+ purchased_runs: 3000,
+ period_start: "2026-11-01T00:00:00Z",
+ period_end: "2026-12-01T00:00:00Z",
+ },
+ });
+ const client = new ApiClient("https://api.example.test");
+ const summary = await client.getWorkspaceSubscriptionSummary();
+ expect(summary?.availableActions.purchaseAutopilotRuns).toBe(true);
+ expect(summary?.autopilotAddon).toEqual({
+ purchasedRuns: 3000,
+ periodStart: "2026-11-01T00:00:00Z",
+ periodEnd: "2026-12-01T00:00:00Z",
+ });
+
+ // Malformed add-on fields never take the summary down: no add-on offered.
+ stubFetchJson({
+ ...base,
+ available_actions: {
+ checkout: false,
+ portal: true,
+ purchase_seats: true,
+ purchase_autopilot_runs: "yes",
+ },
+ autopilot_addon: { purchased_runs: -1 },
+ });
+ const malformed = await client.getWorkspaceSubscriptionSummary();
+ expect(malformed).not.toBeNull();
+ expect(malformed?.availableActions.purchaseAutopilotRuns).toBe(false);
+ expect(malformed?.autopilotAddon).toBeNull();
+ });
+
it("reads a plan change that still holds the subscription", async () => {
stubFetchJson({
entitlement,
@@ -1899,12 +1952,96 @@ describe("workspace subscription contract", () => {
expect(prices?.pro.year.interval).toBe("year");
expect(prices?.business.month.unitAmount).toBe(3000);
expect(prices?.business.year.unitAmount).toBe(28800);
+ // An older cloud sells no add-on pack.
+ expect(prices?.autopilotAddon).toBeNull();
// A zero or missing amount must not be rendered next to a purchase button.
stubFetchJson({ pro: planPrices(0, 14400), business: planPrices(3000, 28800) });
expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();
});
+ it("reads the add-on pack price on its own", async () => {
+ const client = new ApiClient("https://api.example.test");
+ stubFetchJson({
+ pro: planPrices(1500, 14400),
+ business: planPrices(3000, 28800),
+ autopilot_addon: { currency: "usd", unit_amount: 1000, runs_per_pack: 1000 },
+ });
+ expect((await client.getWorkspaceSubscriptionPrices())?.autopilotAddon).toEqual({
+ currency: "usd",
+ unitAmount: 1000,
+ runsPerPack: 1000,
+ });
+
+ // A malformed pack price hides the add-on but keeps the plan prices.
+ for (const malformed of [
+ { currency: "usd", unit_amount: 0, runs_per_pack: 1000 },
+ { currency: "USD", unit_amount: 1000, runs_per_pack: 1000 },
+ { currency: "usd", unit_amount: 1000 },
+ "1000",
+ ]) {
+ stubFetchJson({
+ pro: planPrices(1500, 14400),
+ business: planPrices(3000, 28800),
+ autopilot_addon: malformed,
+ });
+ const prices = await client.getWorkspaceSubscriptionPrices();
+ expect(prices?.pro.month.unitAmount).toBe(1500);
+ expect(prices?.autopilotAddon).toBeNull();
+ }
+ });
+
+ it("starts an add-on Checkout with the accepted price and reads the session back", async () => {
+ const client = new ApiClient("https://api.example.test");
+ stubFetchJson({ session_id: "cs_test_1", url: "https://checkout.stripe.com/c/pay/cs_test_1" });
+ await expect(
+ client.createWorkspaceAutopilotAddonCheckout({
+ packs: 3,
+ expectedUnitAmount: 1000,
+ currency: "usd",
+ idempotencyKey: "addon-1",
+ }),
+ ).resolves.toEqual({ sessionId: "cs_test_1", url: "https://checkout.stripe.com/c/pay/cs_test_1" });
+ expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(
+ "https://api.example.test/api/cloud-subscriptions/autopilot-addon/checkout-sessions",
+ expect.objectContaining({
+ method: "POST",
+ body: JSON.stringify({
+ packs: 3,
+ expected_unit_amount: 1000,
+ currency: "usd",
+ idempotency_key: "addon-1",
+ }),
+ }),
+ );
+ // A Checkout URL that is not Stripe's HTTPS page is never followed.
+ stubFetchJson({ session_id: "cs_test_1", url: "javascript:alert(1)" });
+ expect(
+ await client.createWorkspaceAutopilotAddonCheckout({
+ packs: 1,
+ expectedUnitAmount: 1000,
+ currency: "usd",
+ idempotencyKey: "addon-2",
+ }),
+ ).toBeNull();
+
+ // An unknown status keeps waiting instead of claiming an outcome.
+ for (const [status, expected] of [
+ ["paid", "paid"],
+ ["expired", "expired"],
+ ["complete", "open"],
+ ] as const) {
+ stubFetchJson({ session_id: "cs_test_1", status, packs: 1, runs: 1000, currency: "usd", amount: 1000 });
+ expect((await client.getWorkspaceAutopilotAddonCheckout("cs_test_1"))?.status).toBe(expected);
+ }
+ expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(
+ "https://api.example.test/api/cloud-subscriptions/autopilot-addon/checkout-sessions/cs_test_1",
+ expect.anything(),
+ );
+ stubFetchJson({ session_id: "cs_test_1", status: "paid", packs: 0, runs: 1000, currency: "usd", amount: 1000 });
+ expect(await client.getWorkspaceAutopilotAddonCheckout("cs_test_1")).toBeNull();
+ });
+
it("rejects prices that omit a paid plan or use the retired flat shape", async () => {
const client = new ApiClient("https://api.example.test");
@@ -1980,6 +2117,7 @@ describe("workspace subscription contract", () => {
nextInvoiceAmount: 57600,
invoiceNow: false,
quotedAt: "2026-11-18T08:00:00Z",
+ autopilotRunsLimitAfter: null,
});
expect(vi.mocked(fetch)).toHaveBeenLastCalledWith(
"https://api.example.test/api/cloud-subscriptions/plan-changes/preview",
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index d4fe0a9846..215cbf94be 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -44,6 +44,9 @@ import type {
WorkspaceSubscriptionPrice,
WorkspaceSubscriptionPlanPrices,
WorkspaceSubscriptionPrices,
+ CreateWorkspaceAutopilotAddonCheckoutResponse,
+ WorkspaceAutopilotAddonCheckout,
+ WorkspaceAutopilotAddonPrice,
CreateWorkspaceSubscriptionCheckoutResponse,
WorkspacePlanChangePreview,
ChangeWorkspacePlanResponse,
@@ -3700,7 +3703,21 @@ export const WorkspaceSubscriptionSummarySchema = z
// Absent on a cloud that predates plan switching: no switch is offered.
change_plan: z.boolean().optional(),
check_plan_change: z.boolean().optional(),
+ // Absent on a cloud that predates add-ons; a malformed value offers none.
+ purchase_autopilot_runs: z.boolean().optional().catch(undefined),
}).loose(),
+ // Absent on an older cloud, and a malformed value reads as no add-ons:
+ // the limit in the entitlement already includes them.
+ autopilot_addon: z
+ .object({
+ purchased_runs: z.number().int().nonnegative(),
+ period_start: z.string().min(1),
+ period_end: z.string().min(1),
+ })
+ .loose()
+ .nullable()
+ .optional()
+ .catch(null),
// Absent on an older cloud, and a malformed value reads as no hold: the
// server still refuses the operations a hold blocks.
plan_change: z
@@ -3771,7 +3788,16 @@ export const WorkspaceSubscriptionSummarySchema = z
purchaseSeats: value.available_actions.purchase_seats,
changePlan: value.available_actions.change_plan ?? false,
checkPlanChange: value.available_actions.check_plan_change ?? false,
+ purchaseAutopilotRuns:
+ value.available_actions.purchase_autopilot_runs ?? false,
},
+ autopilotAddon: value.autopilot_addon
+ ? {
+ purchasedRuns: value.autopilot_addon.purchased_runs,
+ periodStart: value.autopilot_addon.period_start,
+ periodEnd: value.autopilot_addon.period_end,
+ }
+ : null,
planChange: value.plan_change
? {
targetPlan: value.plan_change.target_plan,
@@ -3879,18 +3905,75 @@ const WorkspaceSubscriptionPlanPricesSchema = z
}),
);
+// The add-on pack is optional and read on its own: a missing or malformed
+// pack price hides the add-on without taking the plan prices down with it.
+const WorkspaceAutopilotAddonPriceSchema = z
+ .object({
+ currency: z.string().regex(/^[a-z]{3}$/),
+ unit_amount: z.number().int().positive(),
+ runs_per_pack: z.number().int().positive(),
+ })
+ .loose()
+ .transform(
+ (value): WorkspaceAutopilotAddonPrice => ({
+ currency: value.currency,
+ unitAmount: value.unit_amount,
+ runsPerPack: value.runs_per_pack,
+ }),
+ );
+
// Every paid plan must be priced: a response missing one plan reads as "prices
// unavailable" as a whole rather than offering one plan without the other.
export const WorkspaceSubscriptionPricesSchema = z
.object({
pro: WorkspaceSubscriptionPlanPricesSchema,
business: WorkspaceSubscriptionPlanPricesSchema,
+ autopilot_addon: WorkspaceAutopilotAddonPriceSchema.nullable()
+ .optional()
+ .catch(null),
})
.loose()
.transform(
(value): WorkspaceSubscriptionPrices => ({
pro: value.pro,
business: value.business,
+ autopilotAddon: value.autopilot_addon ?? null,
+ }),
+ );
+
+export const CreateWorkspaceAutopilotAddonCheckoutResponseSchema = z
+ .object({
+ session_id: z.string().min(1),
+ url: StripeHostedURLSchema,
+ })
+ .loose()
+ .transform(
+ (value): CreateWorkspaceAutopilotAddonCheckoutResponse => ({
+ sessionId: value.session_id,
+ url: value.url,
+ }),
+ );
+
+// A session status this client does not know reads as open: the page keeps
+// waiting for Stripe instead of claiming success or failure.
+export const WorkspaceAutopilotAddonCheckoutSchema = z
+ .object({
+ session_id: z.string().min(1),
+ status: z.enum(["paid", "open", "unpaid", "expired"]).catch("open"),
+ packs: z.number().int().positive(),
+ runs: z.number().int().positive(),
+ currency: z.string().regex(/^[a-z]{3}$/),
+ amount: z.number().int().nonnegative(),
+ })
+ .loose()
+ .transform(
+ (value): WorkspaceAutopilotAddonCheckout => ({
+ sessionId: value.session_id,
+ status: value.status,
+ packs: value.packs,
+ runs: value.runs,
+ currency: value.currency,
+ amount: value.amount,
}),
);
@@ -4054,6 +4137,14 @@ export const WorkspacePlanChangePreviewSchema = z
next_invoice_amount: z.number().int().nonnegative(),
invoice_now: z.boolean(),
quoted_at: z.string().min(1),
+ // Absent on a cloud that predates add-ons.
+ autopilot_runs_limit_after: z
+ .number()
+ .int()
+ .nonnegative()
+ .nullable()
+ .optional()
+ .catch(null),
})
.loose()
.refine((value) => value.current_plan !== value.target_plan, {
@@ -4071,6 +4162,7 @@ export const WorkspacePlanChangePreviewSchema = z
nextInvoiceAmount: value.next_invoice_amount,
invoiceNow: value.invoice_now,
quotedAt: value.quoted_at,
+ autopilotRunsLimitAfter: value.autopilot_runs_limit_after ?? null,
}),
);
diff --git a/packages/core/billing/recovery.test.ts b/packages/core/billing/recovery.test.ts
index 7295f92764..5f0a7ce60b 100644
--- a/packages/core/billing/recovery.test.ts
+++ b/packages/core/billing/recovery.test.ts
@@ -8,6 +8,7 @@ const actions = (
purchaseSeats: boolean;
changePlan: boolean;
checkPlanChange: boolean;
+ purchaseAutopilotRuns: boolean;
}> = {},
) => ({
checkout: false,
@@ -15,6 +16,7 @@ const actions = (
purchaseSeats: false,
changePlan: false,
checkPlanChange: false,
+ purchaseAutopilotRuns: false,
...overrides,
});
@@ -71,4 +73,57 @@ describe("resolveBillingRecovery", () => {
}),
).toBe("billing_unavailable");
});
+
+ it("offers add-on runs to a paying workspace only on autopilot surfaces", () => {
+ // Pro/Business manager: Cloud allows both the add-on and the portal.
+ const paidManager = actions({
+ portal: true,
+ purchaseSeats: true,
+ changePlan: true,
+ purchaseAutopilotRuns: true,
+ });
+ expect(
+ resolveBillingRecovery({
+ actions: paidManager,
+ billingEnabled: true,
+ loading: false,
+ autopilotAddon: true,
+ }),
+ ).toBe("autopilot_addon");
+ // Other limit surfaces keep their previous recovery.
+ expect(
+ resolveBillingRecovery({
+ actions: paidManager,
+ billingEnabled: true,
+ loading: false,
+ }),
+ ).toBe("portal");
+ // Free or a no-card trial: upgrading still comes first.
+ expect(
+ resolveBillingRecovery({
+ actions: actions({ checkout: true, purchaseAutopilotRuns: true }),
+ billingEnabled: true,
+ loading: false,
+ autopilotAddon: true,
+ }),
+ ).toBe("checkout");
+ // past_due: Cloud withholds the add-on, so the portal is the way back.
+ expect(
+ resolveBillingRecovery({
+ actions: actions({ portal: true }),
+ billingEnabled: true,
+ loading: false,
+ autopilotAddon: true,
+ }),
+ ).toBe("portal");
+ // A member: nothing to buy.
+ expect(
+ resolveBillingRecovery({
+ actions: actions(),
+ billingEnabled: true,
+ loading: false,
+ autopilotAddon: true,
+ }),
+ ).toBe("contact_admin");
+ });
});
diff --git a/packages/core/billing/recovery.ts b/packages/core/billing/recovery.ts
index e21b2bc346..cf5573f866 100644
--- a/packages/core/billing/recovery.ts
+++ b/packages/core/billing/recovery.ts
@@ -3,6 +3,7 @@ import type { WorkspaceSubscriptionSummary } from "../types";
export type BillingRecoveryKind =
| "billing_disabled"
| "checkout"
+ | "autopilot_addon"
| "portal"
| "billing"
| "contact_admin"
@@ -15,24 +16,58 @@ type BillingActions = WorkspaceSubscriptionSummary["availableActions"];
* Resolve the one recovery state shared by every issue/quota-limit surface.
* Cloud's complete availableActions object is authoritative: callers must not
* infer checkout or portal access from a locally cached member role or plan.
+ *
+ * `autopilotAddon` is set by autopilot-quota surfaces: buying more runs then
+ * comes right after an upgrade from Free and before the Billing Portal, so a
+ * paying workspace that ran out is offered more runs, not only the portal.
*/
export function resolveBillingRecovery({
actions,
billingEnabled,
loading,
portalFailed = false,
+ autopilotAddon = false,
}: {
actions: BillingActions | undefined;
billingEnabled: boolean;
loading: boolean;
portalFailed?: boolean;
+ autopilotAddon?: boolean;
}): BillingRecoveryKind {
if (!billingEnabled) return "billing_disabled";
if (portalFailed) return "billing_unavailable";
if (actions?.checkout) return "checkout";
+ if (autopilotAddon && actions?.purchaseAutopilotRuns) return "autopilot_addon";
if (actions?.portal) return "portal";
if (actions?.purchaseSeats) return "billing";
if (actions) return "contact_admin";
if (loading) return "checking";
return "billing_unavailable";
}
+
+/**
+ * What a member without billing access should ask an admin for when the
+ * autopilot allowance runs out. Display only: the plan picks the wording,
+ * never an action.
+ */
+export type AutopilotQuotaAdminAsk = "upgrade" | "addon_or_upgrade" | "addon";
+
+export function autopilotQuotaAdminAsk(
+ summary: WorkspaceSubscriptionSummary | null | undefined,
+): AutopilotQuotaAdminAsk {
+ if (!summary?.autopilotAddon) return "upgrade";
+ return summary.entitlement.plan === "business" ? "addon" : "addon_or_upgrade";
+}
+
+/**
+ * Whether the add-on recovery also offers moving up to Business: Cloud allows
+ * a plan change and the workspace is on Pro.
+ */
+export function canUpgradeToBusinessFromAddon(
+ summary: WorkspaceSubscriptionSummary | null | undefined,
+): boolean {
+ return (
+ summary?.availableActions.changePlan === true &&
+ summary.entitlement.plan === "pro"
+ );
+}
diff --git a/packages/core/billing/trial.test.ts b/packages/core/billing/trial.test.ts
index e288e674c4..af75965619 100644
--- a/packages/core/billing/trial.test.ts
+++ b/packages/core/billing/trial.test.ts
@@ -38,7 +38,9 @@ function summary(
purchaseSeats: false,
changePlan: false,
checkPlanChange: false,
+ purchaseAutopilotRuns: false,
},
+ autopilotAddon: null,
planChange: null,
trial: trial
? {
diff --git a/packages/core/billing/workspace-subscription-mutations.ts b/packages/core/billing/workspace-subscription-mutations.ts
index 55a8ef331a..35c78eff6b 100644
--- a/packages/core/billing/workspace-subscription-mutations.ts
+++ b/packages/core/billing/workspace-subscription-mutations.ts
@@ -4,10 +4,12 @@ import type {
ChangeWorkspacePlanRequest,
CreateWorkspaceSubscriptionCheckoutRequest,
PreviewWorkspacePlanChangeRequest,
+ CreateWorkspaceAutopilotAddonCheckoutRequest,
PreviewWorkspaceSeatPurchaseRequest,
PurchaseWorkspaceSeatsRequest,
} from "../types";
import { workspaceSubscriptionKeys } from "./workspace-subscription-queries";
+import { autopilotKeys } from "../autopilots/queries";
export function useCreateWorkspaceSubscriptionCheckout(wsId: string) {
const queryClient = useQueryClient();
@@ -91,3 +93,27 @@ export function useCreateWorkspaceSubscriptionPortal(wsId: string) {
},
});
}
+
+/**
+ * Refresh everything a paid add-on changes: the summary and add-on reads
+ * (limit, this month's add-ons) and the autopilot usage meter.
+ */
+export function invalidateAfterAutopilotAddon(
+ queryClient: ReturnType<typeof useQueryClient>,
+ wsId: string,
+) {
+ void queryClient.invalidateQueries({
+ queryKey: workspaceSubscriptionKeys.all(wsId),
+ });
+ void queryClient.invalidateQueries({
+ queryKey: autopilotKeys.usage(wsId),
+ });
+}
+
+/** Start paying for autopilot add-on packs on Stripe Checkout. */
+export function useCreateWorkspaceAutopilotAddonCheckout() {
+ return useMutation({
+ mutationFn: (data: CreateWorkspaceAutopilotAddonCheckoutRequest) =>
+ api.createWorkspaceAutopilotAddonCheckout(data),
+ });
+}
diff --git a/packages/core/billing/workspace-subscription-queries.test.ts b/packages/core/billing/workspace-subscription-queries.test.ts
index f13a8ec06a..38ef3ae306 100644
--- a/packages/core/billing/workspace-subscription-queries.test.ts
+++ b/packages/core/billing/workspace-subscription-queries.test.ts
@@ -23,6 +23,7 @@ const planPrices = (monthAmount: number, yearAmount: number) =>
const validPrices = {
pro: planPrices(1_500, 14_400),
business: planPrices(3_000, 28_800),
+ autopilotAddon: null,
};
describe("workspace subscription price query", () => {
diff --git a/packages/core/billing/workspace-subscription-queries.ts b/packages/core/billing/workspace-subscription-queries.ts
index de4ed3efd6..a537c38243 100644
--- a/packages/core/billing/workspace-subscription-queries.ts
+++ b/packages/core/billing/workspace-subscription-queries.ts
@@ -19,6 +19,8 @@ export const workspaceSubscriptionKeys = {
[...workspaceSubscriptionKeys.all(wsId), "summary"] as const,
prices: (wsId: string) =>
[...workspaceSubscriptionKeys.all(wsId), "prices"] as const,
+ autopilotAddonCheckout: (wsId: string, sessionId: string) =>
+ [...workspaceSubscriptionKeys.all(wsId), "autopilot-addon-checkout", sessionId] as const,
};
/**
@@ -71,3 +73,17 @@ export function workspaceSubscriptionPricesOptions(wsId: string) {
retry: false,
});
}
+
+/**
+ * An add-on Checkout Session the payer came back from. Cloud records a paid
+ * session before answering, so this is also what confirms the purchase.
+ */
+export function workspaceAutopilotAddonCheckoutOptions(wsId: string, sessionId: string) {
+ return queryOptions({
+ queryKey: workspaceSubscriptionKeys.autopilotAddonCheckout(wsId, sessionId),
+ queryFn: () => api.getWorkspaceAutopilotAddonCheckout(sessionId),
+ enabled: wsId.length > 0 && sessionId.length > 0,
+ staleTime: 0,
+ retry: false,
+ });
+}
diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.ts
index 531c7cb2a7..960f9f145a 100644
--- a/packages/core/types/billing.ts
+++ b/packages/core/types/billing.ts
@@ -250,7 +250,18 @@ export interface WorkspaceSubscriptionSummary {
changePlan: boolean;
/** Ask Cloud to settle a plan change that is still confirming. */
checkPlanChange: boolean;
+ /**
+ * Buy autopilot run add-on packs for the current month. False on a cloud
+ * that predates add-ons.
+ */
+ purchaseAutopilotRuns: boolean;
};
+ /**
+ * This month's autopilot add-ons. Null on Free, without a subscription, and
+ * on a cloud that predates add-ons. `entitlement.limits.autopilotRuns`
+ * already includes `purchasedRuns`.
+ */
+ autopilotAddon: WorkspaceAutopilotAddonSummary | null;
/**
* A plan change that still holds the subscription. While present, seat
* purchases and other plan changes are unavailable.
@@ -323,10 +334,64 @@ export interface WorkspaceSubscriptionPlanPrices {
year: WorkspaceSubscriptionPrice;
}
-export type WorkspaceSubscriptionPrices = Record<
- WorkspaceSubscriptionPaidPlan,
- WorkspaceSubscriptionPlanPrices
->;
+export interface WorkspaceSubscriptionPrices {
+ pro: WorkspaceSubscriptionPlanPrices;
+ business: WorkspaceSubscriptionPlanPrices;
+ /**
+ * The one-time autopilot add-on pack. Null when Cloud does not sell one, or
+ * on a cloud that predates add-ons.
+ */
+ autopilotAddon: WorkspaceAutopilotAddonPrice | null;
+}
+
+/** Autopilot runs bought this month, valid until the month ends. */
+export interface WorkspaceAutopilotAddonSummary {
+ purchasedRuns: number;
+ periodStart: string;
+ periodEnd: string;
+}
+
+/** The price of one autopilot add-on pack. */
+export interface WorkspaceAutopilotAddonPrice {
+ currency: string;
+ /** Minor currency units per pack, e.g. 1000 for $10.00. */
+ unitAmount: number;
+ runsPerPack: number;
+}
+
+export interface CreateWorkspaceAutopilotAddonCheckoutRequest {
+ packs: number;
+ /** The pack price the payer saw; Cloud refuses a checkout at another price. */
+ expectedUnitAmount: number;
+ currency: string;
+ idempotencyKey: string;
+}
+
+export interface CreateWorkspaceAutopilotAddonCheckoutResponse {
+ sessionId: string;
+ /** Stripe Checkout page the payer completes the payment on. */
+ url: string;
+}
+
+/**
+ * paid: the runs are in this month's limit. open: Stripe has not finished the
+ * payment yet. unpaid: the session completed without a payment. expired: the
+ * payer left and nothing was charged.
+ */
+export type WorkspaceAutopilotAddonCheckoutStatus =
+ | "paid"
+ | "open"
+ | "unpaid"
+ | "expired";
+
+export interface WorkspaceAutopilotAddonCheckout {
+ sessionId: string;
+ status: WorkspaceAutopilotAddonCheckoutStatus;
+ packs: number;
+ runs: number;
+ currency: string;
+ amount: number;
+}
export interface CreateWorkspaceSubscriptionCheckoutRequest {
plan: WorkspaceSubscriptionPaidPlan;
@@ -407,6 +472,11 @@ export interface WorkspacePlanChangePreview {
/** True when the proration is invoiced immediately (upgrades). */
invoiceNow: boolean;
quotedAt: string;
+ /**
+ * The monthly autopilot run limit right after the change, including this
+ * month's add-ons. Null on a cloud that predates add-ons.
+ */
+ autopilotRunsLimitAfter: number | null;
}
export interface ChangeWorkspacePlanRequest {
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 0701b7e7c8..e30a56161f 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -416,6 +416,12 @@ export type {
WorkspaceSubscriptionPrice,
WorkspaceSubscriptionPlanPrices,
WorkspaceSubscriptionPrices,
+ WorkspaceAutopilotAddonSummary,
+ WorkspaceAutopilotAddonPrice,
+ CreateWorkspaceAutopilotAddonCheckoutRequest,
+ CreateWorkspaceAutopilotAddonCheckoutResponse,
+ WorkspaceAutopilotAddonCheckoutStatus,
+ WorkspaceAutopilotAddonCheckout,
WorkspacePlanChangeHold,
WorkspaceTrial,
WorkspaceTrialState,
diff --git a/packages/views/billing/autopilot-addon-dialog.test.tsx b/packages/views/billing/autopilot-addon-dialog.test.tsx
new file mode 100644
index 0000000000..608c0658ac
--- /dev/null
+++ b/packages/views/billing/autopilot-addon-dialog.test.tsx
@@ -0,0 +1,142 @@
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enBilling from "../locales/en/billing.json";
+
+const apiMock = vi.hoisted(() => ({
+ getWorkspaceSubscriptionPrices: vi.fn(),
+ createWorkspaceAutopilotAddonCheckout: vi.fn(),
+ getAutopilotQuotaUsage: vi.fn(),
+}));
+const mockOpenExternal = vi.hoisted(() => vi.fn());
+
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api: apiMock,
+}));
+
+vi.mock("../platform", () => ({ openExternal: mockOpenExternal }));
+
+import { ApiError } from "@multica/core/api";
+import { AutopilotAddonDialog } from "./autopilot-addon-dialog";
+
+const recurring = (unitAmount: number, interval: "month" | "year") => ({
+ currency: "usd",
+ unitAmount,
+ interval,
+ intervalCount: 1,
+});
+
+const prices = (addon: unknown = { currency: "usd", unitAmount: 1000, runsPerPack: 1000 }) => ({
+ pro: { month: recurring(1500, "month"), year: recurring(14400, "year") },
+ business: { month: recurring(3000, "month"), year: recurring(28800, "year") },
+ autopilotAddon: addon,
+});
+
+function renderDialog() {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ render(
+ <I18nProvider locale="en" resources={{ en: { billing: enBilling } }}>
+ <QueryClientProvider client={client}>
+ <AutopilotAddonDialog wsId="ws-1" open onOpenChange={vi.fn()} />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+}
+
+describe("AutopilotAddonDialog", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ apiMock.getWorkspaceSubscriptionPrices.mockResolvedValue(prices());
+ apiMock.getAutopilotQuotaUsage.mockResolvedValue({
+ action: "enforce",
+ used: 12000,
+ reserved: 0,
+ total: 12000,
+ limit: 12000,
+ reached: true,
+ period_start: "2026-11-01T00:00:00Z",
+ period_end: "2026-12-01T00:00:00Z",
+ reset_at: "2026-12-01T00:00:00Z",
+ blocked_counts: {},
+ });
+ });
+
+ afterEach(cleanup);
+
+ it("sends the chosen packs at the shown price to Stripe Checkout", async () => {
+ apiMock.createWorkspaceAutopilotAddonCheckout.mockResolvedValue({
+ sessionId: "cs_test_1",
+ url: "https://checkout.stripe.com/c/pay/cs_test_1",
+ });
+ const user = userEvent.setup();
+ renderDialog();
+
+ expect(await screen.findByRole("radio", { name: /1,000 runs/ })).toHaveAttribute("aria-checked", "true");
+ expect(screen.getByText(/12,000 \/ 12,000 used this month/)).toBeInTheDocument();
+ // No auto top-up and no in-app card charge in the first release.
+ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole("radio", { name: /3,000 runs/ }));
+ await user.click(screen.getByRole("button", { name: "Continue to pay $30.00" }));
+
+ await waitFor(() =>
+ expect(mockOpenExternal).toHaveBeenCalledWith("https://checkout.stripe.com/c/pay/cs_test_1", {
+ webTarget: "same-tab",
+ }),
+ );
+ const request = apiMock.createWorkspaceAutopilotAddonCheckout.mock.calls[0]?.[0];
+ expect(request).toMatchObject({ packs: 3, expectedUnitAmount: 1000, currency: "usd" });
+ expect(request.idempotencyKey).toMatch(/^autopilot-addon-ws-1-/);
+ });
+
+ it("retries a failed request with the same key so it returns the same session", async () => {
+ apiMock.createWorkspaceAutopilotAddonCheckout
+ .mockRejectedValueOnce(new ApiError("unavailable", 503, "Service Unavailable"))
+ .mockResolvedValueOnce({ sessionId: "cs_test_1", url: "https://checkout.stripe.com/c/pay/cs_test_1" });
+ const user = userEvent.setup();
+ renderDialog();
+
+ await user.click(await screen.findByRole("button", { name: "Continue to pay $10.00" }));
+ expect(await screen.findByText("The payment page couldn't be opened. Try again.")).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Continue to pay $10.00" }));
+ await waitFor(() => expect(mockOpenExternal).toHaveBeenCalledTimes(1));
+
+ const [first, second] = apiMock.createWorkspaceAutopilotAddonCheckout.mock.calls.map(
+ (call) => call[0].idempotencyKey,
+ );
+ expect(second).toBe(first);
+ });
+
+ it("explains a refused checkout and starts over with a new key", async () => {
+ apiMock.createWorkspaceAutopilotAddonCheckout
+ .mockRejectedValueOnce(new ApiError("not purchasable", 409, "Conflict"))
+ .mockResolvedValueOnce({ sessionId: "cs_test_2", url: "https://checkout.stripe.com/c/pay/cs_test_2" });
+ const user = userEvent.setup();
+ renderDialog();
+
+ await user.click(await screen.findByRole("button", { name: "Continue to pay $10.00" }));
+ expect(await screen.findByText(/can't be bought right now, or the price changed/)).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Continue to pay $10.00" }));
+ await waitFor(() => expect(mockOpenExternal).toHaveBeenCalledTimes(1));
+
+ const [first, second] = apiMock.createWorkspaceAutopilotAddonCheckout.mock.calls.map(
+ (call) => call[0].idempotencyKey,
+ );
+ expect(second).not.toBe(first);
+ });
+
+ it("offers no purchase when Cloud sells no add-on", async () => {
+ apiMock.getWorkspaceSubscriptionPrices.mockResolvedValue(prices(null));
+ renderDialog();
+
+ expect(
+ await screen.findByText("This workspace can't buy add-on runs right now."),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Continue to payment" })).toBeDisabled();
+ });
+});
diff --git a/packages/views/billing/autopilot-addon-dialog.tsx b/packages/views/billing/autopilot-addon-dialog.tsx
new file mode 100644
index 0000000000..7b94a72ffa
--- /dev/null
+++ b/packages/views/billing/autopilot-addon-dialog.tsx
@@ -0,0 +1,220 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { AlertCircle, ExternalLink, Loader2 } from "@multica/ui/icons";
+import { ApiError } from "@multica/core/api";
+import { autopilotQuotaUsageOptions } from "@multica/core/autopilots";
+import {
+ useCreateWorkspaceAutopilotAddonCheckout,
+ workspaceSubscriptionPricesOptions,
+} from "@multica/core/billing";
+import { Alert, AlertDescription } from "@multica/ui/components/ui/alert";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import { cn } from "@multica/ui/lib/utils";
+import { useLocale, useT } from "../i18n";
+import { openExternal } from "../platform";
+import { formatStripeMinorAmount } from "../settings/components/billing-format";
+
+/** Pack counts the dialog offers; Cloud accepts up to ten. */
+export const AUTOPILOT_ADDON_PACK_OPTIONS = [1, 3, 5] as const;
+
+function createAddonIdempotencyKey(wsId: string): string {
+ const suffix =
+ globalThis.crypto?.randomUUID?.() ??
+ `${Date.now()}-${Math.random().toString(36).slice(2)}`;
+ return `autopilot-addon-${wsId}-${suffix}`.slice(0, 200);
+}
+
+/**
+ * Pick autopilot run add-on packs for the current month, then pay for them on
+ * Stripe Checkout. Stripe handles the card, authentication and declines;
+ * nothing is charged until the payer completes Stripe's page, and the Billing
+ * return confirms the runs.
+ *
+ * Only rendered for managers whose summary allows `purchaseAutopilotRuns`;
+ * Cloud authorizes the purchase again.
+ */
+export function AutopilotAddonDialog({
+ wsId,
+ open,
+ onOpenChange,
+}: {
+ wsId: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const { t } = useT("billing");
+ const locale = useLocale();
+ const pricesQuery = useQuery({
+ ...workspaceSubscriptionPricesOptions(wsId),
+ enabled: open && wsId.length > 0,
+ });
+ const usageQuery = useQuery({
+ ...autopilotQuotaUsageOptions(wsId),
+ enabled: open && wsId.length > 0,
+ });
+ const checkout = useCreateWorkspaceAutopilotAddonCheckout();
+ const [packs, setPacks] = useState<number>(AUTOPILOT_ADDON_PACK_OPTIONS[0]);
+ const [error, setError] = useState<string | null>(null);
+ // One key per pack choice while the dialog is open, so a double click or a
+ // retry after a lost response returns the same Checkout Session.
+ const intentRef = useRef<{ packs: number; key: string } | null>(null);
+
+ useEffect(() => {
+ if (!open) return;
+ setPacks(AUTOPILOT_ADDON_PACK_OPTIONS[0]);
+ setError(null);
+ intentRef.current = null;
+ }, [open, wsId]);
+
+ const price = pricesQuery.data?.autopilotAddon ?? null;
+ const amountFor = (count: number) =>
+ price ? formatStripeMinorAmount(price.unitAmount * count, price.currency, locale) : null;
+ const selectedAmount = amountFor(packs);
+ const numberFormatter = new Intl.NumberFormat(locale);
+ const usage = usageQuery.data;
+ const resetDate = usage?.reset_at
+ ? new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(new Date(usage.reset_at))
+ : null;
+ const usedLine =
+ usage && usage.action !== "off" && usage.total !== null && usage.limit !== null && resetDate
+ ? t(($) => $.autopilot_addon.usage_summary, {
+ used: numberFormatter.format(usage.total),
+ limit: numberFormatter.format(usage.limit),
+ date: resetDate,
+ })
+ : null;
+
+ const submit = async () => {
+ if (!price) return;
+ if (intentRef.current?.packs !== packs) {
+ intentRef.current = { packs, key: createAddonIdempotencyKey(wsId) };
+ }
+ setError(null);
+ try {
+ const session = await checkout.mutateAsync({
+ packs,
+ expectedUnitAmount: price.unitAmount,
+ currency: price.currency,
+ idempotencyKey: intentRef.current.key,
+ });
+ if (!session?.url) {
+ setError(t(($) => $.autopilot_addon.error));
+ return;
+ }
+ openExternal(session.url, { webTarget: "same-tab" });
+ } catch (err) {
+ if (err instanceof ApiError && (err.status === 409 || err.status === 403)) {
+ intentRef.current = null;
+ void pricesQuery.refetch();
+ setError(t(($) => $.autopilot_addon.conflict));
+ return;
+ }
+ setError(t(($) => $.autopilot_addon.error));
+ }
+ };
+
+ const busy = checkout.isPending;
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => !busy && onOpenChange(next)}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>{t(($) => $.autopilot_addon.title)}</DialogTitle>
+ <DialogDescription>{t(($) => $.autopilot_addon.description)}</DialogDescription>
+ </DialogHeader>
+
+ {pricesQuery.isPending ? (
+ <p className="flex items-center gap-2 text-body text-muted-foreground" role="status">
+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
+ {t(($) => $.autopilot_addon.loading)}
+ </p>
+ ) : !price ? (
+ <Alert variant="destructive">
+ <AlertCircle />
+ <AlertDescription>{t(($) => $.autopilot_addon.unavailable)}</AlertDescription>
+ </Alert>
+ ) : (
+ <div className="space-y-4">
+ <div
+ role="radiogroup"
+ aria-label={t(($) => $.autopilot_addon.options_label)}
+ className="space-y-2"
+ >
+ {AUTOPILOT_ADDON_PACK_OPTIONS.map((count) => {
+ const selected = count === packs;
+ return (
+ <button
+ key={count}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ disabled={busy}
+ onClick={() => setPacks(count)}
+ className={cn(
+ "flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left text-body transition-colors",
+ selected
+ ? "border-foreground"
+ : "border-surface-border hover:bg-accent/50",
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ "flex size-4 shrink-0 items-center justify-center rounded-full border",
+ selected ? "border-foreground" : "border-muted-foreground/50",
+ )}
+ >
+ {selected ? <span className="size-2 rounded-full bg-foreground" /> : null}
+ </span>
+ <span className="flex-1 tabular-nums">
+ {t(($) => $.autopilot_addon.option, {
+ runs: numberFormatter.format(count * price.runsPerPack),
+ })}
+ </span>
+ <span className="tabular-nums">{amountFor(count)}</span>
+ </button>
+ );
+ })}
+ </div>
+ {usedLine ? (
+ <p className="text-caption leading-5 text-muted-foreground tabular-nums">{usedLine}</p>
+ ) : null}
+ </div>
+ )}
+
+ {error ? (
+ <Alert variant="destructive">
+ <AlertCircle />
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ ) : null}
+
+ <DialogFooter>
+ <Button variant="outline" disabled={busy} onClick={() => onOpenChange(false)}>
+ {t(($) => $.autopilot_addon.cancel)}
+ </Button>
+ <Button disabled={busy || !price} onClick={() => void submit()}>
+ {busy ? (
+ <Loader2 className="animate-spin motion-reduce:animate-none" />
+ ) : (
+ <ExternalLink />
+ )}
+ {selectedAmount !== null
+ ? t(($) => $.autopilot_addon.pay, { amount: selectedAmount })
+ : t(($) => $.autopilot_addon.pay_fallback)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/packages/views/billing/autopilot-addon-return-notice.test.tsx b/packages/views/billing/autopilot-addon-return-notice.test.tsx
new file mode 100644
index 0000000000..b3a01cf9af
--- /dev/null
+++ b/packages/views/billing/autopilot-addon-return-notice.test.tsx
@@ -0,0 +1,66 @@
+import { cleanup, render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enBilling from "../locales/en/billing.json";
+
+const apiMock = vi.hoisted(() => ({
+ getWorkspaceAutopilotAddonCheckout: vi.fn(),
+}));
+
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api: apiMock,
+}));
+
+import { AutopilotAddonReturnNotice } from "./autopilot-addon-return-notice";
+
+const session = (status: string) => ({
+ sessionId: "cs_test_1",
+ status,
+ packs: 3,
+ runs: 3000,
+ currency: "usd",
+ amount: 3000,
+});
+
+function renderNotice(sessionId: string | null) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const invalidate = vi.spyOn(client, "invalidateQueries");
+ render(
+ <I18nProvider locale="en" resources={{ en: { billing: enBilling } }}>
+ <QueryClientProvider client={client}>
+ <AutopilotAddonReturnNotice wsId="ws-1" sessionId={sessionId} />
+ </QueryClientProvider>
+ </I18nProvider>,
+ );
+ return { invalidate };
+}
+
+describe("AutopilotAddonReturnNotice", () => {
+ beforeEach(() => vi.clearAllMocks());
+ afterEach(cleanup);
+
+ it("confirms a paid session and refreshes the limit and usage", async () => {
+ apiMock.getWorkspaceAutopilotAddonCheckout.mockResolvedValue(session("paid"));
+ const { invalidate } = renderNotice("cs_test_1");
+
+ expect(await screen.findByText("Runs added")).toBeInTheDocument();
+ expect(screen.getByText(/3,000 runs were added/)).toBeInTheDocument();
+ expect(apiMock.getWorkspaceAutopilotAddonCheckout).toHaveBeenCalledWith("cs_test_1");
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ["workspace-subscriptions", "ws-1"] });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: ["autopilots", "ws-1", "usage"] });
+ });
+
+ it("says nothing was charged for an expired session", async () => {
+ apiMock.getWorkspaceAutopilotAddonCheckout.mockResolvedValue(session("expired"));
+ renderNotice("cs_test_1");
+ expect(await screen.findByText("Payment not completed")).toBeInTheDocument();
+ });
+
+ it("claims no outcome without a session to read", () => {
+ renderNotice("not-a-session");
+ expect(screen.getByText("Confirming the payment")).toBeInTheDocument();
+ expect(apiMock.getWorkspaceAutopilotAddonCheckout).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/billing/autopilot-addon-return-notice.tsx b/packages/views/billing/autopilot-addon-return-notice.tsx
new file mode 100644
index 0000000000..fad805d4ff
--- /dev/null
+++ b/packages/views/billing/autopilot-addon-return-notice.tsx
@@ -0,0 +1,87 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { AlertCircle, CheckCircle2, Loader2 } from "@multica/ui/icons";
+import {
+ invalidateAfterAutopilotAddon,
+ workspaceAutopilotAddonCheckoutOptions,
+} from "@multica/core/billing";
+import { Alert, AlertDescription, AlertTitle } from "@multica/ui/components/ui/alert";
+import { useLocale, useT } from "../i18n";
+
+const POLL_INTERVAL_MS = 2_000;
+const POLL_TIMEOUT_MS = 60_000;
+// Stripe Checkout Session IDs: `cs_` plus letters, digits and underscores.
+const SESSION_ID_RE = /^cs_[A-Za-z0-9_]+$/;
+
+/**
+ * Billing banner after the payer returns from an add-on Stripe Checkout.
+ * Reading the session is what confirms it: Cloud records a paid session
+ * before answering, and Multica then makes every API instance read the raised
+ * limit, so the next autopilot run is admitted. While Stripe is still
+ * finishing, the session is read again for a short while.
+ */
+export function AutopilotAddonReturnNotice({
+ wsId,
+ sessionId: rawSessionId,
+}: {
+ wsId: string;
+ sessionId: string | null;
+}) {
+ const sessionId = rawSessionId && SESSION_ID_RE.test(rawSessionId) ? rawSessionId : null;
+ const { t } = useT("billing");
+ const locale = useLocale();
+ const queryClient = useQueryClient();
+ const [startedAt] = useState(() => Date.now());
+ const sessionQuery = useQuery({
+ ...workspaceAutopilotAddonCheckoutOptions(wsId, sessionId ?? ""),
+ refetchInterval: (query) =>
+ query.state.data?.status === "open" && Date.now() - startedAt < POLL_TIMEOUT_MS
+ ? POLL_INTERVAL_MS
+ : false,
+ });
+ const status = sessionQuery.data?.status;
+ const invalidatedRef = useRef(false);
+
+ useEffect(() => {
+ if (status !== "paid" || invalidatedRef.current) return;
+ invalidatedRef.current = true;
+ invalidateAfterAutopilotAddon(queryClient, wsId);
+ }, [queryClient, status, wsId]);
+
+ if (status === "paid" && sessionQuery.data) {
+ return (
+ <Alert>
+ <CheckCircle2 />
+ <AlertTitle>{t(($) => $.autopilot_addon.success_title)}</AlertTitle>
+ <AlertDescription>
+ {t(($) => $.autopilot_addon.success_description, {
+ runs: new Intl.NumberFormat(locale).format(sessionQuery.data.runs),
+ })}
+ </AlertDescription>
+ </Alert>
+ );
+ }
+ if (status === "expired" || status === "unpaid") {
+ return (
+ <Alert>
+ <AlertCircle />
+ <AlertTitle>{t(($) => $.autopilot_addon.not_paid_title)}</AlertTitle>
+ <AlertDescription>{t(($) => $.autopilot_addon.not_paid_description)}</AlertDescription>
+ </Alert>
+ );
+ }
+ // No session to read (a sign-in detour drops it), a read that failed, or a
+ // payment Stripe has not finished within the wait: the webhook still adds
+ // the runs, so point at the usage instead of claiming an outcome.
+ const waiting = sessionId !== null && !sessionQuery.isError &&
+ (sessionQuery.isPending || (status === "open" && Date.now() - startedAt < POLL_TIMEOUT_MS));
+ return (
+ <Alert>
+ {waiting ? <Loader2 className="animate-spin motion-reduce:animate-none" /> : <AlertCircle />}
+ <AlertTitle>{t(($) => $.autopilot_addon.confirming_title)}</AlertTitle>
+ <AlertDescription>{t(($) => $.autopilot_addon.confirming_description)}</AlertDescription>
+ </Alert>
+ );
+}
diff --git a/packages/views/billing/billing-return-page.test.tsx b/packages/views/billing/billing-return-page.test.tsx
index 91c3e4a21c..76bc6d8931 100644
--- a/packages/views/billing/billing-return-page.test.tsx
+++ b/packages/views/billing/billing-return-page.test.tsx
@@ -121,6 +121,32 @@ describe("BillingReturnPage", () => {
);
});
+ it("forwards an add-on return with its Checkout Session so Billing can confirm it", async () => {
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=autopilot_addon&session_id=cs_test_42");
+ await waitFor(() =>
+ expect(mockReplace).toHaveBeenCalledWith(
+ "/acme/settings?tab=billing&result=autopilot_addon&session_id=cs_test_42",
+ ),
+ );
+
+ // Anything but a Stripe session ID shape is dropped.
+ mockReplace.mockReset();
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=autopilot_addon&session_id=../x&y");
+ await waitFor(() =>
+ expect(mockReplace).toHaveBeenCalledWith(
+ "/acme/settings?tab=billing&result=autopilot_addon",
+ ),
+ );
+
+ mockReplace.mockReset();
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=autopilot_addon_cancel&session_id=cs_test_42");
+ await waitFor(() =>
+ expect(mockReplace).toHaveBeenCalledWith(
+ "/acme/settings?tab=billing&result=autopilot_addon_cancel",
+ ),
+ );
+ });
+
// Only `workspace_id` and `result` are read, and the destination is rebuilt
// from paths — so a hand-crafted return link cannot redirect off-app.
it("ignores an unrecognized result instead of forwarding it", async () => {
diff --git a/packages/views/billing/billing-return-page.tsx b/packages/views/billing/billing-return-page.tsx
index db8f183ec5..056cc94ece 100644
--- a/packages/views/billing/billing-return-page.tsx
+++ b/packages/views/billing/billing-return-page.tsx
@@ -33,7 +33,16 @@ import { useT } from "../i18n";
* short message, so the failure states below say what happened.
*/
-const RESULT_VALUES = new Set(["success", "cancel", "portal"]);
+const RESULT_VALUES = new Set([
+ "success",
+ "cancel",
+ "portal",
+ "autopilot_addon",
+ "autopilot_addon_cancel",
+]);
+// An add-on return carries its Checkout Session so Billing can confirm the
+// payment at once. Only Stripe's ID shape is forwarded.
+const SESSION_ID_RE = /^cs_[A-Za-z0-9_]+$/;
// Same shape check the rest of core uses for route UUIDs. Only a well-formed ID
// is worth carrying anywhere, and this one can end up in a third-party OAuth
// state on the login detour below.
@@ -50,6 +59,11 @@ export function BillingReturnPage() {
workspaceIdRaw && UUID_RE.test(workspaceIdRaw) ? workspaceIdRaw : null;
const resultParam = navigation.searchParams.get("result");
const result = resultParam && RESULT_VALUES.has(resultParam) ? resultParam : null;
+ const sessionIdParam = navigation.searchParams.get("session_id");
+ const addonSessionId =
+ result === "autopilot_addon" && sessionIdParam && SESSION_ID_RE.test(sessionIdParam)
+ ? sessionIdParam
+ : null;
const {
data: workspaces,
@@ -97,11 +111,12 @@ export function BillingReturnPage() {
const destination = `${paths.workspace(match.slug).settings()}?tab=billing${
result ? `&result=${result}` : ""
- }`;
+ }${addonSessionId ? `&session_id=${addonSessionId}` : ""}`;
// replace(), not push(): the Stripe hop should not sit in history where a
// back navigation would re-run this redirect.
navigation.replace(destination);
}, [
+ addonSessionId,
isAuthLoading,
isWorkspacesError,
isWorkspacesPending,
diff --git a/packages/views/inbox/components/autopilot-quota-notice.test.tsx b/packages/views/inbox/components/autopilot-quota-notice.test.tsx
index 56b66f9fb4..70a921f209 100644
--- a/packages/views/inbox/components/autopilot-quota-notice.test.tsx
+++ b/packages/views/inbox/components/autopilot-quota-notice.test.tsx
@@ -1,9 +1,52 @@
+import type { ReactElement } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
-import { describe, expect, it, vi } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import type { InboxItem } from "@multica/core/types";
import en from "../../locales/en/inbox.json";
+
+const billingState = vi.hoisted(() => ({
+ enabled: true,
+ summary: null as null | {
+ availableActions: Record<string, boolean>;
+ entitlement: { plan: string };
+ autopilotAddon: { purchasedRuns: number } | null;
+ },
+}));
+
+vi.mock("@multica/core/config", () => ({
+ useFeatureEnabled: () => billingState.enabled,
+}));
+
+vi.mock("@multica/core/billing", () => ({
+ workspaceSubscriptionSummaryOptions: (wsId: string) => ({
+ queryKey: ["workspace-subscriptions", wsId, "summary"],
+ queryFn: async () => billingState.summary,
+ }),
+}));
+
+vi.mock("../../billing/autopilot-addon-dialog", () => ({
+ AutopilotAddonDialog: ({ open }: { open: boolean }) =>
+ open ? <div role="dialog" aria-label="Buy more automation runs" /> : null,
+}));
+
import { AutopilotQuotaNotice } from "./autopilot-quota-notice";
+function renderNotice(ui: ReactElement) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return render(<QueryClientProvider client={client}>{ui}</QueryClientProvider>);
+}
+
+const allowed = (overrides: Record<string, boolean> = {}) => ({
+ checkout: false,
+ portal: false,
+ purchaseSeats: false,
+ changePlan: false,
+ checkPlanChange: false,
+ purchaseAutopilotRuns: false,
+ ...overrides,
+});
+
vi.mock("../../i18n", () => ({
useT: () => ({
t: (accessor: (dict: unknown) => string, params?: Record<string, string>) => {
@@ -43,10 +86,16 @@ function item(overrides: Partial<InboxItem> = {}): InboxItem {
}
describe("AutopilotQuotaNotice", () => {
+ beforeEach(() => {
+ billingState.enabled = true;
+ billingState.summary = null;
+ });
+
it("shows localized rejection facts and opens the shared recovery surface", () => {
+ billingState.enabled = false;
const onOpenRecovery = vi.fn();
- render(
+ renderNotice(
<AutopilotQuotaNotice
item={item()}
onOpenRecovery={onOpenRecovery}
@@ -54,12 +103,57 @@ describe("AutopilotQuotaNotice", () => {
);
expect(screen.getByText(/limit of 100 autopilot runs/)).toBeInTheDocument();
- fireEvent.click(screen.getByRole("button", { name: "View upgrade options" }));
+ expect(screen.getByText(/upgrades or buys more runs/)).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "View options" }));
+ expect(onOpenRecovery).toHaveBeenCalledOnce();
+ });
+
+ it("offers an upgrade to a Free manager", async () => {
+ billingState.summary = {
+ availableActions: allowed({ checkout: true }),
+ entitlement: { plan: "free" },
+ autopilotAddon: null,
+ };
+ const onOpenRecovery = vi.fn();
+ renderNotice(<AutopilotQuotaNotice item={item()} onOpenRecovery={onOpenRecovery} />);
+
+ fireEvent.click(await screen.findByRole("button", { name: "Upgrade" }));
expect(onOpenRecovery).toHaveBeenCalledOnce();
});
+ it("opens the add-on purchase for a paid manager", async () => {
+ billingState.summary = {
+ availableActions: allowed({ portal: true, purchaseAutopilotRuns: true }),
+ entitlement: { plan: "pro" },
+ autopilotAddon: { purchasedRuns: 0 },
+ };
+ const onOpenRecovery = vi.fn();
+ renderNotice(<AutopilotQuotaNotice item={item()} onOpenRecovery={onOpenRecovery} />);
+
+ fireEvent.click(await screen.findByRole("button", { name: "Buy more runs" }));
+ expect(screen.getByRole("dialog", { name: "Buy more automation runs" })).toBeInTheDocument();
+ expect(onOpenRecovery).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["free", null, "Ask a workspace owner or admin to upgrade the plan."],
+ ["pro", { purchasedRuns: 0 }, "Ask a workspace owner or admin to buy more runs or upgrade the plan."],
+ ["business", { purchasedRuns: 0 }, "Ask a workspace owner or admin to buy more runs."],
+ ])("tells a %s member who to ask, without a button", async (plan, autopilotAddon, text) => {
+ billingState.summary = {
+ availableActions: allowed(),
+ entitlement: { plan },
+ autopilotAddon,
+ };
+ renderNotice(<AutopilotQuotaNotice item={item()} onOpenRecovery={vi.fn()} />);
+
+ expect(await screen.findByText(text)).toBeInTheDocument();
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ });
+
it("keeps the first blocked autopilot out of the workspace-level body", () => {
- render(
+ billingState.enabled = false;
+ renderNotice(
<AutopilotQuotaNotice
item={item({
details: {
@@ -74,6 +168,6 @@ describe("AutopilotQuotaNotice", () => {
expect(screen.queryByText(/Daily triage/)).not.toBeInTheDocument();
expect(screen.getByText(/limit of 100 autopilot runs/)).toBeInTheDocument();
- expect(screen.getByRole("button", { name: "View upgrade options" })).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "View options" })).toBeInTheDocument();
});
});
diff --git a/packages/views/inbox/components/autopilot-quota-notice.tsx b/packages/views/inbox/components/autopilot-quota-notice.tsx
index aed08cd615..b5bb20cdfe 100644
--- a/packages/views/inbox/components/autopilot-quota-notice.tsx
+++ b/packages/views/inbox/components/autopilot-quota-notice.tsx
@@ -1,7 +1,17 @@
"use client";
+import { useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { workspaceSubscriptionSummaryOptions } from "@multica/core/billing";
+import {
+ autopilotQuotaAdminAsk,
+ resolveBillingRecovery,
+} from "@multica/core/billing/recovery";
+import { useFeatureEnabled } from "@multica/core/config";
+import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";
import type { InboxItem } from "@multica/core/types";
import { Button } from "@multica/ui/components/ui/button";
+import { AutopilotAddonDialog } from "../../billing/autopilot-addon-dialog";
import { useT } from "../../i18n";
function formatResetAt(value: string | undefined): string {
@@ -14,6 +24,11 @@ function formatResetAt(value: string | undefined): string {
}).format(date);
}
+/**
+ * The workspace ran out of autopilot runs. The recovery action follows
+ * Cloud's billing actions for this reader: upgrade from Free, buy more runs on
+ * a paid plan, or, for a member without billing access, who to ask.
+ */
export function AutopilotQuotaNotice({
item,
onOpenRecovery,
@@ -22,6 +37,16 @@ export function AutopilotQuotaNotice({
onOpenRecovery: () => void;
}) {
const { t } = useT("inbox");
+ const wsId = item.workspace_id;
+ const billingEnabled = useFeatureEnabled(
+ BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG,
+ false,
+ );
+ const summaryQuery = useQuery({
+ ...workspaceSubscriptionSummaryOptions(wsId),
+ enabled: billingEnabled && wsId.length > 0,
+ });
+ const [addonOpen, setAddonOpen] = useState(false);
const details = item.details ?? {};
const resetAt = formatResetAt(details.reset_at);
@@ -33,6 +58,39 @@ export function AutopilotQuotaNotice({
});
}
+ const summary = summaryQuery.data;
+ const recovery = resolveBillingRecovery({
+ actions: summary?.availableActions,
+ billingEnabled,
+ loading: billingEnabled && !summary && summaryQuery.isFetching,
+ autopilotAddon: true,
+ });
+ const adminAsk = autopilotQuotaAdminAsk(summary);
+
+ let action: { label: string; onClick: () => void } | null = null;
+ let note: string | null = null;
+ switch (recovery) {
+ case "checkout":
+ action = { label: t(($) => $.detail.autopilot_quota_upgrade_action), onClick: onOpenRecovery };
+ break;
+ case "autopilot_addon":
+ action = { label: t(($) => $.detail.autopilot_quota_addon_action), onClick: () => setAddonOpen(true) };
+ break;
+ case "portal":
+ action = { label: t(($) => $.detail.autopilot_quota_portal_action), onClick: onOpenRecovery };
+ break;
+ case "contact_admin":
+ note =
+ adminAsk === "addon"
+ ? t(($) => $.detail.autopilot_quota_contact_addon)
+ : adminAsk === "addon_or_upgrade"
+ ? t(($) => $.detail.autopilot_quota_contact_addon_or_upgrade)
+ : t(($) => $.detail.autopilot_quota_contact_upgrade);
+ break;
+ default:
+ action = { label: t(($) => $.detail.autopilot_quota_upgrade), onClick: onOpenRecovery };
+ }
+
return (
<>
{body && (
@@ -40,9 +98,17 @@ export function AutopilotQuotaNotice({
{body}
</div>
)}
- <Button className="mt-4" size="sm" onClick={onOpenRecovery}>
- {t(($) => $.detail.autopilot_quota_upgrade)}
- </Button>
+ {note ? (
+ <p className="mt-4 text-body text-muted-foreground">{note}</p>
+ ) : null}
+ {action ? (
+ <Button className="mt-4" size="sm" onClick={action.onClick}>
+ {action.label}
+ </Button>
+ ) : null}
+ {addonOpen ? (
+ <AutopilotAddonDialog wsId={wsId} open={addonOpen} onOpenChange={setAddonOpen} />
+ ) : null}
</>
);
}
diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.json
index 937757c411..f41ab1a49d 100644
--- a/packages/views/locales/en/billing.json
+++ b/packages/views/locales/en/billing.json
@@ -142,7 +142,14 @@
"metering": "Runs from schedules, webhooks, and agents count. Runs a member starts with Run now don't.",
"storage": "Attachment storage",
"storage_description": "Attachments in issues, comments, and chat.",
- "storage_label": "Attachment storage usage"
+ "storage_label": "Attachment storage usage",
+ "addon": "Add-on runs",
+ "addon_description": "When the allowance runs out, automations pause until next month or until you buy more runs.",
+ "addon_included": "Includes {{runs}} add-on runs",
+ "addon_none": "None this month",
+ "addon_purchased": "{{runs}} bought this month",
+ "addon_buy": "Buy · {{price}} / {{runs}} runs",
+ "addon_buy_fallback": "Buy more runs"
},
"seats": {
"title": "Seats",
@@ -225,7 +232,9 @@
"success_title": "Plan changed",
"success_description": "This workspace is now on {{plan}}.",
"unresolved": "The previous plan change could not be confirmed. Contact support before changing plans.",
- "check_failed": "Could not check the plan change. Try again."
+ "check_failed": "Could not check the plan change. Try again.",
+ "addon_downgrade_notice": "This month's limit becomes {{limit}} runs after the switch, including runs you bought. {{used}} runs are used this month.",
+ "addon_downgrade_notice_limit_only": "This month's limit becomes {{limit}} runs after the switch, including runs you bought."
},
"confirm": {
"title": "Continue to Stripe Checkout?",
@@ -347,5 +356,27 @@
"admin_body_no_figures": "Attachment storage is full. Existing attachments aren't affected.",
"member_body": "Attachment storage is full. Ask an admin to upgrade the plan, or delete attachments you no longer need.",
"dismiss": "Dismiss"
+ },
+ "autopilot_addon": {
+ "title": "Buy more automation runs",
+ "description": "Add-on runs are valid this month and shared by everyone in the workspace. The plan allowance is used first.",
+ "options_label": "Number of runs",
+ "option": "{{runs}} runs",
+ "usage_summary": "{{used}} / {{limit}} used this month, resets {{date}}.",
+ "pay": "Continue to pay {{amount}}",
+ "pay_fallback": "Continue to payment",
+ "cancel": "Cancel",
+ "loading": "Loading the add-on price…",
+ "unavailable": "This workspace can't buy add-on runs right now.",
+ "conflict": "Add-on runs can't be bought right now, or the price changed. Review the options and try again.",
+ "error": "The payment page couldn't be opened. Try again.",
+ "success_title": "Runs added",
+ "success_description": "{{runs}} runs were added for this month. Automations start again with their next run.",
+ "confirming_title": "Confirming the payment",
+ "confirming_description": "Runs are added as soon as Stripe confirms the payment. Check the usage below in a moment.",
+ "not_paid_title": "Payment not completed",
+ "not_paid_description": "Nothing was charged and no runs were added.",
+ "cancel_title": "Payment canceled",
+ "cancel_description": "Nothing was charged."
}
}
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index 2071a46a78..d7670221c6 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -70,13 +70,19 @@
"original_input": "Original input",
"retry_with_context": "Retry with context",
"edit_advanced": "Edit as advanced form",
- "autopilot_quota_exceeded_body": "This workspace has reached its limit of {{limit}} autopilot runs for the current period. Further autopilot runs will not start until the allowance resets {{resetAt}}.",
+ "autopilot_quota_exceeded_body": "This workspace has reached its limit of {{limit}} autopilot runs for the current period. Further autopilot runs will not start until the allowance resets {{resetAt}}, or until the workspace upgrades or buys more runs.",
"project_owner_joined_body": "{{name}} is a workspace owner and added themselves to this private project. They can now see its issues, comments, and attachments.",
"open_project": "Open project",
- "autopilot_quota_upgrade": "View upgrade options",
+ "autopilot_quota_upgrade": "View options",
"archive": "Archive",
"unarchive": "Unarchive",
- "open_doc": "Open doc"
+ "open_doc": "Open doc",
+ "autopilot_quota_upgrade_action": "Upgrade",
+ "autopilot_quota_addon_action": "Buy more runs",
+ "autopilot_quota_portal_action": "Manage billing",
+ "autopilot_quota_contact_upgrade": "Ask a workspace owner or admin to upgrade the plan.",
+ "autopilot_quota_contact_addon": "Ask a workspace owner or admin to buy more runs.",
+ "autopilot_quota_contact_addon_or_upgrade": "Ask a workspace owner or admin to buy more runs or upgrade the plan."
},
"types": {
"issue_assigned": "Assigned",
diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.json
index ab8e241a00..c3d1a93192 100644
--- a/packages/views/locales/en/modals.json
+++ b/packages/views/locales/en/modals.json
@@ -187,15 +187,20 @@
"autopilot_quota_limit": {
"title": "This workspace has reached its autopilot run limit",
"checking_description": "Checking the billing actions available for this workspace…",
- "upgrade_description": "Upgrade to Pro to restore autopilot runs.",
+ "upgrade_description": "Upgrade to Pro to raise the monthly limit and restore autopilot runs, or wait for the allowance to reset.",
"portal_description": "Open Billing Portal to manage this workspace's subscription and restore autopilot runs.",
- "contact_description": "Ask a workspace owner or admin to upgrade to Pro.",
+ "contact_description": "Ask a workspace owner or admin to upgrade the plan, or wait for the allowance to reset.",
"billing_description": "Open Billing to see the upgrade options available for this workspace.",
"billing_unavailable_description": "Billing actions could not be loaded. Open Billing to try again.",
"billing_disabled_description": "Wait for the current allowance to reset, or contact your workspace administrator.",
"upgrade_action": "Upgrade to Pro",
"portal_action": "Open Billing Portal",
- "billing_action": "View Billing"
+ "billing_action": "View Billing",
+ "addon_description": "Buy more runs to restore autopilot runs this month, or wait for the allowance to reset.",
+ "contact_addon_description": "Ask a workspace owner or admin to buy more runs, or wait for the allowance to reset.",
+ "contact_addon_or_upgrade_description": "Ask a workspace owner or admin to buy more runs or upgrade the plan, or wait for the allowance to reset.",
+ "addon_action": "Buy more runs",
+ "upgrade_business_action": "Upgrade to Business"
},
"toast_link_subissues_all_failed": "Failed to link sub-issues",
"toast_link_subissues_partial": "Failed to link {{failed}} of {{total}} sub-issues",
diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.json
index 829be779ec..5f7795e15e 100644
--- a/packages/views/locales/es/billing.json
+++ b/packages/views/locales/es/billing.json
@@ -142,7 +142,14 @@
"metering": "Cuentan las ejecuciones de programaciones, webhooks y agentes. Las que un miembro inicia con Ejecutar ahora no cuentan.",
"storage": "Almacenamiento de adjuntos",
"storage_description": "Adjuntos de incidencias, comentarios y chats.",
- "storage_label": "Uso del almacenamiento de adjuntos"
+ "storage_label": "Uso del almacenamiento de adjuntos",
+ "addon": "Ejecuciones adicionales",
+ "addon_description": "Cuando se agota la asignación, las automatizaciones se pausan hasta el próximo mes o hasta que compres más ejecuciones.",
+ "addon_included": "Incluye {{runs}} ejecuciones adicionales",
+ "addon_none": "Ninguna este mes",
+ "addon_purchased": "{{runs}} compradas este mes",
+ "addon_buy": "Comprar · {{price}} / {{runs}} ejecuciones",
+ "addon_buy_fallback": "Comprar más ejecuciones"
},
"seats": {
"title": "Puestos",
@@ -225,7 +232,9 @@
"success_title": "Plan cambiado",
"success_description": "Este espacio de trabajo ahora usa {{plan}}.",
"unresolved": "No se ha podido confirmar el cambio de plan anterior. Contacta con soporte antes de cambiar de plan.",
- "check_failed": "No se ha podido comprobar el cambio de plan. Vuelve a intentarlo."
+ "check_failed": "No se ha podido comprobar el cambio de plan. Vuelve a intentarlo.",
+ "addon_downgrade_notice": "Tras el cambio, el límite de este mes será de {{limit}} ejecuciones, incluidas las compradas. Este mes se han usado {{used}}.",
+ "addon_downgrade_notice_limit_only": "Tras el cambio, el límite de este mes será de {{limit}} ejecuciones, incluidas las compradas."
},
"confirm": {
"title": "¿Continuar a Stripe Checkout?",
@@ -347,5 +356,27 @@
"admin_body_no_figures": "El almacenamiento de adjuntos está lleno. Los adjuntos existentes no se ven afectados.",
"member_body": "El almacenamiento de adjuntos está lleno. Pide a un administrador que actualice el plan o elimina los adjuntos que ya no necesites.",
"dismiss": "Cerrar"
+ },
+ "autopilot_addon": {
+ "title": "Comprar más ejecuciones de automatización",
+ "description": "Las ejecuciones adicionales valen para este mes y las comparte todo el espacio de trabajo. Primero se usa la asignación del plan.",
+ "options_label": "Número de ejecuciones",
+ "option": "{{runs}} ejecuciones",
+ "usage_summary": "{{used}} / {{limit}} usadas este mes; se restablece el {{date}}.",
+ "pay": "Continuar para pagar {{amount}}",
+ "pay_fallback": "Continuar al pago",
+ "cancel": "Cancelar",
+ "loading": "Cargando el precio del complemento…",
+ "unavailable": "Este espacio de trabajo no puede comprar ejecuciones adicionales ahora.",
+ "conflict": "No se pueden comprar ejecuciones ahora o el precio cambió. Revisa las opciones y vuelve a intentarlo.",
+ "error": "No se pudo abrir la página de pago. Vuelve a intentarlo.",
+ "success_title": "Ejecuciones añadidas",
+ "success_description": "Se añadieron {{runs}} ejecuciones para este mes. Las automatizaciones se reanudan en su próxima ejecución.",
+ "confirming_title": "Confirmando el pago",
+ "confirming_description": "Las ejecuciones se añaden en cuanto Stripe confirma el pago. Revisa el uso más abajo en unos momentos.",
+ "not_paid_title": "Pago no completado",
+ "not_paid_description": "No se cobró nada ni se añadieron ejecuciones.",
+ "cancel_title": "Pago cancelado",
+ "cancel_description": "No se cobró nada."
}
}
diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.json
index c0bad1139e..12c030d772 100644
--- a/packages/views/locales/es/inbox.json
+++ b/packages/views/locales/es/inbox.json
@@ -70,13 +70,19 @@
"original_input": "Entrada original",
"retry_with_context": "Reintentar con contexto",
"edit_advanced": "Editar como formulario avanzado",
- "autopilot_quota_exceeded_body": "Este espacio de trabajo ha alcanzado su límite de {{limit}} ejecuciones de automatizaciones para el periodo actual. No se iniciarán más ejecuciones de automatizaciones hasta que se reinicie la cuota {{resetAt}}.",
+ "autopilot_quota_exceeded_body": "Este espacio de trabajo alcanzó su límite de {{limit}} ejecuciones de autopilot del periodo actual. Las siguientes ejecuciones no se iniciarán hasta que la asignación se restablezca {{resetAt}}, o hasta que el espacio de trabajo mejore su plan o compre más ejecuciones.",
"project_owner_joined_body": "{{name}} es propietario del espacio de trabajo y se ha añadido a este proyecto privado. Ahora puede ver sus tareas, comentarios y archivos adjuntos.",
"open_project": "Abrir proyecto",
- "autopilot_quota_upgrade": "Ver opciones de mejora del plan",
+ "autopilot_quota_upgrade": "Ver opciones",
"archive": "Archivar",
"unarchive": "Desarchivar",
- "open_doc": "Abrir documento"
+ "open_doc": "Abrir documento",
+ "autopilot_quota_upgrade_action": "Mejorar plan",
+ "autopilot_quota_addon_action": "Comprar más ejecuciones",
+ "autopilot_quota_portal_action": "Gestionar facturación",
+ "autopilot_quota_contact_upgrade": "Pide a un propietario o administrador del espacio de trabajo que mejore el plan.",
+ "autopilot_quota_contact_addon": "Pide a un propietario o administrador del espacio de trabajo que compre más ejecuciones.",
+ "autopilot_quota_contact_addon_or_upgrade": "Pide a un propietario o administrador del espacio de trabajo que compre más ejecuciones o mejore el plan."
},
"types": {
"issue_assigned": "Asignada",
diff --git a/packages/views/locales/es/modals.json b/packages/views/locales/es/modals.json
index 4f9ed517de..3251cd4f7a 100644
--- a/packages/views/locales/es/modals.json
+++ b/packages/views/locales/es/modals.json
@@ -162,15 +162,20 @@
"autopilot_quota_limit": {
"title": "Este espacio de trabajo ha alcanzado su límite de ejecuciones de automatizaciones",
"checking_description": "Comprobando las acciones de facturación disponibles para este espacio de trabajo…",
- "upgrade_description": "Actualiza a Pro para restaurar las ejecuciones de automatizaciones.",
+ "upgrade_description": "Mejora a Pro para aumentar el límite mensual y reanudar las ejecuciones de autopilot, o espera a que se restablezca la asignación.",
"portal_description": "Abre el portal de facturación para gestionar la suscripción de este espacio de trabajo y restaurar las ejecuciones de automatizaciones.",
- "contact_description": "Pide a un propietario o administrador del espacio de trabajo que actualice a Pro.",
+ "contact_description": "Pide a un propietario o administrador del espacio de trabajo que mejore el plan, o espera a que se restablezca la asignación.",
"billing_description": "Abre Facturación para ver las opciones de actualización disponibles para este espacio de trabajo.",
"billing_unavailable_description": "No se han podido cargar las acciones de facturación. Abre Facturación para reintentarlo.",
"billing_disabled_description": "Espera a que se reinicie la cuota actual, o contacta con el administrador de tu espacio de trabajo.",
"upgrade_action": "Actualizar a Pro",
"portal_action": "Abrir portal de facturación",
- "billing_action": "Ver facturación"
+ "billing_action": "Ver facturación",
+ "addon_description": "Compra más ejecuciones para reanudar las ejecuciones de autopilot este mes, o espera a que se restablezca la asignación.",
+ "contact_addon_description": "Pide a un propietario o administrador del espacio de trabajo que compre más ejecuciones, o espera a que se restablezca la asignación.",
+ "contact_addon_or_upgrade_description": "Pide a un propietario o administrador del espacio de trabajo que compre más ejecuciones o mejore el plan, o espera a que se restablezca la asignación.",
+ "addon_action": "Comprar más ejecuciones",
+ "upgrade_business_action": "Mejorar a Business"
},
"toast_link_subissues_all_failed": "No se han podido vincular las subtareas",
"toast_link_subissues_partial": "No se han podido vincular {{failed}} de {{total}} subtareas",
diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.json
index 39b70d97bc..388070dfd6 100644
--- a/packages/views/locales/fr/billing.json
+++ b/packages/views/locales/fr/billing.json
@@ -142,7 +142,14 @@
"metering": "Les exécutions lancées par une planification, un webhook ou un agent sont comptées. Celles qu'un membre lance avec Exécuter maintenant ne le sont pas.",
"storage": "Stockage des pièces jointes",
"storage_description": "Pièces jointes des tickets, commentaires et discussions.",
- "storage_label": "Utilisation du stockage des pièces jointes"
+ "storage_label": "Utilisation du stockage des pièces jointes",
+ "addon": "Exécutions supplémentaires",
+ "addon_description": "Une fois l'allocation épuisée, les automatisations sont suspendues jusqu'au mois prochain ou jusqu'à l'achat d'exécutions supplémentaires.",
+ "addon_included": "Dont {{runs}} exécutions supplémentaires",
+ "addon_none": "Aucune ce mois-ci",
+ "addon_purchased": "{{runs}} achetées ce mois-ci",
+ "addon_buy": "Acheter · {{price}} / {{runs}} exécutions",
+ "addon_buy_fallback": "Acheter des exécutions"
},
"seats": {
"title": "Sièges",
@@ -225,7 +232,9 @@
"success_title": "Forfait changé",
"success_description": "Cet espace de travail utilise désormais {{plan}}.",
"unresolved": "Le changement de forfait précédent n'a pas pu être confirmé. Contactez l'assistance avant de changer de forfait.",
- "check_failed": "Impossible de vérifier le changement de forfait. Réessayez."
+ "check_failed": "Impossible de vérifier le changement de forfait. Réessayez.",
+ "addon_downgrade_notice": "Après le changement, la limite de ce mois sera de {{limit}} exécutions, achats compris. {{used}} exécutions ont été utilisées ce mois-ci.",
+ "addon_downgrade_notice_limit_only": "Après le changement, la limite de ce mois sera de {{limit}} exécutions, achats compris."
},
"confirm": {
"title": "Continuer vers Stripe Checkout ?",
@@ -347,5 +356,27 @@
"admin_body_no_figures": "Le stockage des pièces jointes est plein. Les pièces jointes existantes ne sont pas affectées.",
"member_body": "Le stockage des pièces jointes est plein. Demandez à un administrateur de changer de forfait, ou supprimez les pièces jointes dont vous n'avez plus besoin.",
"dismiss": "Fermer"
+ },
+ "autopilot_addon": {
+ "title": "Acheter des exécutions d'automatisation",
+ "description": "Les exécutions supplémentaires sont valables ce mois-ci et partagées par tout l'espace de travail. L'allocation du forfait est utilisée en premier.",
+ "options_label": "Nombre d'exécutions",
+ "option": "{{runs}} exécutions",
+ "usage_summary": "{{used}} / {{limit}} utilisées ce mois-ci, réinitialisation le {{date}}.",
+ "pay": "Continuer pour payer {{amount}}",
+ "pay_fallback": "Continuer vers le paiement",
+ "cancel": "Annuler",
+ "loading": "Chargement du prix du complément…",
+ "unavailable": "Cet espace de travail ne peut pas acheter d'exécutions pour le moment.",
+ "conflict": "Impossible d'acheter des exécutions pour le moment, ou le prix a changé. Vérifiez les options et réessayez.",
+ "error": "La page de paiement n'a pas pu s'ouvrir. Réessayez.",
+ "success_title": "Exécutions ajoutées",
+ "success_description": "{{runs}} exécutions ont été ajoutées pour ce mois. Les automatisations reprennent à leur prochaine exécution.",
+ "confirming_title": "Confirmation du paiement",
+ "confirming_description": "Les exécutions sont ajoutées dès que Stripe confirme le paiement. Consultez l'utilisation ci-dessous dans un instant.",
+ "not_paid_title": "Paiement non finalisé",
+ "not_paid_description": "Rien n'a été débité et aucune exécution n'a été ajoutée.",
+ "cancel_title": "Paiement annulé",
+ "cancel_description": "Rien n'a été débité."
}
}
diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.json
index 35cac43433..b316f30cc8 100644
--- a/packages/views/locales/fr/inbox.json
+++ b/packages/views/locales/fr/inbox.json
@@ -70,13 +70,19 @@
"original_input": "Saisie d'origine",
"retry_with_context": "Réessayer avec le contexte",
"edit_advanced": "Modifier en mode avancé",
- "autopilot_quota_exceeded_body": "Cet espace de travail a atteint sa limite de {{limit}} exécutions d'automatisation pour la période actuelle. Les prochaines exécutions d'automatisation ne démarreront qu'après la réinitialisation du quota {{resetAt}}.",
+ "autopilot_quota_exceeded_body": "Cet espace de travail a atteint sa limite de {{limit}} exécutions d'autopilot pour la période en cours. Les exécutions suivantes ne démarreront pas avant la réinitialisation de l'allocation {{resetAt}}, ou avant que l'espace de travail change de forfait ou achète des exécutions.",
"project_owner_joined_body": "{{name}}, propriétaire de l’espace de travail, s’est ajouté à ce projet privé et peut désormais voir ses tâches, commentaires et pièces jointes.",
"open_project": "Ouvrir le projet",
- "autopilot_quota_upgrade": "Voir les options de mise à niveau",
+ "autopilot_quota_upgrade": "Voir les options",
"archive": "Archiver",
"unarchive": "Désarchiver",
- "open_doc": "Ouvrir le document"
+ "open_doc": "Ouvrir le document",
+ "autopilot_quota_upgrade_action": "Changer de forfait",
+ "autopilot_quota_addon_action": "Acheter des exécutions",
+ "autopilot_quota_portal_action": "Gérer la facturation",
+ "autopilot_quota_contact_upgrade": "Demandez à un propriétaire ou administrateur de l'espace de travail de changer de forfait.",
+ "autopilot_quota_contact_addon": "Demandez à un propriétaire ou administrateur de l'espace de travail d'acheter des exécutions.",
+ "autopilot_quota_contact_addon_or_upgrade": "Demandez à un propriétaire ou administrateur de l'espace de travail d'acheter des exécutions ou de changer de forfait."
},
"types": {
"issue_assigned": "Assigné",
diff --git a/packages/views/locales/fr/modals.json b/packages/views/locales/fr/modals.json
index b5d0308284..ea9833a1e1 100644
--- a/packages/views/locales/fr/modals.json
+++ b/packages/views/locales/fr/modals.json
@@ -187,15 +187,20 @@
"autopilot_quota_limit": {
"title": "Cet espace de travail a atteint sa limite d'exécutions d'automatisation",
"checking_description": "Vérification des actions de facturation disponibles pour cet espace de travail…",
- "upgrade_description": "Passez à Pro pour rétablir les exécutions d'automatisation.",
+ "upgrade_description": "Passez à Pro pour augmenter la limite mensuelle et reprendre les exécutions d'autopilot, ou attendez la réinitialisation de l'allocation.",
"portal_description": "Ouvrez le portail de facturation pour gérer l'abonnement de cet espace de travail et rétablir les exécutions d'automatisation.",
- "contact_description": "Demandez à un propriétaire ou administrateur de l'espace de travail de passer à Pro.",
+ "contact_description": "Demandez à un propriétaire ou administrateur de l'espace de travail de changer de forfait, ou attendez la réinitialisation de l'allocation.",
"billing_description": "Ouvrez Facturation pour voir les options de mise à niveau disponibles pour cet espace de travail.",
"billing_unavailable_description": "Impossible de charger les actions de facturation. Ouvrez Facturation pour réessayer.",
"billing_disabled_description": "Attendez la réinitialisation du quota actuel ou contactez l'administrateur de votre espace de travail.",
"upgrade_action": "Passer à Pro",
"portal_action": "Ouvrir le portail de facturation",
- "billing_action": "Voir la facturation"
+ "billing_action": "Voir la facturation",
+ "addon_description": "Achetez des exécutions pour reprendre les exécutions d'autopilot ce mois-ci, ou attendez la réinitialisation de l'allocation.",
+ "contact_addon_description": "Demandez à un propriétaire ou administrateur de l'espace de travail d'acheter des exécutions, ou attendez la réinitialisation de l'allocation.",
+ "contact_addon_or_upgrade_description": "Demandez à un propriétaire ou administrateur de l'espace de travail d'acheter des exécutions ou de changer de forfait, ou attendez la réinitialisation de l'allocation.",
+ "addon_action": "Acheter des exécutions",
+ "upgrade_business_action": "Passer à Business"
},
"toast_link_subissues_all_failed": "Échec de la liaison des sous-tâches",
"toast_link_subissues_partial": "Échec de la liaison de {{failed}} sous-tâches sur {{total}}",
diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.json
index 858444602f..13a6e45bcd 100644
--- a/packages/views/locales/ja/billing.json
+++ b/packages/views/locales/ja/billing.json
@@ -141,7 +141,14 @@
"metering": "スケジュール、Webhook、エージェントによる実行はカウントされます。メンバーが「今すぐ実行」で開始した実行はカウントされません。",
"storage": "添付ファイルの保存容量",
"storage_description": "タスク、コメント、チャットの添付ファイル。",
- "storage_label": "添付ファイルの保存容量の使用量"
+ "storage_label": "添付ファイルの保存容量の使用量",
+ "addon": "追加の実行回数",
+ "addon_description": "実行枠を使い切ると、翌月のリセットまたは追加購入まで自動化は停止します。",
+ "addon_included": "うち追加分 {{runs}} 回",
+ "addon_none": "今月の追加購入なし",
+ "addon_purchased": "今月 {{runs}} 回を追加購入済み",
+ "addon_buy": "追加購入 · {{price}} / {{runs}} 回",
+ "addon_buy_fallback": "実行回数を追加購入"
},
"seats": {
"title": "席数",
@@ -219,7 +226,9 @@
"success_title": "プランを変更しました",
"success_description": "このワークスペースは {{plan}} になりました。",
"unresolved": "前回のプラン変更を確認できませんでした。プランを変更する前にサポートにお問い合わせください。",
- "check_failed": "プラン変更を確認できませんでした。再度お試しください。"
+ "check_failed": "プラン変更を確認できませんでした。再度お試しください。",
+ "addon_downgrade_notice": "切り替え後、今月の上限は追加購入分を含めて {{limit}} 回になります。今月はすでに {{used}} 回使用しています。",
+ "addon_downgrade_notice_limit_only": "切り替え後、今月の上限は追加購入分を含めて {{limit}} 回になります。"
},
"confirm": {
"title": "Stripe Checkout に進みますか?",
@@ -335,5 +344,27 @@
"admin_body_no_figures": "添付ファイルの保存容量が上限に達しました。既存の添付ファイルには影響しません。",
"member_body": "添付ファイルの保存容量が上限に達しました。管理者にプランのアップグレードを依頼するか、不要な添付ファイルを削除してください。",
"dismiss": "閉じる"
+ },
+ "autopilot_addon": {
+ "title": "自動化の実行回数を追加購入",
+ "description": "追加購入した回数は今月中有効で、ワークスペース全員で共有します。プランの実行枠から先に使われます。",
+ "options_label": "追加する回数",
+ "option": "{{runs}} 回",
+ "usage_summary": "今月の使用量 {{used}} / {{limit}} 回、{{date}} にリセット。",
+ "pay": "{{amount}} の支払いに進む",
+ "pay_fallback": "支払いに進む",
+ "cancel": "キャンセル",
+ "loading": "追加購入の価格を読み込んでいます…",
+ "unavailable": "このワークスペースは現在、実行回数を追加購入できません。",
+ "conflict": "現在は追加購入できないか、価格が変更されました。オプションを確認してもう一度お試しください。",
+ "error": "支払いページを開けませんでした。もう一度お試しください。",
+ "success_title": "実行回数を追加しました",
+ "success_description": "今月の実行回数に {{runs}} 回を追加しました。自動化は次回の実行から再開します。",
+ "confirming_title": "支払いを確認しています",
+ "confirming_description": "Stripe が支払いを確認するとすぐに実行回数が追加されます。しばらくしてから下の使用量を確認してください。",
+ "not_paid_title": "支払いが完了していません",
+ "not_paid_description": "請求は発生しておらず、実行回数も追加されていません。",
+ "cancel_title": "支払いをキャンセルしました",
+ "cancel_description": "請求は発生していません。"
}
}
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index f43e0eb0ad..620ef619f0 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -68,13 +68,19 @@
"original_input": "元の入力",
"retry_with_context": "コンテキストを保持して再試行",
"edit_advanced": "詳細フォームで編集",
- "autopilot_quota_exceeded_body": "このワークスペースは現在の期間の自動化実行上限 {{limit}} 回に達しました。実行枠が {{resetAt}} にリセットされるまで、以降の自動化は開始されません。",
+ "autopilot_quota_exceeded_body": "このワークスペースは現在の期間の自動化実行上限 {{limit}} 回に達しました。実行枠が {{resetAt}} にリセットされるか、アップグレードまたは実行回数の追加購入を行うまで、以降の自動化は開始されません。",
"project_owner_joined_body": "{{name}} はワークスペースのオーナーで、このプライベートプロジェクトに自分を追加しました。タスク、コメント、添付ファイルを閲覧できるようになりました。",
"open_project": "プロジェクトを開く",
- "autopilot_quota_upgrade": "アップグレード方法を見る",
+ "autopilot_quota_upgrade": "オプションを見る",
"archive": "アーカイブ",
"unarchive": "アーカイブ解除",
- "open_doc": "ドキュメントを開く"
+ "open_doc": "ドキュメントを開く",
+ "autopilot_quota_upgrade_action": "アップグレード",
+ "autopilot_quota_addon_action": "実行回数を追加購入",
+ "autopilot_quota_portal_action": "請求を管理",
+ "autopilot_quota_contact_upgrade": "ワークスペースの所有者または管理者にプランのアップグレードを依頼してください。",
+ "autopilot_quota_contact_addon": "ワークスペースの所有者または管理者に実行回数の追加購入を依頼してください。",
+ "autopilot_quota_contact_addon_or_upgrade": "ワークスペースの所有者または管理者に実行回数の追加購入かプランのアップグレードを依頼してください。"
},
"types": {
"issue_assigned": "割り当て済み",
diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.json
index 345716ab18..14473282f1 100644
--- a/packages/views/locales/ja/modals.json
+++ b/packages/views/locales/ja/modals.json
@@ -185,15 +185,20 @@
"autopilot_quota_limit": {
"title": "このワークスペースはオートパイロット実行数の上限に達しました",
"checking_description": "このワークスペースで利用可能な請求操作を確認しています…",
- "upgrade_description": "Pro にアップグレードすると、オートパイロット実行を再開できます。",
+ "upgrade_description": "Pro にアップグレードすると月間上限が増え、オートパイロット実行を再開できます。実行枠のリセットを待つこともできます。",
"portal_description": "請求ポータルを開いてワークスペースのサブスクリプションを管理し、オートパイロット実行を再開してください。",
- "contact_description": "ワークスペースの所有者または管理者に Pro へのアップグレードを依頼してください。",
+ "contact_description": "ワークスペースの所有者または管理者にプランのアップグレードを依頼するか、実行枠のリセットを待ってください。",
"billing_description": "請求設定を開いて、このワークスペースで利用可能なアップグレードオプションを確認してください。",
"billing_unavailable_description": "請求操作を読み込めませんでした。請求設定を開いて再試行してください。",
"billing_disabled_description": "現在の実行枠がリセットされるまで待つか、ワークスペースの管理者に連絡してください。",
"upgrade_action": "Pro にアップグレード",
"portal_action": "請求ポータルを開く",
- "billing_action": "請求設定を表示"
+ "billing_action": "請求設定を表示",
+ "addon_description": "実行回数を追加購入すると今月中にオートパイロット実行を再開できます。実行枠のリセットを待つこともできます。",
+ "contact_addon_description": "ワークスペースの所有者または管理者に実行回数の追加購入を依頼するか、実行枠のリセットを待ってください。",
+ "contact_addon_or_upgrade_description": "ワークスペースの所有者または管理者に実行回数の追加購入かプランのアップグレードを依頼するか、実行枠のリセットを待ってください。",
+ "addon_action": "実行回数を追加購入",
+ "upgrade_business_action": "Business にアップグレード"
},
"toast_link_subissues_all_failed": "サブタスクをリンクできませんでした",
"toast_link_subissues_partial": "サブタスク {{total}} 件中 {{failed}} 件をリンクできませんでした",
diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.json
index 9ba9ea5aa1..e8a3413158 100644
--- a/packages/views/locales/ko/billing.json
+++ b/packages/views/locales/ko/billing.json
@@ -141,7 +141,14 @@
"metering": "일정, Webhook, 에이전트로 시작된 실행은 집계됩니다. 멤버가 지금 실행으로 시작한 실행은 집계되지 않습니다.",
"storage": "첨부 파일 저장 공간",
"storage_description": "이슈, 댓글, 채팅의 첨부 파일입니다.",
- "storage_label": "첨부 파일 저장 공간 사용량"
+ "storage_label": "첨부 파일 저장 공간 사용량",
+ "addon": "추가 실행 횟수",
+ "addon_description": "한도를 다 쓰면 다음 달 초기화되거나 추가 구매할 때까지 자동화가 일시 중지됩니다.",
+ "addon_included": "추가 구매 {{runs}}회 포함",
+ "addon_none": "이번 달 추가 구매 없음",
+ "addon_purchased": "이번 달 {{runs}}회 추가 구매함",
+ "addon_buy": "추가 구매 · {{price}} / {{runs}}회",
+ "addon_buy_fallback": "실행 횟수 추가 구매"
},
"seats": {
"title": "좌석",
@@ -219,7 +226,9 @@
"success_title": "요금제가 변경됨",
"success_description": "이제 이 워크스페이스는 {{plan}} 요금제를 사용합니다.",
"unresolved": "이전 요금제 변경을 확인할 수 없습니다. 요금제를 변경하기 전에 지원팀에 문의하세요.",
- "check_failed": "요금제 변경을 확인할 수 없습니다. 다시 시도하세요."
+ "check_failed": "요금제 변경을 확인할 수 없습니다. 다시 시도하세요.",
+ "addon_downgrade_notice": "변경 후 이번 달 한도는 추가 구매분을 포함해 {{limit}}회가 됩니다. 이번 달에 {{used}}회를 사용했습니다.",
+ "addon_downgrade_notice_limit_only": "변경 후 이번 달 한도는 추가 구매분을 포함해 {{limit}}회가 됩니다."
},
"confirm": {
"title": "Stripe Checkout으로 이동할까요?",
@@ -335,5 +344,27 @@
"admin_body_no_figures": "첨부 파일 저장 공간이 가득 찼습니다. 기존 첨부 파일에는 영향이 없습니다.",
"member_body": "첨부 파일 저장 공간이 가득 찼습니다. 관리자에게 요금제 업그레이드를 요청하거나 필요 없는 첨부 파일을 삭제하세요.",
"dismiss": "닫기"
+ },
+ "autopilot_addon": {
+ "title": "자동화 실행 횟수 추가 구매",
+ "description": "추가 구매한 횟수는 이번 달에만 유효하며 워크스페이스 전체가 함께 사용합니다. 플랜 한도를 먼저 사용합니다.",
+ "options_label": "추가할 횟수",
+ "option": "{{runs}}회",
+ "usage_summary": "이번 달 {{used}} / {{limit}}회 사용, {{date}}에 초기화.",
+ "pay": "{{amount}} 결제하러 가기",
+ "pay_fallback": "결제하러 가기",
+ "cancel": "취소",
+ "loading": "추가 구매 가격을 불러오는 중…",
+ "unavailable": "이 워크스페이스는 지금 실행 횟수를 추가 구매할 수 없습니다.",
+ "conflict": "지금은 추가 구매할 수 없거나 가격이 변경되었습니다. 옵션을 확인한 후 다시 시도하세요.",
+ "error": "결제 페이지를 열지 못했습니다. 다시 시도하세요.",
+ "success_title": "실행 횟수를 추가했습니다",
+ "success_description": "이번 달에 {{runs}}회가 추가되었습니다. 자동화는 다음 실행부터 다시 시작됩니다.",
+ "confirming_title": "결제를 확인하는 중",
+ "confirming_description": "Stripe가 결제를 확인하면 바로 실행 횟수가 추가됩니다. 잠시 후 아래 사용량을 확인하세요.",
+ "not_paid_title": "결제가 완료되지 않았습니다",
+ "not_paid_description": "청구되지 않았으며 실행 횟수도 추가되지 않았습니다.",
+ "cancel_title": "결제를 취소했습니다",
+ "cancel_description": "청구되지 않았습니다."
}
}
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index 6b7dba8fcd..e2d7e36699 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -68,13 +68,19 @@
"original_input": "원본 입력",
"retry_with_context": "컨텍스트를 유지하여 재시도",
"edit_advanced": "고급 양식으로 수정",
- "autopilot_quota_exceeded_body": "이 워크스페이스는 현재 기간의 자동화 실행 한도 {{limit}}회에 도달했습니다. 한도가 {{resetAt}}에 초기화될 때까지 이후 자동화 실행은 시작되지 않습니다.",
+ "autopilot_quota_exceeded_body": "이 워크스페이스는 현재 기간의 오토파일럿 실행 한도 {{limit}}회에 도달했습니다. 한도가 {{resetAt}}에 초기화되거나 업그레이드 또는 실행 횟수를 추가 구매할 때까지 이후 오토파일럿 실행은 시작되지 않습니다.",
"project_owner_joined_body": "{{name}} 님은 워크스페이스 소유자이며 이 비공개 프로젝트에 자신을 추가했습니다. 이제 태스크, 댓글, 첨부 파일을 볼 수 있습니다.",
"open_project": "프로젝트 열기",
- "autopilot_quota_upgrade": "업그레이드 옵션 보기",
+ "autopilot_quota_upgrade": "옵션 보기",
"archive": "보관",
"unarchive": "보관 해제",
- "open_doc": "문서 열기"
+ "open_doc": "문서 열기",
+ "autopilot_quota_upgrade_action": "업그레이드",
+ "autopilot_quota_addon_action": "실행 횟수 추가 구매",
+ "autopilot_quota_portal_action": "결제 관리",
+ "autopilot_quota_contact_upgrade": "워크스페이스 소유자나 관리자에게 플랜 업그레이드를 요청하세요.",
+ "autopilot_quota_contact_addon": "워크스페이스 소유자나 관리자에게 실행 횟수 추가 구매를 요청하세요.",
+ "autopilot_quota_contact_addon_or_upgrade": "워크스페이스 소유자나 관리자에게 실행 횟수 추가 구매나 플랜 업그레이드를 요청하세요."
},
"types": {
"issue_assigned": "할당됨",
diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.json
index d008eec970..14d1ce9ec5 100644
--- a/packages/views/locales/ko/modals.json
+++ b/packages/views/locales/ko/modals.json
@@ -185,15 +185,20 @@
"autopilot_quota_limit": {
"title": "이 워크스페이스가 오토파일럿 실행 한도에 도달했습니다",
"checking_description": "이 워크스페이스에서 사용할 수 있는 결제 작업을 확인하는 중입니다…",
- "upgrade_description": "Pro로 업그레이드하면 오토파일럿 실행을 복구할 수 있습니다.",
+ "upgrade_description": "Pro로 업그레이드하면 월간 한도가 늘어나 오토파일럿 실행이 재개됩니다. 한도가 초기화될 때까지 기다릴 수도 있습니다.",
"portal_description": "결제 포털을 열어 이 워크스페이스의 구독을 관리하고 오토파일럿 실행을 복구하세요.",
- "contact_description": "워크스페이스 소유자 또는 관리자에게 Pro 업그레이드를 요청하세요.",
+ "contact_description": "워크스페이스 소유자나 관리자에게 플랜 업그레이드를 요청하거나 한도가 초기화될 때까지 기다리세요.",
"billing_description": "결제 설정에서 이 워크스페이스에 사용 가능한 업그레이드 옵션을 확인하세요.",
"billing_unavailable_description": "결제 작업을 불러오지 못했습니다. 결제 설정을 열어 다시 시도하세요.",
"billing_disabled_description": "현재 실행 할당량이 재설정될 때까지 기다리거나 워크스페이스 관리자에게 문의하세요.",
"upgrade_action": "Pro로 업그레이드",
"portal_action": "결제 포털 열기",
- "billing_action": "결제 설정 보기"
+ "billing_action": "결제 설정 보기",
+ "addon_description": "실행 횟수를 추가 구매하면 이번 달에 오토파일럿 실행이 재개됩니다. 한도가 초기화될 때까지 기다릴 수도 있습니다.",
+ "contact_addon_description": "워크스페이스 소유자나 관리자에게 실행 횟수 추가 구매를 요청하거나 한도가 초기화될 때까지 기다리세요.",
+ "contact_addon_or_upgrade_description": "워크스페이스 소유자나 관리자에게 실행 횟수 추가 구매나 플랜 업그레이드를 요청하거나 한도가 초기화될 때까지 기다리세요.",
+ "addon_action": "실행 횟수 추가 구매",
+ "upgrade_business_action": "Business로 업그레이드"
},
"toast_link_subissues_all_failed": "하위 태스크를 연결하지 못했습니다",
"toast_link_subissues_partial": "하위 태스크 {{total}}개 중 {{failed}}개를 연결하지 못했습니다",
diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.json
index abc2a05c75..ed5cf52239 100644
--- a/packages/views/locales/ru/billing.json
+++ b/packages/views/locales/ru/billing.json
@@ -144,7 +144,14 @@
"metering": "Учитываются запуски по расписанию, через вебхук и агентами. Запуски, которые участник начинает кнопкой «Запустить сейчас», не учитываются.",
"storage": "Хранилище вложений",
"storage_description": "Вложения в задачах, комментариях и чатах.",
- "storage_label": "Использование хранилища вложений"
+ "storage_label": "Использование хранилища вложений",
+ "addon": "Дополнительные запуски",
+ "addon_description": "Когда лимит исчерпан, автоматизации приостанавливаются до следующего месяца или до покупки дополнительных запусков.",
+ "addon_included": "Включая дополнительные: {{runs}}",
+ "addon_none": "В этом месяце не покупались",
+ "addon_purchased": "Куплено в этом месяце: {{runs}}",
+ "addon_buy": "Купить · {{price}} за {{runs}}",
+ "addon_buy_fallback": "Купить запуски"
},
"seats": {
"title": "Места",
@@ -237,7 +244,9 @@
"success_title": "Тариф изменён",
"success_description": "Теперь это рабочее пространство использует {{plan}}.",
"unresolved": "Не удалось подтвердить предыдущую смену тарифа. Обратитесь в поддержку, прежде чем менять тариф.",
- "check_failed": "Не удалось проверить смену тарифа. Повторите попытку."
+ "check_failed": "Не удалось проверить смену тарифа. Повторите попытку.",
+ "addon_downgrade_notice": "После смены лимит этого месяца составит {{limit}} запусков с учётом купленных. В этом месяце использовано: {{used}}.",
+ "addon_downgrade_notice_limit_only": "После смены лимит этого месяца составит {{limit}} запусков с учётом купленных."
},
"confirm": {
"title": "Перейти к оформлению в Stripe Checkout?",
@@ -371,5 +380,27 @@
"admin_body_no_figures": "Хранилище вложений заполнено. Существующие вложения не затронуты.",
"member_body": "Хранилище вложений заполнено. Попросите администратора сменить тариф или удалите ненужные вложения.",
"dismiss": "Закрыть"
+ },
+ "autopilot_addon": {
+ "title": "Купить дополнительные запуски автоматизаций",
+ "description": "Дополнительные запуски действуют в этом месяце и общие для всего рабочего пространства. Сначала расходуется лимит тарифа.",
+ "options_label": "Количество запусков",
+ "option": "Запусков: {{runs}}",
+ "usage_summary": "Использовано в этом месяце: {{used}} / {{limit}}, сброс {{date}}.",
+ "pay": "Перейти к оплате {{amount}}",
+ "pay_fallback": "Перейти к оплате",
+ "cancel": "Отмена",
+ "loading": "Загрузка цены пакета…",
+ "unavailable": "Сейчас это рабочее пространство не может купить дополнительные запуски.",
+ "conflict": "Сейчас нельзя купить запуски, или цена изменилась. Проверьте варианты и попробуйте снова.",
+ "error": "Не удалось открыть страницу оплаты. Попробуйте снова.",
+ "success_title": "Запуски добавлены",
+ "success_description": "Добавлено запусков на этот месяц: {{runs}}. Автоматизации возобновятся со следующего запуска.",
+ "confirming_title": "Подтверждаем оплату",
+ "confirming_description": "Запуски добавятся, как только Stripe подтвердит оплату. Проверьте использование ниже чуть позже.",
+ "not_paid_title": "Оплата не завершена",
+ "not_paid_description": "Деньги не списаны, запуски не добавлены.",
+ "cancel_title": "Оплата отменена",
+ "cancel_description": "Деньги не списаны."
}
}
diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.json
index a2a3e80315..92fb53b273 100644
--- a/packages/views/locales/ru/inbox.json
+++ b/packages/views/locales/ru/inbox.json
@@ -74,13 +74,19 @@
"original_input": "Исходный ввод",
"retry_with_context": "Повторить с контекстом",
"edit_advanced": "Редактировать как расширенную форму",
- "autopilot_quota_exceeded_body": "Это рабочее пространство достигло лимита в {{limit}} запусков Автопилота за текущий период. Новые запуски Автопилота не начнутся, пока лимит не будет сброшен {{resetAt}}.",
+ "autopilot_quota_exceeded_body": "Рабочее пространство исчерпало лимит в {{limit}} запусков автопилота за текущий период. Новые запуски не начнутся, пока лимит не сбросится {{resetAt}}, или пока рабочее пространство не сменит тариф либо не купит дополнительные запуски.",
"project_owner_joined_body": "{{name}}, владелец рабочего пространства, теперь участвует в этом закрытом проекте и видит его задачи, комментарии и вложения.",
"open_project": "Открыть проект",
- "autopilot_quota_upgrade": "Посмотреть варианты обновления",
+ "autopilot_quota_upgrade": "Посмотреть варианты",
"archive": "Архивировать",
"unarchive": "Восстановить из архива",
- "open_doc": "Открыть документ"
+ "open_doc": "Открыть документ",
+ "autopilot_quota_upgrade_action": "Сменить тариф",
+ "autopilot_quota_addon_action": "Купить запуски",
+ "autopilot_quota_portal_action": "Управление оплатой",
+ "autopilot_quota_contact_upgrade": "Попросите владельца или администратора рабочего пространства сменить тариф.",
+ "autopilot_quota_contact_addon": "Попросите владельца или администратора рабочего пространства купить дополнительные запуски.",
+ "autopilot_quota_contact_addon_or_upgrade": "Попросите владельца или администратора рабочего пространства купить дополнительные запуски или сменить тариф."
},
"types": {
"issue_assigned": "Назначено",
diff --git a/packages/views/locales/ru/modals.json b/packages/views/locales/ru/modals.json
index 3f36233a2e..99dbb0ed23 100644
--- a/packages/views/locales/ru/modals.json
+++ b/packages/views/locales/ru/modals.json
@@ -185,15 +185,20 @@
"autopilot_quota_limit": {
"title": "Это рабочее пространство достигло лимита запусков Автопилота",
"checking_description": "Проверяем доступные для этого рабочего пространства действия по оплате…",
- "upgrade_description": "Перейдите на Pro, чтобы восстановить запуски Автопилота.",
+ "upgrade_description": "Перейдите на Pro, чтобы увеличить месячный лимит и возобновить запуски автопилота, или дождитесь сброса лимита.",
"portal_description": "Откройте портал биллинга, чтобы управлять подпиской этого рабочего пространства и восстановить запуски Автопилота.",
- "contact_description": "Попросите владельца или администратора рабочего пространства перейти на Pro.",
+ "contact_description": "Попросите владельца или администратора рабочего пространства сменить тариф или дождитесь сброса лимита.",
"billing_description": "Откройте раздел «Биллинг», чтобы увидеть доступные варианты обновления для этого рабочего пространства.",
"billing_unavailable_description": "Не удалось загрузить действия по оплате. Откройте «Биллинг», чтобы попробовать снова.",
"billing_disabled_description": "Дождитесь сброса текущего лимита или обратитесь к администратору рабочего пространства.",
"upgrade_action": "Перейти на Pro",
"portal_action": "Открыть портал биллинга",
- "billing_action": "Просмотреть биллинг"
+ "billing_action": "Просмотреть биллинг",
+ "addon_description": "Купите дополнительные запуски, чтобы возобновить запуски автопилота в этом месяце, или дождитесь сброса лимита.",
+ "contact_addon_description": "Попросите владельца или администратора рабочего пространства купить дополнительные запуски или дождитесь сброса лимита.",
+ "contact_addon_or_upgrade_description": "Попросите владельца или администратора рабочего пространства купить дополнительные запуски или сменить тариф, либо дождитесь сброса лимита.",
+ "addon_action": "Купить запуски",
+ "upgrade_business_action": "Перейти на Business"
},
"toast_link_subissues_all_failed": "Не удалось связать подзадачи",
"toast_link_subissues_partial": "Не удалось связать {{failed}} из {{total}} подзадач",
diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.json
index 0739b95031..22204b3f1c 100644
--- a/packages/views/locales/zh-Hans/billing.json
+++ b/packages/views/locales/zh-Hans/billing.json
@@ -141,7 +141,14 @@
"metering": "时间表、Webhook 和智能体发起的运行计入额度,成员点击\"立即运行\"不计入。",
"storage": "附件存储",
"storage_description": "任务、评论和聊天中的附件。",
- "storage_label": "附件存储用量"
+ "storage_label": "附件存储用量",
+ "addon": "加购执行次数",
+ "addon_description": "额度用完后自动化会暂停,直到下月重置或加购。",
+ "addon_included": "其中加购 {{runs}} 次",
+ "addon_none": "本月未加购",
+ "addon_purchased": "本月已加购 {{runs}} 次",
+ "addon_buy": "加购 · {{price}} / {{runs}} 次",
+ "addon_buy_fallback": "加购执行次数"
},
"seats": {
"title": "席位",
@@ -219,7 +226,9 @@
"success_title": "套餐已更换",
"success_description": "这个工作区现在使用 {{plan}}。",
"unresolved": "上一次套餐变更的结果没有确认。请先联系支持,再更换套餐。",
- "check_failed": "无法检查套餐变更,请重试。"
+ "check_failed": "无法检查套餐变更,请重试。",
+ "addon_downgrade_notice": "切换后本月上限变为 {{limit}} 次(含已加购的次数),本月已用 {{used}} 次。",
+ "addon_downgrade_notice_limit_only": "切换后本月上限变为 {{limit}} 次(含已加购的次数)。"
},
"confirm": {
"title": "前往 Stripe Checkout?",
@@ -335,5 +344,27 @@
"admin_body_no_figures": "附件存储已满,已有附件不受影响。",
"member_body": "附件存储已满。请联系管理员升级套餐,或删除不需要的附件。",
"dismiss": "关闭"
+ },
+ "autopilot_addon": {
+ "title": "加购自动化执行",
+ "description": "加购的次数在本月有效,所有成员共享,先用套餐额度再用加购。",
+ "options_label": "加购次数",
+ "option": "{{runs}} 次",
+ "usage_summary": "本月已用 {{used}} / {{limit}} 次,{{date}} 重置。",
+ "pay": "去支付 {{amount}}",
+ "pay_fallback": "去支付",
+ "cancel": "取消",
+ "loading": "正在加载加购价格…",
+ "unavailable": "该工作区现在无法加购。",
+ "conflict": "现在无法加购,或价格已变化。请查看选项后重试。",
+ "error": "无法打开付款页面。请重试。",
+ "success_title": "已加购",
+ "success_description": "本月已增加 {{runs}} 次,自动化会在下一次运行时恢复。",
+ "confirming_title": "正在确认付款",
+ "confirming_description": "Stripe 确认付款后会立即加上次数。请稍后查看下方的用量。",
+ "not_paid_title": "付款未完成",
+ "not_paid_description": "没有扣款,也没有加上次数。",
+ "cancel_title": "已取消付款",
+ "cancel_description": "没有扣款。"
}
}
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index 6cb246b30d..888bc17575 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -68,13 +68,19 @@
"original_input": "原始输入",
"retry_with_context": "保留上下文重试",
"edit_advanced": "在完整表单中编辑",
- "autopilot_quota_exceeded_body": "当前周期的 {{limit}} 次自动化执行额度已用完。在 {{resetAt}} 重置前,后续自动化执行将不会启动。",
+ "autopilot_quota_exceeded_body": "当前周期的 {{limit}} 次自动化执行额度已用完。在 {{resetAt}} 重置、升级套餐或加购之前,后续自动化执行将不会启动。",
"project_owner_joined_body": "{{name}} 是工作区所有者,已把自己加入这个私有项目,现在可以看到其中的任务、评论和附件。",
"open_project": "打开项目",
- "autopilot_quota_upgrade": "查看升级方案",
+ "autopilot_quota_upgrade": "查看选项",
"archive": "归档",
"unarchive": "取消归档",
- "open_doc": "打开文档"
+ "open_doc": "打开文档",
+ "autopilot_quota_upgrade_action": "升级",
+ "autopilot_quota_addon_action": "加购执行次数",
+ "autopilot_quota_portal_action": "管理账单",
+ "autopilot_quota_contact_upgrade": "请联系工作区所有者或管理员升级套餐。",
+ "autopilot_quota_contact_addon": "请联系工作区所有者或管理员加购执行次数。",
+ "autopilot_quota_contact_addon_or_upgrade": "请联系工作区所有者或管理员加购执行次数或升级套餐。"
},
"types": {
"issue_assigned": "已分配",
diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.json
index a605f437cb..68340a7d68 100644
--- a/packages/views/locales/zh-Hans/modals.json
+++ b/packages/views/locales/zh-Hans/modals.json
@@ -185,15 +185,20 @@
"autopilot_quota_limit": {
"title": "该工作区的自动化执行次数已达到上限",
"checking_description": "正在查询该工作区可用的账单操作…",
- "upgrade_description": "升级到 Pro 后可恢复自动化执行。",
+ "upgrade_description": "升级到 Pro 可提高每月上限并恢复自动化执行,也可以等待额度重置。",
"portal_description": "打开账单门户管理该工作区的订阅,以恢复自动化执行。",
- "contact_description": "请联系工作区所有者或管理员升级到 Pro。",
+ "contact_description": "请联系工作区所有者或管理员升级套餐,或等待额度重置。",
"billing_description": "请前往账单设置查看该工作区可用的升级选项。",
"billing_unavailable_description": "暂时无法加载账单操作,请前往账单设置重试。",
"billing_disabled_description": "请等待当前额度重置,或联系工作区管理员。",
"upgrade_action": "升级到 Pro",
"portal_action": "打开账单门户",
- "billing_action": "查看账单"
+ "billing_action": "查看账单",
+ "addon_description": "加购执行次数可在本月恢复自动化执行,也可以等待额度重置。",
+ "contact_addon_description": "请联系工作区所有者或管理员加购执行次数,或等待额度重置。",
+ "contact_addon_or_upgrade_description": "请联系工作区所有者或管理员加购执行次数或升级套餐,或等待额度重置。",
+ "addon_action": "加购执行次数",
+ "upgrade_business_action": "升级到 Business"
},
"toast_link_subissues_all_failed": "关联子任务失败",
"toast_link_subissues_partial": "{{total}} 个子任务中有 {{failed}} 个关联失败",
diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.json
index 3fec70126b..db0a54e8d8 100644
--- a/packages/views/locales/zh-Hant/billing.json
+++ b/packages/views/locales/zh-Hant/billing.json
@@ -141,7 +141,14 @@
"metering": "時間表、Webhook 和 AI 代理發起的執行計入額度,成員點擊\"立即執行\"不計入。",
"storage": "附件儲存空間",
"storage_description": "任務、留言和聊天中的附件。",
- "storage_label": "附件儲存空間用量"
+ "storage_label": "附件儲存空間用量",
+ "addon": "加購執行次數",
+ "addon_description": "額度用完後自動化會暫停,直到下月重置或加購。",
+ "addon_included": "其中加購 {{runs}} 次",
+ "addon_none": "本月未加購",
+ "addon_purchased": "本月已加購 {{runs}} 次",
+ "addon_buy": "加購 · {{price}} / {{runs}} 次",
+ "addon_buy_fallback": "加購執行次數"
},
"seats": {
"title": "席位",
@@ -219,7 +226,9 @@
"success_title": "套餐已更換",
"success_description": "這個工作區現在使用 {{plan}}。",
"unresolved": "上一次套餐變更的結果沒有確認。請先聯絡支援,再更換套餐。",
- "check_failed": "無法檢查套餐變更,請重試。"
+ "check_failed": "無法檢查套餐變更,請重試。",
+ "addon_downgrade_notice": "切換後本月上限變為 {{limit}} 次(含已加購的次數),本月已用 {{used}} 次。",
+ "addon_downgrade_notice_limit_only": "切換後本月上限變為 {{limit}} 次(含已加購的次數)。"
},
"confirm": {
"title": "前往 Stripe Checkout?",
@@ -335,5 +344,27 @@
"admin_body_no_figures": "附件儲存空間已滿,既有附件不受影響。",
"member_body": "附件儲存空間已滿。請聯絡管理員升級套餐,或刪除不需要的附件。",
"dismiss": "關閉"
+ },
+ "autopilot_addon": {
+ "title": "加購自動化執行",
+ "description": "加購的次數在本月有效,所有成員共用,先用方案額度再用加購。",
+ "options_label": "加購次數",
+ "option": "{{runs}} 次",
+ "usage_summary": "本月已用 {{used}} / {{limit}} 次,{{date}} 重置。",
+ "pay": "前往支付 {{amount}}",
+ "pay_fallback": "前往付款",
+ "cancel": "取消",
+ "loading": "正在載入加購價格…",
+ "unavailable": "該工作區現在無法加購。",
+ "conflict": "現在無法加購,或價格已變化。請查看選項後重試。",
+ "error": "無法開啟付款頁面。請重試。",
+ "success_title": "已加購",
+ "success_description": "本月已增加 {{runs}} 次,自動化會在下一次執行時恢復。",
+ "confirming_title": "正在確認付款",
+ "confirming_description": "Stripe 確認付款後會立即加上次數。請稍後查看下方的用量。",
+ "not_paid_title": "付款未完成",
+ "not_paid_description": "沒有扣款,也沒有加上次數。",
+ "cancel_title": "已取消付款",
+ "cancel_description": "沒有扣款。"
}
}
diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.json
index ac20c9fd3a..839d78eb9f 100644
--- a/packages/views/locales/zh-Hant/inbox.json
+++ b/packages/views/locales/zh-Hant/inbox.json
@@ -68,13 +68,19 @@
"original_input": "原始輸入",
"retry_with_context": "保留上下文重試",
"edit_advanced": "在完整表單中編輯",
- "autopilot_quota_exceeded_body": "當前週期的 {{limit}} 次自動化執行額度已用完。在 {{resetAt}} 重置前,後續自動化執行將不會啟動。",
+ "autopilot_quota_exceeded_body": "目前週期的 {{limit}} 次自動化執行額度已用完。在 {{resetAt}} 重置、升級方案或加購之前,後續自動化執行將不會啟動。",
"project_owner_joined_body": "{{name}} 是工作區所有者,已把自己加入這個私有專案,現在可以看到其中的任務、評論和附件。",
"open_project": "開啟專案",
- "autopilot_quota_upgrade": "檢視升級方案",
+ "autopilot_quota_upgrade": "查看選項",
"archive": "歸檔",
"unarchive": "取消歸檔",
- "open_doc": "開啟文件"
+ "open_doc": "開啟文件",
+ "autopilot_quota_upgrade_action": "升級",
+ "autopilot_quota_addon_action": "加購執行次數",
+ "autopilot_quota_portal_action": "管理帳單",
+ "autopilot_quota_contact_upgrade": "請聯絡工作區所有者或管理員升級方案。",
+ "autopilot_quota_contact_addon": "請聯絡工作區所有者或管理員加購執行次數。",
+ "autopilot_quota_contact_addon_or_upgrade": "請聯絡工作區所有者或管理員加購執行次數或升級方案。"
},
"types": {
"issue_assigned": "已分配",
diff --git a/packages/views/locales/zh-Hant/modals.json b/packages/views/locales/zh-Hant/modals.json
index 0bd63abcb1..c8523463c4 100644
--- a/packages/views/locales/zh-Hant/modals.json
+++ b/packages/views/locales/zh-Hant/modals.json
@@ -185,15 +185,20 @@
"autopilot_quota_limit": {
"title": "該工作區的自動化執行次數已達到上限",
"checking_description": "正在查詢該工作區可用的帳單操作…",
- "upgrade_description": "升級到 Pro 後可恢復自動化執行。",
+ "upgrade_description": "升級到 Pro 可提高每月上限並恢復自動化執行,也可以等待額度重置。",
"portal_description": "開啟帳單門戶管理該工作區的訂閱,以恢復自動化執行。",
- "contact_description": "請聯絡工作區所有者或管理員升級到 Pro。",
+ "contact_description": "請聯絡工作區所有者或管理員升級方案,或等待額度重置。",
"billing_description": "請前往帳單設定檢視該工作區可用的升級選項。",
"billing_unavailable_description": "暫時無法載入帳單操作,請前往帳單設定重試。",
"billing_disabled_description": "請等待當前額度重置,或聯絡工作區管理員。",
"upgrade_action": "升級到 Pro",
"portal_action": "開啟帳單門戶",
- "billing_action": "檢視帳單"
+ "billing_action": "檢視帳單",
+ "addon_description": "加購執行次數可在本月恢復自動化執行,也可以等待額度重置。",
+ "contact_addon_description": "請聯絡工作區所有者或管理員加購執行次數,或等待額度重置。",
+ "contact_addon_or_upgrade_description": "請聯絡工作區所有者或管理員加購執行次數或升級方案,或等待額度重置。",
+ "addon_action": "加購執行次數",
+ "upgrade_business_action": "升級到 Business"
},
"toast_link_subissues_all_failed": "關聯子任務失敗",
"toast_link_subissues_partial": "{{total}} 個子任務中有 {{failed}} 個關聯失敗",
diff --git a/packages/views/modals/limit-recovery-dialog.test.tsx b/packages/views/modals/limit-recovery-dialog.test.tsx
index cb226fd972..326c8e0e90 100644
--- a/packages/views/modals/limit-recovery-dialog.test.tsx
+++ b/packages/views/modals/limit-recovery-dialog.test.tsx
@@ -24,6 +24,14 @@ interface AvailableActions {
checkout: boolean;
portal: boolean;
purchaseSeats: boolean;
+ changePlan?: boolean;
+ purchaseAutopilotRuns?: boolean;
+}
+
+interface SummaryFixture {
+ availableActions: AvailableActions;
+ entitlement?: { plan: string };
+ autopilotAddon?: { purchasedRuns: number } | null;
}
const mockPush = vi.hoisted(() => vi.fn());
@@ -33,9 +41,9 @@ const mockSummaryQuery = vi.hoisted(() => vi.fn());
const featureState = vi.hoisted(() => ({ billingEnabled: true }));
const workspaceState = vi.hoisted(() => ({ id: "ws-test" }));
const summaryState = vi.hoisted(() => ({
- value: null as null | { availableActions: AvailableActions },
+ value: null as null | SummaryFixture,
error: null as Error | null,
- pending: null as Promise<{ availableActions: AvailableActions } | null> | null,
+ pending: null as Promise<SummaryFixture | null> | null,
}));
vi.mock("@multica/core/hooks", () => ({
@@ -70,6 +78,11 @@ vi.mock("@multica/core/billing", () => ({
}),
}));
+vi.mock("../billing/autopilot-addon-dialog", () => ({
+ AutopilotAddonDialog: ({ open }: { open: boolean }) =>
+ open ? <div role="dialog" aria-label="Buy more automation runs" /> : null,
+}));
+
import { LimitRecoveryDialog } from "./limit-recovery-dialog";
import { useLimitRecoveryPrompt } from "./use-limit-recovery-prompt";
@@ -215,7 +228,9 @@ describe("LimitRecoveryDialog", () => {
}),
).toBeInTheDocument();
expect(
- await screen.findByText("Upgrade to Pro to restore autopilot runs."),
+ await screen.findByText(
+ "Upgrade to Pro to raise the monthly limit and restore autopilot runs, or wait for the allowance to reset.",
+ ),
).toBeInTheDocument();
act(() => useModalStore.getState().dismissLimitRecovery());
@@ -353,7 +368,7 @@ describe("LimitRecoveryDialog", () => {
expect(
await screen.findByText(
- "Ask a workspace owner or admin to upgrade to Pro.",
+ "Ask a workspace owner or admin to upgrade the plan, or wait for the allowance to reset.",
),
).toBeInTheDocument();
expect(
@@ -401,4 +416,82 @@ describe("LimitRecoveryDialog", () => {
).not.toBeInTheDocument();
expect(mockSummaryQuery).not.toHaveBeenCalled();
});
+
+ it("offers Pro managers more runs first and Business as the alternative", async () => {
+ summaryState.value = {
+ availableActions: actions({
+ portal: true,
+ purchaseSeats: true,
+ changePlan: true,
+ purchaseAutopilotRuns: true,
+ }),
+ entitlement: { plan: "pro" },
+ autopilotAddon: { purchasedRuns: 0 },
+ };
+ renderPrompt();
+ const user = await openPrompt();
+
+ expect(
+ await screen.findByText(
+ "Buy more runs to restore autopilot runs this month, or wait for the allowance to reset.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Open Billing Portal" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Upgrade to Business" }),
+ ).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Buy more runs" }));
+ await waitFor(() => expect(queryRecoveryDialog()).not.toBeInTheDocument());
+ expect(
+ screen.getByRole("dialog", { name: "Buy more automation runs" }),
+ ).toBeInTheDocument();
+ });
+
+ it("offers Business managers more runs without another upgrade", async () => {
+ summaryState.value = {
+ availableActions: actions({
+ portal: true,
+ changePlan: true,
+ purchaseAutopilotRuns: true,
+ }),
+ entitlement: { plan: "business" },
+ autopilotAddon: { purchasedRuns: 1000 },
+ };
+ renderPrompt();
+ await openPrompt();
+
+ expect(
+ await screen.findByRole("button", { name: "Buy more runs" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: "Upgrade to Business" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it.each([
+ [
+ "pro",
+ "Ask a workspace owner or admin to buy more runs or upgrade the plan, or wait for the allowance to reset.",
+ ],
+ [
+ "business",
+ "Ask a workspace owner or admin to buy more runs, or wait for the allowance to reset.",
+ ],
+ ])("tells a %s member what to ask an admin for, without a payment action", async (plan, text) => {
+ summaryState.value = {
+ availableActions: actions(),
+ entitlement: { plan },
+ autopilotAddon: { purchasedRuns: 0 },
+ };
+ renderPrompt();
+ await openPrompt();
+
+ expect(await screen.findByText(text)).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Buy|Upgrade|Billing/ }),
+ ).not.toBeInTheDocument();
+ });
});
diff --git a/packages/views/modals/limit-recovery-dialog.tsx b/packages/views/modals/limit-recovery-dialog.tsx
index 01617f5970..0f79a76018 100644
--- a/packages/views/modals/limit-recovery-dialog.tsx
+++ b/packages/views/modals/limit-recovery-dialog.tsx
@@ -7,7 +7,12 @@ import {
useCreateWorkspaceSubscriptionPortal,
workspaceSubscriptionSummaryOptions,
} from "@multica/core/billing";
-import { resolveBillingRecovery } from "@multica/core/billing/recovery";
+import {
+ autopilotQuotaAdminAsk,
+ canUpgradeToBusinessFromAddon,
+ resolveBillingRecovery,
+ type AutopilotQuotaAdminAsk,
+} from "@multica/core/billing/recovery";
import { useFeatureEnabled } from "@multica/core/config";
import { BILLING_WORKSPACE_SUBSCRIPTIONS_FLAG } from "@multica/core/feature-flags";
import { useWorkspaceId } from "@multica/core/hooks";
@@ -26,6 +31,7 @@ import {
DialogHeader,
DialogTitle,
} from "@multica/ui/components/ui/dialog";
+import { AutopilotAddonDialog } from "../billing/autopilot-addon-dialog";
import { useT } from "../i18n";
import { useNavigation } from "../navigation";
import { openExternal } from "../platform";
@@ -75,6 +81,7 @@ export function LimitRecoveryDialog() {
const portalIntentKeyRef = useRef<string | null>(null);
const [openingPortal, setOpeningPortal] = useState(false);
const [portalFailed, setPortalFailed] = useState(false);
+ const [addonOpen, setAddonOpen] = useState(false);
useEffect(() => {
if (recoveryWorkspaceId !== null && recoveryWorkspaceId !== wsId) {
@@ -113,19 +120,30 @@ export function LimitRecoveryDialog() {
}
};
- const actions = summaryQuery.data?.availableActions;
+ const openAddon = () => {
+ dismiss();
+ setAddonOpen(true);
+ };
+
+ const summary = summaryQuery.data;
+ const actions = summary?.availableActions;
const copy = getRecoveryCopy(t, recoveryReason);
const recovery = resolveRecoveryPresentation({
actions,
billingEnabled,
loading: billingEnabled && !actions && summaryQuery.isFetching,
portalFailed,
+ autopilotAddon: recoveryReason === "autopilot_quota",
+ adminAsk: autopilotQuotaAdminAsk(summary),
+ upgradeToBusiness: canUpgradeToBusinessFromAddon(summary),
copy,
openBilling,
openPortal,
+ openAddon,
});
return (
+ <>
<Dialog
open={visible}
modal
@@ -166,6 +184,16 @@ export function LimitRecoveryDialog() {
>
{t(($) => $.common.close)}
</Button>
+ {recovery.secondaryAction && (
+ <Button
+ variant="outline"
+ size="lg"
+ className="sm:min-w-28"
+ onClick={recovery.secondaryAction.onClick}
+ >
+ {recovery.secondaryAction.label}
+ </Button>
+ )}
{recovery.action && (
<Button
size="lg"
@@ -180,6 +208,10 @@ export function LimitRecoveryDialog() {
</DialogFooter>
</DialogContent>
</Dialog>
+ {addonOpen ? (
+ <AutopilotAddonDialog wsId={wsId} open={addonOpen} onOpenChange={setAddonOpen} />
+ ) : null}
+ </>
);
}
@@ -189,6 +221,10 @@ interface RecoveryPresentation {
label: string;
onClick: () => void;
};
+ secondaryAction?: {
+ label: string;
+ onClick: () => void;
+ };
}
interface RecoveryCopy {
@@ -197,12 +233,17 @@ interface RecoveryCopy {
upgradeDescription: string;
portalDescription: string;
contactDescription: string;
+ contactAddonDescription: string;
+ contactAddonOrUpgradeDescription: string;
+ addonDescription: string;
billingDescription: string;
billingUnavailableDescription: string;
checkingDescription: string;
upgradeAction: string;
portalAction: string;
billingAction: string;
+ addonAction: string;
+ upgradeBusinessAction: string;
}
function getRecoveryCopy(
@@ -226,6 +267,17 @@ function getRecoveryCopy(
contactDescription: t(
($) => $.create_issue.autopilot_quota_limit.contact_description,
),
+ contactAddonDescription: t(
+ ($) => $.create_issue.autopilot_quota_limit.contact_addon_description,
+ ),
+ contactAddonOrUpgradeDescription: t(
+ ($) =>
+ $.create_issue.autopilot_quota_limit
+ .contact_addon_or_upgrade_description,
+ ),
+ addonDescription: t(
+ ($) => $.create_issue.autopilot_quota_limit.addon_description,
+ ),
billingDescription: t(
($) => $.create_issue.autopilot_quota_limit.billing_description,
),
@@ -245,6 +297,12 @@ function getRecoveryCopy(
billingAction: t(
($) => $.create_issue.autopilot_quota_limit.billing_action,
),
+ addonAction: t(
+ ($) => $.create_issue.autopilot_quota_limit.addon_action,
+ ),
+ upgradeBusinessAction: t(
+ ($) => $.create_issue.autopilot_quota_limit.upgrade_business_action,
+ ),
};
}
}
@@ -254,23 +312,32 @@ function resolveRecoveryPresentation({
billingEnabled,
loading,
portalFailed,
+ autopilotAddon,
+ adminAsk,
+ upgradeToBusiness,
copy,
openBilling,
openPortal,
+ openAddon,
}: {
actions: BillingActions | undefined;
billingEnabled: boolean;
loading: boolean;
portalFailed: boolean;
+ autopilotAddon: boolean;
+ adminAsk: AutopilotQuotaAdminAsk;
+ upgradeToBusiness: boolean;
copy: RecoveryCopy;
openBilling: () => void;
openPortal: () => Promise<void>;
+ openAddon: () => void;
}): RecoveryPresentation {
const recovery = resolveBillingRecovery({
actions,
billingEnabled,
loading,
portalFailed,
+ autopilotAddon,
});
switch (recovery) {
@@ -286,6 +353,22 @@ function resolveRecoveryPresentation({
onClick: openBilling,
},
};
+ case "autopilot_addon":
+ return {
+ description: copy.addonDescription,
+ action: {
+ label: copy.addonAction,
+ onClick: openAddon,
+ },
+ ...(upgradeToBusiness
+ ? {
+ secondaryAction: {
+ label: copy.upgradeBusinessAction,
+ onClick: openBilling,
+ },
+ }
+ : {}),
+ };
case "portal":
return {
description: copy.portalDescription,
@@ -306,7 +389,12 @@ function resolveRecoveryPresentation({
};
case "contact_admin":
return {
- description: copy.contactDescription,
+ description:
+ adminAsk === "addon"
+ ? copy.contactAddonDescription
+ : adminAsk === "addon_or_upgrade"
+ ? copy.contactAddonOrUpgradeDescription
+ : copy.contactDescription,
};
case "checking":
return {
diff --git a/packages/views/settings/components/billing-state.test.ts b/packages/views/settings/components/billing-state.test.ts
index 8ee9072381..dd7a7be770 100644
--- a/packages/views/settings/components/billing-state.test.ts
+++ b/packages/views/settings/components/billing-state.test.ts
@@ -168,7 +168,9 @@ describe("billing subscription state", () => {
purchaseSeats: false,
changePlan: false,
checkPlanChange: false,
+ purchaseAutopilotRuns: false,
},
+ autopilotAddon: null,
planChange: null,
trial: null,
} satisfies WorkspaceSubscriptionSummary;
@@ -210,7 +212,9 @@ describe("resolvePlanChangeTarget", () => {
purchaseSeats: true,
changePlan,
checkPlanChange: false,
+ purchaseAutopilotRuns: false,
},
+ autopilotAddon: null,
planChange: null,
trial: null,
});
diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsx
index 06cc1fbafe..69de888bb7 100644
--- a/packages/views/settings/components/billing-tab.test.tsx
+++ b/packages/views/settings/components/billing-tab.test.tsx
@@ -92,7 +92,9 @@ const mocks = vi.hoisted(() => ({
purchaseSeats: false,
changePlan: false,
checkPlanChange: false,
+ purchaseAutopilotRuns: false,
},
+ autopilotAddon: null,
planChange: null as WorkspaceSubscriptionSummary["planChange"],
trial: null as WorkspaceSubscriptionSummary["trial"],
} as WorkspaceSubscriptionSummary,
@@ -187,6 +189,17 @@ vi.mock("../../navigation", () => ({
vi.mock("../../platform", () => ({ openExternal: mocks.openExternal }));
+vi.mock("../../billing/autopilot-addon-dialog", () => ({
+ AutopilotAddonDialog: ({ open }: { open: boolean }) =>
+ open ? <div role="dialog" aria-label="Buy more automation runs" /> : null,
+}));
+
+vi.mock("../../billing/autopilot-addon-return-notice", () => ({
+ AutopilotAddonReturnNotice: ({ sessionId }: { sessionId: string | null }) => (
+ <div role="status" aria-label="Add-on return">{sessionId}</div>
+ ),
+}));
+
import { BillingTab, formatStripeMinorAmount } from "./billing-tab";
// The component formats dates in the viewer's own time zone, so a midnight-UTC
@@ -274,6 +287,7 @@ describe("BillingTab", () => {
intervalCount: 1,
},
},
+ autopilotAddon: null,
};
mocks.changePlanPending = false;
mocks.pricesLoading = false;
@@ -314,7 +328,9 @@ describe("BillingTab", () => {
purchaseSeats: false,
changePlan: false,
checkPlanChange: false,
+ purchaseAutopilotRuns: false,
},
+ autopilotAddon: null,
planChange: null,
trial: null,
});
@@ -1018,6 +1034,24 @@ describe("BillingTab", () => {
);
});
+ it("hands an add-on return's Checkout Session to the return notice after clearing the URL", () => {
+ navigationState.search = "tab=billing&result=autopilot_addon&session_id=cs_test_7";
+
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.getByRole("status", { name: "Add-on return" })).toHaveTextContent("cs_test_7");
+ expect(navigationState.replace).toHaveBeenCalledWith("/acme/settings?tab=billing");
+ });
+
+ it("says nothing was charged when an add-on Checkout is canceled", () => {
+ navigationState.search = "tab=billing&result=autopilot_addon_cancel";
+
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.getByText("Payment canceled")).toBeInTheDocument();
+ expect(screen.getByText("Nothing was charged.")).toBeInTheDocument();
+ });
+
it("polls after a success callback and surfaces a bounded sync timeout", () => {
vi.useFakeTimers();
navigationState.search = "tab=billing&result=success&session_id=cs_test_1";
@@ -1657,6 +1691,65 @@ describe("BillingTab", () => {
).toBeInTheDocument();
});
+ it("shows this month's add-on runs and lets a manager buy more", async () => {
+ Object.assign(mocks.entitlements, { plan: "pro", status: "active" });
+ Object.assign(mocks.summary, {
+ autopilotAddon: {
+ purchasedRuns: 2000,
+ periodStart: "2030-01-01T00:00:00Z",
+ periodEnd: "2030-02-01T00:00:00Z",
+ },
+ });
+ Object.assign(mocks.summary.availableActions, {
+ checkout: false,
+ purchaseAutopilotRuns: true,
+ });
+ mocks.prices = {
+ ...mocks.prices!,
+ autopilotAddon: { currency: "usd", unitAmount: 1000, runsPerPack: 1000 },
+ };
+
+ const user = userEvent.setup();
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.getByText("Includes 2,000 add-on runs")).toBeInTheDocument();
+ expect(screen.getByText("2,000 bought this month")).toBeInTheDocument();
+ await user.click(
+ screen.getByRole("button", { name: "Buy · $10.00 / 1,000 runs" }),
+ );
+ expect(
+ await screen.findByRole("dialog", { name: "Buy more automation runs" }),
+ ).toBeInTheDocument();
+ });
+
+ it("shows add-on runs without a purchase button to a member", () => {
+ Object.assign(mocks.entitlements, { plan: "business", status: "active" });
+ Object.assign(mocks.summary, {
+ autopilotAddon: {
+ purchasedRuns: 0,
+ periodStart: "2030-01-01T00:00:00Z",
+ periodEnd: "2030-02-01T00:00:00Z",
+ },
+ });
+ Object.assign(mocks.summary.availableActions, {
+ checkout: false,
+ purchaseAutopilotRuns: false,
+ });
+
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.getByText("None this month")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /^Buy/ }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("hides add-on runs on a cloud that predates them", () => {
+ renderWithI18n(<BillingTab />);
+
+ expect(screen.queryByText("Add-on runs")).not.toBeInTheDocument();
+ });
+
it("shows observed usage over the limit without reporting it reached", () => {
Object.assign(mocks.usage, {
action: "observe",
@@ -2185,6 +2278,43 @@ describe("BillingTab", () => {
).toBeInTheDocument();
});
+ it("tells a downgrading manager this month's limit when add-ons were bought", async () => {
+ const user = userEvent.setup();
+ setPaidPlan("business");
+ mocks.entitlements.limits = {
+ autopilotRuns: { mode: "limited", limit: 4000 },
+ };
+ Object.assign(mocks.summary, {
+ autopilotAddon: {
+ purchasedRuns: 1000,
+ periodStart: "2030-01-01T00:00:00Z",
+ periodEnd: "2030-02-01T00:00:00Z",
+ },
+ });
+ mocks.previewPlanChange.mockResolvedValue({
+ currentPlan: "business",
+ targetPlan: "pro",
+ interval: "month",
+ seats: 1,
+ subscriptionVersion: 8,
+ currency: "usd",
+ prorationAmount: -1200,
+ nextInvoiceAmount: 1500,
+ invoiceNow: false,
+ quotedAt: "2030-01-15T00:00:00Z",
+ autopilotRunsLimitAfter: 2000,
+ });
+ renderWithI18n(<BillingTab />);
+
+ await user.click(screen.getByRole("button", { name: "Switch to Pro" }));
+ const dialog = await screen.findByRole("dialog");
+ expect(
+ await within(dialog).findByText(
+ "This month's limit becomes 2,000 runs after the switch, including runs you bought. 5 runs are used this month.",
+ ),
+ ).toBeInTheDocument();
+ });
+
it("requests a fresh quote when Cloud reports the quote changed", async () => {
const user = userEvent.setup();
setPaidPlan("pro");
diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsx
index a74e81c940..99aa88847e 100644
--- a/packages/views/settings/components/billing-tab.tsx
+++ b/packages/views/settings/components/billing-tab.tsx
@@ -108,6 +108,8 @@ import {
yearlyPriceMonthlyEquivalent,
} from "./billing-state";
import { formatStripeMinorAmount } from "./billing-format";
+import { AutopilotAddonDialog } from "../../billing/autopilot-addon-dialog";
+import { AutopilotAddonReturnNotice } from "../../billing/autopilot-addon-return-notice";
import { BillingTrialSection } from "./billing-trial-section";
import { settingsHref } from "./settings-navigation";
@@ -139,7 +141,12 @@ const SEAT_PURCHASE_POLL_TIMEOUT_MS = 2 * 60_000;
const SEAT_PURCHASE_PREVIEW_DEBOUNCE_MS = 800;
const PAID_PLANS = ["pro", "business"] as const;
-type WorkspaceBillingReturnResult = "success" | "cancel" | "portal";
+type WorkspaceBillingReturnResult =
+ | "success"
+ | "cancel"
+ | "portal"
+ | "autopilot_addon"
+ | "autopilot_addon_cancel";
function parseReturnResult(
value: string | null,
@@ -148,6 +155,8 @@ function parseReturnResult(
case "success":
case "cancel":
case "portal":
+ case "autopilot_addon":
+ case "autopilot_addon_cancel":
return value;
default:
return null;
@@ -237,10 +246,12 @@ function BillingTabContent() {
workspaceId: string | null;
result: WorkspaceBillingReturnResult | null;
observedAt: number | null;
+ sessionId: string | null;
}>(() => ({
workspaceId: wsId || null,
result: returnResultParam,
observedAt: returnResultParam === "success" ? Date.now() : null,
+ sessionId: returnSessionId,
}));
const returnStateMatchesWorkspace =
returnState.workspaceId === null || returnState.workspaceId === wsId;
@@ -381,6 +392,7 @@ function BillingTabContent() {
workspaceId: wsId || null,
result: returnResultParam,
observedAt: returnResultParam === "success" ? Date.now() : null,
+ sessionId: returnSessionId,
});
if (returnResultParam === "cancel") checkoutIntentRef.current = null;
@@ -391,7 +403,7 @@ function BillingTabContent() {
navigation.replace(
query ? `${navigation.pathname}?${query}` : navigation.pathname,
);
- }, [callbackKey, navigation, returnResultParam, wsId]);
+ }, [callbackKey, navigation, returnResultParam, returnSessionId, wsId]);
useEffect(() => {
if (returnResult !== "success") {
@@ -475,9 +487,14 @@ function BillingTabContent() {
const quotaUsageQuery = useQuery(autopilotQuotaUsageOptions(wsId));
const hasSeatCapacity = hasActiveWorkspaceSeatCapacity(summaryQuery.data);
const canUpgrade = summaryQuery.data?.availableActions.checkout === true;
+ const [autopilotAddonOpen, setAutopilotAddonOpen] = useState(false);
const pricesQuery = useQuery({
...workspaceSubscriptionPricesOptions(wsId),
- enabled: wsId.length > 0 && canUpgrade,
+ // Also read for the add-on pack price shown on the Buy button.
+ enabled:
+ wsId.length > 0 &&
+ (canUpgrade ||
+ summaryQuery.data?.availableActions.purchaseAutopilotRuns === true),
});
const checkoutMutation = useCreateWorkspaceSubscriptionCheckout(wsId);
const portalMutation = useCreateWorkspaceSubscriptionPortal(wsId);
@@ -1289,6 +1306,18 @@ function BillingTabContent() {
storageUsageQuery.isError,
entitlements?.limits.storageBytes,
);
+ // This month's add-on runs, already part of the limit Cloud reports.
+ const autopilotAddon = summaryQuery.data?.autopilotAddon ?? null;
+ const canBuyAutopilotAddon =
+ summaryQuery.data?.availableActions.purchaseAutopilotRuns === true;
+ const autopilotAddonPrice = pricesQuery.data?.autopilotAddon ?? null;
+ const formattedAutopilotAddonPrice = autopilotAddonPrice
+ ? formatStripeMinorAmount(
+ autopilotAddonPrice.unitAmount,
+ autopilotAddonPrice.currency,
+ locale,
+ )
+ : null;
// Members and pending invitations against the plan's member limit, shown
// whenever Cloud applies one (observed or enforced).
const memberLimitData = memberLimitQuery.data;
@@ -1448,6 +1477,20 @@ function BillingTabContent() {
</Alert>
) : null}
+ {returnResult === "autopilot_addon" ? (
+ <AutopilotAddonReturnNotice wsId={wsId} sessionId={returnState.sessionId} />
+ ) : null}
+
+ {returnResult === "autopilot_addon_cancel" ? (
+ <Alert>
+ <AlertCircle />
+ <AlertTitle>{t(($) => $.autopilot_addon.cancel_title)}</AlertTitle>
+ <AlertDescription>
+ {t(($) => $.autopilot_addon.cancel_description)}
+ </AlertDescription>
+ </Alert>
+ ) : null}
+
{returnResult === "portal" ? (
<Alert>
<CheckCircle2 />
@@ -1958,6 +2001,13 @@ function BillingTabContent() {
reserved: numberFormatter.format(quotaUsage.reserved),
})}
</p>
+ {autopilotAddon ? (
+ <p className="text-caption text-muted-foreground tabular-nums">
+ {t(($) => $.workspace.limits.addon_included, {
+ runs: numberFormatter.format(autopilotAddon.purchasedRuns),
+ })}
+ </p>
+ ) : null}
{quotaResetAt ? (
<p className="text-caption text-muted-foreground tabular-nums">
{t(($) => $.workspace.limits.resets_at, {
@@ -2054,6 +2104,38 @@ function BillingTabContent() {
)}
</SettingsRow>
) : null}
+ {autopilotAddon ? (
+ <SettingsRow
+ label={t(($) => $.workspace.limits.addon)}
+ description={t(($) => $.workspace.limits.addon_description)}
+ >
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end">
+ <span className="text-body text-muted-foreground tabular-nums">
+ {autopilotAddon.purchasedRuns > 0
+ ? t(($) => $.workspace.limits.addon_purchased, {
+ runs: numberFormatter.format(autopilotAddon.purchasedRuns),
+ })
+ : t(($) => $.workspace.limits.addon_none)}
+ </span>
+ {canBuyAutopilotAddon ? (
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => setAutopilotAddonOpen(true)}
+ >
+ <Plus />
+ {autopilotAddonPrice && formattedAutopilotAddonPrice
+ ? t(($) => $.workspace.limits.addon_buy, {
+ price: formattedAutopilotAddonPrice,
+ runs: numberFormatter.format(autopilotAddonPrice.runsPerPack),
+ })
+ : t(($) => $.workspace.limits.addon_buy_fallback)}
+ </Button>
+ ) : null}
+ </div>
+ </SettingsRow>
+ ) : null}
{memberLimit ? (
<SettingsRow label={t(($) => $.workspace.limits.members)}>
<div className="flex flex-col gap-1 sm:items-end">
@@ -2562,6 +2644,24 @@ function BillingTabContent() {
</p>
</div>
) : null}
+ {planChangePreview &&
+ !planChangeIsUpgrade &&
+ (autopilotAddon?.purchasedRuns ?? 0) > 0 &&
+ planChangePreview.autopilotRunsLimitAfter !== null ? (
+ <Alert>
+ <AlertCircle />
+ <AlertDescription>
+ {quotaUsage.kind === "metered"
+ ? t(($) => $.workspace.plan_change.addon_downgrade_notice, {
+ limit: numberFormatter.format(planChangePreview.autopilotRunsLimitAfter),
+ used: numberFormatter.format(quotaUsage.total),
+ })
+ : t(($) => $.workspace.plan_change.addon_downgrade_notice_limit_only, {
+ limit: numberFormatter.format(planChangePreview.autopilotRunsLimitAfter),
+ })}
+ </AlertDescription>
+ </Alert>
+ ) : null}
</div>
<DialogFooter>
<Button
@@ -2651,6 +2751,13 @@ function BillingTabContent() {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+ {autopilotAddonOpen ? (
+ <AutopilotAddonDialog
+ wsId={wsId}
+ open={autopilotAddonOpen}
+ onOpenChange={setAutopilotAddonOpen}
+ />
+ ) : null}
</SettingsTab>
);
}
diff --git a/packages/views/settings/components/seat-invite-purchase.test.ts b/packages/views/settings/components/seat-invite-purchase.test.ts
index 5facc263f7..58bcb62794 100644
--- a/packages/views/settings/components/seat-invite-purchase.test.ts
+++ b/packages/views/settings/components/seat-invite-purchase.test.ts
@@ -60,7 +60,9 @@ function summary(purchased: number, available: number): WorkspaceSubscriptionSum
purchaseSeats: true,
changePlan: false,
checkPlanChange: false,
+ purchaseAutopilotRuns: false,
},
+ autopilotAddon: null,
planChange: null,
trial: null,
};
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 655ccc3729..36dd6bb2be 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2171,6 +2171,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/plan-changes/preview", h.PreviewCloudWorkspaceSubscriptionPlanChange)
r.Post("/plan-changes", h.ChangeCloudWorkspaceSubscriptionPlan)
r.Post("/portal-sessions", h.CreateCloudWorkspaceSubscriptionPortal)
+ r.Post("/autopilot-addon/checkout-sessions", h.CreateCloudWorkspaceAutopilotAddonCheckout)
+ r.Get("/autopilot-addon/checkout-sessions/{sessionId}", h.GetCloudWorkspaceAutopilotAddonCheckout)
})
})
diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.md
index 3df5ab8ac4..96e4455026 100644
--- a/server/internal/entitlement/README.md
+++ b/server/internal/entitlement/README.md
@@ -35,10 +35,13 @@ The client reads:
limit and period parameters as `enforce`. Multica also downgrades an expired
cached `enforce` instruction to `observe` locally (see below).
- `gates.*.notifications`: an optional, additive delivery policy. The autopilot
- quota consumer recognizes `first_rejection_per_period` and delivers one
- workspace notice for the first rejected execution in the Cloud-defined quota
- period. A malformed notification policy is ignored without invalidating an
- otherwise valid enforcement gate.
+ quota consumer recognizes two values. `first_rejection_per_period` delivers
+ one notice for the first rejected execution in the Cloud-defined quota
+ period. `first_rejection_per_limit` (revision 6) delivers one notice for the
+ first rejection at each limit within the period, so a limit raised by an
+ add-on purchase re-arms the notice. Any other value, or a malformed
+ notification policy, disables notices without invalidating an otherwise
+ valid enforcement gate.
- `features`: paid-feature restrictions, one `{"action": ...}` per feature
(revision 4). See [Paid features](#paid-features). Each feature is parsed on
its own, after the rest of the policy: a missing, unknown, or malformed
@@ -144,6 +147,14 @@ 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`).
+`FreshRefresher.RefreshGateNow` fetches without the reuse window; concurrent
+callers for a workspace share one fetch. The autopilot quota calls it right
+before rejecting a run: the admission transaction sees the quota is full on
+the cached policy, leaves the transaction, fetches the current policy and runs
+the admission once more on it. A limit Cloud raised moments ago, such as an
+add-on Stripe's webhook confirmed before the payer returned to the app, admits
+the next run on every instance. Each rejection costs one Cloud request.
+
## Member limit
`members` caps the members of a workspace on a plan with a member limit
diff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.go
index b5f95f38d3..a36bee97c6 100644
--- a/server/internal/entitlement/client.go
+++ b/server/internal/entitlement/client.go
@@ -61,6 +61,7 @@ type Client struct {
var (
_ Provider = (*Client)(nil)
_ Refresher = (*Client)(nil)
+ _ FreshRefresher = (*Client)(nil)
_ FeatureProvider = (*Client)(nil)
)
@@ -140,6 +141,26 @@ func (c *Client) RefreshGate(ctx context.Context, workspaceID uuid.UUID, name Ga
return c.recordDecision(name, decisionFromEntry(entry, name, reason, false))
}
+// RefreshGateNow fetches the workspace's policy from Cloud now, without
+// RefreshGate's reuse window, then resolves the gate from it. Concurrent
+// callers for the workspace share one fetch. When the fetch fails it answers
+// exactly like Gate, from the cache or fail-open.
+func (c *Client) RefreshGateNow(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, "now:"+workspaceID.String(),
+ func(cacheEntry, time.Time) bool { return false })
+ 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 {
@@ -523,7 +544,12 @@ func normalizeFeature(raw json.RawMessage) featureEntry {
// notification object must never invalidate the enforcement gate and fail open
// the underlying quota, so it is dropped independently.
func normalizeNotificationPolicy(wire *wireNotificationPolicy) *NotificationPolicy {
- if wire == nil || wire.OnRejection != NotificationFirstRejectionPerPeriod {
+ if wire == nil {
+ return nil
+ }
+ switch wire.OnRejection {
+ case NotificationFirstRejectionPerPeriod, NotificationFirstRejectionPerLimit:
+ default:
return nil
}
return &NotificationPolicy{
diff --git a/server/internal/entitlement/client_test.go b/server/internal/entitlement/client_test.go
index ba7063e240..0f9dd3defc 100644
--- a/server/internal/entitlement/client_test.go
+++ b/server/internal/entitlement/client_test.go
@@ -136,6 +136,16 @@ func TestNotificationPolicyDoesNotControlQuotaValidity(t *testing.T) {
t.Fatalf("valid notification gate = %+v, err = %v", gate, err)
}
+ perLimit := base
+ perLimit.Notifications = &wireNotificationPolicy{
+ OnRejection: NotificationFirstRejectionPerLimit,
+ }
+ gate, err = normalizeGate(GateAutopilotRuns, perLimit)
+ if err != nil || gate.Notifications == nil ||
+ gate.Notifications.OnRejection != NotificationFirstRejectionPerLimit {
+ t.Fatalf("per-limit notification gate = %+v, err = %v", gate, err)
+ }
+
malformed := base
malformed.Notifications = &wireNotificationPolicy{
OnRejection: "future_mode",
diff --git a/server/internal/entitlement/entitlementtest/stub.go b/server/internal/entitlement/entitlementtest/stub.go
index d5dc82e0a3..b82921f932 100644
--- a/server/internal/entitlement/entitlementtest/stub.go
+++ b/server/internal/entitlement/entitlementtest/stub.go
@@ -27,6 +27,7 @@ type Stub struct {
var (
_ entitlement.Provider = (*Stub)(nil)
_ entitlement.Refresher = (*Stub)(nil)
+ _ entitlement.FreshRefresher = (*Stub)(nil)
_ entitlement.FeatureProvider = (*Stub)(nil)
)
@@ -69,7 +70,12 @@ func (s *Stub) RefreshGate(ctx context.Context, workspaceID uuid.UUID, name enti
return s.Gate(ctx, workspaceID, name)
}
-// Refreshes lists every RefreshGate call.
+// RefreshGateNow behaves like RefreshGate: every stub refresh is forced.
+func (s *Stub) RefreshGateNow(ctx context.Context, workspaceID uuid.UUID, name entitlement.GateName) entitlement.Decision {
+ return s.RefreshGate(ctx, workspaceID, name)
+}
+
+// Refreshes lists every RefreshGate and RefreshGateNow call.
func (s *Stub) Refreshes() []Call {
s.mu.RLock()
defer s.mu.RUnlock()
diff --git a/server/internal/entitlement/members_gate_test.go b/server/internal/entitlement/members_gate_test.go
index 04a3b38d73..58e9bf30cf 100644
--- a/server/internal/entitlement/members_gate_test.go
+++ b/server/internal/entitlement/members_gate_test.go
@@ -241,3 +241,43 @@ func TestStorageBytesGateFailsOpenAlone(t *testing.T) {
})
}
}
+
+func TestRefreshGateNowSkipsTheReuseWindow(t *testing.T) {
+ clock := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
+ var calls atomic.Int64
+ var limit atomic.Int64
+ limit.Store(10)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ policy := samplePolicy(6, 1, 60, ActionEnforce)
+ gate := policy.Gates[string(GateAutopilotRuns)]
+ value := int(limit.Load())
+ gate.Limit = &value
+ policy.Gates[string(GateAutopilotRuns)] = gate
+ 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, GateAutopilotRuns); first.Gate.Limit == nil || *first.Gate.Limit != 10 {
+ t.Fatalf("first = %+v; want limit 10", first)
+ }
+
+ // Cloud raises the limit one second later (an add-on confirmed by
+ // Stripe's webhook), inside RefreshGate's reuse window.
+ limit.Store(1010)
+ clock = clock.Add(time.Second)
+ if reused := client.RefreshGate(context.Background(), workspaceID, GateAutopilotRuns); *reused.Gate.Limit != 10 || calls.Load() != 1 {
+ t.Fatalf("RefreshGate = %+v, calls = %d; it reuses a policy this young", reused, calls.Load())
+ }
+ refreshed := client.RefreshGateNow(context.Background(), workspaceID, GateAutopilotRuns)
+ if refreshed.Gate.Limit == nil || *refreshed.Gate.Limit != 1010 || refreshed.Reason != ReasonRefreshed || calls.Load() != 2 {
+ t.Fatalf("RefreshGateNow = %+v, calls = %d; want the new limit", refreshed, calls.Load())
+ }
+ // The refreshed policy is cached for everyone else.
+ if cached := client.Gate(context.Background(), workspaceID, GateAutopilotRuns); *cached.Gate.Limit != 1010 || calls.Load() != 2 {
+ t.Fatalf("Gate after refresh = %+v, calls = %d", cached, calls.Load())
+ }
+}
diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.go
index 241434db32..b03f302649 100644
--- a/server/internal/entitlement/types.go
+++ b/server/internal/entitlement/types.go
@@ -39,7 +39,13 @@ const (
ActionObserve Action = "observe"
ActionEnforce Action = "enforce"
+ // NotificationFirstRejectionPerPeriod notifies on the first rejection of
+ // a period only.
NotificationFirstRejectionPerPeriod = "first_rejection_per_period"
+ // NotificationFirstRejectionPerLimit notifies on the first rejection for
+ // each limit within a period, so a limit raised by an add-on purchase
+ // re-arms the notice (policy revision 6).
+ NotificationFirstRejectionPerLimit = "first_rejection_per_limit"
)
type Reason string
@@ -110,6 +116,15 @@ type Refresher interface {
RefreshGate(ctx context.Context, workspaceID uuid.UUID, name GateName) Decision
}
+// FreshRefresher re-reads one gate from Cloud now, skipping the short reuse
+// window RefreshGate applies; concurrent callers for a workspace share one
+// fetch. The autopilot quota calls it right before rejecting a run, so a limit
+// Cloud raised moments ago (a paid add-on confirmed by Stripe's webhook) is
+// never refused on a policy any instance cached before it.
+type FreshRefresher interface {
+ RefreshGateNow(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 string
diff --git a/server/internal/handler/cloud_billing_autopilot_addon.go b/server/internal/handler/cloud_billing_autopilot_addon.go
new file mode 100644
index 0000000000..3e8d2f76c1
--- /dev/null
+++ b/server/internal/handler/cloud_billing_autopilot_addon.go
@@ -0,0 +1,148 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/cloudruntime"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// Autopilot add-on packs (MUL-9487): a one-time purchase of extra autopilot
+// runs for the current month, paid on Stripe Checkout. Cloud owns the Price,
+// the Checkout Session and the limit; Multica forwards an allowlisted request
+// and, once Cloud reports a session paid, makes every API instance read the
+// raised limit before it rejects another run.
+
+// maxAutopilotAddonPacks mirrors Cloud's bound on one purchase.
+const maxAutopilotAddonPacks = 10
+
+const maxCloudSubscriptionAutopilotAddonIdempotencyKeyLength = 200
+
+type cloudSubscriptionAutopilotAddonCheckoutRequest struct {
+ Packs int `json:"packs"`
+ ExpectedUnitAmount int64 `json:"expected_unit_amount"`
+ Currency string `json:"currency"`
+ IdempotencyKey string `json:"idempotency_key,omitempty"`
+}
+
+// cloudSubscriptionAutopilotAddonSessionStatus is the one field Multica reads
+// from Cloud's session response; the body is forwarded unchanged.
+type cloudSubscriptionAutopilotAddonSessionStatus struct {
+ Status string `json:"status"`
+}
+
+// CreateCloudWorkspaceAutopilotAddonCheckout forwards a request to pay for
+// add-on packs on Stripe Checkout. The allowlisted body names only the pack
+// count and the price the caller saw; Cloud repeats the price check, owns
+// idempotency and returns the Checkout URL.
+func (h *Handler) CreateCloudWorkspaceAutopilotAddonCheckout(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")
+ if !ok {
+ return
+ }
+ body, ok := readCloudRuntimeJSONBody(w, r)
+ if !ok {
+ return
+ }
+ var in cloudSubscriptionAutopilotAddonCheckoutRequest
+ if err := json.Unmarshal(body, &in); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if in.Packs < 1 || in.Packs > maxAutopilotAddonPacks || in.ExpectedUnitAmount < 1 || !isASCIICurrency(in.Currency) {
+ writeError(w, http.StatusBadRequest, "invalid autopilot add-on purchase")
+ return
+ }
+ key, ok := requireCloudSubscriptionIdempotencyKey(w, r, in.IdempotencyKey)
+ if !ok {
+ return
+ }
+ if len(key) > maxCloudSubscriptionAutopilotAddonIdempotencyKeyLength {
+ writeError(w, http.StatusBadRequest, "autopilot add-on idempotency key must be at most 200 bytes")
+ return
+ }
+ in.Currency = strings.ToLower(in.Currency)
+ in.IdempotencyKey = key
+ upstreamBody, err := json.Marshal(in)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to build autopilot add-on purchase")
+ return
+ }
+ h.proxyCloudSubscription(w, r, http.MethodPost,
+ "/api/v1/subscriptions/"+workspaceID+"/autopilot-addon/checkout-sessions", userID, upstreamBody,
+ http.Header{idempotencyKeyHeader: []string{key}})
+}
+
+// GetCloudWorkspaceAutopilotAddonCheckout forwards a Checkout Session status
+// read. Cloud settles a paid session before answering, so the Billing return
+// page learns at once that the runs were added.
+func (h *Handler) GetCloudWorkspaceAutopilotAddonCheckout(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r, "owner", "admin")
+ if !ok {
+ return
+ }
+ sessionID := chi.URLParam(r, "sessionId")
+ if !isValidStripeSessionID(sessionID) {
+ writeError(w, http.StatusBadRequest, "invalid session_id")
+ return
+ }
+ h.proxyCloudAutopilotAddonPurchase(w, r, http.MethodGet,
+ "/api/v1/subscriptions/"+workspaceID+"/autopilot-addon/checkout-sessions/"+sessionID, workspaceID, userID, nil, nil)
+}
+
+func (h *Handler) proxyCloudAutopilotAddonPurchase(
+ w http.ResponseWriter,
+ r *http.Request,
+ method, path, workspaceID, userID string,
+ body []byte,
+ headers http.Header,
+) {
+ if h.CloudRuntime == nil || !h.CloudRuntime.Enabled() {
+ writeFeatureDisabled(w, "cloud_runtime_not_configured", "cloud runtime is not configured")
+ return
+ }
+ resp, err := h.CloudRuntime.Do(r.Context(), cloudruntime.Request{
+ Method: method,
+ Path: path,
+ Body: body,
+ UserID: userID,
+ RequestID: cloudRuntimeRequestID(r),
+ Op: "billing",
+ Headers: headers,
+ })
+ if err != nil {
+ writeCloudRuntimeError(w, r, err)
+ return
+ }
+ if resp.StatusCode == http.StatusOK {
+ var status cloudSubscriptionAutopilotAddonSessionStatus
+ if json.Unmarshal(resp.Body, &status) == nil && status.Status == "paid" {
+ h.recordAutopilotAddonPaid(r, workspaceID)
+ }
+ }
+ writeCloudRuntimeResponse(w, resp)
+}
+
+// recordAutopilotAddonPaid refreshes this instance's cached policy so the
+// Billing page shows the raised limit at once. Admission does not depend on
+// it: every instance fetches the policy from Cloud before rejecting a run.
+func (h *Handler) recordAutopilotAddonPaid(r *http.Request, workspaceID string) {
+ workspaceUUID, err := util.ParseUUID(workspaceID)
+ if err != nil {
+ return
+ }
+ refresher, ok := h.Entitlements.(entitlement.FreshRefresher)
+ if !ok {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second)
+ defer cancel()
+ refresher.RefreshGateNow(ctx, uuid.UUID(workspaceUUID.Bytes), entitlement.GateAutopilotRuns)
+}
diff --git a/server/internal/handler/cloud_billing_autopilot_addon_test.go b/server/internal/handler/cloud_billing_autopilot_addon_test.go
new file mode 100644
index 0000000000..d4e81e01eb
--- /dev/null
+++ b/server/internal/handler/cloud_billing_autopilot_addon_test.go
@@ -0,0 +1,130 @@
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/cloudruntime"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+)
+
+func TestCloudWorkspaceAutopilotAddonCheckoutForwardsOnlyAllowlistedFields(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+ session := []byte(`{"session_id":"cs_test_1","url":"https://checkout.stripe.com/c/pay/cs_test_1"}`)
+ proxy := &fakeCloudRuntimeProxy{enabled: true, resp: &cloudruntime.Response{StatusCode: http.StatusOK, Body: session}}
+ useCloudRuntimeProxy(t, proxy)
+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodPost, "/api/cloud-subscriptions/autopilot-addon/checkout-sessions", map[string]any{
+ "workspace_id": "00000000-0000-0000-0000-000000000001",
+ "runs": 999999,
+ "success_url": "https://evil.example/",
+ "packs": 3,
+ "expected_unit_amount": 1000,
+ "currency": "USD",
+ "idempotency_key": "addon-request-1",
+ }), "owner")
+ w := httptest.NewRecorder()
+ testHandler.CreateCloudWorkspaceAutopilotAddonCheckout(w, req)
+
+ if w.Code != http.StatusOK || w.Body.String() != string(session) || proxy.req.Method != http.MethodPost ||
+ proxy.req.Path != "/api/v1/subscriptions/"+testWorkspaceID+"/autopilot-addon/checkout-sessions" ||
+ proxy.req.UserID != testUserID {
+ t.Fatalf("status=%d upstream=%s %s body=%s", w.Code, proxy.req.Method, proxy.req.Path, w.Body.String())
+ }
+ var body map[string]any
+ if err := json.Unmarshal(proxy.req.Body, &body); err != nil {
+ t.Fatal(err)
+ }
+ for _, leaked := range []string{"workspace_id", "runs", "success_url"} {
+ if _, ok := body[leaked]; ok {
+ t.Fatalf("client %s leaked upstream: %v", leaked, body)
+ }
+ }
+ if body["packs"] != float64(3) || body["expected_unit_amount"] != float64(1000) ||
+ body["currency"] != "usd" || body["idempotency_key"] != "addon-request-1" {
+ t.Fatalf("upstream body=%v", body)
+ }
+ if proxy.req.Headers.Get(idempotencyKeyHeader) != "addon-request-1" {
+ t.Fatalf("upstream idempotency=%q", proxy.req.Headers.Get(idempotencyKeyHeader))
+ }
+}
+
+func TestCloudWorkspaceAutopilotAddonCheckoutValidatesLocally(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+ cases := map[string]map[string]any{
+ "zero packs": {"packs": 0, "expected_unit_amount": 1000, "currency": "usd", "idempotency_key": "k"},
+ "too many packs": {"packs": 11, "expected_unit_amount": 1000, "currency": "usd", "idempotency_key": "k"},
+ "missing price": {"packs": 1, "currency": "usd", "idempotency_key": "k"},
+ "bad currency": {"packs": 1, "expected_unit_amount": 1000, "currency": "us", "idempotency_key": "k"},
+ "missing idempotency": {"packs": 1, "expected_unit_amount": 1000, "currency": "usd"},
+ }
+ for name, body := range cases {
+ t.Run(name, func(t *testing.T) {
+ proxy := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, proxy)
+ w := httptest.NewRecorder()
+ testHandler.CreateCloudWorkspaceAutopilotAddonCheckout(w, withCloudSubscriptionWorkspace(
+ newRequest(http.MethodPost, "/api/cloud-subscriptions/autopilot-addon/checkout-sessions", body), "owner"))
+ if w.Code != http.StatusBadRequest || proxy.called {
+ t.Fatalf("status=%d called=%v body=%s", w.Code, proxy.called, w.Body.String())
+ }
+ })
+ }
+
+ member := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, member)
+ w := httptest.NewRecorder()
+ testHandler.CreateCloudWorkspaceAutopilotAddonCheckout(w, withCloudSubscriptionWorkspace(
+ newRequest(http.MethodPost, "/api/cloud-subscriptions/autopilot-addon/checkout-sessions", map[string]any{
+ "packs": 1, "expected_unit_amount": 1000, "currency": "usd", "idempotency_key": "member",
+ }), "member"))
+ if w.Code != http.StatusForbidden || member.called {
+ t.Fatalf("member checkout status=%d called=%v", w.Code, member.called)
+ }
+}
+
+func TestCloudWorkspaceAutopilotAddonSessionStatusIsForwarded(t *testing.T) {
+ withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, true)
+ read := func(status string) *httptest.ResponseRecorder {
+ t.Helper()
+ body := []byte(`{"session_id":"cs_test_1","status":"` + status + `","runs":1000}`)
+ proxy := &fakeCloudRuntimeProxy{enabled: true, resp: &cloudruntime.Response{StatusCode: http.StatusOK, Body: body}}
+ useCloudRuntimeProxy(t, proxy)
+ req := withURLParam(withCloudSubscriptionWorkspace(
+ newRequest(http.MethodGet, "/api/cloud-subscriptions/autopilot-addon/checkout-sessions/cs_test_1", nil), "owner"),
+ "sessionId", "cs_test_1")
+ w := httptest.NewRecorder()
+ testHandler.GetCloudWorkspaceAutopilotAddonCheckout(w, req)
+ if w.Code != http.StatusOK || w.Body.String() != string(body) ||
+ proxy.req.Path != "/api/v1/subscriptions/"+testWorkspaceID+"/autopilot-addon/checkout-sessions/cs_test_1" {
+ t.Fatalf("status=%d upstream=%s body=%s", w.Code, proxy.req.Path, w.Body.String())
+ }
+ return w
+ }
+
+ read("open")
+ read("paid")
+
+ invalid := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, invalid)
+ req := withURLParam(withCloudSubscriptionWorkspace(
+ newRequest(http.MethodGet, "/api/cloud-subscriptions/autopilot-addon/checkout-sessions/x", nil), "owner"),
+ "sessionId", "../../billing/balance")
+ w := httptest.NewRecorder()
+ testHandler.GetCloudWorkspaceAutopilotAddonCheckout(w, req)
+ if w.Code != http.StatusBadRequest || invalid.called {
+ t.Fatalf("invalid id status=%d called=%v", w.Code, invalid.called)
+ }
+
+ member := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, member)
+ req = withURLParam(withCloudSubscriptionWorkspace(
+ newRequest(http.MethodGet, "/api/cloud-subscriptions/autopilot-addon/checkout-sessions/cs_test_1", nil), "member"),
+ "sessionId", "cs_test_1")
+ w = httptest.NewRecorder()
+ testHandler.GetCloudWorkspaceAutopilotAddonCheckout(w, req)
+ if w.Code != http.StatusForbidden || member.called {
+ t.Fatalf("member read status=%d called=%v", w.Code, member.called)
+ }
+}
diff --git a/server/internal/service/autopilot_quota.go b/server/internal/service/autopilot_quota.go
index 68be1c9a71..9fee08b8cd 100644
--- a/server/internal/service/autopilot_quota.go
+++ b/server/internal/service/autopilot_quota.go
@@ -63,6 +63,11 @@ type autopilotQuotaPolicy struct {
notifications *entitlement.NotificationPolicy
}
+// errAutopilotQuotaWouldReject leaves the admission transaction before a
+// rejection so the caller can fetch the policy from Cloud again (outside the
+// period lock) and run the admission once more on it.
+var errAutopilotQuotaWouldReject = errors.New("autopilot quota would reject on the cached policy")
+
func newAutopilotIdempotencyKey() string { return uuid.NewString() }
// NewRequestIdempotencyKey is used only when an HTTP caller omitted its key;
@@ -82,7 +87,32 @@ func (s *AutopilotService) quotaPolicy(ctx context.Context, workspaceID pgtype.U
if s.Entitlements == nil || !workspaceID.Valid {
return autopilotQuotaPolicy{}, false
}
- decision := s.Entitlements.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateAutopilotRuns)
+ return autopilotQuotaPolicyFromDecision(
+ s.Entitlements.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateAutopilotRuns),
+ )
+}
+
+// refreshedQuotaPolicy fetches the policy from Cloud right before a
+// rejection, skipping any reuse window, so a limit raised moments ago — an
+// add-on Stripe's webhook confirmed while the buyer has not returned to the
+// app yet — admits the run whichever instance cached the old one.
+func (s *AutopilotService) refreshedQuotaPolicy(ctx context.Context, workspaceID pgtype.UUID) (autopilotQuotaPolicy, bool) {
+ if s.Entitlements == nil || !workspaceID.Valid {
+ return autopilotQuotaPolicy{}, false
+ }
+ workspace := uuid.UUID(workspaceID.Bytes)
+ var decision entitlement.Decision
+ if fresh, ok := s.Entitlements.(entitlement.FreshRefresher); ok {
+ decision = fresh.RefreshGateNow(ctx, workspace, entitlement.GateAutopilotRuns)
+ } else if refresher, ok := s.Entitlements.(entitlement.Refresher); ok {
+ decision = refresher.RefreshGate(ctx, workspace, entitlement.GateAutopilotRuns)
+ } else {
+ decision = s.Entitlements.Gate(ctx, workspace, entitlement.GateAutopilotRuns)
+ }
+ return autopilotQuotaPolicyFromDecision(decision)
+}
+
+func autopilotQuotaPolicyFromDecision(decision entitlement.Decision) (autopilotQuotaPolicy, bool) {
gate := decision.Gate
if gate.Action == entitlement.ActionOff {
return autopilotQuotaPolicy{}, false
@@ -224,7 +254,31 @@ func (s *AutopilotService) createAutopilotRunWithQuota(
run, err := s.Queries.CreateAutopilotRun(ctx, params)
return run, false, err
}
+ run, reused, err := s.admitAutopilotRunWithQuota(ctx, policy, true, workspaceID, source, idempotencyKey, params)
+ if !errors.Is(err, errAutopilotQuotaWouldReject) {
+ return run, reused, err
+ }
+ // The run was about to be rejected on the cached policy. Decide once more
+ // on Cloud's current one, so an add-on paid moments ago admits it.
+ policy, enabled = s.refreshedQuotaPolicy(ctx, workspaceID)
+ if !enabled {
+ run, err := s.Queries.CreateAutopilotRun(ctx, params)
+ return run, false, err
+ }
+ return s.admitAutopilotRunWithQuota(ctx, policy, false, workspaceID, source, idempotencyKey, params)
+}
+// admitAutopilotRunWithQuota is one admission attempt under policy. With
+// refreshBeforeReject set, a rejection returns errAutopilotQuotaWouldReject
+// instead, before anything is written.
+func (s *AutopilotService) admitAutopilotRunWithQuota(
+ ctx context.Context,
+ policy autopilotQuotaPolicy,
+ refreshBeforeReject bool,
+ workspaceID pgtype.UUID,
+ source, idempotencyKey string,
+ params db.CreateAutopilotRunParams,
+) (db.AutopilotRun, bool, error) {
tx, err := s.TxStarter.Begin(ctx)
if err != nil {
return db.AutopilotRun{}, false, fmt.Errorf("begin quota admission: %w", err)
@@ -292,6 +346,11 @@ func (s *AutopilotService) createAutopilotRunWithQuota(
}
wouldBlock := period.UsedCount+period.ReservedCount >= policy.limit
+ if wouldBlock && policy.action == entitlement.ActionEnforce && refreshBeforeReject {
+ // Nothing was written yet; the deferred rollback releases the period
+ // lock before the caller calls Cloud.
+ return db.AutopilotRun{}, false, errAutopilotQuotaWouldReject
+ }
if wouldBlock && policy.action == entitlement.ActionEnforce {
period, err = qtx.IncrementAutopilotQuotaBlocked(ctx, db.IncrementAutopilotQuotaBlockedParams{
Source: source, WorkspaceID: workspaceID,
diff --git a/server/internal/service/autopilot_quota_addon_test.go b/server/internal/service/autopilot_quota_addon_test.go
new file mode 100644
index 0000000000..db15b04a7e
--- /dev/null
+++ b/server/internal/service/autopilot_quota_addon_test.go
@@ -0,0 +1,365 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+)
+
+// fakeCloudPolicy serves the internal entitlement-policy endpoint with an
+// enforced autopilot_runs gate whose limit a test can raise, standing in for
+// Cloud after an add-on purchase.
+type fakeCloudPolicy struct {
+ server *httptest.Server
+ limit atomic.Int64
+ fetches atomic.Int64
+ periodStart time.Time
+ periodEnd time.Time
+}
+
+func newFakeCloudPolicy(t *testing.T, f *autopilotQuotaFixture, limit int64) *fakeCloudPolicy {
+ t.Helper()
+ cloud := &fakeCloudPolicy{periodStart: f.periodStart, periodEnd: f.periodEnd}
+ cloud.limit.Store(limit)
+ cloud.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ cloud.fetches.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "schema_version": entitlement.SchemaVersion,
+ "policy_revision": 6,
+ "subscription_version": 3,
+ "valid_until": time.Now().Add(time.Minute).UTC().Format(time.RFC3339),
+ "valid_for_seconds": 60,
+ "gates": map[string]any{
+ "autopilot_runs": map[string]any{
+ "action": "enforce",
+ "limit": cloud.limit.Load(),
+ "period_start": cloud.periodStart.Format(time.RFC3339),
+ "period_end": cloud.periodEnd.Format(time.RFC3339),
+ "reset_at": cloud.periodEnd.Format(time.RFC3339),
+ "notifications": map[string]any{"on_rejection": entitlement.NotificationFirstRejectionPerLimit},
+ },
+ },
+ })
+ }))
+ t.Cleanup(cloud.server.Close)
+ return cloud
+}
+
+// newAutopilotQuotaInstance is one API instance: its own entitlement client
+// and policy cache over the shared database.
+func newAutopilotQuotaInstance(t *testing.T, f *autopilotQuotaFixture, cloud *fakeCloudPolicy) *AutopilotService {
+ t.Helper()
+ client, err := entitlement.New(entitlement.Config{
+ BaseURL: cloud.server.URL,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ })
+ if err != nil {
+ t.Fatalf("entitlement client: %v", err)
+ }
+ return &AutopilotService{Queries: f.queries, TxStarter: f.pool, Bus: events.New(), Entitlements: client}
+}
+
+func cleanupPolicyChange(t *testing.T, f *autopilotQuotaFixture) {
+ t.Helper()
+ t.Cleanup(func() { cleanupNotices(t, f) })
+}
+
+func cleanupNotices(t *testing.T, f *autopilotQuotaFixture) {
+ t.Helper()
+ f.pool.Exec(context.Background(), `DELETE FROM inbox_item WHERE workspace_id = $1 AND type = 'autopilot_quota_exceeded'`, f.workspaceID)
+}
+
+func countAutopilotQuotaNotices(t *testing.T, f *autopilotQuotaFixture) map[string]int {
+ t.Helper()
+ rows, err := f.pool.Query(context.Background(), `
+ SELECT recipient_id FROM inbox_item
+ WHERE workspace_id = $1 AND type = 'autopilot_quota_exceeded'`, f.workspaceID)
+ if err != nil {
+ t.Fatalf("list quota notices: %v", err)
+ }
+ defer rows.Close()
+ out := make(map[string]int)
+ for rows.Next() {
+ var recipientID pgtype.UUID
+ if err := rows.Scan(&recipientID); err != nil {
+ t.Fatalf("scan quota notice: %v", err)
+ }
+ out[util.UUIDToString(recipientID)]++
+ }
+ return out
+}
+
+func scheduleRun(ctx context.Context, svc *AutopilotService, f *autopilotQuotaFixture, key string) error {
+ params := f.createRunArgs
+ params.Source = "schedule"
+ _, _, err := svc.createAutopilotRunWithQuota(ctx, f.workspaceID, "schedule", key, params)
+ return err
+}
+
+// Stripe's webhook confirmed the add-on to Cloud while the payer has not
+// returned to the app, so no Multica instance has heard of it. Instance B
+// cached the old limit a moment ago (well inside RefreshGate's 5 s reuse
+// window); its very next scheduled run must still start, without a "limit
+// reached" notice.
+func TestAutopilotQuotaWebhookConfirmedAddonAdmitsNextRunBeforeReturn(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ cleanupPolicyChange(t, fixture)
+ cloud := newFakeCloudPolicy(t, fixture, 1)
+ instanceA := newAutopilotQuotaInstance(t, fixture, cloud)
+ instanceB := newAutopilotQuotaInstance(t, fixture, cloud)
+ ctx := context.Background()
+
+ // Both instances hold the full quota's policy.
+ if err := scheduleRun(ctx, instanceB, fixture, "fill-on-b"); err != nil {
+ t.Fatalf("fill quota on B: %v", err)
+ }
+ var quotaErr *AutopilotQuotaExceededError
+ if err := scheduleRun(ctx, instanceA, fixture, "reject-on-a"); !errors.As(err, &quotaErr) {
+ t.Fatalf("run on A before the add-on = %v, want quota error", err)
+ }
+ if err := scheduleRun(ctx, instanceB, fixture, "reject-on-b"); !errors.As(err, &quotaErr) {
+ t.Fatalf("run on B before the add-on = %v, want quota error", err)
+ }
+ cleanupNotices(t, fixture)
+ fetchesBefore := cloud.fetches.Load()
+
+ // Webhook settles the add-on in Cloud. Nothing happens in Multica.
+ cloud.limit.Store(1001)
+
+ if err := scheduleRun(ctx, instanceB, fixture, "after-addon-on-b"); err != nil {
+ t.Fatalf("scheduled run on B after the webhook = %v, want admitted", err)
+ }
+ if err := scheduleRun(ctx, instanceA, fixture, "after-addon-on-a"); err != nil {
+ t.Fatalf("scheduled run on A after the webhook = %v, want admitted", err)
+ }
+ if got := cloud.fetches.Load() - fetchesBefore; got != 2 {
+ t.Fatalf("instances fetched the policy %d times after the change, want one refresh each", got)
+ }
+ if notices := countAutopilotQuotaNotices(t, fixture); len(notices) != 0 {
+ t.Fatalf("limit-reached notices after the add-on = %v, want none", notices)
+ }
+}
+
+// Every rejection asks Cloud for the current policy first, once, and still
+// rejects when the limit is really reached; the notice goes out once per
+// limit, not once per rejection.
+func TestAutopilotQuotaRejectionFetchesThePolicyOnce(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ cleanupPolicyChange(t, fixture)
+ cloud := newFakeCloudPolicy(t, fixture, 1)
+ instance := newAutopilotQuotaInstance(t, fixture, cloud)
+ ctx := context.Background()
+
+ if err := scheduleRun(ctx, instance, fixture, "fill"); err != nil {
+ t.Fatalf("fill quota: %v", err)
+ }
+ fetchesBefore := cloud.fetches.Load()
+ for i := range 3 {
+ var quotaErr *AutopilotQuotaExceededError
+ if err := scheduleRun(ctx, instance, fixture, fmt.Sprintf("reject-%d", i)); !errors.As(err, &quotaErr) {
+ t.Fatalf("rejection %d = %v, want quota error", i, err)
+ }
+ }
+ if got := cloud.fetches.Load() - fetchesBefore; got != 3 {
+ t.Fatalf("3 rejections fetched the policy %d times, want one each", got)
+ }
+ total := 0
+ for _, n := range countAutopilotQuotaNotices(t, fixture) {
+ total += n
+ }
+ if total == 0 {
+ t.Fatal("no limit-reached notice for a real rejection")
+ }
+ first := total
+ if err := scheduleRun(ctx, instance, fixture, "reject-again"); err == nil {
+ t.Fatal("run past the limit admitted")
+ }
+ total = 0
+ for _, n := range countAutopilotQuotaNotices(t, fixture) {
+ total += n
+ }
+ if total != first {
+ t.Fatalf("notices grew from %d to %d on the same limit", first, total)
+ }
+}
+
+// When nobody confirmed the add-on in the app (the payer closed the Stripe
+// tab and Cloud settled it from the webhook), a rejection still asks for the
+// current policy first, so a raised limit admits the run.
+func TestAutopilotQuotaRejectionRefreshesThePolicyFromTheStub(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ cleanupPolicyChange(t, fixture)
+ if _, _, err := fixture.service.createAutopilotRunWithQuota(
+ context.Background(), fixture.workspaceID, "schedule", "fill", fixture.createRunArgs,
+ ); err != nil {
+ t.Fatalf("fill quota: %v", err)
+ }
+ raised := 1001
+ fixture.stub.SetRefreshed(fixture.workspace, entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{
+ Action: entitlement.ActionEnforce, Limit: &raised,
+ PeriodStart: &fixture.periodStart, PeriodEnd: &fixture.periodEnd, ResetAt: &fixture.resetAt,
+ },
+ PolicyRevision: 6, SubscriptionVersion: 11,
+ })
+ refreshesBefore := len(fixture.stub.Refreshes())
+ if _, _, err := fixture.service.createAutopilotRunWithQuota(
+ context.Background(), fixture.workspaceID, "schedule", "after-webhook", fixture.createRunArgs,
+ ); err != nil {
+ t.Fatalf("run after an add-on settled by webhook = %v, want admitted", err)
+ }
+ if got := len(fixture.stub.Refreshes()) - refreshesBefore; got != 1 {
+ t.Fatalf("refreshes = %d, want one before rejecting", got)
+ }
+}
+
+func (f *autopilotQuotaFixture) setPerLimitNotificationPolicy(limit int) {
+ f.stub.Set(f.workspace, entitlement.GateAutopilotRuns, entitlement.Decision{
+ Gate: entitlement.Gate{
+ Action: entitlement.ActionEnforce, Limit: &limit,
+ PeriodStart: &f.periodStart, PeriodEnd: &f.periodEnd, ResetAt: &f.resetAt,
+ Notifications: &entitlement.NotificationPolicy{
+ OnRejection: entitlement.NotificationFirstRejectionPerLimit,
+ },
+ },
+ PolicyRevision: 6, SubscriptionVersion: 11,
+ })
+}
+
+// Per limit, a rejection at a raised limit notifies again; concurrent
+// rejections at one limit notify once.
+func TestAutopilotQuotaPerLimitNoticeRearmsAfterTheLimitGrows(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 1)
+ cleanupPolicyChange(t, fixture)
+ fixture.setPerLimitNotificationPolicy(1)
+ ctx := context.Background()
+ owner := util.UUIDToString(fixture.publisherID)
+
+ rejectConcurrently := func(prefix string, attempts int) {
+ t.Helper()
+ start := make(chan struct{})
+ var wg sync.WaitGroup
+ errs := make(chan error, attempts)
+ for i := range attempts {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ var quotaErr *AutopilotQuotaExceededError
+ if err := scheduleRun(ctx, fixture.service, fixture, fmt.Sprintf("%s-%d", prefix, i)); !errors.As(err, &quotaErr) {
+ errs <- fmt.Errorf("%s %d = %v, want quota error", prefix, i, err)
+ }
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ t.Error(err)
+ }
+ }
+
+ if err := scheduleRun(ctx, fixture.service, fixture, "fill-1"); err != nil {
+ t.Fatalf("fill: %v", err)
+ }
+ rejectConcurrently("at-limit-1", 8)
+ if got := countAutopilotQuotaNotices(t, fixture)[owner]; got != 1 {
+ t.Fatalf("notices at limit 1 = %d, want one", got)
+ }
+
+ // An add-on raises the limit; the workspace runs out again.
+ fixture.setPerLimitNotificationPolicy(2)
+ if err := scheduleRun(ctx, fixture.service, fixture, "fill-2"); err != nil {
+ t.Fatalf("run after the add-on: %v", err)
+ }
+ rejectConcurrently("at-limit-2", 8)
+ if got := countAutopilotQuotaNotices(t, fixture)[owner]; got != 2 {
+ t.Fatalf("notices after the limit grew = %d, want one more", got)
+ }
+
+ // The legacy per-period policy keeps one notice for the whole period.
+ fixture.setNotificationPolicy(2)
+ rejectConcurrently("per-period", 3)
+ if got := countAutopilotQuotaNotices(t, fixture)[owner]; got != 2 {
+ t.Fatalf("per-period notices = %d, want no more", got)
+ }
+}
+
+func TestAutopilotQuotaNoticeReachesTheAutopilotCreator(t *testing.T) {
+ cases := []struct {
+ name string
+ // creator returns the autopilot creator and the recipients expected
+ // besides the owner.
+ setup func(t *testing.T, f *autopilotQuotaFixture) (creator pgtype.UUID, want []pgtype.UUID)
+ }{
+ {
+ name: "admin and member creator",
+ setup: func(t *testing.T, f *autopilotQuotaFixture) (pgtype.UUID, []pgtype.UUID) {
+ admin := addAutopilotQuotaMember(t, f, "admin")
+ creator := addAutopilotQuotaMember(t, f, "member")
+ return creator, []pgtype.UUID{admin, creator}
+ },
+ },
+ {
+ name: "creator is an admin",
+ setup: func(t *testing.T, f *autopilotQuotaFixture) (pgtype.UUID, []pgtype.UUID) {
+ creator := addAutopilotQuotaMember(t, f, "admin")
+ return creator, []pgtype.UUID{creator}
+ },
+ },
+ {
+ name: "creator left the workspace",
+ setup: func(t *testing.T, f *autopilotQuotaFixture) (pgtype.UUID, []pgtype.UUID) {
+ admin := addAutopilotQuotaMember(t, f, "admin")
+ creator := addAutopilotQuotaMember(t, f, "member")
+ if _, err := f.pool.Exec(context.Background(),
+ `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, f.workspaceID, creator); err != nil {
+ t.Fatalf("remove creator: %v", err)
+ }
+ return creator, []pgtype.UUID{admin}
+ },
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ fixture := newAutopilotQuotaFixture(t, entitlement.ActionEnforce, 0)
+ cleanupPolicyChange(t, fixture)
+ fixture.setPerLimitNotificationPolicy(0)
+ creator, extra := tc.setup(t, fixture)
+ if _, err := fixture.pool.Exec(context.Background(),
+ `UPDATE autopilot SET created_by_type = 'member', created_by_id = $2 WHERE id = $1`,
+ fixture.autopilotID, creator); err != nil {
+ t.Fatalf("set autopilot creator: %v", err)
+ }
+ var quotaErr *AutopilotQuotaExceededError
+ if err := scheduleRun(context.Background(), fixture.service, fixture, "rejected"); !errors.As(err, &quotaErr) {
+ t.Fatalf("rejection = %v, want quota error", err)
+ }
+ got := countAutopilotQuotaNotices(t, fixture)
+ want := append([]pgtype.UUID{fixture.publisherID}, extra...)
+ if len(got) != len(want) {
+ t.Fatalf("recipients = %v, want %d recipients", got, len(want))
+ }
+ for _, id := range want {
+ if got[util.UUIDToString(id)] != 1 {
+ t.Fatalf("recipient %s notices = %d, want one (all: %v)", util.UUIDToString(id), got[util.UUIDToString(id)], got)
+ }
+ }
+ })
+ }
+}
diff --git a/server/internal/service/autopilot_quota_notifications.go b/server/internal/service/autopilot_quota_notifications.go
index 8aaba6ef5c..41c009acdf 100644
--- a/server/internal/service/autopilot_quota_notifications.go
+++ b/server/internal/service/autopilot_quota_notifications.go
@@ -38,8 +38,12 @@ func (s *AutopilotService) deliverAutopilotQuotaRejectionNotice(
source string,
params db.CreateAutopilotRunParams,
) {
- if policy.action != entitlement.ActionEnforce || policy.notifications == nil ||
- policy.notifications.OnRejection != entitlement.NotificationFirstRejectionPerPeriod {
+ if policy.action != entitlement.ActionEnforce || policy.notifications == nil {
+ return
+ }
+ switch policy.notifications.OnRejection {
+ case entitlement.NotificationFirstRejectionPerPeriod, entitlement.NotificationFirstRejectionPerLimit:
+ default:
return
}
if _, err := s.createAutopilotQuotaRejectionNotice(ctx, policy, workspaceID, source, params); err != nil {
@@ -52,8 +56,26 @@ func (s *AutopilotService) deliverAutopilotQuotaRejectionNotice(
}
}
-// createAutopilotQuotaRejectionNotice writes the period's first rejection
-// notice and, once that commits, announces each row.
+// autopilotQuotaRejectionAlreadyNotified reports whether the period's marker
+// already covers a rejection at limit. Per period, any notice covers the rest
+// of the period. Per limit, a notice covers only the limit it was sent at, so
+// a limit raised by an add-on re-arms it. A notice from before the limit was
+// recorded counts as covering the period: it cannot be told apart, and a
+// duplicate notice is worse than a missed re-arm in that one period.
+func autopilotQuotaRejectionAlreadyNotified(period db.AutopilotQuotaPeriod, mode string, limit int64) bool {
+ if !period.RejectionNotifiedAt.Valid {
+ return false
+ }
+ if mode != entitlement.NotificationFirstRejectionPerLimit || !period.RejectionNotifiedLimit.Valid {
+ return true
+ }
+ return period.RejectionNotifiedLimit.Int64 == limit
+}
+
+// createAutopilotQuotaRejectionNotice writes the first rejection notice of the
+// period (or of the limit, per the notification policy) and, once that
+// commits, announces each row. The period row lock serialises concurrent
+// rejections, so one limit is notified once.
func (s *AutopilotService) createAutopilotQuotaRejectionNotice(
ctx context.Context,
policy autopilotQuotaPolicy,
@@ -75,7 +97,11 @@ func (s *AutopilotService) createAutopilotQuotaRejectionNotice(
if err != nil {
return nil, fmt.Errorf("lock quota period for rejection notice: %w", err)
}
- if period.RejectionNotifiedAt.Valid {
+ mode := entitlement.NotificationFirstRejectionPerPeriod
+ if policy.notifications != nil {
+ mode = policy.notifications.OnRejection
+ }
+ if autopilotQuotaRejectionAlreadyNotified(period, mode, policy.limit) {
if err := tx.Commit(ctx); err != nil {
return nil, fmt.Errorf("commit already-delivered quota rejection notice: %w", err)
}
@@ -105,9 +131,10 @@ func (s *AutopilotService) createAutopilotQuotaRejectionNotice(
return nil, nil
}
if _, err := q.MarkAutopilotQuotaRejectionNotified(ctx, db.MarkAutopilotQuotaRejectionNotifiedParams{
- WorkspaceID: period.WorkspaceID,
- PeriodStart: period.PeriodStart,
- PeriodEnd: period.PeriodEnd,
+ WorkspaceID: period.WorkspaceID,
+ PeriodStart: period.PeriodStart,
+ PeriodEnd: period.PeriodEnd,
+ NotifiedLimit: pgtype.Int8{Int64: policy.limit, Valid: true},
}); err != nil {
return nil, fmt.Errorf("mark autopilot quota rejection notified: %w", err)
}
@@ -126,7 +153,8 @@ func (s *AutopilotService) createAutopilotQuotaInboxItems(
) ([]db.InboxItem, error) {
autopilotTitle := ""
autopilot, err := q.GetAutopilot(ctx, facts.AutopilotID)
- if err == nil {
+ autopilotFound := err == nil
+ if autopilotFound {
autopilotTitle = autopilot.Title
} else if !errors.Is(err, pgx.ErrNoRows) {
return nil, fmt.Errorf("load autopilot for quota notice: %w", err)
@@ -135,10 +163,23 @@ func (s *AutopilotService) createAutopilotQuotaInboxItems(
if err != nil {
return nil, fmt.Errorf("list workspace billing notification recipients: %w", err)
}
+ // The person responsible for the rejected autopilot hears about it too,
+ // even without billing access: its member creator, or the owner of the
+ // agent that created it. A creator who left the workspace is skipped, and
+ // one who already manages billing is not notified twice.
+ if autopilotFound {
+ creator, ok, err := ResolveAutopilotNotificationRecipient(ctx, q, autopilot)
+ if err != nil {
+ return nil, fmt.Errorf("resolve autopilot creator for quota notice: %w", err)
+ }
+ if ok && !containsAutopilotNotificationRecipient(recipients, creator) {
+ recipients = append(recipients, creator)
+ }
+ }
resetAt := facts.ResetAt.UTC().Format("January 2, 2006 at 15:04 UTC")
body := fmt.Sprintf(
- "This workspace has reached its limit of %d autopilot runs for the current period. Further autopilot runs will not start until the allowance resets at %s.",
+ "This workspace has reached its limit of %d autopilot runs for the current period. Further autopilot runs will not start until the allowance resets at %s, or until the workspace upgrades its plan or buys more runs.",
facts.Limit, resetAt,
)
details, err := json.Marshal(map[string]string{
@@ -177,3 +218,12 @@ func (s *AutopilotService) createAutopilotQuotaInboxItems(
}
return items, nil
}
+
+func containsAutopilotNotificationRecipient(recipients []AutopilotNotificationRecipient, candidate AutopilotNotificationRecipient) bool {
+ for _, recipient := range recipients {
+ if recipient.Type == candidate.Type && recipient.ID == candidate.ID {
+ return true
+ }
+ }
+ return false
+}
diff --git a/server/internal/service/autopilot_quota_test.go b/server/internal/service/autopilot_quota_test.go
index a8a6ef8508..59b785760d 100644
--- a/server/internal/service/autopilot_quota_test.go
+++ b/server/internal/service/autopilot_quota_test.go
@@ -634,6 +634,15 @@ func TestAutopilotQuotaNoticeRetriesAfterWorkspaceManagerIsRestored(t *testing.T
); err != nil {
t.Fatalf("remove final workspace manager role: %v", err)
}
+ // The demoted owner also created the autopilot, and an autopilot's creator
+ // is notified too. Point the autopilot at a creator who is no longer a
+ // member so the rejection has no recipient at all.
+ if _, err := fixture.pool.Exec(ctx, `
+ UPDATE autopilot SET created_by_type = 'member', created_by_id = $2 WHERE id = $1`,
+ fixture.autopilotID, uuid.New(),
+ ); err != nil {
+ t.Fatalf("point autopilot at a departed creator: %v", err)
+ }
assertRejected := func(key string) {
t.Helper()
diff --git a/server/migrations/710_autopilot_quota_limit_notice.down.sql b/server/migrations/710_autopilot_quota_limit_notice.down.sql
new file mode 100644
index 0000000000..0156cde13e
--- /dev/null
+++ b/server/migrations/710_autopilot_quota_limit_notice.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE autopilot_quota_period
+ DROP COLUMN IF EXISTS rejection_notified_limit;
diff --git a/server/migrations/710_autopilot_quota_limit_notice.up.sql b/server/migrations/710_autopilot_quota_limit_notice.up.sql
new file mode 100644
index 0000000000..712720add8
--- /dev/null
+++ b/server/migrations/710_autopilot_quota_limit_notice.up.sql
@@ -0,0 +1,6 @@
+-- rejection_notified_limit: the limit the period's last rejection notice was
+-- sent at. A notification policy of first_rejection_per_limit notifies again
+-- once the limit differs, such as after an add-on purchase raised it.
+-- Metadata-only change: nullable, no default, no rewrite, no index.
+ALTER TABLE autopilot_quota_period
+ ADD COLUMN IF NOT EXISTS rejection_notified_limit BIGINT;
diff --git a/server/pkg/db/generated/autopilot_quota.sql.go b/server/pkg/db/generated/autopilot_quota.sql.go
index 70dcea6616..cde955999e 100644
--- a/server/pkg/db/generated/autopilot_quota.sql.go
+++ b/server/pkg/db/generated/autopilot_quota.sql.go
@@ -37,7 +37,7 @@ FROM changed
WHERE p.workspace_id = changed.workspace_id
AND p.period_start = changed.period_start
AND p.period_end = changed.period_end
-RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at, p.rejection_notified_at
+RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at, p.rejection_notified_at, p.rejection_notified_limit
`
// used_count is monotonic within a period: consuming a reserved slot is the
@@ -55,6 +55,7 @@ func (q *Queries) ConsumeAutopilotQuotaReservation(ctx context.Context, reservat
&i.CreatedAt,
&i.UpdatedAt,
&i.RejectionNotifiedAt,
+ &i.RejectionNotifiedLimit,
)
return i, err
}
@@ -109,7 +110,7 @@ INSERT INTO autopilot_quota_period (workspace_id, period_start, period_end)
VALUES ($1, $2, $3)
ON CONFLICT (workspace_id, period_start, period_end) DO UPDATE
SET updated_at = autopilot_quota_period.updated_at
-RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at, rejection_notified_limit
`
type EnsureAutopilotQuotaPeriodParams struct {
@@ -133,12 +134,13 @@ func (q *Queries) EnsureAutopilotQuotaPeriod(ctx context.Context, arg EnsureAuto
&i.CreatedAt,
&i.UpdatedAt,
&i.RejectionNotifiedAt,
+ &i.RejectionNotifiedLimit,
)
return i, err
}
const getAutopilotQuotaPeriod = `-- name: GetAutopilotQuotaPeriod :one
-SELECT workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at FROM autopilot_quota_period
+SELECT workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at, rejection_notified_limit FROM autopilot_quota_period
WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3
`
@@ -161,6 +163,7 @@ func (q *Queries) GetAutopilotQuotaPeriod(ctx context.Context, arg GetAutopilotQ
&i.CreatedAt,
&i.UpdatedAt,
&i.RejectionNotifiedAt,
+ &i.RejectionNotifiedLimit,
)
return i, err
}
@@ -217,7 +220,7 @@ SET blocked_counts = jsonb_set(
WHERE workspace_id = $2
AND period_start = $3
AND period_end = $4
-RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at, rejection_notified_limit
`
type IncrementAutopilotQuotaBlockedParams struct {
@@ -245,6 +248,7 @@ func (q *Queries) IncrementAutopilotQuotaBlocked(ctx context.Context, arg Increm
&i.CreatedAt,
&i.UpdatedAt,
&i.RejectionNotifiedAt,
+ &i.RejectionNotifiedLimit,
)
return i, err
}
@@ -254,7 +258,7 @@ UPDATE autopilot_quota_period
SET reserved_count = reserved_count + 1,
updated_at = now()
WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3
-RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at, rejection_notified_limit
`
type IncrementAutopilotQuotaReservedParams struct {
@@ -276,6 +280,7 @@ func (q *Queries) IncrementAutopilotQuotaReserved(ctx context.Context, arg Incre
&i.CreatedAt,
&i.UpdatedAt,
&i.RejectionNotifiedAt,
+ &i.RejectionNotifiedLimit,
)
return i, err
}
@@ -353,22 +358,31 @@ func (q *Queries) ListRecoverableAutopilotQuotaReservations(ctx context.Context,
const markAutopilotQuotaRejectionNotified = `-- name: MarkAutopilotQuotaRejectionNotified :one
UPDATE autopilot_quota_period
-SET rejection_notified_at = COALESCE(rejection_notified_at, now()),
+SET rejection_notified_at = now(),
+ rejection_notified_limit = $1::bigint,
updated_at = now()
-WHERE workspace_id = $1
- AND period_start = $2
- AND period_end = $3
-RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at
+WHERE workspace_id = $2
+ AND period_start = $3
+ AND period_end = $4
+RETURNING workspace_id, period_start, period_end, used_count, reserved_count, blocked_counts, created_at, updated_at, rejection_notified_at, rejection_notified_limit
`
type MarkAutopilotQuotaRejectionNotifiedParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- PeriodStart pgtype.Timestamptz `json:"period_start"`
- PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ NotifiedLimit pgtype.Int8 `json:"notified_limit"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
}
+// rejection_notified_limit records the limit the notice was sent at, so a
+// per-limit notification policy can notify again after the limit changes.
func (q *Queries) MarkAutopilotQuotaRejectionNotified(ctx context.Context, arg MarkAutopilotQuotaRejectionNotifiedParams) (AutopilotQuotaPeriod, error) {
- row := q.db.QueryRow(ctx, markAutopilotQuotaRejectionNotified, arg.WorkspaceID, arg.PeriodStart, arg.PeriodEnd)
+ row := q.db.QueryRow(ctx, markAutopilotQuotaRejectionNotified,
+ arg.NotifiedLimit,
+ arg.WorkspaceID,
+ arg.PeriodStart,
+ arg.PeriodEnd,
+ )
var i AutopilotQuotaPeriod
err := row.Scan(
&i.WorkspaceID,
@@ -380,6 +394,7 @@ func (q *Queries) MarkAutopilotQuotaRejectionNotified(ctx context.Context, arg M
&i.CreatedAt,
&i.UpdatedAt,
&i.RejectionNotifiedAt,
+ &i.RejectionNotifiedLimit,
)
return i, err
}
@@ -409,7 +424,7 @@ FROM changed
WHERE p.workspace_id = changed.workspace_id
AND p.period_start = changed.period_start
AND p.period_end = changed.period_end
-RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at, p.rejection_notified_at
+RETURNING p.workspace_id, p.period_start, p.period_end, p.used_count, p.reserved_count, p.blocked_counts, p.created_at, p.updated_at, p.rejection_notified_at, p.rejection_notified_limit
`
// Release is intentionally limited to still-reserved work. A consumed
@@ -427,6 +442,7 @@ func (q *Queries) ReleaseAutopilotQuotaReservation(ctx context.Context, reservat
&i.CreatedAt,
&i.UpdatedAt,
&i.RejectionNotifiedAt,
+ &i.RejectionNotifiedLimit,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index b7a124a7b6..87be2c0a2b 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -316,15 +316,16 @@ type AutopilotCollaborator struct {
}
type AutopilotQuotaPeriod struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- PeriodStart pgtype.Timestamptz `json:"period_start"`
- PeriodEnd pgtype.Timestamptz `json:"period_end"`
- UsedCount int64 `json:"used_count"`
- ReservedCount int64 `json:"reserved_count"`
- BlockedCounts []byte `json:"blocked_counts"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- RejectionNotifiedAt pgtype.Timestamptz `json:"rejection_notified_at"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PeriodStart pgtype.Timestamptz `json:"period_start"`
+ PeriodEnd pgtype.Timestamptz `json:"period_end"`
+ UsedCount int64 `json:"used_count"`
+ ReservedCount int64 `json:"reserved_count"`
+ BlockedCounts []byte `json:"blocked_counts"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ RejectionNotifiedAt pgtype.Timestamptz `json:"rejection_notified_at"`
+ RejectionNotifiedLimit pgtype.Int8 `json:"rejection_notified_limit"`
}
type AutopilotQuotaReservation struct {
diff --git a/server/pkg/db/queries/autopilot_quota.sql b/server/pkg/db/queries/autopilot_quota.sql
index 783d32c0e9..e9f667fdc5 100644
--- a/server/pkg/db/queries/autopilot_quota.sql
+++ b/server/pkg/db/queries/autopilot_quota.sql
@@ -48,8 +48,11 @@ WHERE workspace_id = @workspace_id
RETURNING *;
-- name: MarkAutopilotQuotaRejectionNotified :one
+-- rejection_notified_limit records the limit the notice was sent at, so a
+-- per-limit notification policy can notify again after the limit changes.
UPDATE autopilot_quota_period
-SET rejection_notified_at = COALESCE(rejection_notified_at, now()),
+SET rejection_notified_at = now(),
+ rejection_notified_limit = sqlc.narg('notified_limit')::bigint,
updated_at = now()
WHERE workspace_id = @workspace_id
AND period_start = @period_start