Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(apps): monthly app tool call limit per workspace by plan and seats (MUL-10047) (#11397)
Multica Evecffeb7fe0af9
diff --git a/apps/mobile/components/inbox/detail-label.tsx b/apps/mobile/components/inbox/detail-label.tsxindex aa408ed23b..a0585bbdae 100644--- a/apps/mobile/components/inbox/detail-label.tsx+++ b/apps/mobile/components/inbox/detail-label.tsx@@ -59,6 +59,7 @@ const TYPE_KEY: Record<InboxItemType, string> = {quick_create_unconfirmed: "type.quick_create_unconfirmed",autopilot_paused: "type.autopilot_paused",autopilot_quota_exceeded: "type.autopilot_quota_exceeded",+ app_tool_calls_quota_exceeded: "type.app_tool_calls_quota_exceeded",children_done: "type.children_done",blockers_done: "type.blockers_done",project_owner_joined: "type.project_owner_joined",@@ -173,6 +174,8 @@ export function InboxDetailLabel({}case "autopilot_quota_exceeded":return t("type.run_limit_blocked");+ case "app_tool_calls_quota_exceeded":+ return t("type.app_tool_calls_limit_blocked");default:return t(TYPE_KEY[item.type]) ?? item.type;}diff --git a/apps/mobile/lib/inbox-display.ts b/apps/mobile/lib/inbox-display.tsindex a8af079d06..4471795a97 100644--- a/apps/mobile/lib/inbox-display.ts+++ b/apps/mobile/lib/inbox-display.ts@@ -49,6 +49,11 @@ export function getInboxNoticeBody(item: InboxItem): string | null {name: item.details.joined_by,});}+ if (item.type === "app_tool_calls_quota_exceeded") {+ const resetAt = formatResetAt(item.details?.reset_at);+ if (!item.details?.limit || !resetAt) return item.body;+ return i18n.t("inbox:body.app_tool_calls_limit", { limit: item.details.limit, resetAt });+ }return getAutopilotQuotaBody(item);}@@ -84,6 +89,8 @@ export function getInboxDisplayTitle(item: InboxItem): string {switch (item.type) {case "autopilot_quota_exceeded":return i18n.t("inbox:type.autopilot_quota_exceeded");+ case "app_tool_calls_quota_exceeded":+ return i18n.t("inbox:type.app_tool_calls_quota_exceeded");}if (item.type === "quick_create_done") {const cleanedTitle = stripQuickCreatePrefix(item.title, details.identifier);@@ -105,6 +112,7 @@ export function getInboxDisplayTitle(item: InboxItem): string {export function isInboxNotice(type: InboxItem["type"]): boolean {return (type === "autopilot_quota_exceeded" ||+ type === "app_tool_calls_quota_exceeded" ||type === "autopilot_paused" ||type === "project_owner_joined");diff --git a/apps/mobile/locales/en/inbox.json b/apps/mobile/locales/en/inbox.jsonindex ed7473f1ac..1de34423b5 100644--- a/apps/mobile/locales/en/inbox.json+++ b/apps/mobile/locales/en/inbox.json@@ -73,6 +73,7 @@"blockers_done": "Waiting tasks ended","project_owner_joined": "Owner joined project","autopilot_quota_exceeded": "Autopilot run limit reached",+ "app_tool_calls_quota_exceeded": "App call limit reached","set_status": "Set status to","set_priority": "Set priority to","assigned_to": "Assigned to {{name}}",@@ -83,6 +84,7 @@"created_with_agent": "Created with agent: {{identifier}}","failed_with_detail": "Failed: {{detail}}","run_limit_blocked": "Run blocked because the limit was reached",+ "app_tool_calls_limit_blocked": "Agents can no longer run app tools this month","app_action_requested": "Needs your confirmation","app_action_reminder": "Confirmation expiring soon","app_connect_requested": "Connect an app",@@ -91,6 +93,7 @@"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}}; 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.",+ "app_tool_calls_limit": "This workspace has used its {{limit}} app calls for this month. Agents can't run app tools until the allowance resets {{resetAt}}, or until the workspace upgrades or adds seats.","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.jsonindex 70bf282418..a9e708a5c9 100644--- a/apps/mobile/locales/zh-Hans/inbox.json+++ b/apps/mobile/locales/zh-Hans/inbox.json@@ -73,6 +73,7 @@"blockers_done": "等待的任务已结束","project_owner_joined": "所有者加入了项目","autopilot_quota_exceeded": "自动化运行次数已达上限",+ "app_tool_calls_quota_exceeded": "应用调用次数已用完","set_status": "状态设为","set_priority": "优先级设为","assigned_to": "分配给 {{name}}",@@ -83,6 +84,7 @@"created_with_agent": "由智能体创建:{{identifier}}","failed_with_detail": "失败:{{detail}}","run_limit_blocked": "已达到上限,本次运行被阻止",+ "app_tool_calls_limit_blocked": "本月智能体无法再调用应用工具","app_action_requested": "等待你确认","app_action_reminder": "确认即将过期","app_connect_requested": "请连接应用",@@ -91,6 +93,7 @@"body": {"autopilot_title_limit": "自动化 \"{{title}}\" 未启动,因为该工作区已达到当前周期 {{limit}} 次运行的上限。额度将在 {{resetAt}} 重置;工作区所有者或管理员也可以升级套餐或加购执行次数。","autopilot_limit": "该工作区已达到当前周期 {{limit}} 次自动化运行的上限。此执行未启动。额度将在 {{resetAt}} 重置;工作区所有者或管理员也可以升级套餐或加购执行次数。",+ "app_tool_calls_limit": "本工作区本月的 {{limit}} 次应用调用已用完。在 {{resetAt}} 重置、升级套餐或增加席位之前,智能体无法调用应用工具。","project_owner_joined": "{{name}} 是工作区所有者,已把自己加入这个私有项目,现在可以看到其中的任务、评论和附件。"}}diff --git a/apps/mobile/locales/zh-Hant/inbox.json b/apps/mobile/locales/zh-Hant/inbox.jsonindex 2966309dd2..bac8f2b070 100644--- a/apps/mobile/locales/zh-Hant/inbox.json+++ b/apps/mobile/locales/zh-Hant/inbox.json@@ -73,6 +73,7 @@"blockers_done": "等待的任務已結束","project_owner_joined": "所有者加入了專案","autopilot_quota_exceeded": "自動化執行次數已達上限",+ "app_tool_calls_quota_exceeded": "應用呼叫次數已用完","set_status": "狀態設為","set_priority": "優先順序設為","assigned_to": "分配給 {{name}}",@@ -83,6 +84,7 @@"created_with_agent": "由 AI 代理建立:{{identifier}}","failed_with_detail": "失敗:{{detail}}","run_limit_blocked": "已達到上限,本次執行被阻止",+ "app_tool_calls_limit_blocked": "本月 AI 代理無法再呼叫應用工具","app_action_requested": "等待你確認","app_action_reminder": "確認即將過期","app_connect_requested": "請連線應用",@@ -91,6 +93,7 @@"body": {"autopilot_title_limit": "自動化 \"{{title}}\" 未啟動,因為該工作區已達到當前週期 {{limit}} 次執行的上限。額度將在 {{resetAt}} 重置;工作區所有者或管理員也可以升級方案或加購執行次數。","autopilot_limit": "該工作區已達到當前週期 {{limit}} 次自動化執行的上限。此執行未啟動。額度將在 {{resetAt}} 重置;工作區所有者或管理員也可以升級方案或加購執行次數。",+ "app_tool_calls_limit": "本工作區本月的 {{limit}} 次應用呼叫已用完。在 {{resetAt}} 重置、升級方案或增加席位之前,AI 代理無法呼叫應用工具。","project_owner_joined": "{{name}} 是工作區所有者,已把自己加入這個私有專案,現在可以看到其中的任務、評論和附件。"}}diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex a34b35febb..0ad59147b2 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -299,6 +299,7 @@ import type {WorkspaceFeatures,MemberLimit,StorageUsage,+ AppCallUsage,CreateWorkspaceSubscriptionCheckoutRequest,CreateWorkspaceSubscriptionCheckoutResponse,WorkspaceSubscriptionSeatReconcileResult,@@ -473,6 +474,7 @@ import {WorkspaceFeaturesSchema,MemberLimitSchema,StorageUsageSchema,+ AppCallUsageSchema,CreateWorkspaceSubscriptionCheckoutResponseSchema,WorkspaceSubscriptionSeatReconcileResultSchema,WorkspaceSeatPurchasePreviewSchema,@@ -2736,6 +2738,18 @@ export class ApiClient {);}+ // The plan's monthly app call limit (MUL-10047). A response that cannot be+ // read falls back to no limit: the gateway still checks every call.+ async getAppCallUsage(workspaceId: string): Promise<AppCallUsage> {+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/app-call-usage`);+ return parseWithFallback<AppCallUsage>(+ raw,+ AppCallUsageSchema,+ { action: "off", used: null, limit: null, reached: null, resetAt: null, members: [] },+ { endpoint: "GET /api/workspaces/:id/app-call-usage" },+ );+ }+async getWorkspaceSubscriptionPrices(): Promise<WorkspaceSubscriptionPrices | null> {const raw = await this.fetch<unknown>("/api/cloud-subscriptions/prices");return parseWithFallback<WorkspaceSubscriptionPrices | null>(diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex e950553616..089154dfb4 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -40,6 +40,7 @@ import type {WorkspaceFeatures,MemberLimit,StorageUsage,+ AppCallUsage,WorkspaceSubscriptionSummary,WorkspaceSubscriptionPrice,WorkspaceSubscriptionPlanPrices,@@ -3734,6 +3735,9 @@ export const WorkspaceSubscriptionEntitlementsSchema = z// Newer than autopilot_runs: an older Cloud omits it, and a malformed// one only hides its own row.dashboard_history_days: WorkspaceEntitlementLimitSchema.nullable().catch(null).default(null),+ // Newer still: an older Cloud omits it, and a malformed one only+ // hides its own row.+ app_tool_calls: WorkspaceEntitlementLimitSchema.nullable().catch(null).default(null),}).loose(),current_period_end: z.string().nullable().optional(),@@ -3751,6 +3755,7 @@ export const WorkspaceSubscriptionEntitlementsSchema = zautopilotRuns: value.limits.autopilot_runs,storageBytes: value.limits.storage_bytes ?? null,dashboardHistoryDays: value.limits.dashboard_history_days,+ appToolCalls: value.limits.app_tool_calls,},currentPeriodEnd: value.current_period_end ?? null,snapshotExpiresAt: value.snapshot_expires_at ?? null,@@ -4178,6 +4183,42 @@ export const StorageUsageSchema = z},);+// App call usage that cannot be read, or an action from a newer server, reads+// as off: the gateway still checks every call. A malformed breakdown only+// drops the breakdown.+export const AppCallUsageSchema = z+ .object({+ action: z.enum(["off", "observe", "enforce"]).catch("off"),+ used: z.number().int().nonnegative().nullable().catch(null).default(null),+ limit: z.number().int().nonnegative().nullable().catch(null).default(null),+ reached: z.boolean().nullable().catch(null).default(null),+ reset_at: z.string().nullable().catch(null).default(null),+ members: z+ .array(+ z.object({+ user_id: z.string().nullable().catch(null).default(null),+ calls: z.number().int().nonnegative(),+ }),+ )+ .nullable()+ .catch(null)+ .default(null),+ })+ .loose()+ .transform(+ (value): AppCallUsage =>+ value.action === "off" || value.limit === null || value.used === null+ ? { action: "off", used: null, limit: null, reached: null, resetAt: null, members: [] }+ : {+ action: value.action,+ used: value.used,+ limit: value.limit,+ reached: value.action === "enforce" ? (value.reached ?? value.used >= value.limit) : null,+ resetAt: value.reset_at,+ members: (value.members ?? []).map((m) => ({ userId: m.user_id, calls: m.calls })),+ },+ );+export const CreateWorkspaceSubscriptionCheckoutResponseSchema = z.object({request_id: z.string(),diff --git a/packages/core/billing/app-call-limit.test.ts b/packages/core/billing/app-call-limit.test.tsnew file mode 100644index 0000000000..69054cd843--- /dev/null+++ b/packages/core/billing/app-call-limit.test.ts@@ -0,0 +1,127 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";++import { AppCallUsageSchema, WorkspaceSubscriptionEntitlementsSchema } from "../api/schemas";+import type { AppCallUsage } from "../types";+import { resolveAppCallRow } from "./app-call-limit";++const OFF: AppCallUsage = { action: "off", used: null, limit: null, reached: null, resetAt: null, members: [] };+const RESET_AT = "2026-12-01T00:00:00Z";++describe("AppCallUsageSchema", () => {+ it("reads an enforced limit with its figures and per-person breakdown", () => {+ expect(+ AppCallUsageSchema.parse({+ action: "enforce",+ used: 100,+ limit: 100,+ reached: true,+ period_start: "2026-11-01T00:00:00Z",+ reset_at: RESET_AT,+ members: [+ { user_id: "u1", calls: 70 },+ { user_id: null, calls: 30 },+ ],+ }),+ ).toEqual({+ action: "enforce",+ used: 100,+ limit: 100,+ reached: true,+ resetAt: RESET_AT,+ members: [+ { userId: "u1", calls: 70 },+ { userId: null, calls: 30 },+ ],+ });+ });++ it("never reports an observed limit as reached, and reads a missing breakdown as none", () => {+ expect(AppCallUsageSchema.parse({ action: "observe", used: 500, limit: 100, reset_at: RESET_AT })).toEqual({+ action: "observe",+ used: 500,+ limit: 100,+ reached: null,+ resetAt: RESET_AT,+ members: [],+ });+ });++ it("drops only a malformed breakdown", () => {+ expect(+ AppCallUsageSchema.parse({ action: "enforce", used: 1, limit: 5, reached: false, members: [{ calls: "x" }] }),+ ).toMatchObject({ used: 1, limit: 5, members: [] });+ });++ it("reads off, an unknown action, or missing figures as no limit", () => {+ expect(AppCallUsageSchema.parse({ action: "off" })).toEqual(OFF);+ expect(AppCallUsageSchema.parse({ action: "block", used: 1, limit: 5 })).toEqual(OFF);+ expect(AppCallUsageSchema.parse({ action: "enforce", used: "1", limit: 5 })).toEqual(OFF);+ });+});++describe("entitlement app_tool_calls", () => {+ const entitlement = (limits: Record<string, unknown>) => ({+ workspace_id: "ws",+ plan: "pro",+ status: "active",+ seats: 3,+ limits: { autopilot_runs: { mode: "limited", limit: 3000 }, ...limits },+ version: 1,+ });++ it("reads the plan's app call limit, and an older or malformed one as none", () => {+ expect(+ WorkspaceSubscriptionEntitlementsSchema.parse(entitlement({ app_tool_calls: { mode: "limited", limit: 1500 } }))+ .limits.appToolCalls,+ ).toEqual({ mode: "limited", limit: 1500 });+ expect(WorkspaceSubscriptionEntitlementsSchema.parse(entitlement({})).limits.appToolCalls).toBeNull();+ expect(+ WorkspaceSubscriptionEntitlementsSchema.parse(entitlement({ app_tool_calls: { mode: "bogus" } })).limits+ .appToolCalls,+ ).toBeNull();+ });+});++describe("resolveAppCallRow", () => {+ const usage = (over: Partial<AppCallUsage>): AppCallUsage => ({+ action: "enforce",+ used: 90,+ limit: 100,+ reached: false,+ resetAt: RESET_AT,+ members: [],+ ...over,+ });+ const plan = (limit: number) => ({ mode: "limited", limit });++ it("meters usage against the limit, and only an enforced limit is reached", () => {+ expect(resolveAppCallRow(usage({}), false, null)).toEqual({+ kind: "metered",+ used: 90,+ limit: 100,+ reached: false,+ resetAt: RESET_AT,+ members: [],+ });+ expect(resolveAppCallRow(usage({ used: 100 }), false, null)).toMatchObject({ reached: true });+ expect(resolveAppCallRow(usage({ action: "observe", used: 500 }), false, null)).toMatchObject({ reached: false });+ });++ // Right after an upgrade or a seat purchase the usage read can still carry+ // the policy cached before it; the entitlement has the new limit.+ it("takes the limit from the plan when the entitlement has one", () => {+ expect(resolveAppCallRow(usage({ used: 100 }), false, plan(1500))).toMatchObject({+ used: 100,+ limit: 1500,+ reached: false,+ });+ });++ it("shows a failed read as unavailable, and nothing without a limit", () => {+ expect(resolveAppCallRow(undefined, true, plan(100))).toEqual({ kind: "unavailable", limit: 100 });+ expect(resolveAppCallRow(undefined, true, null)).toBeNull();+ expect(resolveAppCallRow(OFF, false, plan(100))).toBeNull();+ expect(resolveAppCallRow(undefined, false, plan(100))).toBeNull();+ });+});diff --git a/packages/core/billing/app-call-limit.ts b/packages/core/billing/app-call-limit.tsnew file mode 100644index 0000000000..2e6acbfa0a--- /dev/null+++ b/packages/core/billing/app-call-limit.ts@@ -0,0 +1,66 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";+import type { AppCallMemberUsage, AppCallUsage } from "../types";++/**+ * Monthly app call limit (MUL-10047).+ *+ * The calls agents send to connected apps each month are limited per+ * workspace. When the workspace runs out, the gateway refuses further calls+ * and the agent says so; this module reads the limit for Billing.+ */+export const appCallUsageKeys = {+ all: (wsId: string) => ["workspace-app-call-usage", wsId] as const,+};++/** Refetched on focus: an upgrade happens outside this tab, in Stripe. */+export function appCallUsageOptions(wsId: string) {+ return queryOptions({+ queryKey: appCallUsageKeys.all(wsId),+ queryFn: () => api.getAppCallUsage(wsId),+ enabled: wsId.length > 0,+ staleTime: 30 * 1000,+ refetchOnWindowFocus: true,+ });+}++/** The Billing row for app calls. */+export type AppCallRow =+ | {+ kind: "metered";+ used: number;+ limit: number;+ reached: boolean;+ resetAt: string | null;+ members: AppCallMemberUsage[];+ }+ | { kind: "unavailable"; limit: number | null };++/**+ * What Billing shows for app calls, or null when no limit applies.+ *+ * The limit comes from the entitlement snapshot when it has one, as for+ * storage: a page that has just upgraded or added seats shows the new limit+ * at once, while the usage read can still carry a policy cached before it.+ */+export function resolveAppCallRow(+ usage: AppCallUsage | undefined,+ usageFailed: boolean,+ entitlementLimit: { mode: string; limit: number | null } | null | undefined,+): AppCallRow | null {+ const planLimit = entitlementLimit?.mode === "limited" ? entitlementLimit.limit : null;+ if (usageFailed || !usage) {+ return usageFailed && planLimit !== null ? { kind: "unavailable", limit: planLimit } : null;+ }+ if (usage.action === "off" || usage.used === null || usage.limit === null) return null;+ const limit = planLimit ?? usage.limit;+ return {+ kind: "metered",+ used: usage.used,+ limit,+ // Only an enforced limit is ever reached; observe never refuses.+ reached: usage.action === "enforce" && usage.used >= limit,+ resetAt: usage.resetAt,+ members: usage.members,+ };+}diff --git a/packages/core/billing/index.ts b/packages/core/billing/index.tsindex 6c8dd81639..0c21f83744 100644--- a/packages/core/billing/index.ts+++ b/packages/core/billing/index.ts@@ -8,3 +8,4 @@ export * from "./trial";export * from "./trial-notice-store";export * from "./member-limit";export * from "./storage-limit";+export * from "./app-call-limit";diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.tsindex 59dd562c3a..65bfb25562 100644--- a/packages/core/types/billing.ts+++ b/packages/core/types/billing.ts@@ -221,6 +221,8 @@ export interface WorkspaceSubscriptionEntitlements {storageBytes?: WorkspaceEntitlementLimit | null;/** Dashboard history range in days. Null when Cloud did not send it. */dashboardHistoryDays?: WorkspaceEntitlementLimit | null;+ /** Monthly app calls (MUL-10047); absent from older Cloud. */+ appToolCalls?: WorkspaceEntitlementLimit | null;};currentPeriodEnd: string | null;snapshotExpiresAt: string | null;@@ -576,6 +578,28 @@ export interface StorageUsage {reached: boolean | null;}+/**+ * The plan's monthly app call limit (MUL-10047): calls agents send to+ * connected apps, shared by the workspace. `off` means no limit applies,+ * which is also every self-hosted workspace; the figures are null then.+ */+export interface AppCallUsage {+ action: "off" | "observe" | "enforce";+ used: number | null;+ limit: number | null;+ /** Set only under enforce: observe never refuses a call. */+ reached: boolean | null;+ resetAt: string | null;+ /** This period's calls per person, for owners and admins; empty otherwise. */+ members: AppCallMemberUsage[];+}++export interface AppCallMemberUsage {+ /** Null for runs no person started. */+ userId: string | null;+ calls: number;+}+export interface MemberLimit {action: "off" | "observe" | "enforce";limit: number | null;diff --git a/packages/core/types/connected-apps.ts b/packages/core/types/connected-apps.tsindex 3b15fe9565..4756366b08 100644--- a/packages/core/types/connected-apps.ts+++ b/packages/core/types/connected-apps.ts@@ -96,7 +96,8 @@ export type AppCallOutcome =| "pending"| "approved"| "rejected"- | "rate_limited";+ | "rate_limited"+ | "quota_exceeded";/** One call an issue's runs made through an app. */export interface IssueAppCall {diff --git a/packages/core/types/inbox.ts b/packages/core/types/inbox.tsindex 2729150e0b..dbc3cb86ed 100644--- a/packages/core/types/inbox.ts+++ b/packages/core/types/inbox.ts@@ -37,6 +37,8 @@ export type InboxItemType =// same Inbox model so read/archive/realtime behavior remains consistent.| "autopilot_paused"| "autopilot_quota_exceeded"+ // The workspace used its monthly app tool calls; sent to owners and admins.+ | "app_tool_calls_quota_exceeded"// Sub-issues of an issue assigned to the recipient closed (the child_done// system rule notifies a member assignee instead of waking an agent).| "children_done"diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 37ee938716..31aa9dbc73 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -460,6 +460,8 @@ export type {WorkspaceFeatureLimits,MemberLimit,StorageUsage,+ AppCallUsage,+ AppCallMemberUsage,} from "./billing";export type { IssueWakeup, IssueWakeupInput, SystemWakeup, WorkspaceSystemWakeup, WakeupPreview, IssueWakeupSummaryRow, WakeupCondition, WakeupPausedReason, WakeupRun, PausedWakeup, WakeupSource } from "./issue-wakeup";diff --git a/packages/views/apps/components/app-account-dialog.tsx b/packages/views/apps/components/app-account-dialog.tsxindex 21a6165706..75eb020433 100644--- a/packages/views/apps/components/app-account-dialog.tsx+++ b/packages/views/apps/components/app-account-dialog.tsx@@ -55,6 +55,7 @@ function ActivityList({ scope, slug }: { scope: AppAccountScope; slug: string })case "approved":case "rejected":case "rate_limited":+ case "quota_exceeded":return t(($) => $.connected_apps.outcomes[outcome]);default:return outcome;diff --git a/packages/views/inbox/components/app-call-quota-notice.tsx b/packages/views/inbox/components/app-call-quota-notice.tsxnew file mode 100644index 0000000000..6be31f0b0b--- /dev/null+++ b/packages/views/inbox/components/app-call-quota-notice.tsx@@ -0,0 +1,41 @@+"use client";++import { useWorkspacePaths } from "@multica/core/paths";+import type { InboxItem } from "@multica/core/types";+import { Button } from "@multica/ui/components/ui/button";+import { useT } from "../../i18n";+import { useNavigation } from "../../navigation";++function formatResetAt(value: string | undefined): string {+ if (!value) return "";+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return "";+ return new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" }).format(date);+}++/**+ * The workspace used its monthly app calls (MUL-10047). Only owners and admins+ * receive it, so it leads to Billing, where they upgrade or add seats.+ */+export function AppCallQuotaNotice({ item }: { item: InboxItem }) {+ const { t } = useT("inbox");+ const navigation = useNavigation();+ const wsPaths = useWorkspacePaths();+ const details = item.details ?? {};+ const resetAt = formatResetAt(details.reset_at);+ const body =+ details.limit && resetAt+ ? t(($) => $.detail.app_tool_calls_quota_exceeded_body, { limit: details.limit, resetAt })+ : item.body;++ return (+ <>+ {body ? (+ <div className="mt-4 whitespace-pre-wrap text-body leading-relaxed text-foreground">{body}</div>+ ) : null}+ <Button className="mt-4" size="sm" onClick={() => navigation.push(`${wsPaths.settings()}?tab=billing`)}>+ {t(($) => $.detail.app_tool_calls_quota_action)}+ </Button>+ </>+ );+}diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsxindex bed8c784d6..6b1e2bb5df 100644--- a/packages/views/inbox/components/inbox-detail-label.tsx+++ b/packages/views/inbox/components/inbox-detail-label.tsx@@ -41,6 +41,7 @@ export function useTypeLabels(): Record<InboxItemType, string> {quick_create_unconfirmed: t(($) => $.types.quick_create_unconfirmed),autopilot_paused: t(($) => $.types.autopilot_paused),autopilot_quota_exceeded: t(($) => $.types.autopilot_quota_exceeded),+ app_tool_calls_quota_exceeded: t(($) => $.types.app_tool_calls_quota_exceeded),children_done: t(($) => $.types.children_done),blockers_done: t(($) => $.types.blockers_done),project_owner_joined: t(($) => $.types.project_owner_joined),@@ -153,6 +154,8 @@ export function InboxDetailLabel({ item }: { item: InboxItem }) {}case "autopilot_quota_exceeded":return <span>{t(($) => $.labels.autopilot_quota_blocked)}</span>;+ case "app_tool_calls_quota_exceeded":+ return <span>{t(($) => $.labels.app_tool_calls_quota_blocked)}</span>;case "children_done": {// The stage arrives as a JSON number; details are typed as strings.const stage = details.stage != null ? String(details.stage) : "";diff --git a/packages/views/inbox/components/inbox-display.test.ts b/packages/views/inbox/components/inbox-display.test.tsindex 51aaa856b5..7006ef8273 100644--- a/packages/views/inbox/components/inbox-display.test.ts+++ b/packages/views/inbox/components/inbox-display.test.ts@@ -8,6 +8,7 @@ import {inboxRowHref,isAutopilotQuotaNotice,isQuickCreateOutcome,+ isQuotaNotice,resolveDetailItem,stripQuickCreatePrefix,} from "./inbox-display";@@ -110,6 +111,15 @@ describe("inbox display helpers", () => {it("keeps paused autopilot title and body on the same server fallback path", () => {expect(isAutopilotQuotaNotice("autopilot_paused")).toBe(false);expect(isAutopilotQuotaNotice("autopilot_quota_exceeded")).toBe(true);+ expect(isAutopilotQuotaNotice("app_tool_calls_quota_exceeded")).toBe(false);+ });++ // Both limit notices are titled in the reader's locale, not by the stored+ // English fallback.+ it("titles both limit notices from their type", () => {+ expect(isQuotaNotice("autopilot_quota_exceeded")).toBe(true);+ expect(isQuotaNotice("app_tool_calls_quota_exceeded")).toBe(true);+ expect(isQuotaNotice("autopilot_paused")).toBe(false);});});diff --git a/packages/views/inbox/components/inbox-display.ts b/packages/views/inbox/components/inbox-display.tsindex d2bb9463f6..6974a5fb3d 100644--- a/packages/views/inbox/components/inbox-display.ts+++ b/packages/views/inbox/components/inbox-display.ts@@ -59,6 +59,14 @@ export function isAutopilotQuotaNotice(type: InboxItem["type"]): boolean {return type === "autopilot_quota_exceeded";}+/**+ * Limit notices whose stored title is English fallback copy; the reader's+ * locale titles them from the type instead.+ */+export function isQuotaNotice(type: InboxItem["type"]): boolean {+ return type === "autopilot_quota_exceeded" || type === "app_tool_calls_quota_exceeded";+}+export function getQuickCreateOutcomeDetail(item: InboxItem): string {const details = item.details ?? {};return singleLine(details.error) || singleLine(item.body);diff --git a/packages/views/inbox/components/inbox-kept-actions.tsx b/packages/views/inbox/components/inbox-kept-actions.tsxindex dc411203b3..10910cee7d 100644--- a/packages/views/inbox/components/inbox-kept-actions.tsx+++ b/packages/views/inbox/components/inbox-kept-actions.tsx@@ -14,7 +14,7 @@ import { ActionShortcutKeycaps } from "../../common/shortcut-keycaps";import type { IssueAgentState } from "../../issues/surface/use-issue-agent-state";import { useStatusLabel } from "../../issues/utils/status-label";import { formatSnoozeTime } from "./inbox-snooze-time";-import { getInboxDisplayTitle, isAutopilotQuotaNotice } from "./inbox-display";+import { getInboxDisplayTitle, isQuotaNotice } from "./inbox-display";import { InboxBar, InboxBarKeycaps, InboxBarSeparator, InboxBarStatus } from "./inbox-bar";import { useInboxUndoShortcut } from "./use-inbox-shortcut";@@ -151,7 +151,7 @@ export function InboxKeptActions({/** Opens the next notification, named in its tooltip; E does the same. */export function InboxNextButton({ next, onNext }: { next: InboxItem; onNext: () => void }) {const { t } = useT("inbox");- const title = isAutopilotQuotaNotice(next.type) ? t(($) => $.types[next.type]) : getInboxDisplayTitle(next);+ const title = isQuotaNotice(next.type) ? t(($) => $.types[next.type]) : getInboxDisplayTitle(next);return (<TooltipHintlabel={t(($) => $.kept.next_tooltip, { title })}diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsxindex 0f2bdf503a..5fb31cce58 100644--- a/packages/views/inbox/components/inbox-list-item.tsx+++ b/packages/views/inbox/components/inbox-list-item.tsx@@ -17,7 +17,7 @@ import { InboxDetailLabel, useTypeLabels } from "./inbox-detail-label";import {getInboxDisplayTitle,inboxIssueRef,- isAutopilotQuotaNotice,+ isQuotaNotice,} from "./inbox-display";import { useInboxContextMenu } from "./inbox-context-menu";import { useStatusLabel } from "../../issues/utils/status-label";@@ -78,7 +78,7 @@ export function InboxListItem({? paths.workspace(slug).issueDetail(inboxIssueRef(item, item.issue_id)): null;const intentNavigate = useIntentNavigate();- const displayTitle = isAutopilotQuotaNotice(item.type)+ const displayTitle = isQuotaNotice(item.type)? typeLabels[item.type]: getInboxDisplayTitle(item);const isArchivedView = view === "archived";diff --git a/packages/views/inbox/components/inbox-page.tsx b/packages/views/inbox/components/inbox-page.tsxindex 26848ba5c8..c03e2461b4 100644--- a/packages/views/inbox/components/inbox-page.tsx+++ b/packages/views/inbox/components/inbox-page.tsx@@ -109,10 +109,12 @@ import {getInboxDisplayTitle,inboxRowHref,isAutopilotQuotaNotice,+ isQuotaNotice,isQuickCreateOutcome,resolveDetailItem,} from "./inbox-display";import { AutopilotQuotaNotice } from "./autopilot-quota-notice";+import { AppCallQuotaNotice } from "./app-call-quota-notice";import { InboxEmptyState } from "./inbox-empty-state";import { InboxKeptActions, useKeptInboxRowText } from "./inbox-kept-actions";import { inboxListLoad, useFilteredInboxRows } from "./use-filtered-inbox-rows";@@ -1162,7 +1164,7 @@ export function InboxPage() {{keptNotice}<div key={detailItem.id} className="animate-inbox-enter-fade p-6"><h2 className="text-title font-semibold">- {isAutopilotQuotaNotice(detailItem.type)+ {isQuotaNotice(detailItem.type)? typeLabels[detailItem.type]: getInboxDisplayTitle(detailItem)}</h2>@@ -1174,6 +1176,8 @@ export function InboxPage() {item={detailItem}onOpenRecovery={showAutopilotQuotaRecoveryPrompt}/>+ ) : detailItem.type === "app_tool_calls_quota_exceeded" ? (+ <AppCallQuotaNotice item={detailItem} />) : detailItem.type === "project_owner_joined" && detailItem.details?.joined_by ? (<div className="mt-4 text-body leading-relaxed text-foreground">{t(($) => $.detail.project_owner_joined_body, { name: detailItem.details.joined_by })}diff --git a/packages/views/issues/components/app-call-chips.tsx b/packages/views/issues/components/app-call-chips.tsxindex b6bf080927..1d49d30b14 100644--- a/packages/views/issues/components/app-call-chips.tsx+++ b/packages/views/issues/components/app-call-chips.tsx@@ -49,6 +49,7 @@ export function outcomeLabel(outcome: string, t: IssuesT): string {case "approved":case "rejected":case "rate_limited":+ case "quota_exceeded":return t(($) => $.app_calls.outcome[outcome]);default:return outcome;@@ -66,6 +67,8 @@ export function OutcomeIcon({ outcome, className }: { outcome: string; classNamereturn <Clock className={cn(cls, "text-warning")} />;case "blocked":return <Ban className={cn(cls, "text-muted-foreground")} />;+ case "quota_exceeded":+ return <Ban className={cn(cls, "text-warning")} />;default:return <XCircle className={cn(cls, "text-destructive")} />;}diff --git a/packages/views/issues/components/issue-apps-section.tsx b/packages/views/issues/components/issue-apps-section.tsxindex be8ed5ad18..e756e13b6a 100644--- a/packages/views/issues/components/issue-apps-section.tsx+++ b/packages/views/issues/components/issue-apps-section.tsx@@ -16,7 +16,7 @@ type AppGroup = {};/** Outcomes worth calling out next to an app; plain successes are not. */-const NOTABLE = ["pending", "blocked", "rejected", "error", "rate_limited"] as const;+const NOTABLE = ["pending", "blocked", "rejected", "error", "rate_limited", "quota_exceeded"] as const;/*** "Apps" in the issue sidebar: which apps, through which account, thisdiff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.jsonindex 0c51ea7033..17f3ff1e10 100644--- a/packages/views/locales/en/billing.json+++ b/packages/views/locales/en/billing.json@@ -29,6 +29,7 @@"retry": "Retry","retry_autopilots": "Retry autopilot usage","retry_storage": "Retry attachment storage usage",+ "retry_app_calls": "Retry app call usage","upgrade_to": "Upgrade to {{plan}}","switch_to": "Switch to {{plan}}","manage": "Manage billing",@@ -143,6 +144,12 @@"storage": "Attachment storage","storage_description": "Attachments in issues, comments, and chat.","storage_label": "Attachment storage usage",+ "app_calls": "App calls",+ "app_calls_description": "Calls agents run in connected apps. Searching for tools doesn't count.",+ "app_calls_label": "App call usage",+ "app_calls_by_member": "App calls by person",+ "app_calls_no_person": "Automated runs",+ "app_calls_former_member": "Former member","addon": "Add-on runs","addon_description": "When the allowance runs out, autopilots pause until next month or until you buy more runs.","addon_included": "Includes {{runs}} add-on runs",diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.jsonindex 76ce633ea3..b30eec6030 100644--- a/packages/views/locales/en/inbox.json+++ b/packages/views/locales/en/inbox.json@@ -72,6 +72,8 @@"retry_with_context": "Retry with context","edit_advanced": "Open full 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}}, or until the workspace upgrades or buys more runs.",+ "app_tool_calls_quota_exceeded_body": "This workspace has used its {{limit}} app calls for this month. Agents can't run app tools until the allowance resets {{resetAt}}, or until the workspace upgrades or adds seats.",+ "app_tool_calls_quota_action": "Manage billing","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","open_app": "Open app",@@ -111,6 +113,7 @@"children_done": "Sub-issues finished","project_owner_joined": "Owner joined project","autopilot_quota_exceeded": "Autopilot run limit reached",+ "app_tool_calls_quota_exceeded": "App call limit reached","app_action_requested": "Needs your confirmation","app_action_reminder": "Confirmation expiring soon","app_connect_requested": "Connect an app",@@ -133,6 +136,7 @@"created_with_agent": "Created with agent: {{identifier}}","failed_with_detail": "Failed: {{detail}}","autopilot_quota_blocked": "Run blocked because the limit was reached",+ "app_tool_calls_quota_blocked": "Agents can no longer run app tools this month","children_done_stage": "Stage {{stage}}'s sub-issues finished"},"toasts": {diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex b3c180ed58..1e095d81bd 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -2030,7 +2030,8 @@"pending": "Waiting","approved": "Approved","rejected": "Declined",- "rate_limited": "Rate limited"+ "rate_limited": "Rate limited",+ "quota_exceeded": "Monthly limit reached"}},"environments": {diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex 47f400303e..3678789d7e 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1923,7 +1923,8 @@"pending": "Waiting","approved": "Approved","rejected": "Declined",- "rate_limited": "Rate limited"+ "rate_limited": "Rate limited",+ "quota_exceeded": "Monthly limit reached"},"scopes": {"team": "Team account",diff --git a/packages/views/locales/es/billing.json b/packages/views/locales/es/billing.jsonindex 5fc9ef3e6a..9e08014daf 100644--- a/packages/views/locales/es/billing.json+++ b/packages/views/locales/es/billing.json@@ -29,6 +29,7 @@"retry": "Reintentar","retry_autopilots": "Reintentar el uso de automatización","retry_storage": "Reintentar uso del almacenamiento de adjuntos",+ "retry_app_calls": "Reintentar el uso de llamadas a aplicaciones","upgrade_to": "Actualizar a {{plan}}","switch_to": "Cambiar a {{plan}}","manage": "Gestionar facturación",@@ -143,6 +144,12 @@"storage": "Almacenamiento de adjuntos","storage_description": "Adjuntos de incidencias, comentarios y chats.","storage_label": "Uso del almacenamiento de adjuntos",+ "app_calls": "Llamadas a aplicaciones",+ "app_calls_description": "Llamadas que los agentes ejecutan en aplicaciones conectadas. Buscar herramientas no cuenta.",+ "app_calls_label": "Uso de llamadas a aplicaciones",+ "app_calls_by_member": "Llamadas a aplicaciones por persona",+ "app_calls_no_person": "Ejecuciones automáticas",+ "app_calls_former_member": "Antiguo miembro","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",diff --git a/packages/views/locales/es/inbox.json b/packages/views/locales/es/inbox.jsonindex 9ed027c118..a2935367f6 100644--- a/packages/views/locales/es/inbox.json+++ b/packages/views/locales/es/inbox.json@@ -72,6 +72,8 @@"retry_with_context": "Reintentar con contexto","edit_advanced": "Abrir formulario completo","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.",+ "app_tool_calls_quota_exceeded_body": "Este espacio de trabajo usó sus {{limit}} llamadas a aplicaciones de este mes. Los agentes no pueden usar herramientas de aplicaciones hasta que el límite se restablezca {{resetAt}}, o hasta que el espacio de trabajo mejore su plan o añada puestos.",+ "app_tool_calls_quota_action": "Gestionar facturación","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","open_app": "Abrir app",@@ -111,6 +113,7 @@"children_done": "Sub-tareas finalizadas","project_owner_joined": "El propietario se unió al proyecto","autopilot_quota_exceeded": "Límite de ejecuciones de automatizaciones alcanzado",+ "app_tool_calls_quota_exceeded": "Límite de llamadas a aplicaciones alcanzado","app_action_requested": "Necesita tu confirmación","app_action_reminder": "La confirmación caduca pronto","app_connect_requested": "Conectar una aplicación",@@ -133,6 +136,7 @@"created_with_agent": "Creada con agente: {{identifier}}","failed_with_detail": "Falló: {{detail}}","autopilot_quota_blocked": "Ejecución bloqueada porque se alcanzó el límite",+ "app_tool_calls_quota_blocked": "Los agentes ya no pueden usar herramientas de aplicaciones este mes","children_done_stage": "Sub-tareas de la etapa {{stage}} finalizadas"},"toasts": {diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex 171dc49f9d..dc9d2bc6f5 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -2030,7 +2030,8 @@"pending": "En espera","approved": "Aprobada","rejected": "Rechazada",- "rate_limited": "Límite de llamadas alcanzado"+ "rate_limited": "Límite de llamadas alcanzado",+ "quota_exceeded": "Límite mensual alcanzado"}},"environments": {diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex fcf9a5a2a7..bc7e7cc90f 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -1923,7 +1923,8 @@"pending": "En espera","approved": "Aprobada","rejected": "Rechazada",- "rate_limited": "Límite de llamadas alcanzado"+ "rate_limited": "Límite de llamadas alcanzado",+ "quota_exceeded": "Límite mensual alcanzado"},"scopes": {"team": "Cuenta del equipo",diff --git a/packages/views/locales/fr/billing.json b/packages/views/locales/fr/billing.jsonindex d4ffb8fa32..d472506d21 100644--- a/packages/views/locales/fr/billing.json+++ b/packages/views/locales/fr/billing.json@@ -29,6 +29,7 @@"retry": "Réessayer","retry_autopilots": "Réessayer le chargement de la consommation des automatisations","retry_storage": "Réessayer l'utilisation du stockage des pièces jointes",+ "retry_app_calls": "Réessayer la consommation d'appels d'apps","upgrade_to": "Passer à {{plan}}","switch_to": "Basculer vers {{plan}}","manage": "Gérer la facturation",@@ -143,6 +144,12 @@"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",+ "app_calls": "Appels d'apps",+ "app_calls_description": "Appels que les agents exécutent dans les apps connectées. La recherche d'outils n'est pas comptée.",+ "app_calls_label": "Consommation d'appels d'apps",+ "app_calls_by_member": "Appels d'apps par personne",+ "app_calls_no_person": "Exécutions automatiques",+ "app_calls_former_member": "Ancien membre","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",diff --git a/packages/views/locales/fr/inbox.json b/packages/views/locales/fr/inbox.jsonindex 9d65537a6e..1c4821f7b6 100644--- a/packages/views/locales/fr/inbox.json+++ b/packages/views/locales/fr/inbox.json@@ -72,6 +72,8 @@"retry_with_context": "Réessayer avec le contexte","edit_advanced": "Ouvrir le formulaire complet","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.",+ "app_tool_calls_quota_exceeded_body": "Cet espace de travail a utilisé ses {{limit}} appels d'apps de ce mois. Les agents ne peuvent plus utiliser les outils d'apps avant la réinitialisation {{resetAt}}, ou tant que l'espace de travail n'est pas passé à un plan supérieur ou n'a pas ajouté de places.",+ "app_tool_calls_quota_action": "Gérer la facturation","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","open_app": "Ouvrir l'app",@@ -111,6 +113,7 @@"children_done": "Sous-tâches terminées","project_owner_joined": "Le propriétaire a rejoint le projet","autopilot_quota_exceeded": "Limite d'exécutions d'automatisation atteinte",+ "app_tool_calls_quota_exceeded": "Limite d'appels d'apps atteinte","app_action_requested": "Confirmation requise","app_action_reminder": "Confirmation bientôt expirée","app_connect_requested": "Connecter une app",@@ -133,6 +136,7 @@"created_with_agent": "Créé avec un agent : {{identifier}}","failed_with_detail": "Échec : {{detail}}","autopilot_quota_blocked": "Exécution bloquée car la limite a été atteinte",+ "app_tool_calls_quota_blocked": "Les agents ne peuvent plus utiliser les outils d'apps ce mois-ci","children_done_stage": "Sous-tâches de l’étape {{stage}} terminées"},"toasts": {diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 288e060e1e..70e23b154a 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -2030,7 +2030,8 @@"pending": "En attente","approved": "Approuvé","rejected": "Refusé",- "rate_limited": "Limite atteinte"+ "rate_limited": "Limite atteinte",+ "quota_exceeded": "Limite mensuelle atteinte"}},"environments": {diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex 42f0559360..00789890be 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -1923,7 +1923,8 @@"pending": "En attente","approved": "Approuvé","rejected": "Refusé",- "rate_limited": "Limite atteinte"+ "rate_limited": "Limite atteinte",+ "quota_exceeded": "Limite mensuelle atteinte"},"scopes": {"team": "Compte d'équipe",diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.jsonindex a0b9a7342d..e9acf286b6 100644--- a/packages/views/locales/ja/billing.json+++ b/packages/views/locales/ja/billing.json@@ -29,6 +29,7 @@"retry": "再試行","retry_autopilots": "自動化の使用量を再取得","retry_storage": "添付ファイルの保存容量の使用量を再試行",+ "retry_app_calls": "アプリ呼び出しの使用量を再読み込み","upgrade_to": "{{plan}} にアップグレード","switch_to": "{{plan}} に切り替え","manage": "請求を管理",@@ -142,6 +143,12 @@"storage": "添付ファイルの保存容量","storage_description": "タスク、コメント、チャットの添付ファイル。","storage_label": "添付ファイルの保存容量の使用量",+ "app_calls": "アプリ呼び出し",+ "app_calls_description": "エージェントが接続済みアプリで実行する呼び出し。ツールの検索はカウントされません。",+ "app_calls_label": "アプリ呼び出しの使用量",+ "app_calls_by_member": "メンバー別のアプリ呼び出し",+ "app_calls_no_person": "自動実行",+ "app_calls_former_member": "退出したメンバー","addon": "追加の実行回数","addon_description": "実行枠を使い切ると、翌月のリセットまたは追加購入まで自動化は停止します。","addon_included": "うち追加分 {{runs}} 回",diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.jsonindex 2b07f39f16..9e8049ed31 100644--- a/packages/views/locales/ja/inbox.json+++ b/packages/views/locales/ja/inbox.json@@ -70,6 +70,8 @@"retry_with_context": "コンテキストを保持して再試行","edit_advanced": "詳細フォームを開く","autopilot_quota_exceeded_body": "このワークスペースは現在の期間の自動化実行上限 {{limit}} 回に達しました。実行枠が {{resetAt}} にリセットされるか、アップグレードまたは実行回数の追加購入を行うまで、以降の自動化は開始されません。",+ "app_tool_calls_quota_exceeded_body": "このワークスペースは今月のアプリ呼び出し {{limit}} 回を使い切りました。{{resetAt}} にリセットされるか、アップグレードまたはシートを追加するまで、エージェントはアプリのツールを実行できません。",+ "app_tool_calls_quota_action": "請求を管理","project_owner_joined_body": "{{name}} はワークスペースのオーナーで、このプライベートプロジェクトに自分を追加しました。タスク、コメント、添付ファイルを閲覧できるようになりました。","open_project": "プロジェクトを開く","open_app": "アプリを開く",@@ -109,6 +111,7 @@"children_done": "サブタスクがすべて終わりました","project_owner_joined": "オーナーがプロジェクトに参加","autopilot_quota_exceeded": "自動化の実行上限に達しました",+ "app_tool_calls_quota_exceeded": "アプリ呼び出しの上限に達しました","app_action_requested": "確認が必要","app_action_reminder": "確認の期限が近い","app_connect_requested": "アプリの接続依頼",@@ -131,6 +134,7 @@"created_with_agent": "エージェントで作成: {{identifier}}","failed_with_detail": "失敗: {{detail}}","autopilot_quota_blocked": "上限に達したため実行をブロックしました",+ "app_tool_calls_quota_blocked": "今月はエージェントがアプリのツールを実行できません","children_done_stage": "ステージ {{stage}} のサブタスクがすべて終わりました"},"toasts": {diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 444fc50f5f..96da34b2c6 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -1946,7 +1946,8 @@"pending": "確認待ち","approved": "承認済み","rejected": "却下",- "rate_limited": "レート制限"+ "rate_limited": "レート制限",+ "quota_exceeded": "月間上限に到達"}},"environments": {diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex abf72ae19d..05fca74ce1 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1906,7 +1906,8 @@"pending": "確認待ち","approved": "承認済み","rejected": "却下",- "rate_limited": "レート制限"+ "rate_limited": "レート制限",+ "quota_exceeded": "月間上限に到達"},"scopes": {"team": "チームアカウント",diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.jsonindex 4d81115693..b4fded15f2 100644--- a/packages/views/locales/ko/billing.json+++ b/packages/views/locales/ko/billing.json@@ -29,6 +29,7 @@"retry": "다시 시도","retry_autopilots": "자동화 사용량 다시 시도","retry_storage": "첨부 파일 저장 공간 사용량 다시 시도",+ "retry_app_calls": "앱 호출 사용량 다시 불러오기","upgrade_to": "{{plan}}로 업그레이드","switch_to": "{{plan}}로 전환","manage": "결제 관리",@@ -142,6 +143,12 @@"storage": "첨부 파일 저장 공간","storage_description": "이슈, 댓글, 채팅의 첨부 파일입니다.","storage_label": "첨부 파일 저장 공간 사용량",+ "app_calls": "앱 호출",+ "app_calls_description": "에이전트가 연결된 앱에서 실행하는 호출입니다. 도구 검색은 집계되지 않습니다.",+ "app_calls_label": "앱 호출 사용량",+ "app_calls_by_member": "멤버별 앱 호출",+ "app_calls_no_person": "자동 실행",+ "app_calls_former_member": "나간 멤버","addon": "추가 실행 횟수","addon_description": "한도를 다 쓰면 다음 달 초기화되거나 추가 구매할 때까지 자동화가 일시 중지됩니다.","addon_included": "추가 구매 {{runs}}회 포함",diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.jsonindex c0efee2d4e..bd01dd9f5f 100644--- a/packages/views/locales/ko/inbox.json+++ b/packages/views/locales/ko/inbox.json@@ -70,6 +70,8 @@"retry_with_context": "컨텍스트를 유지하여 재시도","edit_advanced": "전체 양식 열기","autopilot_quota_exceeded_body": "이 워크스페이스는 현재 기간의 오토파일럿 실행 한도 {{limit}}회에 도달했습니다. 한도가 {{resetAt}}에 초기화되거나 업그레이드 또는 실행 횟수를 추가 구매할 때까지 이후 오토파일럿 실행은 시작되지 않습니다.",+ "app_tool_calls_quota_exceeded_body": "이 워크스페이스는 이번 달 앱 호출 {{limit}}회를 모두 사용했습니다. 한도가 {{resetAt}}에 초기화되거나 업그레이드 또는 시트를 추가할 때까지 에이전트는 앱 도구를 실행할 수 없습니다.",+ "app_tool_calls_quota_action": "결제 관리","project_owner_joined_body": "{{name}} 님은 워크스페이스 소유자이며 이 비공개 프로젝트에 자신을 추가했습니다. 이제 태스크, 댓글, 첨부 파일을 볼 수 있습니다.","open_project": "프로젝트 열기","open_app": "앱 열기",@@ -109,6 +111,7 @@"children_done": "하위 태스크가 모두 끝났습니다","project_owner_joined": "소유자가 프로젝트에 참여함","autopilot_quota_exceeded": "자동화 실행 한도 도달",+ "app_tool_calls_quota_exceeded": "앱 호출 한도 도달","app_action_requested": "확인 필요","app_action_reminder": "확인 곧 만료","app_connect_requested": "앱 연결 요청",@@ -131,6 +134,7 @@"created_with_agent": "에이전트가 생성: {{identifier}}","failed_with_detail": "실패: {{detail}}","autopilot_quota_blocked": "한도에 도달하여 실행이 차단됨",+ "app_tool_calls_quota_blocked": "이번 달에는 에이전트가 앱 도구를 더 이상 실행할 수 없습니다","children_done_stage": "{{stage}}단계 하위 태스크가 모두 끝났습니다"},"toasts": {diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex b27f6ac81b..bfd86c33dd 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -1946,7 +1946,8 @@"pending": "대기 중","approved": "승인됨","rejected": "거절됨",- "rate_limited": "속도 제한"+ "rate_limited": "속도 제한",+ "quota_exceeded": "월 한도 도달"}},"environments": {diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 5ce1158b1c..c4a45bec28 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1906,7 +1906,8 @@"pending": "확인 대기","approved": "승인됨","rejected": "거절됨",- "rate_limited": "속도 제한"+ "rate_limited": "속도 제한",+ "quota_exceeded": "월 한도 도달"},"scopes": {"team": "팀 계정",diff --git a/packages/views/locales/ru/billing.json b/packages/views/locales/ru/billing.jsonindex 2dafd8080e..c14665640e 100644--- a/packages/views/locales/ru/billing.json+++ b/packages/views/locales/ru/billing.json@@ -29,6 +29,7 @@"retry": "Повторить","retry_autopilots": "Повторить получение использования автоматизации","retry_storage": "Повторить загрузку использования хранилища вложений",+ "retry_app_calls": "Повторить загрузку вызовов приложений","upgrade_to": "Перейти на {{plan}}","switch_to": "Переключиться на {{plan}}","manage": "Управление биллингом",@@ -145,6 +146,12 @@"storage": "Хранилище вложений","storage_description": "Вложения в задачах, комментариях и чатах.","storage_label": "Использование хранилища вложений",+ "app_calls": "Вызовы приложений",+ "app_calls_description": "Вызовы, которые агенты выполняют в подключённых приложениях. Поиск инструментов не учитывается.",+ "app_calls_label": "Использование вызовов приложений",+ "app_calls_by_member": "Вызовы приложений по участникам",+ "app_calls_no_person": "Автоматические запуски",+ "app_calls_former_member": "Бывший участник","addon": "Дополнительные запуски","addon_description": "Когда лимит исчерпан, автоматизации приостанавливаются до следующего месяца или до покупки дополнительных запусков.","addon_included": "Включая дополнительные: {{runs}}",diff --git a/packages/views/locales/ru/inbox.json b/packages/views/locales/ru/inbox.jsonindex 5459531502..8a0dd7d7de 100644--- a/packages/views/locales/ru/inbox.json+++ b/packages/views/locales/ru/inbox.json@@ -76,6 +76,8 @@"retry_with_context": "Повторить с контекстом","edit_advanced": "Открыть полную форму","autopilot_quota_exceeded_body": "Рабочее пространство исчерпало лимит в {{limit}} запусков автопилота за текущий период. Новые запуски не начнутся, пока лимит не сбросится {{resetAt}}, или пока рабочее пространство не сменит тариф либо не купит дополнительные запуски.",+ "app_tool_calls_quota_exceeded_body": "Рабочее пространство израсходовало {{limit}} вызовов приложений за этот месяц. Агенты не смогут использовать инструменты приложений, пока лимит не обновится {{resetAt}} или пока рабочее пространство не перейдёт на другой план или не добавит места.",+ "app_tool_calls_quota_action": "Управление оплатой","project_owner_joined_body": "{{name}}, владелец рабочего пространства, теперь участвует в этом закрытом проекте и видит его задачи, комментарии и вложения.","open_project": "Открыть проект","open_app": "Открыть приложение",@@ -115,6 +117,7 @@"children_done": "Подзадачи завершены","project_owner_joined": "Владелец присоединился к проекту","autopilot_quota_exceeded": "Достигнут лимит запусков Автопилота",+ "app_tool_calls_quota_exceeded": "Лимит вызовов приложений исчерпан","app_action_requested": "Требуется ваше подтверждение","app_action_reminder": "Срок подтверждения скоро истечёт","app_connect_requested": "Подключить приложение",@@ -137,6 +140,7 @@"created_with_agent": "Создано с помощью агента: {{identifier}}","failed_with_detail": "Ошибка: {{detail}}","autopilot_quota_blocked": "Запуск заблокирован, так как достигнут лимит",+ "app_tool_calls_quota_blocked": "В этом месяце агенты больше не могут использовать инструменты приложений","children_done_stage": "Подзадачи этапа {{stage}} завершены"},"toasts": {diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex 0c312f8161..288c6bcb1d 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -2204,7 +2204,8 @@"pending": "Ожидание","approved": "Одобрено","rejected": "Отклонено",- "rate_limited": "Лимит вызовов достигнут"+ "rate_limited": "Лимит вызовов достигнут",+ "quota_exceeded": "Месячный лимит исчерпан"}},"environments": {diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex c6bc496ebd..973e509b14 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -1957,7 +1957,8 @@"pending": "Ожидание","approved": "Одобрено","rejected": "Отклонено",- "rate_limited": "Лимит вызовов достигнут"+ "rate_limited": "Лимит вызовов достигнут",+ "quota_exceeded": "Месячный лимит исчерпан"},"scopes": {"team": "Аккаунт команды",diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.jsonindex fe7cd8fc5d..8c27c9c5d3 100644--- a/packages/views/locales/zh-Hans/billing.json+++ b/packages/views/locales/zh-Hans/billing.json@@ -29,6 +29,7 @@"retry": "重试","retry_autopilots": "重试加载自动化用量","retry_storage": "重试加载附件存储用量",+ "retry_app_calls": "重新加载应用调用用量","upgrade_to": "升级到 {{plan}}","switch_to": "切换到 {{plan}}","manage": "管理账单",@@ -142,6 +143,12 @@"storage": "附件存储","storage_description": "任务、评论和聊天中的附件。","storage_label": "附件存储用量",+ "app_calls": "应用调用",+ "app_calls_description": "智能体在已连接应用中执行的调用。搜索工具不计入。",+ "app_calls_label": "应用调用用量",+ "app_calls_by_member": "各成员的应用调用",+ "app_calls_no_person": "自动运行",+ "app_calls_former_member": "已离开的成员","addon": "加购运行次数","addon_description": "额度用完后自动化会暂停,直到下月重置或加购。","addon_included": "其中加购 {{runs}} 次",diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.jsonindex 4e66ab0d97..504a720e47 100644--- a/packages/views/locales/zh-Hans/inbox.json+++ b/packages/views/locales/zh-Hans/inbox.json@@ -70,6 +70,8 @@"retry_with_context": "保留上下文重试","edit_advanced": "在完整表单中编辑","autopilot_quota_exceeded_body": "当前周期的 {{limit}} 次自动化执行额度已用完。在 {{resetAt}} 重置、升级套餐或加购之前,后续自动化执行将不会启动。",+ "app_tool_calls_quota_exceeded_body": "本工作区本月的 {{limit}} 次应用调用已用完。在 {{resetAt}} 重置、升级套餐或增加席位之前,智能体无法调用应用工具。",+ "app_tool_calls_quota_action": "管理账单","project_owner_joined_body": "{{name}} 是工作区所有者,已把自己加入这个私有项目,现在可以看到其中的任务、评论和附件。","open_project": "打开项目","open_app": "打开应用",@@ -109,6 +111,7 @@"children_done": "子任务已全部结束","project_owner_joined": "所有者加入了项目","autopilot_quota_exceeded": "自动化执行次数已用完",+ "app_tool_calls_quota_exceeded": "应用调用次数已用完","app_action_requested": "等待你确认","app_action_reminder": "确认即将过期","app_connect_requested": "请连接应用",@@ -131,6 +134,7 @@"created_with_agent": "通过智能体创建:{{identifier}}","failed_with_detail": "失败:{{detail}}","autopilot_quota_blocked": "执行已被阻止:额度已用完",+ "app_tool_calls_quota_blocked": "本月智能体无法再调用应用工具","children_done_stage": "第 {{stage}} 阶段的子任务已全部结束"},"toasts": {diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 597c86a891..9a9f0ef76a 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -1946,7 +1946,8 @@"pending": "等待确认","approved": "已批准","rejected": "已拒绝",- "rate_limited": "已限流"+ "rate_limited": "已限流",+ "quota_exceeded": "已达月度上限"}},"environments": {diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex afa43ffa84..7a712396cc 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1906,7 +1906,8 @@"pending": "等待确认","approved": "已批准","rejected": "已拒绝",- "rate_limited": "已限流"+ "rate_limited": "已限流",+ "quota_exceeded": "已达月度上限"},"scopes": {"team": "团队账号",diff --git a/packages/views/locales/zh-Hant/billing.json b/packages/views/locales/zh-Hant/billing.jsonindex 5c01861770..7a84fac752 100644--- a/packages/views/locales/zh-Hant/billing.json+++ b/packages/views/locales/zh-Hant/billing.json@@ -29,6 +29,7 @@"retry": "重試","retry_autopilots": "重試載入自動化用量","retry_storage": "重試附件儲存空間用量",+ "retry_app_calls": "重新載入應用呼叫用量","upgrade_to": "升級到 {{plan}}","switch_to": "切換到 {{plan}}","manage": "管理帳單",@@ -142,6 +143,12 @@"storage": "附件儲存空間","storage_description": "任務、留言和聊天中的附件。","storage_label": "附件儲存空間用量",+ "app_calls": "應用呼叫",+ "app_calls_description": "AI 代理在已連線應用中執行的呼叫。搜尋工具不計入。",+ "app_calls_label": "應用呼叫用量",+ "app_calls_by_member": "各成員的應用呼叫",+ "app_calls_no_person": "自動執行",+ "app_calls_former_member": "已離開的成員","addon": "加購執行次數","addon_description": "額度用完後自動化會暫停,直到下月重置或加購。","addon_included": "其中加購 {{runs}} 次",diff --git a/packages/views/locales/zh-Hant/inbox.json b/packages/views/locales/zh-Hant/inbox.jsonindex 23144ac94e..aefad1386e 100644--- a/packages/views/locales/zh-Hant/inbox.json+++ b/packages/views/locales/zh-Hant/inbox.json@@ -70,6 +70,8 @@"retry_with_context": "保留上下文重試","edit_advanced": "開啟完整表單","autopilot_quota_exceeded_body": "目前週期的 {{limit}} 次自動化執行額度已用完。在 {{resetAt}} 重置、升級方案或加購之前,後續自動化執行將不會啟動。",+ "app_tool_calls_quota_exceeded_body": "本工作區本月的 {{limit}} 次應用呼叫已用完。在 {{resetAt}} 重置、升級方案或增加席位之前,AI 代理無法呼叫應用工具。",+ "app_tool_calls_quota_action": "管理帳單","project_owner_joined_body": "{{name}} 是工作區所有者,已把自己加入這個私有專案,現在可以看到其中的任務、評論和附件。","open_project": "開啟專案","open_app": "開啟應用程式",@@ -109,6 +111,7 @@"children_done": "子任務已全部結束","project_owner_joined": "所有者加入了專案","autopilot_quota_exceeded": "自動化執行次數已用完",+ "app_tool_calls_quota_exceeded": "應用呼叫次數已用完","app_action_requested": "等待你確認","app_action_reminder": "確認即將過期","app_connect_requested": "請連線應用",@@ -131,6 +134,7 @@"created_with_agent": "透過 AI 代理建立:{{identifier}}","failed_with_detail": "失敗:{{detail}}","autopilot_quota_blocked": "執行已被阻止:額度已用完",+ "app_tool_calls_quota_blocked": "本月 AI 代理無法再呼叫應用工具","children_done_stage": "第 {{stage}} 階段的子任務已全部結束"},"toasts": {diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 64aa2d9d70..3aa52926e8 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -1946,7 +1946,8 @@"pending": "等待確認","approved": "已核准","rejected": "已拒絕",- "rate_limited": "已限流"+ "rate_limited": "已限流",+ "quota_exceeded": "已達每月上限"}},"environments": {diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 04f2eb83d0..d857ed4f0b 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -1906,7 +1906,8 @@"pending": "等待確認","approved": "已核准","rejected": "已拒絕",- "rate_limited": "已限流"+ "rate_limited": "已限流",+ "quota_exceeded": "已達每月上限"},"scopes": {"team": "團隊帳號",diff --git a/packages/views/settings/components/app-calls-limit-row.tsx b/packages/views/settings/components/app-calls-limit-row.tsxnew file mode 100644index 0000000000..fad1ac1d08--- /dev/null+++ b/packages/views/settings/components/app-calls-limit-row.tsx@@ -0,0 +1,127 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import type { AppCallRow } from "@multica/core/billing";+import { memberListOptions } from "@multica/core/workspace/queries";+import { Button } from "@multica/ui/components/ui/button";+import { Loader2, RefreshCw } from "@multica/ui/icons";+import {+ Progress,+ ProgressLabel,+ ProgressValue,+} from "@multica/ui/components/ui/progress";+import { useLocale, useT } from "../../i18n";+import { SettingsRow } from "./settings-layout";++function formatResetAt(value: string | null, locale: string): string | null {+ if (!value) return null;+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return null;+ return new Intl.DateTimeFormat(locale, { dateStyle: "medium" }).format(date);+}++/**+ * Billing's row for the monthly app call limit (MUL-10047): this month's+ * calls against the workspace's limit and, for owners and admins, who made+ * them.+ */+export function AppCallsLimitRow({+ wsId,+ row,+ retrying,+ onRetry,+}: {+ wsId: string;+ row: AppCallRow;+ retrying: boolean;+ onRetry: () => void;+}) {+ const { t } = useT("billing");+ const locale = useLocale();+ const numberFormatter = new Intl.NumberFormat(locale);+ const members = row.kind === "metered" ? row.members : [];+ const memberQuery = useQuery({ ...memberListOptions(wsId), enabled: members.length > 0 });+ const nameOf = (userId: string | null) => {+ if (userId === null) return t(($) => $.workspace.limits.app_calls_no_person);+ return memberQuery.data?.find((m) => m.user_id === userId)?.name ?? t(($) => $.workspace.limits.app_calls_former_member);+ };++ if (row.kind === "unavailable") {+ return (+ <SettingsRow+ label={t(($) => $.workspace.limits.app_calls)}+ description={t(($) => $.workspace.limits.app_calls_description)}+ >+ <div className="flex flex-col gap-2 sm:items-end">+ {row.limit !== null ? (+ <span className="tabular-nums">+ {t(($) => $.workspace.limits.per_month, { count: row.limit })}+ </span>+ ) : null}+ <span className="text-caption text-muted-foreground">+ {t(($) => $.workspace.limits.usage_unavailable)}+ </span>+ <Button+ type="button"+ variant="outline"+ size="sm"+ aria-label={t(($) => $.workspace.actions.retry_app_calls)}+ aria-busy={retrying}+ disabled={retrying}+ onClick={onRetry}+ >+ {retrying ? <Loader2 className="animate-spin motion-reduce:animate-none" /> : <RefreshCw />}+ {t(($) => $.workspace.actions.retry)}+ </Button>+ </div>+ </SettingsRow>+ );+ }++ const resetAt = formatResetAt(row.resetAt, locale);+ return (+ <SettingsRow+ label={t(($) => $.workspace.limits.app_calls)}+ description={t(($) => $.workspace.limits.app_calls_description)}+ >+ <div className="w-full max-w-72 space-y-2">+ <Progress+ value={row.limit <= 0 ? 100 : Math.min(100, (row.used / row.limit) * 100)}+ aria-label={t(($) => $.workspace.limits.app_calls_label)}+ >+ <ProgressLabel>+ {row.reached+ ? t(($) => $.workspace.limits.reached)+ : t(($) => $.workspace.limits.current_usage)}+ </ProgressLabel>+ <ProgressValue>+ {() =>+ t(($) => $.workspace.limits.usage_total, {+ total: numberFormatter.format(row.used),+ limit: numberFormatter.format(row.limit),+ })+ }+ </ProgressValue>+ </Progress>+ {resetAt ? (+ <p className="text-caption text-muted-foreground tabular-nums">+ {t(($) => $.workspace.limits.resets_at, { date: resetAt })}+ </p>+ ) : null}+ {members.length > 0 ? (+ <ul+ className="space-y-1 pt-1 text-caption text-muted-foreground"+ aria-label={t(($) => $.workspace.limits.app_calls_by_member)}+ >+ {members.map((m) => (+ <li key={m.userId ?? "none"} className="flex justify-between gap-3">+ <span className="truncate">{nameOf(m.userId)}</span>+ <span className="shrink-0 tabular-nums">{numberFormatter.format(m.calls)}</span>+ </li>+ ))}+ </ul>+ ) : null}+ </div>+ </SettingsRow>+ );+}diff --git a/packages/views/settings/components/billing-tab.test.tsx b/packages/views/settings/components/billing-tab.test.tsxindex 71879aeb9c..23be635d5d 100644--- a/packages/views/settings/components/billing-tab.test.tsx+++ b/packages/views/settings/components/billing-tab.test.tsx@@ -8,6 +8,7 @@ import type {AutopilotQuotaUsage,MemberLimit,StorageUsage,+ AppCallUsage,WorkspaceSubscriptionEntitlements,WorkspaceSubscriptionPrices,WorkspaceSubscriptionSummary,@@ -39,6 +40,8 @@ const mocks = vi.hoisted(() => ({memberLimit: { action: "off", limit: null, members: null, pendingInvitations: null } as MemberLimit,storageUsage: { action: "off", usedBytes: null, limitBytes: null, reached: null } as StorageUsage,refetchStorage: vi.fn(),+ appCallUsage: { action: "off", used: null, limit: null, reached: null, resetAt: null, members: [] } as AppCallUsage,+ members: [] as { user_id: string; name: string }[],prices: null as WorkspaceSubscriptionPrices | null,pricesLoading: false,pricesFetching: false,@@ -349,11 +352,19 @@ describe("BillingTab", () => {localStorage.clear();mocks.memberLimit = { action: "off", limit: null, members: null, pendingInvitations: null };mocks.storageUsage = { action: "off", usedBytes: null, limitBytes: null, reached: null };+ mocks.appCallUsage = { action: "off", used: null, limit: null, reached: null, resetAt: null, members: [] };+ mocks.members = [];mocks.useQuery.mockImplementation((options: unknown) => {const queryKey = (options as { queryKey?: readonly unknown[] }).queryKey;if (queryKey?.[0] === "workspace-storage-usage") {return { data: mocks.storageUsage, isPending: false, isError: false, refetch: mocks.refetchStorage };}+ if (queryKey?.[0] === "workspace-app-call-usage") {+ return { data: mocks.appCallUsage, isPending: false, isError: false, isFetching: false, refetch: vi.fn() };+ }+ if (queryKey?.length === 3 && queryKey[0] === "workspaces" && queryKey[2] === "members") {+ return { data: mocks.members, isPending: false, isError: false };+ }if (queryKey?.[queryKey.length - 1] === "limit") {return { data: mocks.memberLimit, isPending: false, isError: false };}@@ -937,6 +948,42 @@ describe("BillingTab", () => {expect(mocks.invalidateQueries).toHaveBeenCalledWith({ queryKey: ["workspace-storage-usage", expect.any(String)] });});+ it("shows this month's app calls against the plan's limit, for every person (MUL-10047)", () => {+ const names = ["Ada", "Ben", "Cy", "Di", "Ed", "Flo"];+ mocks.members = names.map((name) => ({ user_id: `user-${name}`, name }));+ mocks.appCallUsage = {+ action: "observe",+ used: 230,+ limit: 1500,+ reached: null,+ resetAt: "2030-02-01T00:00:00Z",+ members: [+ ...names.map((name, i) => ({ userId: `user-${name}`, calls: 60 - i * 10 })),+ { userId: null, calls: 20 },+ ],+ };+ renderWithI18n(<BillingTab />);++ expect(screen.getByText("App calls")).toBeInTheDocument();+ expect(screen.getByText("230 / 1,500")).toBeInTheDocument();+ const byPerson = screen.getByRole("list", { name: "App calls by person" });+ expect(within(byPerson).getAllByRole("listitem")).toHaveLength(7);+ for (const name of names) expect(within(byPerson).getByText(name)).toBeInTheDocument();+ expect(within(byPerson).getByText("Automated runs")).toBeInTheDocument();+ });++ it("reports enforced app calls as reached, and hides them without a limit", () => {+ mocks.appCallUsage = { action: "enforce", used: 100, limit: 100, reached: true, resetAt: null, members: [] };+ const { unmount } = renderWithI18n(<BillingTab />);+ expect(screen.getByText("100 / 100")).toBeInTheDocument();+ expect(screen.getAllByText("Limit reached").length).toBeGreaterThan(0);+ unmount();++ mocks.appCallUsage = { action: "off", used: null, limit: null, reached: null, resetAt: null, members: [] };+ renderWithI18n(<BillingTab />);+ expect(screen.queryByText("App calls")).not.toBeInTheDocument();+ });+it("shows members and pending invitations against the plan's limit", () => {mocks.memberLimit = { action: "observe", limit: 5, members: 4, pendingInvitations: 2 };renderWithI18n(<BillingTab />);diff --git a/packages/views/settings/components/billing-tab.tsx b/packages/views/settings/components/billing-tab.tsxindex 7f9e141459..bc25554bd3 100644--- a/packages/views/settings/components/billing-tab.tsx+++ b/packages/views/settings/components/billing-tab.tsx@@ -32,6 +32,9 @@ import {listCheckoutHeldInvites,memberLimitKeys,memberLimitOptions,+ appCallUsageKeys,+ appCallUsageOptions,+ resolveAppCallRow,formatStorageBytes,resolveStorageRow,storageUsageKeys,@@ -103,6 +106,7 @@ import {SettingsSection,SettingsTab,} from "./settings-layout";+import { AppCallsLimitRow } from "./app-calls-limit-row";import {hasActiveWorkspaceSeatCapacity,resolveAutopilotUsage,@@ -377,6 +381,7 @@ function BillingTabContent() {const [heldInvitesToConfirm, setHeldInvitesToConfirm] = useState<HeldInvite[]>([]);const memberLimitQuery = useQuery(memberLimitOptions(wsId));const storageUsageQuery = useQuery(storageUsageOptions(wsId));+ const appCallUsageQuery = useQuery(appCallUsageOptions(wsId));useEffect(() => {checkoutIntentRef.current = null;@@ -483,9 +488,9 @@ function BillingTabContent() {const dashboardHistoryLimit = entitlements?.limits.dashboardHistoryDays;const dashboardHistoryDays =dashboardHistoryLimit?.mode === "limited" ? dashboardHistoryLimit.limit : null;- // A confirmed upgrade or seat purchase changes the storage limit; the- // entitlement already carries the new one, and this refreshes the usage- // read behind it.+ // A confirmed upgrade or seat purchase changes the storage and app call+ // limits; the entitlement already carries the new ones, and this refreshes+ // the usage reads behind them.const subscriptionVersion = summaryQuery.data?.entitlement.version;const seenSubscriptionVersionRef = useRef(subscriptionVersion);useEffect(() => {@@ -493,6 +498,7 @@ function BillingTabContent() {seenSubscriptionVersionRef.current = subscriptionVersion;if (seen === undefined || subscriptionVersion === undefined || seen === subscriptionVersion) return;void queryClient.invalidateQueries({ queryKey: storageUsageKeys.all(wsId) });+ void queryClient.invalidateQueries({ queryKey: appCallUsageKeys.all(wsId) });}, [queryClient, subscriptionVersion, wsId]);// Checkout is done once paid seats are in effect. Neither the plan nor// Checkout going away proves it: a trial already reports Business, and a@@ -1349,6 +1355,11 @@ function BillingTabContent() {storageUsageQuery.isError,entitlements?.limits.storageBytes,);+ const appCallRow = resolveAppCallRow(+ appCallUsageQuery.data,+ appCallUsageQuery.isError,+ entitlements?.limits.appToolCalls,+ );// This month's add-on runs, already part of the limit Cloud reports.const autopilotAddon = summaryQuery.data?.autopilotAddon ?? null;const canBuyAutopilotAddon =@@ -2147,6 +2158,14 @@ function BillingTabContent() {)}</SettingsRow>) : null}+ {appCallRow ? (+ <AppCallsLimitRow+ wsId={wsId}+ row={appCallRow}+ retrying={appCallUsageQuery.isFetching}+ onRetry={() => void appCallUsageQuery.refetch()}+ />+ ) : null}{autopilotAddon ? (<SettingsRowlabel={t(($) => $.workspace.limits.addon)}diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 5f1e65d168..a3760b9072 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,8 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "749_app_tool_call_quota_period_scope_idx": "uq_app_tool_call_quota_period_scope",+ "751_app_tool_call_workspace_metered_idx": "idx_app_tool_call_workspace_metered","736_task_usage_hourly_squad_uq_idx": "uq_task_usage_hourly_squad_key_idx","737_task_usage_hourly_dirty_squad_uq_idx": "uq_task_usage_hourly_dirty_squad_key_idx","738_task_usage_hourly_workspace_squad_idx": "idx_task_usage_hourly_workspace_squad_time",diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 07e328e5a1..f565d6b57d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1436,6 +1436,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusPublicBaseURL: callbackBase,Bus: bus,}+ // Monthly app calls (MUL-10047) are metered only+ // while Multica Cloud is connected.+ if h.Entitlements != nil {+ appsCfg.CallQuota = service.AppToolCallQuota{+ Queries: queries, Entitlements: h.Entitlements, TxStarter: pool, Bus: bus,+ }+ }// Remote MCP apps (MUL-9792) store OAuth tokens, so// they need their own at-rest key; without it they// stay off and Composio apps work as before.@@ -1928,6 +1935,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// is checked on the server regardless.r.Get("/member-limit", h.GetMemberLimit)r.Get("/storage-usage", h.GetStorageUsage)+ r.Get("/app-call-usage", h.GetAppCallUsage)r.Post("/leave", h.LeaveWorkspace)r.Get("/invitations", h.ListWorkspaceInvitations)// Listing GitHub installations is member-visible so thediff --git a/server/internal/connectedapps/gateway.go b/server/internal/connectedapps/gateway.goindex 301e5d9f27..86c9cc0ff0 100644--- a/server/internal/connectedapps/gateway.go+++ b/server/internal/connectedapps/gateway.go@@ -529,7 +529,8 @@ func (s *Service) toolRun(ctx context.Context, rn *run, toolSlug string, args ma}// refuseCall applies what stands between an allowed policy and executing a-// call: a blocking rule, the run losing access, and the account's rate limit.+// call: a blocking rule, the run losing access, the account's rate limit, and+// the workspace's monthly app call allowance.// It records and returns the refusal, or nil when the call may run.func (s *Service) refuseCall(ctx context.Context, rn *run, app db.AgentApp, call *toolCall, policy string) map[string]any {if policy == PolicyBlock {@@ -556,6 +557,10 @@ func (s *Service) refuseCall(ctx context.Context, rn *run, app db.AgentApp, calls.recordCall(ctx, *call)return textResult(fmt.Sprintf("rate limited: this %s account already ran %d calls in the last minute. Wait a minute before the next call, and batch work where the app allows it.", call.toolkit, s.perMinute), true)}+ // Last: it counts the call, which runs as soon as this returns nil.+ if exceeded := s.overQuota(ctx, call); exceeded != nil {+ return textResult(exceeded.Message(), true)+ }return nil}diff --git a/server/internal/connectedapps/quota.go b/server/internal/connectedapps/quota.gonew file mode 100644index 0000000000..a1a2c40019--- /dev/null+++ b/server/internal/connectedapps/quota.go@@ -0,0 +1,50 @@+package connectedapps++import (+ "context"+ "fmt"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+)++// CallQuota meters the calls a workspace sends to Composio each period (the+// app_tool_calls entitlement gate, MUL-10047). Admit runs right before a call+// is sent and counts it, so a call that then fails upstream still counts. It+// returns the start of the period the call was counted in (zero when it was+// not counted) and, when the call must not run, the refusal. Every failure to+// decide admits. Remote MCP apps and meta tools (listing, searching,+// connection requests) never reach it: they do not run through Composio.+type CallQuota interface {+ Admit(ctx context.Context, workspaceID pgtype.UUID) (countedIn time.Time, refused *CallQuotaExceeded)+}++// CallQuotaExceeded is a refusal: the workspace used its allowance.+type CallQuotaExceeded struct {+ Used int64+ Limit int64+ ResetAt time.Time+}++// Message is what the agent, and the approver of a confirmed call, read.+func (e *CallQuotaExceeded) Message() string {+ return fmt.Sprintf("app call limit reached: this workspace has used %d of its %d app calls for this period; the allowance resets at %s. "++ "Do not retry. Tell the person that this workspace is out of app calls until then, or until it upgrades its plan or adds seats.",+ e.Used, e.Limit, e.ResetAt.UTC().Format("2006-01-02 15:04 UTC"))+}++// overQuota counts a call against the workspace's allowance right before it+// runs, and records and returns the refusal when the allowance is used up.+func (s *Service) overQuota(ctx context.Context, call *toolCall) *CallQuotaExceeded {+ if s.quota == nil {+ return nil+ }+ countedIn, exceeded := s.quota.Admit(ctx, call.workspaceID)+ if exceeded == nil {+ call.meteredPeriod = countedIn+ return nil+ }+ call.outcome, call.err = "quota_exceeded", ""+ s.recordCall(ctx, *call)+ return exceeded+}diff --git a/server/internal/connectedapps/requests.go b/server/internal/connectedapps/requests.goindex 2ec013665f..1e7a2b5dda 100644--- a/server/internal/connectedapps/requests.go+++ b/server/internal/connectedapps/requests.go@@ -401,8 +401,8 @@ func (s *Service) executeApproved(ctx context.Context, req db.AppActionRequest)acct: account{scope: req.AccountScope, owner: personalOwner(req)},toolkit: req.ToolkitSlug, tool: req.ToolSlug, class: req.ActionClass, requestID: req.ID,}- fail := func(msg string) (db.AppActionRequest, string) {- call.outcome, call.err = "error", truncate(msg, 500)+ failAs := func(outcome, msg string) (db.AppActionRequest, string) {+ call.outcome, call.err = outcome, truncate(msg, 500)s.recordCall(ctx, call)row, err := s.q.SetAppActionRequestOutcome(ctx, db.SetAppActionRequestOutcomeParams{ID: req.ID, WorkspaceID: req.WorkspaceID, Status: "failed",@@ -413,6 +413,7 @@ func (s *Service) executeApproved(ctx context.Context, req db.AppActionRequest)}return row, fmt.Sprintf("Your %s was approved, but running it failed: %s. Decide how to continue; do not resubmit the same call unless the failure was transient.", label, msg)}+ fail := func(msg string) (db.AppActionRequest, string) { return failAs("error", msg) }app, ok := s.agentApp(ctx, req.AgentID, req.ToolkitSlug)if !ok {@@ -442,6 +443,14 @@ func (s *Service) executeApproved(ctx context.Context, req db.AppActionRequest)if Decide(req.ToolkitSlug, app.Level, class, rule) == PolicyBlock {return fail("a rule now blocks this call")}+ // Last: it counts the call, which runs right after.+ if s.quota != nil {+ countedIn, exceeded := s.quota.Admit(ctx, req.WorkspaceID)+ if exceeded != nil {+ return failAs("quota_exceeded", exceeded.Message())+ }+ call.meteredPeriod = countedIn+ }resp, err := s.composio.ExecuteTool(ctx, acct.connectedAccountID, acct.composioUserID, *tool, args)s.touch(ctx, req.WorkspaceID, acct)if err != nil {diff --git a/server/internal/connectedapps/service.go b/server/internal/connectedapps/service.goindex 9c81872b70..57e918e0f5 100644--- a/server/internal/connectedapps/service.go+++ b/server/internal/connectedapps/service.go@@ -105,6 +105,9 @@ type Config struct {// Remote MCP apps are off unless both are set.SecretBox SealerDB TxStarter+ // CallQuota meters the calls sent to Composio against the workspace's+ // monthly allowance. Nil, as without Multica Cloud, meters nothing.+ CallQuota CallQuota// RemoteApps overrides BuiltinRemoteApps; RemoteUpstream overrides the// network client. Both are for tests.RemoteApps []RemoteApp@@ -122,6 +125,7 @@ type Service struct {now func() time.Timeresumer ResumerperMinute int+ quota CallQuotaremote *remoteSupport}@@ -154,6 +158,7 @@ func New(cfg Config) (*Service, error) {bus: cfg.Bus,now: now,perMinute: perMinute,+ quota: cfg.CallQuota,remote: newRemoteSupport(cfg, base),}, nil}@@ -467,6 +472,9 @@ type toolCall struct {toolkit, tool, class, outcome stringrequestID pgtype.UUIDerr string+ // meteredPeriod is the start of the period the monthly app call allowance+ // counted the call in; zero when it was not counted.+ meteredPeriod time.Time}// Upstream errors can contain tool arguments or private app data. Log only@@ -500,6 +508,7 @@ func (s *Service) recordCall(ctx context.Context, c toolCall) {Outcome: c.outcome,RequestID: c.requestID,Error: pgtype.Text{String: c.err, Valid: c.err != ""},+ MeteredPeriodStart: pgtype.Timestamptz{Time: c.meteredPeriod, Valid: !c.meteredPeriod.IsZero()},})if s.bus != nil && c.issueID.Valid {s.bus.Publish(events.Event{diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.mdindex 6edaa01ddb..c9ccdf7833 100644--- a/server/internal/entitlement/README.md+++ b/server/internal/entitlement/README.md@@ -17,7 +17,7 @@ The client reads:- `schema_version`: only version 1 is accepted.- `policy_revision`: the effective-instruction generation, currently fixed at- `9` by Cloud and not deployment configuration. Cloud advances it when the+ `10` by Cloud and not deployment configuration. Cloud advances it when themeaning or set of actionable instructions changes, including additiveinstructions; `schema_version` changes only for incompatible wire parsing.- `subscription_version`: the workspace's monotonic subscription revision. A@@ -79,6 +79,11 @@ missing or malformed gate, including a `limit` outside 1–365 or one carrying aperiod, is `off` with reason `gate_missing` or `gate_invalid` for that gatealone. See [Dashboard history limit](#dashboard-history-limit).+`gates.app_tool_calls` (revision 10) is optional like `members`: a missing or+malformed gate, including one without its period, is `off` with reason+`gate_missing` or `gate_invalid` for that gate alone. See+[Monthly app call limit](#monthly-app-call-limit).+Responses tolerate unknown JSON fields and gates for additive compatibility.Unknown schema/action, malformed fields, a missing `autopilot_runs` gate, HTTPfailures, and timeouts fail open.@@ -222,6 +227,54 @@ Clients read `GET /api/workspaces/{id}/storage-usage` (member-readable), whichreturns `action` and, while a limit applies, `used_bytes` and `limit_bytes`;`reached` is present only under `enforce`.+## Monthly app call limit++`app_tool_calls` caps the Connected Apps tool calls a workspace sends to+Composio in a Cloud-defined period (a UTC calendar month). Like+`autopilot_runs` it carries a `limit`, the period, and under `enforce` a+`first_rejection_per_limit` notification policy. `service.AppToolCallQuota`+(`server/internal/service/app_tool_call_quota.go`) checks it; the gateway+calls it through `connectedapps.CallQuota`.++Usage is a counter, `app_tool_call_quota_period.used_count` per workspace and+period, never a `COUNT` over `app_tool_call`. One conditional upsert counts a+call right before it is sent to Composio: under `enforce` it only increments+below the limit, so concurrent calls cannot take a workspace past it; under+`observe` it always increments. A call that then fails upstream still counts,+as Composio bills it.++| Counted | Not counted |+| --- | --- |+| `apps_run_tool` calls the gateway sends to Composio (`toolRun`) | blocked calls, per-minute rate-limited calls, refused calls themselves |+| Confirmed calls when the approval executes them (`executeApproved`) | pending confirmations, meta tools (list, search, get tool, connection requests), Remote MCP apps |++Team and personal accounts both count toward the workspace that started the+run. `enforce` refuses past the limit only after re-reading the policy with+`RefreshGateNow`, so a workspace that upgraded or added seats moments ago is+admitted. A cached policy whose period has already ended (the first minute of+a month) is re-read the same way before counting a call or answering Billing;+if Cloud still sends the old period, the call is admitted without counting and+Billing shows no limit for that moment. The agent gets a tool error with the count, the limit and the reset+time; the call is logged in `app_tool_call` as `quota_exceeded`, and a refused+confirmed call fails its request. Owners and admins get one+`app_tool_calls_quota_exceeded` Inbox item per limit and period, also when+the limit returns to one already notified; a delivery with no recipient leaves+the marker unset for the next refusal. Attempts past+the limit are recorded in `entitlement_limit_overage` under gate+`app_tool_calls`. `off`, and every self-hosted deployment, touches no table;+the per-account per-minute limit applies regardless.++Clients read `GET /api/workspaces/{id}/app-call-usage` (member-readable),+which returns `action` and, while a limit applies, `used`, `limit`,+`period_start` and `reset_at`; `reached` only under `enforce`. Owners and+admins also get `members`: the period's calls per person who started the run+or approved the call (`user_id` null for runs no person started), read from+the `app_tool_call` rows whose `metered_period_start` is the period. The+quota returns the period it counted a call in and the gateway records it, so+the breakdown matches the counter even for a call that finishes after the+month turned. Refused calls, an approved call that fails its checks before+running, Remote MCP calls and every call while the gate is off have none.+## Paid featuresA paid feature is restricted for a workspace whose plan does not include it.diff --git a/server/internal/entitlement/app_tool_calls_gate_test.go b/server/internal/entitlement/app_tool_calls_gate_test.gonew file mode 100644index 0000000000..00cf772e21--- /dev/null+++ b/server/internal/entitlement/app_tool_calls_gate_test.go@@ -0,0 +1,88 @@+package entitlement++import (+ "context"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/google/uuid"+)++func appToolCallsGate(action Action, limit int) wireGate {+ start := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)+ end := start.AddDate(0, 1, 0)+ gate := wireGate{Action: string(action)}+ if action != ActionOff {+ gate.Limit = &limit+ gate.PeriodStart, gate.PeriodEnd, gate.ResetAt = &start, &end, &end+ gate.Notifications = &wireNotificationPolicy{OnRejection: NotificationFirstRejectionPerLimit}+ }+ return gate+}++func TestAppToolCallsGateIsAMonthlyBudget(t *testing.T) {+ for _, action := range []Action{ActionOff, ActionObserve, ActionEnforce} {+ t.Run(string(action), func(t *testing.T) {+ server := httptest.NewServer(policyHandler(func(p *wirePolicy) {+ p.Gates[string(GateAppToolCalls)] = appToolCallsGate(action, 1500)+ }))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)++ decision := client.Gate(context.Background(), uuid.New(), GateAppToolCalls)+ if decision.Gate.Action != action || decision.Reason != ReasonRefreshed {+ t.Fatalf("decision = %+v", decision)+ }+ if action == ActionOff {+ return+ }+ gate := decision.Gate+ if gate.Limit == nil || *gate.Limit != 1500 || gate.PeriodStart == nil || gate.PeriodEnd == nil ||+ gate.ResetAt == nil || gate.Notifications == nil ||+ gate.Notifications.OnRejection != NotificationFirstRejectionPerLimit {+ t.Fatalf("gate = %+v, want limit 1500 with its period and notices", gate)+ }+ })+ }+}++// Cloud and Multica deploy independently. A Cloud that does not send+// app_tool_calls yet, or sends it malformed, leaves the gate off without+// touching the autopilot quota in the same policy.+func TestAppToolCallsGateFailsOpenAlone(t *testing.T) {+ limit := 100+ for _, tt := range []struct {+ name string+ mutate func(*wirePolicy)+ reason Reason+ }{+ {"missing", func(*wirePolicy) {}, ReasonGateMissing},+ {"enforce without limit", func(p *wirePolicy) {+ gate := appToolCallsGate(ActionEnforce, limit)+ gate.Limit = nil+ p.Gates[string(GateAppToolCalls)] = gate+ }, ReasonGateInvalid},+ {"enforce without period", func(p *wirePolicy) {+ p.Gates[string(GateAppToolCalls)] = wireGate{Action: string(ActionEnforce), Limit: &limit}+ }, ReasonGateInvalid},+ {"unknown action", func(p *wirePolicy) {+ p.Gates[string(GateAppToolCalls)] = wireGate{Action: "block"}+ }, ReasonGateInvalid},+ } {+ t.Run(tt.name, func(t *testing.T) {+ server := httptest.NewServer(policyHandler(tt.mutate))+ defer server.Close()+ client := newTestClient(t, server.URL, nil)+ workspaceID := uuid.New()++ calls := client.Gate(context.Background(), workspaceID, GateAppToolCalls)+ if calls.Gate.Action != ActionOff || calls.Reason != tt.reason {+ t.Fatalf("app_tool_calls = %+v, want off/%s", calls, tt.reason)+ }+ if autopilot := client.Gate(context.Background(), workspaceID, GateAutopilotRuns); autopilot.Gate.Action != ActionEnforce {+ t.Fatalf("autopilot = %+v, want the enforced quota from the same policy", autopilot)+ }+ })+ }+}diff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.goindex 95668d72b2..4c005616b3 100644--- a/server/internal/entitlement/client.go+++ b/server/internal/entitlement/client.go@@ -410,7 +410,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {return fetchedPolicy{}, ErrInvalidPolicy}// Unknown gates are ignored for additive compatibility.- gates := make(map[GateName]Gate, 4)+ gates := make(map[GateName]Gate, 5)wireAutopilot, ok := wire.Gates[string(GateAutopilotRuns)]if !ok {return fetchedPolicy{}, ErrInvalidPolicy@@ -425,7 +425,7 @@ func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {// Cloud and Multica can deploy in either order and a bad value cannot turn// the autopilot quota off.gateReasons := make(map[GateName]Reason)- for _, name := range []GateName{GateMembers, GateStorageBytes, GateDashboardHistoryDays} {+ for _, name := range []GateName{GateMembers, GateStorageBytes, GateDashboardHistoryDays, GateAppToolCalls} {if wire.undecodableGates[string(name)] {gates[name] = Gate{Action: ActionOff}gateReasons[name] = ReasonGateInvalid@@ -481,7 +481,8 @@ func normalizeGate(name GateName, wire wireGate) (Gate, error) {if periodFields != 0 && periodFields != 3 {return Gate{}, ErrInvalidPolicy}- if name == GateAutopilotRuns && periodFields != 3 {+ // A budget that resets needs its period.+ if (name == GateAutopilotRuns || name == GateAppToolCalls) && periodFields != 3 {return Gate{}, ErrInvalidPolicy}// A day count: positive, within the product's range, never a period.diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.goindex 3332609f82..fea5e75024 100644--- a/server/internal/entitlement/types.go+++ b/server/internal/entitlement/types.go@@ -22,6 +22,10 @@ const (// GateDashboardHistoryDays caps how many calendar days back the workspace// dashboard can read. Limit is a day count with no period.GateDashboardHistoryDays GateName = "dashboard_history_days"+ // GateAppToolCalls caps the app tool calls a workspace sends to the+ // provider in a period. Like autopilot_runs it is a budget with a+ // Cloud-defined period that resets.+ GateAppToolCalls GateName = "app_tool_calls")// MaxDashboardHistoryDays is the largest dashboard_history_days limit Cloud@@ -30,7 +34,7 @@ const MaxDashboardHistoryDays = 365func (n GateName) valid() bool {switch n {- case GateAutopilotRuns, GateMembers, GateStorageBytes, GateDashboardHistoryDays:+ case GateAutopilotRuns, GateMembers, GateStorageBytes, GateDashboardHistoryDays, GateAppToolCalls:return truedefault:return falsediff --git a/server/internal/handler/app_call_limit.go b/server/internal/handler/app_call_limit.gonew file mode 100644index 0000000000..6cf15f158c--- /dev/null+++ b/server/internal/handler/app_call_limit.go@@ -0,0 +1,86 @@+package handler++import (+ "log/slog"+ "net/http"+ "time"++ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/util"+)++// Monthly app call limit (MUL-10047). The limit itself lives in+// service.AppToolCallQuota and is checked by the Connected Apps gateway right+// before a call reaches Composio; this file serves the Billing read.++func (h *Handler) appToolCallQuota() service.AppToolCallQuota {+ return service.AppToolCallQuota{Queries: h.Queries, Entitlements: h.Entitlements}+}++// AppCallUsageResponse is the monthly app call limit as clients render it.+// action is off when no limit applies, including self-hosted deployments.+// While a limit applies used, limit, period_start and reset_at are present;+// reached only under enforce. members is the period's calls per person, for+// owners and admins only; a null user_id is runs no person started.+type AppCallUsageResponse struct {+ Action string `json:"action"`+ Used *int64 `json:"used,omitempty"`+ Limit *int64 `json:"limit,omitempty"`+ Reached *bool `json:"reached,omitempty"`+ PeriodStart *string `json:"period_start,omitempty"`+ ResetAt *string `json:"reset_at,omitempty"`+ Members []AppCallMemberUsageEntry `json:"members,omitempty"`+}++type AppCallMemberUsageEntry struct {+ UserID *string `json:"user_id"`+ Calls int64 `json:"calls"`+}++// GetAppCallUsage — GET /api/workspaces/{id}/app-call-usage+//+// Member-readable: an agent's refusal names the limit, and members read why.+// The per-person breakdown is for owners and admins.+func (h *Handler) GetAppCallUsage(w http.ResponseWriter, r *http.Request) {+ wsID := workspaceIDFromURL(r, "id")+ member, ok := h.requireWorkspaceMember(w, r, wsID, "workspace not found")+ if !ok {+ return+ }+ workspaceID, ok := parseUUIDOrBadRequest(w, wsID, "workspace id")+ if !ok {+ return+ }+ quota := h.appToolCallQuota()+ usage, err := quota.Usage(r.Context(), workspaceID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load app call usage")+ return+ }+ resp := AppCallUsageResponse{Action: string(usage.Action), Used: usage.Used, Limit: usage.Limit, Reached: usage.Reached}+ if usage.PeriodStart != nil {+ v := usage.PeriodStart.UTC().Format(time.RFC3339)+ resp.PeriodStart = &v+ }+ if usage.ResetAt != nil {+ v := usage.ResetAt.UTC().Format(time.RFC3339)+ resp.ResetAt = &v+ }+ if usage.PeriodStart != nil && (member.Role == "owner" || member.Role == "admin") {+ members, err := quota.MemberUsage(r.Context(), workspaceID, *usage.PeriodStart)+ if err != nil {+ // The breakdown is secondary; the total still renders.+ slog.WarnContext(r.Context(), "app call usage by member failed", "workspace_id", wsID, "error", err)+ }+ resp.Members = make([]AppCallMemberUsageEntry, 0, len(members))+ for _, m := range members {+ entry := AppCallMemberUsageEntry{Calls: m.Calls}+ if m.UserID.Valid {+ id := util.UUIDToString(m.UserID)+ entry.UserID = &id+ }+ resp.Members = append(resp.Members, entry)+ }+ }+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/connected_apps_quota_test.go b/server/internal/handler/connected_apps_quota_test.gonew file mode 100644index 0000000000..e29930db75--- /dev/null+++ b/server/internal/handler/connected_apps_quota_test.go@@ -0,0 +1,159 @@+package handler++import (+ "context"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/google/uuid"++ "github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+)++// newAppsQuotaFixture meters the fixture's gateway with the real app call+// quota under an enforced limit.+func newAppsQuotaFixture(t *testing.T, limit int) (*appsFixture, *entitlementtest.Stub) {+ t.Helper()+ if testHandler == nil {+ t.Skip("database not available")+ }+ stub := entitlementtest.New()+ start := time.Now().UTC().Truncate(time.Second)+ end := start.AddDate(0, 1, 0)+ stub.Set(uuid.MustParse(testWorkspaceID), entitlement.GateAppToolCalls, entitlement.Decision{Gate: entitlement.Gate{+ Action: entitlement.ActionEnforce, Limit: &limit, PeriodStart: &start, PeriodEnd: &end, ResetAt: &end,+ Notifications: &entitlement.NotificationPolicy{OnRejection: entitlement.NotificationFirstRejectionPerLimit},+ }})+ f := newAppsFixture(t, func(cfg *connectedapps.Config) {+ cfg.CallQuota = service.AppToolCallQuota{Queries: testHandler.Queries, Entitlements: stub, TxStarter: testPool}+ })+ f.h.Entitlements = stub+ t.Cleanup(func() {+ ctx := context.Background()+ testPool.Exec(ctx, `DELETE FROM app_tool_call_quota_period WHERE workspace_id = $1`, testWorkspaceID)+ testPool.Exec(ctx, `DELETE FROM entitlement_limit_overage WHERE workspace_id = $1 AND gate = 'app_tool_calls'`, testWorkspaceID)+ })+ return f, stub+}++func (f *appsFixture) callOutcomes(t *testing.T) []string {+ t.Helper()+ rows, err := testPool.Query(context.Background(),+ `SELECT outcome FROM app_tool_call WHERE workspace_id = $1 AND task_id = $2 ORDER BY created_at`, testWorkspaceID, f.taskID)+ if err != nil {+ t.Fatalf("list calls: %v", err)+ }+ defer rows.Close()+ var out []string+ for rows.Next() {+ var outcome string+ rows.Scan(&outcome)+ out = append(out, outcome)+ }+ return out+}++// A call past the monthly limit never reaches Composio; the agent is told+// why, the call is logged as quota_exceeded, and meta tools stay free.+func TestConnectedApps_MonthlyQuotaRefusesGatewayCalls(t *testing.T) {+ f, _ := newAppsQuotaFixture(t, 1)+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "write"}})+ run := map[string]any{"tool": "GMAIL_FETCH_EMAILS", "arguments": map[string]any{}}++ if _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", run); isErr {+ t.Fatalf("call within the limit = %s", text)+ }+ for _, meta := range []string{"apps_list", "apps_search_tools", "apps_get_tool"} {+ f.gateway(t, f.token(t), meta, map[string]any{"app": "gmail", "tool": "GMAIL_FETCH_EMAILS"})+ }+ _, text, isErr := f.gateway(t, f.token(t), "apps_run_tool", run)+ if !isErr || !strings.HasPrefix(text, "app call limit reached") || !strings.Contains(text, "used 1 of its 1") {+ t.Fatalf("call past the limit = %s (error %v)", text, isErr)+ }+ if n := len(f.sdk.executions()); n != 1 {+ t.Fatalf("executions = %d, want only the call within the limit", n)+ }+ if got := f.callOutcomes(t); len(got) != 2 || got[0] != "ok" || got[1] != "quota_exceeded" {+ t.Fatalf("call log = %v, want [ok quota_exceeded]", got)+ }+ // The executed call carries the period the counter charged; the refused+ // one none.+ var counted, uncounted int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*) FILTER (WHERE p.period_start IS NOT NULL), count(*) FILTER (WHERE c.metered_period_start IS NULL)+ FROM app_tool_call c+ LEFT JOIN app_tool_call_quota_period p ON p.workspace_id = c.workspace_id AND p.period_start = c.metered_period_start+ WHERE c.task_id = $1`, f.taskID).Scan(&counted, &uncounted); err != nil || counted != 1 || uncounted != 1 {+ t.Fatalf("metered periods: %d counted, %d uncounted (err %v); want 1 and 1", counted, uncounted, err)+ }+ if n := f.inboxCount(t, testUserID, service.AppToolCallQuotaNoticeType); n != 1 {+ t.Fatalf("owner notices = %d, want 1", n)+ }+}++// A confirmed call approved after the workspace ran out fails the request+// instead of running it.+func TestConnectedApps_MonthlyQuotaRefusesApprovedCalls(t *testing.T) {+ f, _ := newAppsQuotaFixture(t, 0)+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "confirm_writes"}})+ request := f.legacyRequest(t, "personal", "gmail", "GMAIL_SEND_EMAIL", "send", map[string]any{"to": "x"}, "")++ out := f.approve(t, request.ID, nil)+ if out.Status != "failed" || out.Error == nil || !strings.HasPrefix(*out.Error, "app call limit reached") {+ t.Fatalf("approved over the limit = %+v", out)+ }+ if n := len(f.sdk.executions()); n != 0 {+ t.Fatalf("executions = %d, want none", n)+ }+ if got := f.callOutcomes(t); len(got) != 1 || got[0] != "quota_exceeded" {+ t.Fatalf("call log = %v, want [quota_exceeded]", got)+ }+}++// Billing reads the period's count and, for owners and admins, who made it.+// An approved call that fails its checks before running never reached+// Composio, so it is not in the breakdown either.+func TestGetAppCallUsage(t *testing.T) {+ f, _ := newAppsQuotaFixture(t, 5)+ f.putAgentApps(t, testUserID, []map[string]string{{"toolkit_slug": "gmail", "account_scope": "personal", "level": "write"}})+ f.gateway(t, f.token(t), "apps_run_tool", map[string]any{"tool": "GMAIL_FETCH_EMAILS", "arguments": map[string]any{}})+ request := f.legacyRequest(t, "personal", "gmail", "GMAIL_SEND_EMAIL", "send", map[string]any{"to": "x"}, "")+ testPool.Exec(context.Background(), `DELETE FROM user_composio_connection WHERE user_id = $1 AND toolkit_slug = 'gmail'`, testUserID)+ if out := f.approve(t, request.ID, nil); out.Status != "failed" {+ t.Fatalf("approved call without an account = %+v, want failed", out)+ }+ if got := f.callOutcomes(t); len(got) != 2 || got[1] != "error" {+ t.Fatalf("call log = %v, want the run and the failed approval", got)+ }++ path := "/api/workspaces/" + testWorkspaceID + "/app-call-usage"+ var owner AppCallUsageResponse+ testutil.Call(t, f.h.GetAppCallUsage, withURLParam(newRequestAs(testUserID, http.MethodGet, path, nil), "id", testWorkspaceID)).+ Want(http.StatusOK).JSON(&owner)+ if owner.Action != "enforce" || owner.Used == nil || *owner.Used != 1 || owner.Limit == nil || *owner.Limit != 5 ||+ owner.Reached == nil || *owner.Reached || owner.ResetAt == nil ||+ len(owner.Members) != 1 || owner.Members[0].UserID == nil || *owner.Members[0].UserID != testUserID || owner.Members[0].Calls != 1 {+ t.Fatalf("owner usage = %+v", owner)+ }++ var member AppCallUsageResponse+ testutil.Call(t, f.h.GetAppCallUsage, withURLParam(newRequestAs(f.member, http.MethodGet, path, nil), "id", testWorkspaceID)).+ Want(http.StatusOK).JSON(&member)+ if member.Used == nil || *member.Used != 1 || member.Members != nil {+ t.Fatalf("member usage = %+v, want the total without the breakdown", member)+ }++ f.h.Entitlements = nil+ var off AppCallUsageResponse+ testutil.Call(t, f.h.GetAppCallUsage, withURLParam(newRequestAs(testUserID, http.MethodGet, path, nil), "id", testWorkspaceID)).+ Want(http.StatusOK).JSON(&off)+ if off.Action != "off" || off.Used != nil || off.Limit != nil {+ t.Fatalf("self-hosted usage = %+v", off)+ }+}diff --git a/server/internal/handler/connected_apps_test.go b/server/internal/handler/connected_apps_test.goindex 7763b1032e..0c1d8aa26d 100644--- a/server/internal/handler/connected_apps_test.go+++ b/server/internal/handler/connected_apps_test.go@@ -100,7 +100,7 @@ type appsFixture struct {member string}-func newAppsFixture(t *testing.T) *appsFixture {+func newAppsFixture(t *testing.T, opts ...func(*connectedapps.Config)) *appsFixture {t.Helper()if testHandler == nil {t.Skip("database not available")@@ -116,13 +116,17 @@ func newAppsFixture(t *testing.T) *appsFixture {}h := *testHandlerh.Composio = svc- apps, err := connectedapps.New(connectedapps.Config{+ cfg := connectedapps.Config{Queries: h.Queries,TxStarter: testPool,Composio: svc,TokenSecret: connectedapps.DeriveTokenSecret([]byte("apps-test-secret")),PublicBaseURL: "https://api.multica.test",- })+ }+ for _, opt := range opts {+ opt(&cfg)+ }+ apps, err := connectedapps.New(cfg)if err != nil {t.Fatalf("connectedapps.New: %v", err)}diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex ca0df4df36..2ce6412eda 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -1515,6 +1515,10 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {name: "delete autopilot quota periods",run: func() error { return qtx.DeleteWorkspaceAutopilotQuotaPeriods(ctx, requester.WorkspaceID) },},+ {+ name: "delete app tool call quota periods",+ run: func() error { return qtx.DeleteWorkspaceAppToolCallQuotaPeriods(ctx, requester.WorkspaceID) },+ },{name: "delete entitlement limit overages",run: func() error { return qtx.DeleteWorkspaceEntitlementLimitOverages(ctx, requester.WorkspaceID) },diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 0de1849ef8..6e71213949 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -180,6 +180,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"app_action_rule": workspaceDelete,"app_action_request": workspaceDelete,"app_tool_call": workspaceDelete,+ "app_tool_call_quota_period": workspaceDelete,"issue_environment": workspaceDelete,"issue_environment_command": workspaceDelete,"issue_environment_config": workspaceDelete,diff --git a/server/internal/inbox/registry.go b/server/internal/inbox/registry.goindex c19de484bf..44e9e68ccc 100644--- a/server/internal/inbox/registry.go+++ b/server/internal/inbox/registry.go@@ -55,9 +55,11 @@ var typeGroups = map[string]string{"quick_create_unconfirmed": "","autopilot_paused": "","autopilot_quota_exceeded": "",- "children_done": "",- "blockers_done": "",- "project_owner_joined": "",+ // The workspace used its monthly app calls (MUL-10047); owners and admins.+ "app_tool_calls_quota_exceeded": "",+ "children_done": "",+ "blockers_done": "",+ "project_owner_joined": "",// The agent is stopped until the person answers these."app_action_requested": "","app_action_reminder": "",diff --git a/server/internal/service/app_tool_call_quota.go b/server/internal/service/app_tool_call_quota.gonew file mode 100644index 0000000000..aa29dacbd8--- /dev/null+++ b/server/internal/service/app_tool_call_quota.go@@ -0,0 +1,361 @@+package service++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "strconv"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/inbox"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid"+)++// Monthly app tool call limit (MUL-10047).+//+// Cloud sends the calls a workspace may send to the app provider in a period+// through the "app_tool_calls" gate. Every call the gateway is about to send+// to Composio is counted in app_tool_call_quota_period with one conditional+// upsert, before it runs, so a call that then fails upstream still counts, as+// the provider bills it. Under enforce the increment only happens below the+// limit, so concurrent calls never take a workspace past it. off, which is+// also the self-hosted behavior, touches no table.++// AppToolCallQuotaNoticeType is the Inbox type of the limit notice.+const AppToolCallQuotaNoticeType = "app_tool_calls_quota_exceeded"++// AppToolCallQuota checks the app_tool_calls gate. A zero value with no+// Entitlements admits every call without reading the database.+type AppToolCallQuota struct {+ Queries *db.Queries+ Entitlements entitlement.Provider+ // TxStarter writes the limit notice; without it no notice is sent.+ TxStarter TxStarter+ Bus *events.Bus+ now func() time.Time+}++var _ connectedapps.CallQuota = AppToolCallQuota{}++type appToolCallPolicy struct {+ action entitlement.Action+ limit int64+ periodStart time.Time+ periodEnd time.Time+ resetAt time.Time+ notifications *entitlement.NotificationPolicy+}++func appToolCallPolicyFrom(decision entitlement.Decision) (appToolCallPolicy, bool) {+ gate := decision.Gate+ if (gate.Action != entitlement.ActionObserve && gate.Action != entitlement.ActionEnforce) ||+ gate.Limit == nil || *gate.Limit < 0 || gate.PeriodStart == nil || gate.PeriodEnd == nil ||+ gate.ResetAt == nil || !gate.PeriodStart.Before(*gate.PeriodEnd) {+ return appToolCallPolicy{}, false+ }+ return appToolCallPolicy{+ action: gate.Action,+ limit: int64(*gate.Limit),+ periodStart: gate.PeriodStart.UTC(),+ periodEnd: gate.PeriodEnd.UTC(),+ resetAt: gate.ResetAt.UTC(),+ notifications: gate.Notifications,+ }, true+}++// sameBudget reports whether two policies count the same calls against the+// same limit, so re-counting under the other would decide the same way.+func (p appToolCallPolicy) sameBudget(other appToolCallPolicy) bool {+ return p.action == other.action && p.limit == other.limit &&+ p.periodStart.Equal(other.periodStart) && p.periodEnd.Equal(other.periodEnd)+}++// policy is the workspace's current app call policy. One cached before its+// period ended (the first minute of a month) is re-read, so neither a call+// nor Billing lands on the month that is over; if Cloud still sends the old+// period, no limit applies for now.+func (q AppToolCallQuota) policy(ctx context.Context, workspaceID pgtype.UUID) (appToolCallPolicy, bool) {+ if q.Entitlements == nil || q.Queries == nil || !workspaceID.Valid {+ return appToolCallPolicy{}, false+ }+ policy, ok := appToolCallPolicyFrom(q.Entitlements.Gate(ctx, uuid.UUID(workspaceID.Bytes), entitlement.GateAppToolCalls))+ if ok && !q.clock().Before(policy.periodEnd) {+ if policy, ok = q.refreshedPolicy(ctx, workspaceID); ok && !q.clock().Before(policy.periodEnd) {+ return appToolCallPolicy{}, false+ }+ }+ return policy, ok+}++// refreshedPolicy reads Cloud's current policy, skipping the reuse window+// where the provider has one, as the autopilot quota does before a refusal:+// a seat bought or a month started moments ago must not be judged on a policy+// fetched just before.+func (q AppToolCallQuota) refreshedPolicy(ctx context.Context, workspaceID pgtype.UUID) (appToolCallPolicy, bool) {+ workspace := uuid.UUID(workspaceID.Bytes)+ var decision entitlement.Decision+ switch provider := q.Entitlements.(type) {+ case entitlement.FreshRefresher:+ decision = provider.RefreshGateNow(ctx, workspace, entitlement.GateAppToolCalls)+ case entitlement.Refresher:+ decision = provider.RefreshGate(ctx, workspace, entitlement.GateAppToolCalls)+ default:+ decision = q.Entitlements.Gate(ctx, workspace, entitlement.GateAppToolCalls)+ }+ return appToolCallPolicyFrom(decision)+}++func (q AppToolCallQuota) clock() time.Time {+ if q.now != nil {+ return q.now()+ }+ return time.Now()+}++// Admit counts one call that is about to be sent to the provider and returns+// the start of the period it was counted in; zero when it was not counted.+// Under enforce it refuses a call past the limit, after re-reading Cloud's+// policy so a workspace that has just upgraded or added seats is not refused+// on a cached one. Under observe it admits and records the overage. Every+// failure to decide admits without counting.+func (q AppToolCallQuota) Admit(ctx context.Context, workspaceID pgtype.UUID) (time.Time, *connectedapps.CallQuotaExceeded) {+ policy, ok := q.policy(ctx, workspaceID)+ if !ok {+ return time.Time{}, nil+ }+ used, admitted, err := q.increment(ctx, workspaceID, policy)+ if err != nil {+ return time.Time{}, nil+ }+ if !admitted {+ fresh, active := q.refreshedPolicy(ctx, workspaceID)+ if !active {+ return time.Time{}, nil+ }+ if !fresh.sameBudget(policy) {+ policy = fresh+ if used, admitted, err = q.increment(ctx, workspaceID, policy); err != nil {+ return time.Time{}, nil+ }+ }+ }+ if admitted {+ if used > policy.limit {+ q.recordOverage(ctx, workspaceID, policy, used)+ } else {+ EntitlementOverages{Queries: q.Queries}.SyncLimit(+ ctx, workspaceID, entitlement.GateAppToolCalls, policy.periodStart, policy.periodEnd, policy.limit,+ )+ }+ return policy.periodStart, nil+ }+ used = q.used(ctx, workspaceID, policy)+ q.recordOverage(ctx, workspaceID, policy, used+1)+ q.deliverRejectionNotice(ctx, workspaceID, policy, used)+ return time.Time{}, &connectedapps.CallQuotaExceeded{Used: used, Limit: policy.limit, ResetAt: policy.resetAt}+}++// increment counts the call. admitted=false is a refusal under enforce; an+// error admits.+func (q AppToolCallQuota) increment(ctx context.Context, workspaceID pgtype.UUID, policy appToolCallPolicy) (int64, bool, error) {+ used, err := q.Queries.IncrementAppToolCallQuota(ctx, db.IncrementAppToolCallQuotaParams{+ WorkspaceID: workspaceID,+ PeriodStart: pgtype.Timestamptz{Time: policy.periodStart, Valid: true},+ PeriodEnd: pgtype.Timestamptz{Time: policy.periodEnd, Valid: true},+ Enforce: policy.action == entitlement.ActionEnforce,+ LimitValue: policy.limit,+ })+ if errors.Is(err, pgx.ErrNoRows) {+ return 0, false, nil+ }+ if err != nil {+ slog.WarnContext(ctx, "app tool call quota increment failed; admitting",+ "workspace_id", util.UUIDToString(workspaceID), "error", err)+ return 0, false, err+ }+ return used, true, nil+}++// used is the period's count, for a refusal's message. It falls back to the+// limit, which a refused workspace has reached.+func (q AppToolCallQuota) used(ctx context.Context, workspaceID pgtype.UUID, policy appToolCallPolicy) int64 {+ used, err := q.Queries.GetAppToolCallQuotaUsed(ctx, db.GetAppToolCallQuotaUsedParams{+ WorkspaceID: workspaceID,+ PeriodStart: pgtype.Timestamptz{Time: policy.periodStart, Valid: true},+ PeriodEnd: pgtype.Timestamptz{Time: policy.periodEnd, Valid: true},+ })+ if err != nil {+ return policy.limit+ }+ return used+}++func (q AppToolCallQuota) recordOverage(ctx context.Context, workspaceID pgtype.UUID, policy appToolCallPolicy, attempted int64) {+ EntitlementOverages{Queries: q.Queries}.Record(ctx, LimitExceededAttempt{+ WorkspaceID: workspaceID,+ Gate: entitlement.GateAppToolCalls,+ Action: policy.action,+ PeriodStart: policy.periodStart,+ PeriodEnd: policy.periodEnd,+ Limit: policy.limit,+ AttemptedUsage: attempted,+ })+}++// deliverRejectionNotice tells the workspace's owners and admins, once per+// period or once per limit as Cloud asks, that calls are being refused. It+// is best-effort: a failure is logged and never changes the refusal.+func (q AppToolCallQuota) deliverRejectionNotice(ctx context.Context, workspaceID pgtype.UUID, policy appToolCallPolicy, used int64) {+ if q.TxStarter == nil || policy.notifications == nil {+ return+ }+ mode := policy.notifications.OnRejection+ if mode != entitlement.NotificationFirstRejectionPerPeriod && mode != entitlement.NotificationFirstRejectionPerLimit {+ return+ }+ if err := q.createRejectionNotice(ctx, workspaceID, policy, used, mode == entitlement.NotificationFirstRejectionPerLimit); err != nil {+ slog.WarnContext(ctx, "app tool call quota notice delivery failed; the refusal stands",+ "workspace_id", util.UUIDToString(workspaceID), "error", err)+ }+}++func (q AppToolCallQuota) createRejectionNotice(ctx context.Context, workspaceID pgtype.UUID, policy appToolCallPolicy, used int64, perLimit bool) error {+ tx, err := q.TxStarter.Begin(ctx)+ if err != nil {+ return fmt.Errorf("begin app tool call quota notice: %w", err)+ }+ defer tx.Rollback(ctx)+ qtx := q.Queries.WithTx(tx)+ if _, err := qtx.ClaimAppToolCallQuotaRejectionNotice(ctx, db.ClaimAppToolCallQuotaRejectionNoticeParams{+ WorkspaceID: workspaceID,+ PeriodStart: pgtype.Timestamptz{Time: policy.periodStart, Valid: true},+ PeriodEnd: pgtype.Timestamptz{Time: policy.periodEnd, Valid: true},+ LimitValue: policy.limit,+ PerLimit: perLimit,+ }); errors.Is(err, pgx.ErrNoRows) {+ return nil // already notified at this limit+ } else if err != nil {+ return fmt.Errorf("claim app tool call quota notice: %w", err)+ }+ recipients, err := ListWorkspaceManagerNotificationRecipients(ctx, qtx, workspaceID)+ if err != nil {+ return fmt.Errorf("list app tool call quota notice recipients: %w", err)+ }+ resetAt := policy.resetAt.UTC().Format("January 2, 2006 at 15:04 UTC")+ body := fmt.Sprintf(+ "This workspace has used its %d app calls for the current period. Agents cannot run app tools until the allowance resets at %s, or until the workspace upgrades its plan or adds seats.",+ policy.limit, resetAt,+ )+ details, err := json.Marshal(map[string]string{+ "used": strconv.FormatInt(used, 10),+ "limit": strconv.FormatInt(policy.limit, 10),+ "reset_at": policy.resetAt.UTC().Format(time.RFC3339),+ })+ if err != nil {+ return fmt.Errorf("marshal app tool call quota notice details: %w", err)+ }+ var pending inbox.Deferred+ delivered := 0+ for _, recipient := range recipients {+ _, inserted, err := inbox.Deliver(ctx, qtx, &pending, inbox.Notification{Params: db.CreateInboxItemParams{+ ID: dbid.NewV7(), WorkspaceID: workspaceID,+ RecipientType: recipient.Type, RecipientID: recipient.ID,+ Type: AppToolCallQuotaNoticeType, Severity: "attention", IssueID: pgtype.UUID{},+ Title: "App call limit reached", Body: pgtype.Text{String: body, Valid: true},+ ActorType: pgtype.Text{String: "system", Valid: true}, ActorID: pgtype.UUID{},+ Details: details,+ }})+ if err != nil {+ return fmt.Errorf("create app tool call quota inbox item: %w", err)+ }+ if inserted {+ delivered+++ }+ }+ if delivered == 0 {+ // Roll the claim back so a later refusal can reach a manager added since.+ return nil+ }+ if err := tx.Commit(ctx); err != nil {+ return fmt.Errorf("commit app tool call quota notice: %w", err)+ }+ if q.Bus != nil {+ pending.Flush(q.Bus)+ }+ return nil+}++// AppToolCallUsage is the monthly app call limit as clients render it. Limit+// and the period are set only while a limit applies; Reached only under+// enforce, because observe never refuses a call.+type AppToolCallUsage struct {+ Action entitlement.Action+ Used *int64+ Limit *int64+ Reached *bool+ PeriodStart *time.Time+ PeriodEnd *time.Time+ ResetAt *time.Time+}++// Usage reports the workspace's app call limit and this period's count.+func (q AppToolCallQuota) Usage(ctx context.Context, workspaceID pgtype.UUID) (AppToolCallUsage, error) {+ policy, ok := q.policy(ctx, workspaceID)+ if !ok {+ return AppToolCallUsage{Action: entitlement.ActionOff}, nil+ }+ used, err := q.Queries.GetAppToolCallQuotaUsed(ctx, db.GetAppToolCallQuotaUsedParams{+ WorkspaceID: workspaceID,+ PeriodStart: pgtype.Timestamptz{Time: policy.periodStart, Valid: true},+ PeriodEnd: pgtype.Timestamptz{Time: policy.periodEnd, Valid: true},+ })+ if errors.Is(err, pgx.ErrNoRows) {+ used = 0+ } else if err != nil {+ return AppToolCallUsage{}, fmt.Errorf("load app tool call usage: %w", err)+ }+ out := AppToolCallUsage{+ Action: policy.action, Used: &used, Limit: &policy.limit,+ PeriodStart: &policy.periodStart, PeriodEnd: &policy.periodEnd, ResetAt: &policy.resetAt,+ }+ if policy.action == entitlement.ActionEnforce {+ reached := used >= policy.limit+ out.Reached = &reached+ }+ return out, nil+}++// AppToolCallMemberUsage is one person's calls in the period: who started the+// run or approved the call. A zero UserID is runs no person started.+type AppToolCallMemberUsage struct {+ UserID pgtype.UUID+ Calls int64+}++// MemberUsage breaks the period's counted calls down by person, from the+// call log rows Admit counted in the period.+func (q AppToolCallQuota) MemberUsage(ctx context.Context, workspaceID pgtype.UUID, periodStart time.Time) ([]AppToolCallMemberUsage, error) {+ rows, err := q.Queries.ListAppToolCallUsageByMember(ctx, db.ListAppToolCallUsageByMemberParams{+ WorkspaceID: workspaceID,+ MeteredPeriodStart: pgtype.Timestamptz{Time: periodStart.UTC(), Valid: true},+ })+ if err != nil {+ return nil, fmt.Errorf("list app tool call usage by member: %w", err)+ }+ out := make([]AppToolCallMemberUsage, 0, len(rows))+ for _, row := range rows {+ out = append(out, AppToolCallMemberUsage{UserID: row.TriggeredBy, Calls: row.Calls})+ }+ return out, nil+}diff --git a/server/internal/service/app_tool_call_quota_test.go b/server/internal/service/app_tool_call_quota_test.gonew file mode 100644index 0000000000..f42455e13a--- /dev/null+++ b/server/internal/service/app_tool_call_quota_test.go@@ -0,0 +1,429 @@+package service++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"++ "github.com/multica-ai/multica/server/internal/connectedapps"+ "github.com/multica-ai/multica/server/internal/entitlement"+ "github.com/multica-ai/multica/server/internal/entitlement/entitlementtest"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type appToolCallQuotaFixture struct {+ pool *pgxpool.Pool+ quota AppToolCallQuota+ stub *entitlementtest.Stub+ workspace uuid.UUID+ workspaceID pgtype.UUID+ ownerID pgtype.UUID+ periodStart time.Time+ periodEnd time.Time+}++func newAppToolCallQuotaFixture(t *testing.T) *appToolCallQuotaFixture {+ t.Helper()+ pool := newResolveOriginatorPool(t)+ workspaceIDString, ownerID, _, _ := seedAttributionFixture(t, pool)+ workspaceID := util.MustParseUUID(workspaceIDString)+ start := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)+ stub := entitlementtest.New()+ f := &appToolCallQuotaFixture{+ pool: pool, stub: stub,+ workspace: uuid.UUID(workspaceID.Bytes), workspaceID: workspaceID, ownerID: util.MustParseUUID(ownerID),+ periodStart: start, periodEnd: start.AddDate(0, 1, 0),+ quota: AppToolCallQuota{+ Queries: db.New(pool), Entitlements: stub, TxStarter: pool, Bus: events.New(),+ now: func() time.Time { return start.Add(12 * time.Hour) },+ },+ }+ t.Cleanup(func() {+ ctx := context.Background()+ pool.Exec(ctx, `DELETE FROM app_tool_call_quota_period WHERE workspace_id = $1`, workspaceID)+ pool.Exec(ctx, `DELETE FROM entitlement_limit_overage WHERE workspace_id = $1`, workspaceID)+ pool.Exec(ctx, `DELETE FROM inbox_item WHERE workspace_id = $1`, workspaceID)+ })+ return f+}++func (f *appToolCallQuotaFixture) decision(action entitlement.Action, limit int, start time.Time) entitlement.Decision {+ end := start.AddDate(0, 1, 0)+ gate := entitlement.Gate{Action: action}+ if action != entitlement.ActionOff {+ gate.Limit = &limit+ gate.PeriodStart, gate.PeriodEnd, gate.ResetAt = &start, &end, &end+ }+ if action == entitlement.ActionEnforce {+ gate.Notifications = &entitlement.NotificationPolicy{OnRejection: entitlement.NotificationFirstRejectionPerLimit}+ }+ return entitlement.Decision{Gate: gate}+}++func (f *appToolCallQuotaFixture) setPolicy(action entitlement.Action, limit int) {+ f.stub.Set(f.workspace, entitlement.GateAppToolCalls, f.decision(action, limit, f.periodStart))+}++// admit is Admit's refusal; the period a call was counted in is checked where+// it matters.+func (f *appToolCallQuotaFixture) admit(ctx context.Context) *connectedapps.CallQuotaExceeded {+ _, refused := f.quota.Admit(ctx, f.workspaceID)+ return refused+}++func (f *appToolCallQuotaFixture) used(t *testing.T) int64 {+ t.Helper()+ return f.usedIn(t, f.periodStart)+}++func (f *appToolCallQuotaFixture) usedIn(t *testing.T, periodStart time.Time) int64 {+ t.Helper()+ var used int64+ err := f.pool.QueryRow(context.Background(),+ `SELECT COALESCE(SUM(used_count), 0) FROM app_tool_call_quota_period WHERE workspace_id = $1 AND period_start = $2`,+ f.workspaceID, periodStart).Scan(&used)+ if err != nil {+ t.Fatalf("read used: %v", err)+ }+ return used+}++func (f *appToolCallQuotaFixture) overage(t *testing.T) (peak, observed, enforced int64) {+ t.Helper()+ err := f.pool.QueryRow(context.Background(), `+ SELECT peak_usage, observed_count, enforced_count FROM entitlement_limit_overage+ WHERE workspace_id = $1 AND gate = 'app_tool_calls'`, f.workspaceID).Scan(&peak, &observed, &enforced)+ if err != nil {+ t.Fatalf("read overage: %v", err)+ }+ return peak, observed, enforced+}++func (f *appToolCallQuotaFixture) notices(t *testing.T, recipient pgtype.UUID) int {+ t.Helper()+ var n int+ err := f.pool.QueryRow(context.Background(), `+ SELECT count(*) FROM inbox_item+ WHERE workspace_id = $1 AND recipient_id = $2 AND type = $3`,+ f.workspaceID, recipient, AppToolCallQuotaNoticeType).Scan(&n)+ if err != nil {+ t.Fatalf("count notices: %v", err)+ }+ return n+}++// Without Cloud, or with the gate off, every call runs and nothing is written.+func TestAppToolCallQuotaOffTouchesNothing(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ ctx := context.Background()+ if countedIn, got := (AppToolCallQuota{Queries: f.quota.Queries}).Admit(ctx, f.workspaceID); got != nil || !countedIn.IsZero() {+ t.Fatalf("no entitlements: admit = %v, %+v", countedIn, got)+ }+ f.setPolicy(entitlement.ActionOff, 0)+ for range 3 {+ if got := f.admit(ctx); got != nil {+ t.Fatalf("off: admit = %+v", got)+ }+ }+ var rows int+ if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM app_tool_call_quota_period WHERE workspace_id = $1`, f.workspaceID).Scan(&rows); err != nil || rows != 0 {+ t.Fatalf("off wrote %d quota rows (err %v), want none", rows, err)+ }+ usage, err := f.quota.Usage(ctx, f.workspaceID)+ if err != nil || usage.Action != entitlement.ActionOff || usage.Used != nil {+ t.Fatalf("off usage = %+v, err = %v", usage, err)+ }+}++// Concurrent calls at the boundary never take the workspace past its limit;+// each refused call is recorded, and owners and admins hear once.+func TestAppToolCallQuotaEnforceNeverExceedsLimit(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ f.setPolicy(entitlement.ActionEnforce, 5)+ adminID := addAppToolCallQuotaMember(t, f, "admin")+ memberID := addAppToolCallQuotaMember(t, f, "member")+ ctx := context.Background()++ const calls = 20+ var wg sync.WaitGroup+ var mu sync.Mutex+ var refused []*connectedapps.CallQuotaExceeded+ for range calls {+ wg.Add(1)+ go func() {+ defer wg.Done()+ if got := f.admit(ctx); got != nil {+ mu.Lock()+ refused = append(refused, got)+ mu.Unlock()+ }+ }()+ }+ wg.Wait()++ if len(refused) != calls-5 || f.used(t) != 5 {+ t.Fatalf("refused %d, used %d; want %d refused and 5 used", len(refused), f.used(t), calls-5)+ }+ if got := refused[0]; got.Used != 5 || got.Limit != 5 || !got.ResetAt.Equal(f.periodEnd) {+ t.Fatalf("refusal = %+v, want used 5 / limit 5 / reset at %s", got, f.periodEnd)+ }+ if peak, observed, enforced := f.overage(t); peak != 6 || observed != 0 || enforced != calls-5 {+ t.Fatalf("overage peak %d observed %d enforced %d", peak, observed, enforced)+ }+ if f.notices(t, f.ownerID) != 1 || f.notices(t, adminID) != 1 || f.notices(t, memberID) != 0 {+ t.Fatalf("notices: owner %d admin %d member %d; want 1, 1, 0",+ f.notices(t, f.ownerID), f.notices(t, adminID), f.notices(t, memberID))+ }+ usage, err := f.quota.Usage(ctx, f.workspaceID)+ if err != nil || usage.Used == nil || *usage.Used != 5 || usage.Reached == nil || !*usage.Reached {+ t.Fatalf("usage = %+v, err = %v", usage, err)+ }+}++// Observe runs every call, counts it, and records how far over it went.+func TestAppToolCallQuotaObserveCountsPastLimit(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ f.setPolicy(entitlement.ActionObserve, 2)+ ctx := context.Background()+ for i := range 4 {+ countedIn, got := f.quota.Admit(ctx, f.workspaceID)+ if got != nil || !countedIn.Equal(f.periodStart) {+ t.Fatalf("observe call %d = counted in %v, refused %+v; want counted in %v", i, countedIn, got, f.periodStart)+ }+ }+ if f.used(t) != 4 {+ t.Fatalf("used = %d, want 4", f.used(t))+ }+ if peak, observed, enforced := f.overage(t); peak != 4 || observed != 2 || enforced != 0 {+ t.Fatalf("overage peak %d observed %d enforced %d; want 4, 2, 0", peak, observed, enforced)+ }+ if f.notices(t, f.ownerID) != 0 {+ t.Fatal("observe sent a notice")+ }+ usage, err := f.quota.Usage(ctx, f.workspaceID)+ if err != nil || usage.Action != entitlement.ActionObserve || *usage.Used != 4 || usage.Reached != nil {+ t.Fatalf("observe usage = %+v, err = %v", usage, err)+ }+}++// A workspace that upgraded or added seats moments ago is not refused on the+// cached policy, and reaching the new limit notifies again.+func TestAppToolCallQuotaRefreshesBeforeRefusing(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ f.setPolicy(entitlement.ActionEnforce, 1)+ ctx := context.Background()+ if got := f.admit(ctx); got != nil {+ t.Fatalf("first call refused: %+v", got)+ }+ if got := f.admit(ctx); got == nil {+ t.Fatal("second call admitted past limit 1")+ }+ f.stub.SetRefreshed(f.workspace, entitlement.GateAppToolCalls, f.decision(entitlement.ActionEnforce, 3, f.periodStart))+ for i := range 2 {+ if got := f.admit(ctx); got != nil {+ t.Fatalf("call %d after upgrade refused: %+v", i, got)+ }+ }+ if got := f.admit(ctx); got == nil || got.Limit != 3 {+ t.Fatalf("call past the new limit = %+v, want refused at 3", got)+ }+ if f.used(t) != 3 || f.notices(t, f.ownerID) != 2 {+ t.Fatalf("used %d notices %d; want 3 and one per limit (2)", f.used(t), f.notices(t, f.ownerID))+ }+}++// The next period counts from zero.+func TestAppToolCallQuotaResetsWithThePeriod(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ f.setPolicy(entitlement.ActionEnforce, 1)+ ctx := context.Background()+ f.admit(ctx)+ if got := f.admit(ctx); got == nil {+ t.Fatal("call past limit admitted")+ }+ f.stub.Set(f.workspace, entitlement.GateAppToolCalls, f.decision(entitlement.ActionEnforce, 1, f.periodEnd))+ if got := f.admit(ctx); got != nil {+ t.Fatalf("first call of the next period refused: %+v", got)+ }+}++// Right after the month turns, the cached policy still names the month that+// is over. The call counts in the new month, not the old one; a Cloud that+// still sends the old month admits without counting.+func TestAppToolCallQuotaRereadsAPolicyWhosePeriodEnded(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ ctx := context.Background()+ previous := f.periodStart.AddDate(0, -1, 0)+ f.stub.Set(f.workspace, entitlement.GateAppToolCalls, f.decision(entitlement.ActionEnforce, 1, previous))+ f.quota.now = func() time.Time { return f.periodStart.Add(30 * time.Second) }++ if countedIn, got := f.quota.Admit(ctx, f.workspaceID); got != nil || !countedIn.IsZero() {+ t.Fatalf("stale policy, nothing newer: admit = %v, %+v; want uncounted", countedIn, got)+ }+ if f.usedIn(t, previous) != 0 || f.used(t) != 0 {+ t.Fatalf("stale policy counted: previous %d, current %d; want none", f.usedIn(t, previous), f.used(t))+ }++ f.stub.SetRefreshed(f.workspace, entitlement.GateAppToolCalls, f.decision(entitlement.ActionEnforce, 1, f.periodStart))+ if countedIn, got := f.quota.Admit(ctx, f.workspaceID); got != nil || !countedIn.Equal(f.periodStart) {+ t.Fatalf("first call of the month = counted in %v, refused %+v", countedIn, got)+ }+ if f.usedIn(t, previous) != 0 || f.used(t) != 1 {+ t.Fatalf("used previous %d, current %d; want 0 and 1", f.usedIn(t, previous), f.used(t))+ }+}++// Billing opened in the first minute of a month, before any call refreshed the+// cached policy, shows the new month, not the one that is over.+func TestAppToolCallQuotaUsageRereadsAPolicyWhosePeriodEnded(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ ctx := context.Background()+ previous := f.periodStart.AddDate(0, -1, 0)+ f.stub.Set(f.workspace, entitlement.GateAppToolCalls, f.decision(entitlement.ActionEnforce, 5, previous))+ f.quota.now = func() time.Time { return previous.Add(time.Hour) }+ f.admit(ctx)+ f.admit(ctx)++ f.quota.now = func() time.Time { return f.periodStart.Add(30 * time.Second) }+ f.stub.SetRefreshed(f.workspace, entitlement.GateAppToolCalls, f.decision(entitlement.ActionEnforce, 5, f.periodStart))+ usage, err := f.quota.Usage(ctx, f.workspaceID)+ if err != nil || usage.Used == nil || *usage.Used != 0 || usage.ResetAt == nil || !usage.ResetAt.Equal(f.periodEnd) {+ t.Fatalf("usage at the start of the month = %+v, err = %v; want 0 used, resetting %v", usage, err, f.periodEnd)+ }+}++// staleRefreshProvider answers RefreshGate from a policy fetched moments ago,+// as the Cloud client does inside its reuse window; only RefreshGateNow sees+// a seat bought since.+type staleRefreshProvider struct {+ cached, current entitlement.Decision+}++func (p staleRefreshProvider) Gate(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision {+ return p.cached+}++func (p staleRefreshProvider) RefreshGate(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision {+ return p.cached+}++func (p staleRefreshProvider) RefreshGateNow(context.Context, uuid.UUID, entitlement.GateName) entitlement.Decision {+ return p.current+}++// A seat bought moments ago admits the call even when the policy was+// refreshed just before the purchase.+func TestAppToolCallQuotaRefreshSkipsTheReuseWindow(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ ctx := context.Background()+ f.quota.Entitlements = staleRefreshProvider{+ cached: f.decision(entitlement.ActionEnforce, 1, f.periodStart),+ current: f.decision(entitlement.ActionEnforce, 2, f.periodStart),+ }+ for i := range 2 {+ if got := f.admit(ctx); got != nil {+ t.Fatalf("call %d after the seat purchase refused: %+v", i, got)+ }+ }+ if f.used(t) != 2 {+ t.Fatalf("used = %d, want 2", f.used(t))+ }+}++// Managers hear once per limit in a period, also when the limit goes back to+// one they were already told about (seats removed, then added back).+func TestAppToolCallQuotaNotifiesEachLimitOncePerPeriod(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ ctx := context.Background()+ f.setPolicy(entitlement.ActionEnforce, 1)+ f.admit(ctx)+ if got := f.admit(ctx); got == nil {+ t.Fatal("call past limit 1 admitted")+ }+ f.stub.SetRefreshed(f.workspace, entitlement.GateAppToolCalls, f.decision(entitlement.ActionEnforce, 2, f.periodStart))+ f.admit(ctx)+ if got := f.admit(ctx); got == nil || got.Limit != 2 {+ t.Fatalf("call past limit 2 = %+v, want refused", got)+ }+ f.setPolicy(entitlement.ActionEnforce, 1)+ if got := f.admit(ctx); got == nil || got.Limit != 1 {+ t.Fatalf("call back at limit 1 = %+v, want refused", got)+ }+ if n := f.notices(t, f.ownerID); n != 2 {+ t.Fatalf("owner notices = %d, want one each for limits 1 and 2", n)+ }+}++func TestAppToolCallQuotaMemberUsage(t *testing.T) {+ f := newAppToolCallQuotaFixture(t)+ ctx := context.Background()+ var agentID pgtype.UUID+ if err := f.pool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, f.workspaceID).Scan(&agentID); err != nil {+ t.Fatalf("load agent: %v", err)+ }+ t.Cleanup(func() {+ f.pool.Exec(context.Background(), `DELETE FROM app_tool_call WHERE workspace_id = $1`, f.workspaceID)+ })+ inPeriod := f.periodStart.Add(time.Hour)+ next := f.periodEnd+ for _, c := range []struct {+ by pgtype.UUID+ outcome string+ countedIn *time.Time+ at time.Time+ }{+ {f.ownerID, "ok", &f.periodStart, inPeriod},+ {f.ownerID, "error", &f.periodStart, inPeriod},+ {f.ownerID, "approved", &f.periodStart, inPeriod},+ {f.ownerID, "ok", &f.periodStart, f.periodEnd.Add(time.Second)}, // counted at the end of the month, finished after it+ {f.ownerID, "error", nil, inPeriod}, // an approved call that failed its checks before running+ {f.ownerID, "ok", nil, inPeriod}, // a Remote MCP call+ {f.ownerID, "blocked", nil, inPeriod},+ {f.ownerID, "quota_exceeded", nil, inPeriod},+ {pgtype.UUID{}, "ok", &f.periodStart, inPeriod},+ {f.ownerID, "ok", &next, f.periodEnd.Add(time.Hour)},+ } {+ if _, err := f.pool.Exec(ctx, `+ INSERT INTO app_tool_call (workspace_id, agent_id, triggered_by, account_scope, toolkit_slug, tool_slug, action_class, outcome, metered_period_start, created_at)+ VALUES ($1, $2, $3, 'personal', 'gmail', 'GMAIL_SEND_EMAIL', 'send', $4, $5, $6)`,+ f.workspaceID, agentID, c.by, c.outcome, c.countedIn, c.at); err != nil {+ t.Fatalf("insert call: %v", err)+ }+ }+ got, err := f.quota.MemberUsage(ctx, f.workspaceID, f.periodStart)+ if err != nil {+ t.Fatalf("member usage: %v", err)+ }+ byUser := map[string]int64{}+ for _, m := range got {+ byUser[util.UUIDToString(m.UserID)] = m.Calls+ }+ if len(got) != 2 || byUser[util.UUIDToString(f.ownerID)] != 4 || byUser[""] != 1 {+ t.Fatalf("member usage = %+v, want owner 4 and no-person 1", got)+ }+}++func addAppToolCallQuotaMember(t *testing.T, f *appToolCallQuotaFixture, role string) pgtype.UUID {+ t.Helper()+ ctx := context.Background()+ var userID pgtype.UUID+ email := "app-quota-" + role + "-" + uuid.NewString() + "@multica.test"+ if err := f.pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ('App Quota Member', $1) RETURNING id`, email).Scan(&userID); err != nil {+ t.Fatalf("insert user: %v", err)+ }+ if _, err := f.pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, $3)`, f.workspaceID, userID, role); err != nil {+ t.Fatalf("insert member: %v", err)+ }+ t.Cleanup(func() {+ f.pool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1 AND user_id = $2`, f.workspaceID, userID)+ f.pool.Exec(context.Background(), `DELETE FROM "user" WHERE id = $1`, userID)+ })+ return userID+}diff --git a/server/migrations/748_app_tool_call_quota_period.down.sql b/server/migrations/748_app_tool_call_quota_period.down.sqlnew file mode 100644index 0000000000..fa07c89684--- /dev/null+++ b/server/migrations/748_app_tool_call_quota_period.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS app_tool_call_quota_period;diff --git a/server/migrations/748_app_tool_call_quota_period.up.sql b/server/migrations/748_app_tool_call_quota_period.up.sqlnew file mode 100644index 0000000000..736a3ec566--- /dev/null+++ b/server/migrations/748_app_tool_call_quota_period.up.sql@@ -0,0 +1,23 @@+-- Monthly app tool call usage per workspace, for the app_tool_calls+-- entitlement gate (MUL-10047). One row per workspace and Cloud-defined+-- period; admission increments used_count in a single conditional UPDATE, so+-- the gateway never counts app_tool_call rows on the hot path. Limits and+-- period boundaries come from Cloud at runtime; nothing commercial lives here.+--+-- rejection_notified_at and rejection_notified_limits mark the period's limit+-- notices: managers hear once per limit in a period, even when the limit goes+-- back to one they were already told about.+--+-- The scope unique index is built concurrently in 749. No foreign keys (repo+-- rule): workspace deletion removes these rows explicitly.+CREATE TABLE IF NOT EXISTS app_tool_call_quota_period (+ workspace_id UUID NOT NULL,+ period_start TIMESTAMPTZ NOT NULL,+ period_end TIMESTAMPTZ NOT NULL,+ used_count BIGINT NOT NULL DEFAULT 0 CHECK (used_count >= 0),+ rejection_notified_at TIMESTAMPTZ,+ rejection_notified_limits BIGINT[] NOT NULL DEFAULT '{}',+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ CHECK (period_start < period_end)+);diff --git a/server/migrations/749_app_tool_call_quota_period_scope_idx.down.sql b/server/migrations/749_app_tool_call_quota_period_scope_idx.down.sqlnew file mode 100644index 0000000000..109fab1310--- /dev/null+++ b/server/migrations/749_app_tool_call_quota_period_scope_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS uq_app_tool_call_quota_period_scope;diff --git a/server/migrations/749_app_tool_call_quota_period_scope_idx.up.sql b/server/migrations/749_app_tool_call_quota_period_scope_idx.up.sqlnew file mode 100644index 0000000000..920d396f4d--- /dev/null+++ b/server/migrations/749_app_tool_call_quota_period_scope_idx.up.sql@@ -0,0 +1,3 @@+-- Upsert key for the app tool call quota increment and its usage read.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_app_tool_call_quota_period_scope+ ON app_tool_call_quota_period (workspace_id, period_start, period_end);diff --git a/server/migrations/750_app_tool_call_quota_columns.down.sql b/server/migrations/750_app_tool_call_quota_columns.down.sqlnew file mode 100644index 0000000000..9299a7fb34--- /dev/null+++ b/server/migrations/750_app_tool_call_quota_columns.down.sql@@ -0,0 +1,8 @@+ALTER TABLE app_tool_call DROP COLUMN IF EXISTS metered_period_start;++-- 'quota_exceeded' rows must be removed before rolling back; the restored+-- constraint rejects them on the next write.+ALTER TABLE app_tool_call+ DROP CONSTRAINT IF EXISTS app_tool_call_outcome_check,+ ADD CONSTRAINT app_tool_call_outcome_check+ CHECK (outcome IN ('ok', 'error', 'blocked', 'pending', 'approved', 'rejected', 'rate_limited')) NOT VALID;diff --git a/server/migrations/750_app_tool_call_quota_columns.up.sql b/server/migrations/750_app_tool_call_quota_columns.up.sqlnew file mode 100644index 0000000000..5643c2a19d--- /dev/null+++ b/server/migrations/750_app_tool_call_quota_columns.up.sql@@ -0,0 +1,20 @@+-- Monthly app tool call limit (MUL-10047).+--+-- A call refused because the workspace used its allowance is recorded as+-- 'quota_exceeded'. Widening a whitelist cannot fail on existing rows, so the+-- constraint is replaced NOT VALID (no scan), the same as 699.+--+-- metered_period_start is the start of the period the allowance counted the+-- call in, recorded when it was counted, so the per-person breakdown matches+-- the counter even for a call that finishes after the month turned. NULL for+-- every call the allowance did not count: refused or blocked ones, an approved+-- call that fails its checks before running, Remote MCP calls, and every call+-- while the gate is off. Nullable without a default, the ADD COLUMN is+-- catalog-only.+ALTER TABLE app_tool_call+ DROP CONSTRAINT IF EXISTS app_tool_call_outcome_check,+ ADD CONSTRAINT app_tool_call_outcome_check+ CHECK (outcome IN ('ok', 'error', 'blocked', 'pending', 'approved', 'rejected', 'rate_limited', 'quota_exceeded')) NOT VALID;++ALTER TABLE app_tool_call+ ADD COLUMN IF NOT EXISTS metered_period_start TIMESTAMPTZ;diff --git a/server/migrations/751_app_tool_call_workspace_metered_idx.down.sql b/server/migrations/751_app_tool_call_workspace_metered_idx.down.sqlnew file mode 100644index 0000000000..9b4b0b1492--- /dev/null+++ b/server/migrations/751_app_tool_call_workspace_metered_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_app_tool_call_workspace_metered;diff --git a/server/migrations/751_app_tool_call_workspace_metered_idx.up.sql b/server/migrations/751_app_tool_call_workspace_metered_idx.up.sqlnew file mode 100644index 0000000000..fc0a70428c--- /dev/null+++ b/server/migrations/751_app_tool_call_workspace_metered_idx.up.sql@@ -0,0 +1,6 @@+-- Per-person app tool call usage for a period on the billing page: the calls+-- of one workspace counted in that period. Partial, so the many calls the+-- allowance never counted take no space in it.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_app_tool_call_workspace_metered+ ON app_tool_call (workspace_id, metered_period_start)+ WHERE metered_period_start IS NOT NULL;diff --git a/server/pkg/db/generated/app_tool_call_quota.sql.go b/server/pkg/db/generated/app_tool_call_quota.sql.gonew file mode 100644index 0000000000..6af77bcfb3--- /dev/null+++ b/server/pkg/db/generated/app_tool_call_quota.sql.go@@ -0,0 +1,147 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: app_tool_call_quota.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const claimAppToolCallQuotaRejectionNotice = `-- name: ClaimAppToolCallQuotaRejectionNotice :one+INSERT INTO app_tool_call_quota_period (+ workspace_id, period_start, period_end, rejection_notified_at, rejection_notified_limits+) VALUES ($1, $2, $3, now(), ARRAY[$4::bigint])+ON CONFLICT (workspace_id, period_start, period_end) DO UPDATE+SET rejection_notified_at = now(),+ rejection_notified_limits = array_append(app_tool_call_quota_period.rejection_notified_limits, $4::bigint),+ updated_at = now()+WHERE app_tool_call_quota_period.rejection_notified_at IS NULL+ OR ($5::bool+ AND NOT ($4::bigint = ANY (app_tool_call_quota_period.rejection_notified_limits)))+RETURNING used_count+`++type ClaimAppToolCallQuotaRejectionNoticeParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PeriodStart pgtype.Timestamptz `json:"period_start"`+ PeriodEnd pgtype.Timestamptz `json:"period_end"`+ LimitValue int64 `json:"limit_value"`+ PerLimit bool `json:"per_limit"`+}++// Marks the period's limit notice as sent and returns a row only to the one+// caller that should send it: the first rejection of the period, or with+// per_limit the first at a limit not yet notified in the period. Run it in the+// transaction that writes the Inbox items, so a failed delivery leaves the+// marker unset for the next rejection.+func (q *Queries) ClaimAppToolCallQuotaRejectionNotice(ctx context.Context, arg ClaimAppToolCallQuotaRejectionNoticeParams) (int64, error) {+ row := q.db.QueryRow(ctx, claimAppToolCallQuotaRejectionNotice,+ arg.WorkspaceID,+ arg.PeriodStart,+ arg.PeriodEnd,+ arg.LimitValue,+ arg.PerLimit,+ )+ var used_count int64+ err := row.Scan(&used_count)+ return used_count, err+}++const getAppToolCallQuotaUsed = `-- name: GetAppToolCallQuotaUsed :one+SELECT used_count FROM app_tool_call_quota_period+WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3+`++type GetAppToolCallQuotaUsedParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PeriodStart pgtype.Timestamptz `json:"period_start"`+ PeriodEnd pgtype.Timestamptz `json:"period_end"`+}++func (q *Queries) GetAppToolCallQuotaUsed(ctx context.Context, arg GetAppToolCallQuotaUsedParams) (int64, error) {+ row := q.db.QueryRow(ctx, getAppToolCallQuotaUsed, arg.WorkspaceID, arg.PeriodStart, arg.PeriodEnd)+ var used_count int64+ err := row.Scan(&used_count)+ return used_count, err+}++const incrementAppToolCallQuota = `-- name: IncrementAppToolCallQuota :one+INSERT INTO app_tool_call_quota_period (workspace_id, period_start, period_end, used_count)+SELECT $1::uuid, $2::timestamptz, $3::timestamptz, 1+WHERE NOT $4::bool OR $5::bigint > 0+ON CONFLICT (workspace_id, period_start, period_end) DO UPDATE+SET used_count = app_tool_call_quota_period.used_count + 1,+ updated_at = now()+WHERE NOT $4::bool OR app_tool_call_quota_period.used_count < $5::bigint+RETURNING used_count+`++type IncrementAppToolCallQuotaParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PeriodStart pgtype.Timestamptz `json:"period_start"`+ PeriodEnd pgtype.Timestamptz `json:"period_end"`+ Enforce bool `json:"enforce"`+ LimitValue int64 `json:"limit_value"`+}++// Counts one app tool call against the workspace's period in one statement.+// Under enforce the row only moves while used_count is below the limit, so+// concurrent calls can never take a workspace past it; no row back means the+// call is refused. Under observe every call is counted.+func (q *Queries) IncrementAppToolCallQuota(ctx context.Context, arg IncrementAppToolCallQuotaParams) (int64, error) {+ row := q.db.QueryRow(ctx, incrementAppToolCallQuota,+ arg.WorkspaceID,+ arg.PeriodStart,+ arg.PeriodEnd,+ arg.Enforce,+ arg.LimitValue,+ )+ var used_count int64+ err := row.Scan(&used_count)+ return used_count, err+}++const listAppToolCallUsageByMember = `-- name: ListAppToolCallUsageByMember :many+SELECT triggered_by, count(*)::bigint AS calls+FROM app_tool_call+WHERE workspace_id = $1+ AND metered_period_start = $2::timestamptz+GROUP BY triggered_by+ORDER BY calls DESC+`++type ListAppToolCallUsageByMemberParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ MeteredPeriodStart pgtype.Timestamptz `json:"metered_period_start"`+}++type ListAppToolCallUsageByMemberRow struct {+ TriggeredBy pgtype.UUID `json:"triggered_by"`+ Calls int64 `json:"calls"`+}++// Calls counted in a period, per person who started the run or approved the+// call. A NULL triggered_by is a run no person started.+func (q *Queries) ListAppToolCallUsageByMember(ctx context.Context, arg ListAppToolCallUsageByMemberParams) ([]ListAppToolCallUsageByMemberRow, error) {+ rows, err := q.db.Query(ctx, listAppToolCallUsageByMember, arg.WorkspaceID, arg.MeteredPeriodStart)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListAppToolCallUsageByMemberRow{}+ for rows.Next() {+ var i ListAppToolCallUsageByMemberRow+ if err := rows.Scan(&i.TriggeredBy, &i.Calls); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}diff --git a/server/pkg/db/generated/connected_apps.sql.go b/server/pkg/db/generated/connected_apps.sql.goindex 535e0b2e7d..8f1be57297 100644--- a/server/pkg/db/generated/connected_apps.sql.go+++ b/server/pkg/db/generated/connected_apps.sql.go@@ -859,27 +859,28 @@ const insertAppToolCall = `-- name: InsertAppToolCall :execINSERT INTO app_tool_call (workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by,account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class,- outcome, request_id, error+ outcome, request_id, error, metered_period_start) VALUES (- $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15)`type InsertAppToolCallParams struct {- WorkspaceID pgtype.UUID `json:"workspace_id"`- TaskID pgtype.UUID `json:"task_id"`- AgentID pgtype.UUID `json:"agent_id"`- IssueID pgtype.UUID `json:"issue_id"`- ChatSessionID pgtype.UUID `json:"chat_session_id"`- TriggeredBy pgtype.UUID `json:"triggered_by"`- AccountScope string `json:"account_scope"`- AccountOwnerUserID pgtype.UUID `json:"account_owner_user_id"`- ToolkitSlug string `json:"toolkit_slug"`- ToolSlug string `json:"tool_slug"`- ActionClass string `json:"action_class"`- Outcome string `json:"outcome"`- RequestID pgtype.UUID `json:"request_id"`- Error pgtype.Text `json:"error"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ TaskID pgtype.UUID `json:"task_id"`+ AgentID pgtype.UUID `json:"agent_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ TriggeredBy pgtype.UUID `json:"triggered_by"`+ AccountScope string `json:"account_scope"`+ AccountOwnerUserID pgtype.UUID `json:"account_owner_user_id"`+ ToolkitSlug string `json:"toolkit_slug"`+ ToolSlug string `json:"tool_slug"`+ ActionClass string `json:"action_class"`+ Outcome string `json:"outcome"`+ RequestID pgtype.UUID `json:"request_id"`+ Error pgtype.Text `json:"error"`+ MeteredPeriodStart pgtype.Timestamptz `json:"metered_period_start"`}func (q *Queries) InsertAppToolCall(ctx context.Context, arg InsertAppToolCallParams) error {@@ -898,6 +899,7 @@ func (q *Queries) InsertAppToolCall(ctx context.Context, arg InsertAppToolCallPaarg.Outcome,arg.RequestID,arg.Error,+ arg.MeteredPeriodStart,)return err}@@ -1264,7 +1266,7 @@ func (q *Queries) ListDecidedAppActionRequestsForIssue(ctx context.Context, arg}const listIssueAppToolCalls = `-- name: ListIssueAppToolCalls :many-SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at FROM app_tool_call+SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at, metered_period_start FROM app_tool_callWHERE workspace_id = $1 AND issue_id = $2ORDER BY created_at DESCLIMIT 500@@ -1303,6 +1305,7 @@ func (q *Queries) ListIssueAppToolCalls(ctx context.Context, arg ListIssueAppToo&i.RequestID,&i.Error,&i.CreatedAt,+ &i.MeteredPeriodStart,); err != nil {return nil, err}@@ -1670,7 +1673,7 @@ func (q *Queries) ListPersonalAppAgentsForUser(ctx context.Context, arg ListPers}const listPersonalAppToolCalls = `-- name: ListPersonalAppToolCalls :many-SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at FROM app_tool_call+SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at, metered_period_start FROM app_tool_callWHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'personal'AND account_owner_user_id = $3ORDER BY created_at DESC@@ -1716,6 +1719,7 @@ func (q *Queries) ListPersonalAppToolCalls(ctx context.Context, arg ListPersonal&i.RequestID,&i.Error,&i.CreatedAt,+ &i.MeteredPeriodStart,); err != nil {return nil, err}@@ -1778,7 +1782,7 @@ func (q *Queries) ListTeamAccountRequestSummaries(ctx context.Context, workspace}const listTeamAppToolCalls = `-- name: ListTeamAppToolCalls :many-SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at FROM app_tool_call+SELECT id, workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by, account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class, outcome, request_id, error, created_at, metered_period_start FROM app_tool_callWHERE workspace_id = $1 AND toolkit_slug = $2 AND account_scope = 'team'ORDER BY created_at DESCLIMIT $3@@ -1816,6 +1820,7 @@ func (q *Queries) ListTeamAppToolCalls(ctx context.Context, arg ListTeamAppToolC&i.RequestID,&i.Error,&i.CreatedAt,+ &i.MeteredPeriodStart,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 00e671815f..c36a995d1f 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -259,6 +259,18 @@ type AppToolCall struct {RequestID pgtype.UUID `json:"request_id"`Error pgtype.Text `json:"error"`CreatedAt pgtype.Timestamptz `json:"created_at"`+ MeteredPeriodStart pgtype.Timestamptz `json:"metered_period_start"`+}++type AppToolCallQuotaPeriod struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ PeriodStart pgtype.Timestamptz `json:"period_start"`+ PeriodEnd pgtype.Timestamptz `json:"period_end"`+ UsedCount int64 `json:"used_count"`+ RejectionNotifiedAt pgtype.Timestamptz `json:"rejection_notified_at"`+ RejectionNotifiedLimits []int64 `json:"rejection_notified_limits"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`}type AppToolClassOverride struct {diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.goindex 75e5dae79a..43ad1e2c7c 100644--- a/server/pkg/db/generated/workspace_delete.sql.go+++ b/server/pkg/db/generated/workspace_delete.sql.go@@ -120,6 +120,16 @@ func (q *Queries) DeleteWorkspaceAgents(ctx context.Context, workspaceID pgtype.return err}+const deleteWorkspaceAppToolCallQuotaPeriods = `-- name: DeleteWorkspaceAppToolCallQuotaPeriods :exec+DELETE FROM app_tool_call_quota_period+WHERE app_tool_call_quota_period.workspace_id = $1+`++func (q *Queries) DeleteWorkspaceAppToolCallQuotaPeriods(ctx context.Context, workspaceID pgtype.UUID) error {+ _, err := q.db.Exec(ctx, deleteWorkspaceAppToolCallQuotaPeriods, workspaceID)+ return err+}+const deleteWorkspaceAutopilotChildren = `-- name: DeleteWorkspaceAutopilotChildren :execWITHdeleted_triggers AS (diff --git a/server/pkg/db/queries/app_tool_call_quota.sql b/server/pkg/db/queries/app_tool_call_quota.sqlnew file mode 100644index 0000000000..d8b2d38172--- /dev/null+++ b/server/pkg/db/queries/app_tool_call_quota.sql@@ -0,0 +1,45 @@+-- name: IncrementAppToolCallQuota :one+-- Counts one app tool call against the workspace's period in one statement.+-- Under enforce the row only moves while used_count is below the limit, so+-- concurrent calls can never take a workspace past it; no row back means the+-- call is refused. Under observe every call is counted.+INSERT INTO app_tool_call_quota_period (workspace_id, period_start, period_end, used_count)+SELECT @workspace_id::uuid, @period_start::timestamptz, @period_end::timestamptz, 1+WHERE NOT @enforce::bool OR @limit_value::bigint > 0+ON CONFLICT (workspace_id, period_start, period_end) DO UPDATE+SET used_count = app_tool_call_quota_period.used_count + 1,+ updated_at = now()+WHERE NOT @enforce::bool OR app_tool_call_quota_period.used_count < @limit_value::bigint+RETURNING used_count;++-- name: GetAppToolCallQuotaUsed :one+SELECT used_count FROM app_tool_call_quota_period+WHERE workspace_id = $1 AND period_start = $2 AND period_end = $3;++-- name: ClaimAppToolCallQuotaRejectionNotice :one+-- Marks the period's limit notice as sent and returns a row only to the one+-- caller that should send it: the first rejection of the period, or with+-- per_limit the first at a limit not yet notified in the period. Run it in the+-- transaction that writes the Inbox items, so a failed delivery leaves the+-- marker unset for the next rejection.+INSERT INTO app_tool_call_quota_period (+ workspace_id, period_start, period_end, rejection_notified_at, rejection_notified_limits+) VALUES (@workspace_id, @period_start, @period_end, now(), ARRAY[@limit_value::bigint])+ON CONFLICT (workspace_id, period_start, period_end) DO UPDATE+SET rejection_notified_at = now(),+ rejection_notified_limits = array_append(app_tool_call_quota_period.rejection_notified_limits, @limit_value::bigint),+ updated_at = now()+WHERE app_tool_call_quota_period.rejection_notified_at IS NULL+ OR (@per_limit::bool+ AND NOT (@limit_value::bigint = ANY (app_tool_call_quota_period.rejection_notified_limits)))+RETURNING used_count;++-- name: ListAppToolCallUsageByMember :many+-- Calls counted in a period, per person who started the run or approved the+-- call. A NULL triggered_by is a run no person started.+SELECT triggered_by, count(*)::bigint AS calls+FROM app_tool_call+WHERE workspace_id = $1+ AND metered_period_start = sqlc.arg('metered_period_start')::timestamptz+GROUP BY triggered_by+ORDER BY calls DESC;diff --git a/server/pkg/db/queries/connected_apps.sql b/server/pkg/db/queries/connected_apps.sqlindex dabc09c17d..030239313a 100644--- a/server/pkg/db/queries/connected_apps.sql+++ b/server/pkg/db/queries/connected_apps.sql@@ -266,9 +266,9 @@ WHERE workspace_id = $1INSERT INTO app_tool_call (workspace_id, task_id, agent_id, issue_id, chat_session_id, triggered_by,account_scope, account_owner_user_id, toolkit_slug, tool_slug, action_class,- outcome, request_id, error+ outcome, request_id, error, metered_period_start) VALUES (- $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15);-- name: ListTeamAppToolCalls :manydiff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sqlindex 7260026b06..6297b7ac9e 100644--- a/server/pkg/db/queries/workspace_delete.sql+++ b/server/pkg/db/queries/workspace_delete.sql@@ -665,6 +665,10 @@ WHERE autopilot_quota_reservation.workspace_id = $1;DELETE FROM autopilot_quota_periodWHERE autopilot_quota_period.workspace_id = $1;+-- name: DeleteWorkspaceAppToolCallQuotaPeriods :exec+DELETE FROM app_tool_call_quota_period+WHERE app_tool_call_quota_period.workspace_id = $1;+-- name: DeleteWorkspaceEntitlementLimitOverages :execDELETE FROM entitlement_limit_overageWHERE entitlement_limit_overage.workspace_id = $1;